Security Architecture
Multi-layer security approach protecting data, APIs, and user privacy across the entire AltSportsLeagues.ai platform.
π Security Layers
π‘οΈ Layer 1: Edge Security (Cloudflare)
Cloudflare Protection
DDoS Protection:
- Automatic mitigation for all traffic
- 100+ Tbps network capacity
- Always-on protection (no configuration needed)
Web Application Firewall (WAF):
- OWASP Top 10 protection
- Custom rule creation
- Rate limiting (configurable)
SSL/TLS:
- Full (Strict) SSL mode
- TLS 1.2+ minimum
- HTTP β HTTPS auto-redirect
- HSTS headers
Bot Protection:
- Challenge suspicious requests
- Block known bad bots
- JavaScript challenge for verification
Caching & Performance:
- Static asset caching
- API response caching (configurable)
- Brotli compression
- HTTP/2 & HTTP/3 support
Recommended Cloudflare Settings
Security Level: Medium
Challenge Passage: 30 minutes
Browser Integrity Check: On
Hotlink Protection: On
Always Use HTTPS: On
Automatic HTTPS Rewrites: Onπ Layer 2: Platform Security
Google Cloud Run Security
IAM & Access Control:
# Service runs as non-root user
# Defined in Dockerfile:
USER app
# Limited permissions
# No direct SSH access
# Logs via Cloud Logging onlyNetwork Security:
- VPC connector (optional for private resources)
- Ingress control (all, internal, internal + Cloud Load Balancing)
- Binary authorization (image signing)
Secrets Management:
# Use Secret Manager for sensitive data
gcloud secrets create OPENAI_API_KEY --data-file=-
# Mount in Cloud Run
gcloud run services update altsportsleagues-backend \
--update-secrets=OPENAI_API_KEY=OPENAI_API_KEY:latestVercel Security
Edge Security:
- DDoS protection at edge
- Rate limiting per IP
- Geo-blocking (if needed)
Environment Variables:
- Encrypted at rest
- Never exposed to client
- Separate per environment (dev, preview, prod)
Authentication:
- Password protection for preview deployments
- Vercel firewall rules
- Custom middleware support
π Layer 3: Application Security
Authentication Strategy
By Service:
| Service | Auth Method | Token Type |
|---|---|---|
| Frontend | Firebase Auth | ID Token |
| Backend API | Bearer Token + API Keys | JWT |
| Docs Site | Public (no auth) | N/A |
| n8n UI | Username/Password | Session |
| n8n Webhooks | API Key + Signature | Header Auth |
Firebase Authentication Flow
Frontend Code:
import { signInWithPopup, GoogleAuthProvider } from 'firebase/auth';
async function signIn() {
const provider = new GoogleAuthProvider();
const result = await signInWithPopup(auth, provider);
const idToken = await result.user.getIdToken();
// Use token for API calls
fetch('/api/v1/protected', {
headers: {
'Authorization': `Bearer ${idToken}`
}
});
}Backend Code:
from firebase_admin import auth
async def verify_token(token: str):
try:
decoded = auth.verify_id_token(token)
return decoded['uid']
except Exception:
raise HTTPException(status_code=401, detail="Invalid token")API Key Authentication
For external consumers:
# Generate API key (backend admin endpoint)
curl -X POST https://api.altsportsleagues.ai/v1/admin/api-keys \
-H "Authorization: Bearer ADMIN_TOKEN" \
-d '{"name":"Partner XYZ","scopes":["read:leagues"]}'
# Response:
{
"api_key": "ask_live_1234567890abcdef",
"scopes": ["read:leagues"],
"created_at": "2025-11-11T..."
}Usage:
curl https://api.altsportsleagues.ai/v1/leagues \
-H "X-API-Key: ask_live_1234567890abcdef"Input Validation
Backend (Pydantic):
from pydantic import BaseModel, Field, validator
class LeagueCreate(BaseModel):
name: str = Field(..., min_length=3, max_length=100)
sport: str = Field(..., pattern=r'^[a-z_]+$')
tier: int = Field(..., ge=1, le=5)
@validator('name')
def validate_name(cls, v):
if 'script' in v.lower():
raise ValueError('Invalid name')
return vFrontend (Zod):
import { z } from 'zod';
const leagueSchema = z.object({
name: z.string().min(3).max(100),
sport: z.string().regex(/^[a-z_]+$/),
tier: z.number().int().min(1).max(5),
});
// Validate before sending
const validated = leagueSchema.parse(formData);π CORS Configuration
Backend CORS Policy
# apps/backend/server.py
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=[
"https://altsportsleagues.ai",
"https://www.altsportsleagues.ai",
"https://docs.altsportsleagues.ai",
"https://n8n.altsportsleagues.ai",
# Preview deployments
"https://*.vercel.app",
# Local development
"http://localhost:3031",
"http://localhost:3001",
"http://localhost:8090",
],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH"],
allow_headers=["*"],
max_age=600, # 10 minutes preflight cache
)Why Frontend Doesn't Need CORS
The main frontend (altsportsleagues.ai) uses Vercel rewrites, making API calls appear
same-origin. CORS is only needed for:
- Direct API consumers (external partners)
- Docs site API examples
- n8n webhook callbacks
π Database Security
Neo4j Security
Authentication: Username + Password
Encryption: TLS for connections
Access Control: Role-based (read/write)
Backup: Automated snapshotsSupabase Security
Authentication: Service role key (backend only)
Row Level Security (RLS): Enabled
API Keys: Separate for anon vs authenticated
Backups: Automatic (Point-in-time recovery)Firebase Security
Authentication: Google Sign-In only
Firestore Rules: Server-side validation
Storage: Authenticated users only
API Keys: Restricted to domainsChromaDB Security
Access: Local to backend container only
Network: Not exposed publicly
Data: Ephemeral (embeddings can be regenerated)π Security Checklist
Pre-Deployment Security Review
- All API keys stored in Secret Manager (not .env files)
- CORS configured correctly for known domains only
- Firebase Security Rules tested
- Supabase RLS policies enabled
- Neo4j password is strong (16+ characters)
- SSL certificates active for all domains
- Cloudflare proxy enabled (orange cloud)
- Rate limiting configured (if high traffic expected)
- Input validation on all endpoints
- Authentication required for sensitive endpoints
- Audit logging enabled
- Monitoring alerts configured
- Incident response plan documented
Post-Deployment Security Audit
- Penetration testing (recommended annually)
- Dependency vulnerability scanning
- Review Cloud Run logs for suspicious activity
- Monitor Cloudflare security events
- Rotate API keys periodically (every 90 days)
- Review Firebase Auth logs
- Check for exposed secrets (using tools like truffleHog)
- Verify all HTTPS (no mixed content)
π¨ Security Incidents
π«
If you suspect a security incident:
- Immediately rotate affected API keys
- Review logs for unauthorized access
- Disable compromised accounts
- Notify users if data was accessed
- Document the incident
- Implement fixes to prevent recurrence
Emergency Contacts:
- Security Team: (configure in your org)
- Google Cloud Support: cloud.google.com/support (opens in a new tab)
- Vercel Support: vercel.com/support (opens in a new tab)
π Security Best Practices
- β Never commit .env files or API keys to Git
- β Use Secret Manager for production secrets
- β Enable Cloudflare proxy for all public subdomains
- β Rotate API keys every 90 days
- β Monitor logs for suspicious activity
- β Keep dependencies updated (security patches)
- β Use least-privilege access for service accounts