Architecture
Security

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 only

Network 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:latest

Vercel 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:

ServiceAuth MethodToken Type
FrontendFirebase AuthID Token
Backend APIBearer Token + API KeysJWT
Docs SitePublic (no auth)N/A
n8n UIUsername/PasswordSession
n8n WebhooksAPI Key + SignatureHeader 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 v

Frontend (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 snapshots

Supabase 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 domains

ChromaDB 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:

  1. Immediately rotate affected API keys
  2. Review logs for unauthorized access
  3. Disable compromised accounts
  4. Notify users if data was accessed
  5. Document the incident
  6. Implement fixes to prevent recurrence

Emergency Contacts:


πŸ”’ 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

Platform

Documentation

Community

Support

partnership@altsportsdata.comdev@altsportsleagues.ai

2025 Β© AltSportsLeagues.ai. Powered by AI-driven sports business intelligence.

πŸ€– AI-Enhancedβ€’πŸ“Š Data-Drivenβ€’βš‘ Real-Time