Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Engine reference — generated from the canonical engineering source. Do not edit this page by hand.

Authentication Flow

Overview

Limon (Vue.js) → Mango (Python/Tornado) issues tokens → Sol (Erlang/OTP) validates via Mango → user_uuid propagates through ZMQ to workers.

Endpoints

Each action is a dedicated, rate-limited handler:

EndpointHandlerPurpose
POST /auth/loginAuthLoginHandlerUsername/password → token + cookies
POST /auth/logoutAuthLogoutHandlerRevoke token, clear cookies
GET /auth/validateAuthValidateHandlerToken validation (Sol calls this)
POST /auth/service-tokenAuthServiceTokenHandlerShared-secret service tokens
POST /auth/change-passwordAuthChangePasswordHandlerPassword change

The legacy multiplexed path lacked rate limiting on change_password (the security gap the removal closes) and was non-functional for login when enable_token_auth was True.

identity-plane notes

Service-token mint: every non-success answer is the ONE uniform 403 {"error": "forbidden"} (wrong secret, missing/unknown user, allowlist denial, malformed field) — no secret-validity oracle. Body-parse and rate-limit answers do not depend on the secret. The shared service secret must be at least 16 bytes or Mango refuses boot (same floor for the ZMQ bridge, audit-chain and audit-archive keys). Strict security envs: MANGO_ENABLE_TOKEN_AUTH, MANGO_ENABLE_RBAC, MANGO_REQUIRE_AUTH, MANGO_COOKIE_SECURE, MANGO_ALLOW_GLOBAL_TRUST, MANGO_DISABLE_RATE_LIMIT and peers accept on/off, true/false, 1/0, yes/no; any other value is a boot refusal. MANGO_REQUIRE_AUTH=true is enforced centrally in prepare, so anonymous access (including GET /tasks) answers 401. Trusted proxies and loopback: the trusted_proxies mango.conf option is wired through init_app (env fallback preserved). Direct loopback has its own rate bucket; a MANGO_CONTROL_PLANE_TOKEN can require X-Control-Plane-Token for the unlimited exemption. Orchestrator lease: the lease is bound to the token’s user_uuid. A stale steal by a different principal requires takeover authority; the optional request epoch is CAS-checked (lease_epoch_stale); transitions are strictly audited. Bootstrap: a wheel install ships mango-bootstrap-admin; on a completely empty users table Mango can also create the first admin from MANGO_BOOTSTRAP_ADMIN_ACCOUNT/MANGO_BOOTSTRAP_ADMIN_PASSWORD.

identity/storage migration notes

Exact-match CORS. MANGO_CORS_ALLOWED_ORIGINS (comma list or config cors_allowed_origins) lists FULL origins; matching is exact string equality, never a suffix/subdomain wildcard (the any-subdomain posture is retired). The allowlist is evaluated independently of domain, so a split-host Limon deployment needs only the allowlist. Credentials are granted only to an exact allowed origin; domain="*" echoes without credentials. Vary: Origin is set whenever a CORS lever is configured. Metrics default ON. enable_metrics defaults ON (MANGO_ENABLE_METRICS); /metrics stays loopback-only unless metrics_expose / MANGO_METRICS_EXPOSE opens it, and non-loopback access can require MANGO_METRICS_READ_TOKEN. /health carries an explicit metrics: enabled|disabled datum so an opt-out is visible. Deployment mode. MANGO_DEPLOYMENT_MODE (prod/production; dev/development/test; MANGO_ENV is an alias, the explicit lever wins) decides the audit-key boot gate. In prod, loopback is NOT an exemption — the documented topology is loopback behind a reverse proxy. Orchestrator lease authority. Acquire/heartbeat/stale-reclaim require the orchestrator:lease permission (or the bare * admin binding — the legacy admin:* alias is INERT since then/ and migration v0020 strips stored aliases). A plain service token cannot squat the empty lease; a same-node/different-user heartbeat is 403. Audit-key posture. An unset MANGO_AUDIT_CHAIN_SECRET on a prod deployment (including loopback) refuses boot unless the operator sets MANGO_ALLOW_EPHEMERAL_AUDIT_SECRET=1 (CRITICAL). The verifier reports key_source=configured|ephemeral; rows stamp key_epoch, and MANGO_AUDIT_CHAIN_PRIOR_SECRETS keeps older generations verifiable. LDAP mail is the identity key. The resolved directory mail must exact-match (case-insensitive) the login identifier; a custom MANGO_LDAP_USER_FILTER that resolves a different mail is refused. A missing/mismatched mail never silently adopts another identity. LDAP offboarding revalidation. LDAP is consulted only at login bind time, so Mango runs a PERIODIC directory revalidation (default hourly; MANGO_LDAP_REVALIDATION_SECONDS, 0 disables). A federated row is bound to its stable directory entry id (entryUUID/objectGUID/DN): a not_found OR a present entry whose id no longer matches is a MISS. The FIRST miss is an audited QUARANTINE (data.ldap_quarantine; no tokens touched); a SECOND consecutive miss revokes EVERY live token (sessions + service tokens), appends the durable revocation-journal row, bumps the credential generation, emits token.revoked, and tombstones the row (data.ldap_tombstone) — so a later login cannot resurrect the identity. A disabled entry (AD userAccountControl, nsAccountLock, GLAuth accountStatus) behaves as gone. Group removals demote at the sync boundary via the same group→role mapping the login path uses. Blast-radius gate: before writing second-miss tombstones the run refuses when the candidate set exceeds MANGO_LDAP_REVALIDATION_MAX_REVOKES (default 10) or, for >=3 candidates, reaches MANGO_LDAP_REVALIDATION_RATIO_FLOOR (default 0.5) of the answered probes — the typo/ACL-empty directory pages (mango_ldap_revalidation_blast_radius_refused_total + CRITICAL audit) and tombstone nothing. MANGO_LDAP_REVALIDATION_DRY_RUN=1 reports would_revoke without writing. The sweep is bounded/resumable (MANGO_LDAP_REVALIDATION_MAX_SECONDS default 30, MANGO_LDAP_REVALIDATION_MAX_USERS_PER_RUN default 250, persisted cursor) and probes ride a dedicated executor so login capacity is not starved. Review/reverse with DELETE /auth/users/<uuid>/ldap-tombstone (admin, strict-audited); tokens are never resurrected — the user re-authenticates. The verdict instruments mango_ldap_revalidation_*; a run that never completes clean pages via MangoLdapRevalidationStale.

Token-type authority model

Two token types leave the auth plane, and their authority differs deliberately:

Session tokens are interactive: they resolve the owner’s FULL LIVE RBAC set at every validate, so a demotion/revocation binds immediately. They are never scoped. Service tokens are machine credentials with a long TTL (7d default, 90d max) that SURVIVE password changes. Pre- a leaked service token resolved the owner’s full live RBAC set too — a leaked admin CI token was full admin authority for its whole TTL. The mint now accepts an explicit scope (a JSON array of permission verbs, persisted to tokens.scope, migration v0017); validate returns min(user_permissions, token_scope) — the intersection of the owner’s live set with the grant:

a service token can NEVER gain permissions the user loses (revocation and demotion still bind immediately); a scoped token can NEVER reach a verb outside its grant, even while the owner is an admin; the mint REFUSES a scope wider than the owner’s live set (a shared-secret mint cannot escalate; an RBAC lookup failure refuses the mint — never a wider grant); NEW mints default to the documented read-only inventory (users:read, orgs:read, teams:read, tasks:read, roles:read) — least privilege. Set a comma-separated verb list in MANGO_SERVICE_TOKEN_DEFAULT_SCOPE for a different default. The legacy full-RBAC mint (scope: null) requires the explicit one-window MANGO_SERVICE_TOKEN_ALLOW_UNSCOPED=1 lever (or MANGO_SERVICE_TOKEN_DEFAULT_SCOPE=legacy); existing legacy tokens keep their recorded until-rotation posture. A malformed configured default REFUSES the mint (typed 503, CRITICAL log) — it never falls back to the legacy full-RBAC posture .

Inventory + rotation: GET /auth/service-tokens lists every live service token WITH its scope (null = legacy full-RBAC — rotate these). Rotation runbook: mint the replacement with the intended scope, move the integration over, then revoke the legacy token (the 20-token cap evicts oldest-first as a backstop). Sol-side consumption (sol_mango_client.erl stamps the returned permission set onto each task) downscopes automatically — Sol consumes the resolved set verbatim, so no Sol change is REQUIRED for Mango-side scoping; the Sol-side handoff note (stamp + gate the scoped set at dispatch) rides the dnotes.

Contract fixtures: mango/test/test_service_token_scope.py (an admin user’s read-scoped service token cannot reach an admin-only route; a session token is unchanged; a scope wider than the user is refused at the mint).

Sol control-plane service tokens (, documentation obligation). The read-only inventory default above (users:read, orgs:read, teams:read, tasks:read, roles:read) is NOT sufficient for the Sol appliance’s own service account. Sol’s control-plane calls need, at minimum:

revocations:read — GET /auth/revocations (the 60 s revocation-ring resync the Sol bridge consumes); orchestrator:lease — POST /auth/orchestrator/lease, /heartbeat, stale reclaim; the admin/ops verbs for the surfaces that appliance drives (for example infra:manage for provider reload/admin actions, metrics:read for a tokenized scrape).

A token minted with only the read-only inventory scope authenticates but resync/lease answer 403, which surfaces as silent degradation (a stale revocation ring and no lease). The intended posture is an explicit scope at mint time (revocations:read,orchestrator:lease,…), never the inventory default. The Sol boot health check that proves both endpoints are reachable is a server-side obligation tracked with this finding (, carried to the Sol-owning lane; this document is the mint contract it must check against).

Login Flow

Limon                          Mango                          Sol
  │                              │                              │
  │  POST /auth/login            │                              │
  │  {username, password}        │                              │
  │ ──────────────────────►      │                              │
  │                              │  AuthSystem.login()          │
  │                              │  LDAP first (GLAuth), then   │
  │                              │  local bcrypt                │
  │                              │  per-IP + per-account        │
  │                              │  limiters (spend on FAILURE  │
  │                              │  only) + hard lockout window │
  │                              │  timing-constant (DUMMY_HASH)│
  │  {token, user, expires_at,   │                              │
  │   csrf_token}                │                              │
  │  ◄──────────────────────     │                              │
  │  Set-Cookie: zerg_session=...│                              │
  │    HttpOnly; Secure*;        │                              │
  │    SameSite=Strict; Path=/   │                              │
  │  Set-Cookie: zerg_csrf=...   │                              │
  │    (NOT HttpOnly; Max-Age=   │                              │
  │     SESSION_TTL)             │                              │

zerg_csrf Max-Age = SESSION_TTL — default 86400s (1 day), clamped 300s–259200s (MANGO_SESSION_TTL).

Login details (AuthLoginHandler.post, mango/mango/handlers/auth.py):

Input gates: JSON body with username/account + password. Non-str or missing → uniform 400. account ≤ 256 chars; password ≤ 72 bytes . Tokens are 256-bit: secrets.token_urlsafe(32) (32 random bytes), stored SHA-256-hashed at rest (AuthSystem._hash_token). SESSION_TTL defaults to 86400s, capped at 259200s (MANGO_SESSION_TTL). Service tokens (POST /auth/service-token) use SERVICE_TOKEN_TTL — default 604800s (7d), clamped 3600s..7776000s (MANGO_SERVICE_TOKEN_TTL_SECONDS) and are capped at 20 live tokens per user (MANGO_MAX_LIVE_SERVICE_TOKENS_PER_USER), oldest evicted first. Brute-force defense: per-IP limiter (Retry-After: 60 on exhaustion) AND per-account limiter; budget is spent only on credential failure — successful logins refund. Exhaustion enters a HARD LOCKOUT window keyed on the RESOLVED identity unknown accounts keep the string key. A locked account gets the uniform 401 + dummy-bcrypt timing, plus a login_failed audit row. LDAP first, local fallback: AuthSystem.login tries GLAuth LDAP; on success the local user is upserted (LDAP-provisioned users normally have no stored hash → dummy-bcrypt path) and a Mango token is issued. Local bcrypt is the fallback for genuinely LOCAL accounts and service accounts. A DIRECTORY-SOURCED row (data.source == "ldap") that carries a local hash (an admin reset on a federated account) is NOT silently accepted: directory-invalid login is denied unless the explicit break-glass ack MANGO_LDAP_ALLOW_LOCAL_HASH_FALLBACK=true is set, and an accepted fallback writes the login_local_fallback audit row. The directory is authoritative by default; the local hash is a recovery credential, not a second production password. LDAP ops run in the executor (never on the IOLoop — ). Transparent rehash: successful login re-hashes at the configured bcrypt cost (MANGO_BCRYPT_COST, default 12) when the stored hash’s cost differs. Host posture: when allowed_hosts (MANGO_ALLOWED_HOSTS) or a concrete domain is configured, an unknown Host is refused (400) before auth/CSRF/limiter or login work — on /health, /metrics and /auth/login alike. This closes the DNS-rebinding arm where an attacker Origin matched the attacker’s own request host. Duplicate/ambiguous zerg_session / zerg_csrf cookies fail closed (no cookie-auth fallback when both the __Host- and legacy names are present). Error shapes: InfrastructureError (DB outage) → 503, no limiter spend; anything else → uniform 401 (enumeration-resistant). Failures audit login_failed. Success response: {token, user: {uuid, username}, expires_at, csrf_token} + Set-Cookie: zerg_session (HttpOnly, Secure gated by cookie_secure —, SameSite=Strict, Max-Age from expires_at) + Set-Cookie: zerg_csrf (double-submit, Max-Age = SESSION_TTL — see the generated block above, NOT HttpOnly so JS can read it for the X-CSRF-Token header). login audited. Rate-limit posture check: validate_rate_limit_posture fails loudly when per-IP buckets are disabled and warns when the validate budget is pinned to/below the documented topology floor . Credential- failure AUDIT rows are bounded separately by MANGO_CREDENTIAL_FAILURE_AUDIT_RATE_LIMIT (default 60/60s per action+IP) so an attacker cannot grow the HMAC audit chain unbounded.

Token Validation in Sol

Sol middleware (sol_auth_middleware.erl) processes every request:

  1. Exempt paths skip authentication, NOT authorization: exemption assumes an anonymous identity envelope and RBAC still runs (, ). The DEFAULT exempt set is single-sourced from the code (default_exempt_paths/0 = sol_session_shares:share_url_prefix/0 + ?DEFAULT_EXEMPT_PATHS in sol_auth_middleware.erl) and rendered here by ci/docs_constant_parity_lint.py --write:

/api/v1/shares/ /health /api/v1/health /api/v1/ready /api/v1/infra/status /api/v1/infra/maintenance /auth/login /auth/validate /auth/logout /api/v1/auth/login /api/v1/auth/validate /api/v1/auth/logout /api/v1/webhook/

Operators may extend the set via auth_exempt_paths (pprof is NOT exempt by default — it requires an admin token). /api/v1/shares/ is the anonymous share capability prefix; /api/v1/webhook/ is unauthenticated BY DESIGN because the per-channel signature validation (sol_http_webhook:validate_webhook/4) IS the auth. /metrics is NOT exempt: a tokenless scrape is allowed only when the loopback TOPOLOGY holds, otherwise it needs metrics:read. /api-docs is exempt only from the MAINTENANCE-MODE check, not from authentication. 2. Rate limit check first (configurable RPM/burst, cached in persistent_term). 3. Maintenance mode check (503 if active). This is a SEPARATE list (is_maintenance_exempt/1), rendered below by the same generator:

/health /api/v1/health /api/v1/ready /metrics /api/v1/infra /openapi.json /api-docs

The two lists differ: /metrics, /api/v1/infra (subtree), /openapi.json and /api-docs are maintenance-exempt but NOT auth-exempt. 4. Token extraction: Authorization: Bearer <token> header (highest priority) x-api-key: <token> header (bearer-equivalent; the native Anthropic SDK form —; Authorization wins when both are set) Sec-WebSocket-Protocol: zerg_auth, <token> subprotocol ( — browser WebSocket clients cannot set Authorization headers; this is how chat/agent WS authenticate) zerg_session cookie (fallback for cookie-based clients) Query parameter ?token= (LOWEST priority AND opt-in: off by default since then — it leaks into proxy/access logs and Referer headers; enable with allow_token_query=true, each use logs a deprecation warning) 5. Token validation via HTTP call to Mango’s /auth/validate endpoint (uses gun HTTP client). 6. Identity injection: sol_identity key set in process dictionary for request lifetime. 7. RBAC check: If Mango returns permissions, Sol verifies the endpoint’s required scope against them (exact-string membership plus the bare * wildcard; also refuses namespace:*/admin:* role grants at the Mango write boundary — see rbac-scopes.md).

Mango /auth/validate details: valid tokens bucket per-account/uuid (reserve/release); garbage tokens bucket a SEPARATE fail-closed invalid limiter keyed by (ip, invalid) — a garbage flood throttles itself, never the per-user buckets. A DB outage → 503 (retryable, never treated as an invalid token).

Mango-outage behavior (fail-closed): when the /auth/validate call cannot complete (Mango down, timeout), validation fails CLOSED — requests return 401/503, never a dev-admin fallback.

Bounded staleness (Mango identity plane)

Mango is deliberately eventually consistent across three caches. The windows are served by Mango’s loopback-only /ready census (mango/mango/systems/staleness.py) and pinned to their owning constants by mango/test/test_staleness_contract.py:

WindowValueSource / meaning
Sol positive token-validation cache5 s?CACHE_TTL_MS (sol_mango_client.erl); a revoked token keeps working on that node for up to this window. Transport/limiter outcomes are never cached.
Mango process-local permission cache10 s_PERMISSION_CACHE_TTL; normal RBAC mutations invalidate it, so this is the bound for a missed invalidation.
Revocation-ring resync60 szmq_mango_resync_ms; Sol resyncs on every bridge (re)connect and then every 60 s.
Revocation convergence after a lost PUB frame65 sresync (60 s) + Sol cache (5 s); the ring replays the missed entries.
Rights convergence10 smax(Sol cache 5 s, Mango permission cache 10 s).
Multi-process Mangofalsemulti_process_supported=false: the revocation epoch/ring, permission cache, limiters, audit HMAC head and ZMQ PUB socket are process-local. workers>1 is refused unless PG-backed and explicitly opted in, and even then the L1 shared-coherence work does not exist — no HA claim.

(AGENTS.md): identity lives in the Cowboy request process. Must be captured via sol_identity:get_uuid BEFORE gen_server:call.

ZMQ Worker Identity

User identity flows through ZMQ to Luna workers:

Sol HTTP handler
  │ sol_identity:get_uuid()  (process dict)
  │
  ├──► ZMQ Gateway spawn
  │     │ user_uuid injected into Opts
  │     │
  │     ├──► task message ──► ZMQ ──► Luna worker
  │     │     msgpack includes user_uuid
  │     │
  │     ◄── result message ◄── ZMQ ◄── Luna worker
  │           msgpack includes user_uuid
  │
  └──► sol_zmq_handler_agent extracts user_uuid
        from result message, passes to store_result/4

(AGENTS.md): ZMQ gateway/agent handler processes have NO sol_identity. Always extract user_uuid from msgpack message and pass explicitly.

For fire-and-forget background tasks: do_bg_start injects user_uuid from sol_identity:get_uuid into spawn opts. Background task results carry user_uuid back in their ZMQ result messages.

Session Expiry and Refresh

PropertyValue
Session TTL86400s (24h) default, capped at 259200s (3 days) — MANGO_SESSION_TTL
Service-token TTL604800s (7d) default, clamped to 3600s..7776000s — MANGO_SERVICE_TOKEN_TTL_SECONDS
Service-token cap20 live service tokens per user, oldest evicted first (journaled) — MANGO_MAX_LIVE_SERVICE_TOKENS_PER_USER
Service-token scopeExplicit permission-verb array in tokens.scope (migration v0017); validate returns min(user RBAC, scope); NEW mints default to the read-only inventory, legacy full-RBAC requires MANGO_SERVICE_TOKEN_ALLOW_UNSCOPED=1; request scope at mint, override via MANGO_SERVICE_TOKEN_DEFAULT_SCOPE
Cookie refreshNot re-sent on each request; cookie is set once on login
Token refreshDisabled (refresh_token grant returns 401, )
Re-authenticationRequired after expiry; Limon validates token on mount (5-min cache)
LogoutPOST /auth/logout deletes token from DB, clears cookie with Max-Age=0
LDAP offboarding sweepHourly directory revalidation (default 3600s; MANGO_LDAP_REVALIDATION_SECONDS, 0 disables): entry-id binding, two-miss quarantine→tombstone, blast-radius refusal/dry-run, bounded/resumable per-run budget

“Auth refresh uses Bearer token — cookie is set once on login, not re-sent.”

Admin RBAC & first-admin bootstrap

A fresh Mango store has zero users. setup_db creates the schema and seed_admin_rbac grants the * binding to admin rows that ALREADY exist — it does not create an account. The first admin is the documented environment step, executed at boot:

MANGO_BOOTSTRAP_ADMIN_ACCOUNT=<account>
MANGO_BOOTSTRAP_ADMIN_PASSWORD=<password>

maybe_bootstrap_first_admin(db) (mango/mango/bootstrap.py) runs after the migrations on a COMPLETELY EMPTY users table, creates the admin through the normal account path, and seeds its RBAC binding. Both variables must be set together; a partial pair logs a warning and creates nothing, and a non-empty store is never touched. Rotate the password and unset MANGO_BOOTSTRAP_ADMIN_PASSWORD after the first login (mango-bootstrap-admin --auto seeds the binding for an existing admin).

On an empty store WITHOUT the pair, Mango logs a startup WARNING and /health reports "users_empty": true for that boot posture (re-evaluated at the next start) — the install cannot silently dead-end at a login with no account. Tests: mango/test/test_readiness_packaging_http.py covers both the with-env and without-env fresh-DB legs.

Admin role with permissions: ["*"] passes all RBAC checks in Sol and Mango. The users.role column is a create-time bootstrap seed (written only by account creation, read only by seed_admin_rbac at boot); all runtime authorization flows through the team/role tables. Anonymous users have admin access only when enable_token_auth=False + host is localhost (production guard raises ValueError otherwise — ).

Key Security Decisions

DecisionRationale
Cookie auth secondary (Bearer header priority, )Allows JS clients to authenticate without cookie dependency; cookie is fallback for SSE/WS
zerg_session is HttpOnly; Secure (config-gated); SameSite=StrictPrevents XSS token theft; cross-SITE CSRF via same-site enforcement. correction: Strict does NOT cover same-site sibling-subdomain attacks — a malicious sibling subdomain of the configured domain is same-site and can read the non-HttpOnly zerg_csrf, forging the double-submit header. The double-submit gate is therefore defense-in-depth against cross-site origins, not a same-site boundary; treat subdomain delegation as a trust decision.
Mango login limiters per-IP + per-account, spend-on-failurePrevents brute-force password guessing without starving valid logins; hard lockout window guarantees recovery
Timing-constant bcrypt comparisonDummy hash pre-computed at module load; prevents timing oracle on missing users
Refresh tokens disabledSimplifies token model; clients re-authenticate on expiry
Mango permissions flow through ZMQWorkers receive user_uuid + permissions; no separate auth context needed in worker boundary
Two-layer ownership enforcementMiddleware (auth-enabled) + handler defense-in-depth; handlers always check ownership even if middleware misconfigured
WS auth via Sec-WebSocket-Protocol: zerg_auth subprotocolBrowser WebSocket clients cannot set Authorization headers; cookie fallback for SSE. One-time WS tickets landed in; the lifecycle re-mints a fresh single-use ticket on the typed 4401 reauthenticate close and re-handshakes (see docs-site/api/chat.md).