# API.STOCKPRICES.COM - SECURITY IMPLEMENTATION GUIDE

## Overview
This document outlines the complete security implementation for `api.stockprices.com/html`, including API key validation, Bearer token authentication, and rate limiting.

---

## 1. GLOBAL SECURITY FILTERS (Applied to ALL requests)

### A. Authorize Filter - X-API-KEY Validation
**File:** `app/Filters/Authorize.php`
**Purpose:** Ensure all API requests come from known clients
**Validation:** Every request MUST include `x-api-key` header

**How it works:**
```
Request comes in
    ↓
Check for 'x-api-key' header
    ↓
If missing → Return 401 Unauthorized
    ↓
If present → Compare against X_API_KEY constant
    ↓
If mismatch → Return 401 "Access Denied"
    ↓
If match → Continue to next filter
```

**Example Request:**
```bash
curl -X GET https://api.stockprices.com/market/trending-news \
  -H "x-api-key: your_unique_api_key_here"
```

**Configuration:**
- **Constant Location:** `app/Config/Constants.php` (line 153)
- **Current Value:** `X_API_KEY = getenv('X_API_KEY') ?: 'default_api_key_change_in_production'`
- **Production Setup:** Update Constants.php directly with your production API key
- **Development:** Can optionally use .env file with `X_API_KEY` variable (Constants.php reads via getenv())

---

### B. Rate Limit Filter - Per-IP Request Throttling
**File:** `app/Filters/RateLimit.php`
**Purpose:** Prevent abuse and DDoS attacks per IP address
**Validation:** Track request count per IP in Redis

**How it works:**
```
Request comes in from IP address 192.168.1.100
    ↓
Check Redis key: 'rate_limit_sp_192.168.1.100'
    ↓
Is request count < 60? → Proceed
    ↓
Is request count ≥ 60? → Return 429 "Too many requests"
```

**Rate Limit Settings:**
- **Default Limit:** 60 requests per 60 seconds per IP
- **Redis Key Prefix:** `rate_limit_sp_` (unique to stockprices)
- **Configurable Per Route:** Can override defaults in route definition

**Example - Custom Route Rate Limit:**
```php
$routes->get('market/data', 'MarketController::data', ['ratelimit' => [30, 60]]);
// 30 requests per 60 seconds on this specific endpoint
```

**Redis Storage:**
```
Key: rate_limit_sp_192.168.1.100
Value: 45 (current request count)
TTL: 60 seconds (auto-reset)
```

---

## 2. PROTECTED ENDPOINTS - Bearer Token Authentication

### Routes Requiring Bearer Token (`'auth'` filter):

**User Account Routes:**
- `POST   /user/top-picks` → Add top picks
- `POST   /user/watchlist/add` → Add to watchlist
- `GET    /user/watchlist` → Get saved watchlist
- `POST   /user/watchlist/remove` → Remove from watchlist
- `GET    /user/preferences` → Get user preferences
- `GET    /user/top-picks/history` → View history
- `GET    /user/articles` → Get personalized articles
- `GET    /user/news` → Get personalized news
- `GET    /user/profile` → Get user profile
- `POST   /user/update-profile` → Update profile

**Portfolio Routes:**
- `POST   /portfolio/create` → Create new portfolio
- `POST   /portfolio/new` → Save portfolio
- `GET    /user/portfolio` → Get all portfolios
- `POST   /portfolio/addStock` → Add stock to portfolio
- `POST   /portfolio/delete` → Delete portfolio

**Subscription Routes:**
- `GET    /subscription/cancel-subscription` → Cancel subscription
- `GET    /subscription/billing-history` → View billing history

---

## 3. PUBLIC ENDPOINTS (No Bearer Token Required)

These endpoints do NOT need authentication and are available to any client with valid X-API-KEY:

**Market Data:**
- `GET /market/trending-news`
- `GET /market/gainers`
- `GET /market/losers`
- `GET /market/top-yielding-stocks`
- `GET /market/trending-stocks`
- `GET /market-snapshot/*`

**Stock Information:**
- `GET /stock/ticker-search`
- `GET /stock/price-info`
- `GET /stock/about`
- `GET /stock/chart`

**Articles & Content:**
- `GET /articles`
- `GET /articles/:id-slug`
- `GET /expert-analysis`
- `GET /search-articles`

**Authentication (No token needed for signup/signin):**
- `POST /auth/signin` → User login (returns Bearer token)
- `POST /auth/signup` → User registration
- `POST /auth/verify-account` → Verify email
- `POST /auth/forgot-password` → Password reset

**Shop/Public:**
- `GET /shop/homepage-data`
- `GET /shop/search`
- `POST /contact-us`

---

## 4. COMPLETE REQUEST/RESPONSE FLOW

### Scenario 1: Valid User Accessing Protected Endpoint

```
Client Request:
  GET /user/profile HTTP/1.1
  x-api-key: abc123valid_key_here
  Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
  
  ↓ [AUTHORIZE FILTER] ↓
  ✅ X-API-KEY Valid? YES
  
  ↓ [RATE LIMIT FILTER] ↓
  ✅ Request count < 60? YES
  
  ↓ [AUTH FILTER] ↓
  ✅ Bearer token present? YES
  ✅ JWT signature valid? YES
  ✅ Token not expired? YES
  ✅ Sets: $_REQUEST['user_id'], $_REQUEST['email']
  
  ✓ Request Proceeds → UserController::getProfile()
  
Response:
  200 OK
  {
    "success": true,
    "data": {
      "id": "user_123",
      "email": "user@example.com",
      "profile": {...}
    }
  }
```

### Scenario 2: Invalid API Key

```
Client Request:
  GET /market/trending-news HTTP/1.1
  x-api-key: wrong_invalid_key
  
  ↓ [AUTHORIZE FILTER] ↓
  ❌ X-API-KEY mismatch
  
Response:
  401 Unauthorized
  {
    "success": false,
    "message": "Access Denied"
  }
```

### Scenario 3: Rate Limit Exceeded

```
Client Request from IP 192.168.1.100:
  (61st request within 60 seconds)
  
  GET /market/trending-news HTTP/1.1
  x-api-key: valid_key_here
  
  ↓ [AUTHORIZE FILTER] ↓
  ✅ X-API-KEY Valid
  
  ↓ [RATE LIMIT FILTER] ↓
  ❌ Request count (61) ≥ limit (60)
  
Response:
  429 Too Many Requests
  {
    "status": 429,
    "message": "Too many requests. Please try again later."
  }
```

### Scenario 4: Missing Bearer Token on Protected Route

```
Client Request:
  GET /user/profile HTTP/1.1
  x-api-key: valid_key_here
  (NO Authorization header)
  
  ↓ [AUTHORIZE FILTER] ✅
  ↓ [RATE LIMIT FILTER] ✅
  
  ↓ [AUTH FILTER] ↓
  ❌ Authorization header missing
  
Response:
  401 Unauthorized
  {
    "success": false,
    "message": "Token not found."
  }
```

---

## 5. CONFIGURATION & SETUP

### A. Production Configuration (Constants.php)

For production, update `app/Config/Constants.php` directly:

```php
// Line 153 - API Key for client validation
define('X_API_KEY', 'your_production_api_key_32_chars_minimum');

// Lines 130+ - Redis Configuration for Production
if(ENVIRONMENT === 'production') {
    defined('REDIS_SERVER') || define('REDIS_SERVER', '127.0.0.1');
    defined('REDIS_PORT')   || define('REDIS_PORT', '22133');
    defined('ENVIRONMENT')  || define('ENVIRONMENT', 'production');
}
```

Update `app/Config/Site.php`:

```php
public $jwt_key = 'your_production_jwt_key_here';
public $jwt_refresh_key = 'your_production_jwt_refresh_key_here';
```

### B. Development Configuration (Optional .env)

For development convenience, you can use `.env` file. Constants.php will read values via `getenv()`:

```env
# API Key for client validation
X_API_KEY=your_strong_random_32_char_key_here

# CORS origin for frontend
CORS_ALLOWED_ORIGIN=https://ui.stockprices.com

# JWT Keys (consider rotating quarterly)
JWT_KEY=034985761405aadfff229d52d232a7cb2b608dc745dfbb213b45ccbf448354c1
JWT_REFRESH_KEY=1b6d3b9a83044226e862920bdf77045319634a8643c13d94d17d7f0f1ba26730
```

**Note:** `.env` is NOT used in production. All production configuration comes from Constants.php.

### C. Redis Configuration

Rate limiting requires Redis. Settings in `app/Config/Constants.php`:

```php
// Production
if(ENVIRONMENT === 'production') {
    defined('REDIS_SERVER') || define('REDIS_SERVER', '127.0.0.1');
    defined('REDIS_PORT')   || define('REDIS_PORT', '22133');
}

// Development
else {
    defined('REDIS_SERVER') || define('REDIS_SERVER', '192.168.30.106');
    defined('REDIS_PORT')   || define('REDIS_PORT', '6378');
}
```

### D. JWT Configuration
Located in `app/Config/Site.php`:

```php
public $jwt_key = '034985761405aadfff229d52d232a7cb2b608dc745dfbb213b45ccbf448354c1';
public $jwt_refresh_key = '1b6d3b9a83044226e862920bdf77045319634a8643c13d94d17d7f0f1ba26730';
public $token_timeout = 86400;              // 1 day
public $refresh_token_timeout = 2592000;    // 30 days
```

---

## 6. USER AUTHENTICATION FLOW

### Login (Get Bearer Token)

**Request:**
```bash
curl -X POST https://api.stockprices.com/auth/signin \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "email": "user@example.com",
    "password": "userpassword"
  }'
```

**Success Response:**
```json
{
  "success": true,
  "message": "Login successful",
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "123",
    "email": "user@example.com",
    "full_name": "John Doe"
  }
}
```

### Use Access Token for Protected Endpoints

**Request:**
```bash
curl -X GET https://api.stockprices.com/user/profile \
  -H "x-api-key: your_api_key" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

### Refresh Expired Access Token

**Request:**
```bash
curl -X POST https://api.stockprices.com/auth/refresh-token \
  -H "x-api-key: your_api_key" \
  -H "X-Refresh-Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

**Response:**
```json
{
  "success": true,
  "access_token": "new_jwt_token_here",
  "message": "Access token refreshed"
}
```

---

## 7. KEY SECURITY FEATURES

✅ **X-API-KEY Global Validation**
- All requests must include valid API key header
- Prevents unauthorized API access

✅ **Rate Limiting**
- Per-IP throttling: 60 requests per 60 seconds
- Prevents DoS/brute force attacks
- Configurable per route

✅ **JWT Bearer Tokens**
- Access tokens: 1 day expiry
- Refresh tokens: 30 days expiry
- Token stored in Redis for revocation support
- Logout immediately invalidates tokens

✅ **CORS Protection**
- Restricted to allowed origins via environment variable
- Prevents cross-origin API abuse

✅ **Secrets Management**
- API keys in environment variables (not hardcoded)
- `.env` excluded from version control
- `.env.example` provided for reference

---

## 8. TESTING CHECKLIST

- [ ] Test X-API-KEY validation (with/without header)
- [ ] Test rate limiting (send 61+ requests rapidly)
- [ ] Test Bearer token on protected endpoints
- [ ] Test expired token handling (should return 401)
- [ ] Test refresh token flow
- [ ] Test CORS headers match configured origin
- [ ] Test public endpoints (market, articles) don't require auth
- [ ] Test rate limit is per-IP (not global)
- [ ] Verify Redis keys are created in proper format
- [ ] Monitor logs for failed auth attempts

---

## 9. PRODUCTION DEPLOYMENT CHECKLIST

- [ ] Update `app/Config/Constants.php` line 153 with unique `X_API_KEY` (use strong random 32+ char string)
- [ ] Update `app/Config/Site.php` with production `JWT_KEY` and `JWT_REFRESH_KEY` (rotate to new values)
- [ ] Configure Redis server in `app/Config/Constants.php` lines 130-143 (production credentials)
- [ ] Verify Redis is secure and password-protected
- [ ] Enable HTTPS on all endpoints
- [ ] Setup logging for failed auth/rate-limit events in `app/Config/Logger.php`
- [ ] Setup monitoring/alerts for rate-limit spikes (track Redis key patterns)
- [ ] Test all protected endpoints with real Bearer tokens
- [ ] Document API key distribution to client partners
- [ ] Implement API key rotation policy (quarterly) - update Constants.php directly

---

## 10. TROUBLESHOOTING

### "Unauthorized - Access Denied"
- Verify `x-api-key` header is present
- Verify `X_API_KEY` in `app/Config/Constants.php` (line 153) matches request header
- Check for typos in API key

### "Too many requests (429)"
- Wait for 60-second rate limit window to reset
- Check if multiple clients share same IP (corporate network)
- Consider increasing limit for specific endpoints if needed

### "Token not found (401 on protected endpoint)"
- Verify `Authorization: Bearer <token>` header is present
- Verify token is not expired (check expiry in JWT payload)
- Try refreshing token using refresh endpoint

### "Invalid refresh token"
- Verify `X-Refresh-Token` header is present
- Verify refresh token has not expired (30-day limit)
- Re-login to get new tokens

---

**Last Updated:** March 19, 2026
**Status:** ✅ Ready for Production (with pre-deployment checklist completion)
