Authentication Flow Architecture

This document illustrates the authentication flows in the Blueberry IDP, covering both Firebase authentication for web users and API token authentication for CI/CD systems.

Authentication Flow Overview

graph TB subgraph "Users & Systems" WEB_USER[Web User
Browser] CI_SYSTEM[CI/CD System
GitLab/GitHub] API_CLIENT[API Client
Scripts/Tools] end subgraph "Authentication Methods" FIREBASE[Firebase Auth
Google OAuth] API_TOKEN[API Token
Bearer Token] end subgraph "Blueberry Platform" subgraph "API Gateway" AUTH_MIDDLEWARE[Auth Middleware
Token Validation] RATE_LIMITER[Rate Limiter] end subgraph "Core Services" API[FastAPI Backend] TOKEN_SVC[Token Service] USER_SVC[User Service] end subgraph "Data Layer" FIRESTORE[(Firestore
User Data)] SECRET_MGR[Secret Manager
API Tokens] REDIS[(Redis
Session Cache)] end end %% Web User Flow WEB_USER -->|"1. Login Request"| FIREBASE FIREBASE -->|"2. Google OAuth"| WEB_USER WEB_USER -->|"3. Firebase ID Token"| AUTH_MIDDLEWARE AUTH_MIDDLEWARE -->|"4. Validate Token"| FIREBASE FIREBASE -->|"5. User Claims"| AUTH_MIDDLEWARE %% API Token Flow CI_SYSTEM -->|"1. API Token"| AUTH_MIDDLEWARE API_CLIENT -->|"1. API Token"| AUTH_MIDDLEWARE AUTH_MIDDLEWARE -->|"2. Validate Token"| TOKEN_SVC TOKEN_SVC -->|"3. Check Token"| SECRET_MGR TOKEN_SVC -->|"4. Get Scopes"| FIRESTORE %% Common Flow AUTH_MIDDLEWARE -->|"5. Rate Check"| RATE_LIMITER AUTH_MIDDLEWARE -->|"6. Authenticated Request"| API API -->|"7. User Context"| USER_SVC USER_SVC -->|"8. Cache User"| REDIS %% Data Persistence TOKEN_SVC -.->|"Token Metadata"| FIRESTORE USER_SVC -.->|"User Profile"| FIRESTORE classDef user fill:#e3f2fd,stroke:#1976d2,stroke-width:2px classDef auth fill:#fff3e0,stroke:#f57c00,stroke-width:2px classDef api fill:#e8f5e9,stroke:#388e3c,stroke-width:2px classDef data fill:#fce4ec,stroke:#c2185b,stroke-width:2px class WEB_USER,CI_SYSTEM,API_CLIENT user class FIREBASE,API_TOKEN,AUTH_MIDDLEWARE,RATE_LIMITER auth class API,TOKEN_SVC,USER_SVC api class FIRESTORE,SECRET_MGR,REDIS data

Firebase Authentication Sequence

sequenceDiagram participant User participant Browser participant Firebase participant Blueberry API participant Firestore Note over User,Firestore: Web User Authentication Flow User->>Browser: Click "Sign In" Browser->>Firebase: initializeApp(config) Browser->>Firebase: signInWithPopup(GoogleProvider) Firebase->>User: Redirect to Google OAuth User->>Firebase: Authorize application Firebase->>Browser: Return ID token + user info Browser->>Blueberry API: API request with Bearer token Blueberry API->>Firebase: verifyIdToken(token) Firebase->>Blueberry API: Decoded token + claims Blueberry API->>Firestore: Get/create user profile Firestore->>Blueberry API: User data Blueberry API->>Browser: Authenticated response Browser->>User: Show authenticated UI

API Token Authentication Sequence

sequenceDiagram participant CI/CD participant Token Service participant Secret Manager participant Firestore participant API participant Redis Note over CI/CD,Redis: API Token Authentication Flow CI/CD->>API: Request with API token header API->>Token Service: validateToken(token) Token Service->>Secret Manager: getSecret(tokenId) Secret Manager->>Token Service: Token secret value Token Service->>Token Service: Compare token hash Token Service->>Firestore: Get token metadata Firestore->>Token Service: Token scopes & user ID alt Token Valid Token Service->>Redis: Cache token validation Token Service->>API: Token valid + scopes + user API->>CI/CD: Process request else Token Invalid Token Service->>API: Token invalid API->>CI/CD: 401 Unauthorized end

Token Creation and Management

graph LR subgraph "Token Creation" USER[User Request] UI[Web UI] TOKEN_CREATE[Create Token API] GENERATE[Generate Token] HASH[Hash Token] STORE[Store in Secret Manager] META[Store Metadata] end subgraph "Token Usage" REQUEST[API Request] VALIDATE[Validate Token] SCOPE_CHECK[Check Scopes] AUTHORIZE[Authorize Request] end subgraph "Token Management" LIST[List Tokens] REVOKE[Revoke Token] ROTATE[Rotate Token] AUDIT[Audit Usage] end USER --> UI UI --> TOKEN_CREATE TOKEN_CREATE --> GENERATE GENERATE --> HASH HASH --> STORE STORE --> META REQUEST --> VALIDATE VALIDATE --> SCOPE_CHECK SCOPE_CHECK --> AUTHORIZE UI --> LIST UI --> REVOKE UI --> ROTATE VALIDATE --> AUDIT classDef creation fill:#e8f5e9,stroke:#388e3c,stroke-width:2px classDef usage fill:#fff3e0,stroke:#f57c00,stroke-width:2px classDef mgmt fill:#fce4ec,stroke:#c2185b,stroke-width:2px class USER,UI,TOKEN_CREATE,GENERATE,HASH,STORE,META creation class REQUEST,VALIDATE,SCOPE_CHECK,AUTHORIZE usage class LIST,REVOKE,ROTATE,AUDIT mgmt

Authentication Security Model

Firebase Authentication

  • OAuth 2.0/OIDC: Industry standard authentication
  • JWT Tokens: Stateless, cryptographically signed
  • Token Expiration: 1 hour default, automatic refresh
  • User Claims: Role and permission information
  • Revocation: Immediate token invalidation capability

API Token Security

  • Cryptographic Hashing: SHA-256 hashed tokens
  • Scope-based Authorization: Fine-grained permissions
  • Secret Manager Storage: Encrypted at rest
  • Token Rotation: Manual and automatic rotation
  • Usage Auditing: Complete audit trail

Security Controls

Feature Firebase Auth API Tokens
Encryption TLS + JWT signature TLS + Secret Manager
Expiration 1 hour (auto-refresh) User-defined (max 1 year)
Revocation Immediate Immediate
Rate Limiting 100 req/min/user 1000 req/min/token
Audit Logging Full audit trail Full audit trail
Scope Control Role-based Explicit scopes

Authentication Middleware

# Simplified authentication middleware flow
async def authenticate_request(request: Request):
    auth_header = request.headers.get("Authorization")

    if not auth_header:
        raise HTTPException(401, "Missing authorization")

    if auth_header.startswith("Bearer blb_"):
        # API Token authentication
        token = auth_header.replace("Bearer ", "")
        user = await validate_api_token(token)
    elif auth_header.startswith("Bearer "):
        # Firebase ID token authentication
        token = auth_header.replace("Bearer ", "")
        user = await validate_firebase_token(token)
    else:
        raise HTTPException(401, "Invalid token format")

    # Check rate limits
    await check_rate_limit(user)

    # Attach user context to request
    request.state.user = user
    return user

Token Scopes and Permissions

Available Scopes

Scope Description Endpoints
ENV_CREATE Create environments POST /environments
ENV_READ Read environment data GET /environments/*
ENV_DELETE Delete environments DELETE /environments/*
CONFIG_READ Read configurations GET /config-sets/*
CONFIG_WRITE Manage configurations POST,PUT,DELETE /config-sets/*
WEBHOOK_ACCESS Process webhooks POST /webhooks/*
COST_READ Access cost data GET /costs/*

Permission Matrix

User Role Default Scopes
Developer ENV_CREATE, ENV_READ, CONFIG_READ
DevOps ENV_CREATE, ENV_READ, ENV_DELETE, CONFIG_READ, WEBHOOK_ACCESS
Admin All scopes
CI/CD ENV_CREATE, ENV_READ, WEBHOOK_ACCESS
Monitoring ENV_READ, COST_READ

Error Handling

Authentication Errors

Status Code Error Description
401 INVALID_TOKEN Token is malformed or expired
401 TOKEN_REVOKED Token has been revoked
403 INSUFFICIENT_SCOPE Token lacks required permissions
403 USER_DISABLED User account is disabled
429 RATE_LIMITED Too many requests

Rate Limiting

# Rate limiting configuration
rate_limits:
  firebase_auth:
    requests_per_minute: 100
    burst_allowance: 10

  api_tokens:
    requests_per_minute: 1000
    burst_allowance: 50

  unauthenticated:
    requests_per_minute: 10
    burst_allowance: 5

Monitoring and Observability

Authentication Metrics

  • Login success/failure rates
  • Token validation latency
  • Rate limiting events
  • Token usage patterns
  • Failed authentication attempts

Security Alerts

  • Multiple failed login attempts
  • Unusual token usage patterns
  • Token validation failures
  • Rate limit violations
  • Disabled user access attempts

Last Updated: January 2024

Document ID: architecture/diagrams/authentication-flow