Skip to main content
Gateway Documentation

This documents the API gateway architecture and behavior. These are not callable endpoints — they describe how the gateway processes requests.

API Gateway Authentication

Comprehensive guide to the authentication and authorization middleware stack in the Olympus Cloud API Gateway.

Multi-Layered Security

The API Gateway implements six layers of authentication and authorization. All requests pass through this middleware chain before reaching backend services.

Overview

The API Gateway implements a multi-layered authentication system:

LayerMiddlewarePurpose
1API Key ValidationService-to-service and integration authentication
2JWT ValidationUser session authentication
3RBAC EnforcementRole-based access control
4Shell Access ControlFlutter shell-specific authorization
5Continuous AuthZero Trust session validation
6MicrosegmentationNetwork segment isolation

API Key Authentication

Server-to-server and integration partner authentication using API keys.

Headers

X-API-Key: your-api-key-here

Or via query parameter (fallback):

GET /api/v1/endpoint?api_key=your-api-key-here

Exempt Paths

The following paths do not require API key authentication:

Path PatternDescription
/health, /healthzHealth check endpoints
/metricsPrometheus metrics
/ws/*WebSocket connections
/v1/auth/*Authentication endpoints
/api/v1/public/*Public API endpoints
/v1/restaurant/*Public restaurant data
/v1/webhooks/*Webhook receivers

Response Codes

StatusCodeDescription
401UNAUTHORIZEDAPI key header missing
403FORBIDDENAPI key invalid or revoked

Example Error Response

{
"error": "Unauthorized",
"code": "UNAUTHORIZED",
"message": "API key is required to access this resource.",
"request_id": "req-abc123",
"timestamp": "2026-01-19T14:30:00Z"
}

JWT Authentication

User session authentication via Bearer tokens.

Token Format

Access tokens are RS256-signed JWTs with standard claims:

{
"sub": "user_abc123",
"tenant_id": "tenant_xyz",
"location_id": "loc_123",
"roles": ["manager", "staff"],
"allowed_shells": ["staff", "platform"],
"current_shell": "staff",
"permissions": ["orders:read", "orders:write"],
"session_id": "sess_123",
"iat": 1704067200,
"exp": 1704070800,
"iss": "olympus-auth",
"aud": "olympus-api"
}

Authorization Header

Authorization: Bearer eyJhbGciOiJSUzI1NiIs...

Context Extraction

The middleware extracts claims and sets context values:

Context KeySourceDescription
user_idsub claimAuthenticated user ID
tenant_idtenant_id claimTenant/organization ID
location_idlocation_id claimRestaurant/location ID
rolesroles claimUser role assignments
allowed_shellsallowed_shells claimAuthorized Flutter shells
current_shellX-Shell header or claimActive shell for session
auth_tokenBearer tokenRaw JWT for downstream services

Token Validation

The Gateway validates:

  1. Signature - RS256 verification with public key
  2. Expiration - exp claim must be in future
  3. Issuer - iss must match configured issuer
  4. Audience - aud must match API audience

Role-Based Access Control (RBAC)

Endpoint-level access control based on user roles.

Predefined Roles

RoleDescriptionTypical Permissions
super_adminNebusAI platform administratorFull system access
tenant_adminTenant/organization ownerFull tenant access
managerLocation/restaurant managerLocation management
staffRegular staff memberOperational access
customerEnd customerConsumer features
kioskKiosk device identitySelf-service ordering
api_clientIntegration partnerAPI-only access

Enforcement Patterns

Single Role Requirement

// Route requires exactly one specific role
RequireRole("manager")

Response if unauthorized:

{
"error": "Forbidden",
"code": "FORBIDDEN",
"message": "Insufficient permissions. Required role: manager",
"required_role": "manager",
"request_id": "req-abc123"
}

Any Role Requirement

// Route requires at least one of the specified roles
RequireAnyRole("manager", "tenant_admin", "super_admin")

Response if unauthorized:

{
"error": "Forbidden",
"code": "FORBIDDEN",
"message": "Insufficient permissions. Required one of: manager, tenant_admin, super_admin",
"required_roles": ["manager", "tenant_admin", "super_admin"],
"request_id": "req-abc123"
}

Ownership or Role

// Allow if user owns the resource OR has admin role
RequireOwnershipOrRole("tenant_admin")

This pattern allows:

  • Resource owner (user_id matches resource owner)
  • Admin override (user has specified admin role)

Shell-Based Access Control

Authorization based on Flutter application shell context.

Supported Shells

Shell IDApplicationTarget Users
staffRestaurant Staff ShellServers, hosts, bartenders
customerCustomer ShellRestaurant guests
kioskKiosk ShellSelf-service ordering
kdsKitchen DisplayKitchen staff
platformPlatform PortalBusiness owners
adminPlatform AdminTenant administrators
cockpitCockpit ShellNebusAI operations
drive_thruDrive-Thru ShellDrive-thru operators
signageDigital SignageMenu boards
workforceWorkforce ShellEmployee management
creator_adminCreator StudioAI persona builders
audienceAudience ShellFan engagement

Shell Header

Clients must send the active shell:

X-Shell: staff

Or via the App Experience header:

X-App-Experience: restaurant-staff

Shell Validation

The middleware validates:

  1. Allowed Shells - User's allowed_shells JWT claim
  2. Current Shell - Must be in allowed list
  3. Route Access - Shell must have permission for endpoint

Shell-to-Route Mapping

staff:
- /api/v1/orders/*
- /api/v1/tables/*
- /api/v1/payments/*

customer:
- /api/v1/menu/*
- /api/v1/orders/self/*
- /api/v1/loyalty/*

kiosk:
- /api/v1/menu/*
- /api/v1/orders/kiosk/*
- /api/v1/payments/kiosk/*

platform:
- /api/v1/analytics/*
- /api/v1/reports/*
- /api/v1/settings/*

Zero Trust Continuous Authentication

Ongoing session validation beyond initial authentication.

Configuration

continuous_auth:
enabled: true
base_reverification_interval: 30m
min_reverification_interval: 5m
max_reverification_interval: 4h
max_session_age: 24h
risk_score_threshold_for_mfa: 0.6
terminate_on_high_risk: true
high_risk_termination_threshold: 0.95

Risk Scoring Factors

FactorWeightDescription
IP Change0.3Different IP from session start
Device Change0.4Different device fingerprint
Location Anomaly0.3Impossible travel detected
Time Anomaly0.2Unusual access time
Behavior Anomaly0.3Unusual action patterns

Session Actions

ActionTriggerResponse
continueRisk < 0.3Normal operation
silent_reverifyRisk 0.3-0.5Background token refresh
interactive_reverifyRisk 0.5-0.6Prompt for password
step_up_authRisk 0.6-0.95Require MFA
terminateRisk > 0.95Session revoked

Step-Up Authentication Response

When step-up authentication is required:

{
"error": "Step-up authentication required",
"code": "STEP_UP_REQUIRED",
"message": "Additional verification required to continue.",
"step_up_methods": ["totp", "sms", "email"],
"challenge_id": "challenge-abc123",
"expires_in": 300
}

Microsegmentation

Network segment isolation for Zero Trust architecture.

Security Segments

SegmentTrust LevelDescription
public0.0Unauthenticated requests
customer0.3Authenticated customers
staff0.5Restaurant staff
manager0.7Location managers
admin0.8Tenant administrators
platform0.9Platform administrators
internal1.0Service-to-service

Segment Configuration

segments:
customer:
allowed_endpoints:
- /api/v1/menu/**
- /api/v1/orders/self/**
- /api/v1/loyalty/**
denied_endpoints:
- /api/v1/admin/**
- /api/v1/internal/**
required_roles: [customer]
min_trust_level: 0.3
rate_limit_rps: 100
audit_level: basic

staff:
allowed_endpoints:
- /api/v1/orders/**
- /api/v1/tables/**
- /api/v1/inventory/**
denied_endpoints:
- /api/v1/billing/**
- /api/v1/internal/**
required_roles: [staff, manager]
required_shells: [staff, kds]
min_trust_level: 0.5
rate_limit_rps: 500
audit_level: full

Service-to-Service Authentication

Internal microservice communication authentication.

Service Identity Token

Services authenticate using service identity tokens:

Authorization: Bearer service-token-xyz
X-Service-Name: commerce-service
X-Service-Version: 1.2.3

mTLS (Mutual TLS)

Production environments use mTLS for service mesh:

mtls:
enabled: true
certificate_path: /etc/certs/service.crt
key_path: /etc/certs/service.key
ca_path: /etc/certs/ca.crt
verify_client: true

Service Mesh Headers

The API Gateway propagates context headers to downstream services:

HeaderDescription
X-Request-IDUnique request identifier for tracing
X-Correlation-IDCorrelation ID for distributed tracing
X-Tenant-IDTenant context for multi-tenancy
X-User-IDAuthenticated user ID
X-Location-IDRestaurant/location context
X-RolesComma-separated user roles
X-ShellActive Flutter shell

Authentication Flow


Error Responses

Authentication Errors

StatusCodeDescription
401UNAUTHORIZEDNo authentication provided
401INVALID_TOKENToken validation failed
401TOKEN_EXPIREDToken has expired
401INVALID_CREDENTIALSWrong username/password

Authorization Errors

StatusCodeDescription
403FORBIDDENAuthenticated but not authorized
403INSUFFICIENT_PERMISSIONSMissing required role
403SHELL_ACCESS_DENIEDNot authorized for shell
403SEGMENT_VIOLATIONOutside allowed segment

Session Errors

StatusCodeDescription
401SESSION_EXPIREDSession age exceeded
401SESSION_REVOKEDSession manually terminated
403STEP_UP_REQUIREDAdditional auth needed
403MFA_REQUIREDMFA verification needed

Best Practices

Token Management

Security Best Practice

Never store JWT tokens in localStorage or sessionStorage in web applications. Use secure HTTP-only cookies or in-memory storage with refresh token rotation instead.

  1. Store securely - Use secure storage, never localStorage
  2. Refresh proactively - Refresh 5 minutes before expiry
  3. Handle expiration - Implement token refresh interceptor
  4. Clear on logout - Remove all tokens on user logout

Error Handling

  1. Retry on 401 - Attempt token refresh once
  2. Redirect on persistent 401 - Send to login
  3. Display 403 gracefully - Show access denied UI
  4. Log security errors - Track for audit

Shell Context

  1. Set shell header - Always include X-Shell or X-App-Experience
  2. Handle shell changes - Re-authenticate on shell switch
  3. Validate shell access - Check user's allowed shells in JWT