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.

Security Guide

Threat Model

Localhost-only (Default)

By default, Sol binds the HTTP API to 127.0.0.1:21434. This mode is suitable for single-user development on a trusted machine. No authentication is required.

HTTP API: 127.0.0.1 only ZMQ gateway: 127.0.0.1 only No API key required No TLS

Network-exposed (Requires Hardening)

Exposing Sol to a network requires additional security measures.

Current hardening: Change http_ip to bind a specific interface (not 0.0.0.0) Use a reverse proxy (nginx, caddy) for TLS termination Restrict access with firewall rules API key authentication — Bearer token via sol_auth gen_server + Cowboy middleware (/health exempt) Per-key rate limiting — token bucket via sol_rate_limiter (60 RPM default, configurable burst) Mango token delegation — Sol delegates Bearer token validation to Mango HTTP service; user identity (uuid + RBAC) propagated to ZMQ workers

Mango service-token scope

Mango issues two token types with deliberately different authority. Session tokens are interactive and resolve the owner’s full LIVE RBAC set on every validation (a demotion/revocation binds immediately); they are never scoped. Service tokens are machine credentials with long TTLs (7d default, 90d max) that survive password changes; they now carry an explicit scope (a JSON permission-verb array in tokens.scope, migration v0017). Validation returns min(user_permissions, token_scope), so a service token can never gain permissions the user loses and can never exceed its grant even while the owner is an admin. The mint refuses a scope wider than the owner’s live set; a NULL scope is the legacy full-RBAC posture and must be rotated (GET /auth/service-tokens lists each token WITH its scope; set MANGO_SERVICE_TOKEN_DEFAULT_SCOPE=default to make the documented read-only inventory the mint default). A hand-corrupted/unparseable scope fails CLOSED (empty effective set), never back to the owner’s full grant. Sol consumes the resolved set verbatim, so Mango-side scoping downscopes the dispatch surface without a Sol change. Details: docs/auth-flow.md (Token-type authority model). ZMQ state caps — worker (100), listener (1000), pid (10000) caps prevent unbounded memory growth (shipped sys.config; the code fallbacks in sol_zmq.hrl are 256/1024/1024)

Current Security Features

SSRF Prevention

Webhook URL validation blocks requests to private and local IP addresses:

127.0.0.0/8 (loopback) 10.0.0.0/8 (private class A) 172.16.0.0/12 (private class B) 192.168.0.0/16 (private class C) 169.254.0.0/16 (link-local)

DNS resolution is performed before checking. IPv6 private ranges are also blocked. DNS resolution failures now correctly reject the request rather than bypassing the check.

In-process transport admission

execution.sandbox.network = false (the default) is enforced by ONE admission funnel (client/core/transport.lua) before any in-process HTTP client opens a socket: web_fetch, the speculative web paths, http_request, sequential web_search, MCP HTTP/streamable-HTTP, the memory vector search/write-through legs, and the provider/configure setup helpers. The funnel also parses the URL authority with client/core/url_authority.lua (userinfo refused, bracketed IPv6/ports preserved, the exact host drives DNS/policy/pins/redirects) and refuses private/LAN/metadata targets.

Non-loopback targets must use https://. Plaintext HTTP is refused unless the operator makes an EXPLICIT acknowledgement (execution.sandbox.allow_plaintext_http = true or LUNA_ALLOW_PLAINTEXT_HTTP=1); loopback stays reachable for local sidecars. A failed TLS probe is a typed error — core.swarm and core.managed_config never downgrade to plaintext on probe failure (the bearer/credential is never attached to a downgraded URL).

Workspace write boundary and undo replay

Every model-reachable write (write_file, edit_file, multi_edit, apply_patch, notebook, create_directory, delete_file, and the undo replay) runs through client/core/write_policy.lua:

the historical sensitive-name denylist stays; ~/.luna is a write-deny root (and any path carrying a .luna component): hooks, policies, config, MCP servers, settings, approvals, trust markers, keys, agents, tools, and extensions can never be written by a model. The only exception is the narrow data directory ~/.luna/data/; the check is lexical for missing leaves AND realpath-based for existing ones (the deepest existing ancestor is resolved), so a not-yet-created ~/.luna/approvals/trust-x.json is refused too; the gate fails closed if core.sandbox cannot load.

undo_edit re-runs the full workspace/credential/sensitive-path gate on replay, refuses a symlink final component (O_NOFOLLOW open + lstat verification), writes through the shared atomic-write primitive (mkostemp + fsync + checked rename), binds each entry to the workspace it was recorded in, and keeps a session-scoped stack (no cross-session undo).

Legitimate product writes still use their owner APIs (session/memory/blob owners) and are unaffected; only the model-facing tool surface is gated.

Host-locality proof

The tokenless metrics gates (/metrics, /api/v1/metrics) and the auth-disabled dev principal accept a request only when it is HOST-LOCAL. The base test is is_loopback_topology/1: loopback TCP peer AND every forwarded hop (X-Forwarded-For, X-Real-IP, RFC 7239 Forwarded) names a loopback address. That inference is negative — an on-host proxy that never sets a forwarded header satisfies it.

locality_secret / SOL_LOCALITY_SECRET adds a POSITIVE proof. When the secret is configured (≥16 bytes), the on-host proxy must inject:

x-zerg-locality: <unix-seconds>:<lowercase-or-uppercase hex HMAC-SHA256>

over the canonical string METHOD "\n" PATH "\n" TIMESTAMP (the path is the router-canonical form). The verifier accepts ±300 s (bounded replay) and compares in constant time. With the secret set, a loopback peer without a valid proof is refused. Without the secret, the positive proof is an EXPLICIT loopback Host authority (localhost/127.0.0.0/8/::1): an on-host proxy forwarding an external request without a forwarded header still carries the public Host and is refused (, HTTP-08 — the pre-fix negative “no forwarded header” inference is gone); a one-time WARNING records the posture. A configured but short secret fails CLOSED (one-time CRITICAL) rather than silently reverting to the weaker posture.

The active posture is also reported as a boot datum (, B3- residual): sol_auth_locality:boot_posture/0 logs one line at boot — EXPLICIT-LOOPBACK (unset), ENFORCED/positive-proof (configured) or FAIL-CLOSED (weak secret) — and returns the same typed map (#{secret, proof_required, posture}). The datum is advisory and never refuses boot; enforcement stays the verifier above.

Deployment note (wild blueprint): inject the header at the TLS-terminating proxy for local scrape/dev traffic only; never forward a client-supplied x-zerg-locality (strip it at the edge, then mint the proof).

Luna’s project-local config files (.luna.json, .luna/settings.json, .luna/settings.local.json) are untrusted input: a cloned repo can carry them. Destination- and credential-selecting keys therefore join the Security families and are ignored fail-closed unless a hash-keyed consent marker exists in the USER’s approval dir (~/.luna/approvals/trust-<sha256>.json; with a TTY the operator is prompted once):

provider_base_url — the wire destination of every provider request (the resolved Authorization/x-api-key credential rides along); api_key, api_keys — credential sources; auxiliary — the whole auxiliary model plane (base_url/api_key); fallback_providers — failover destinations; otel_endpoint — the Luna-local span sink (fire-and-forget HTTP POST from the worker; no cross-service tracing — Sol/Mango export no spans).

Without the marker the keys are stripped with a loud CRITICAL line naming every family (client/core/repo_config_security.lua is the single list). Defense in depth: client/core/provider.lua:from_model/3 independently refuses a provider_base_url whose effective value still equals the project-carried value while the consent verdict is false (a strip bypass), falls back to the built-in destination, and counts + logs the refusal — value equality keeps a same-key USER-supplied URL legitimate.

Project-sourced extensions (.luna/extensions/*/ in the working directory) are repo-shipped code: on the strength of the user-wide extensions_enabled=true alone they used to auto-load — git clone attacker && cd repo && luna executed them. They now require the SAME hash-keyed per-project consent as .luna/mcp.json servers: an approval record keyed on the canonical parsed manifest hash in the USER-owned approval dir (~/.luna/approvals/extension-<sha256>.json; with a TTY the operator is prompted once per extension, y/N, fail-closed on anything but an explicit yes). ANY manifest change (version bump, permission or hook edit) changes the hash and re-asks. Without a record and without a TTY the project extension is REFUSED (surfaced in the loader’s failed list). User-level ~/.luna/extensions never consults this gate; the extension security scanner and the allow-listed sandbox env remain as defense-in-depth for ALL extensions (client/core/extension_consent.lua owns the gate; both load entry points — load_all and the rescan hot-reload path — enforce it).

<workspace>/.luna/tools/*.lua is repo-shipped CODE: on the strength of the user-wide tools dir alone it used to auto-load — git clone attacker && cd repo && luna executed it. Every NON-home scan directory now loads only with an explicit --allow-repo-tools (this run) or a user-owned, content-keyed trust marker (~/.luna/approvals/trust-<sha256>.json, hashed over the sorted tool-file contents; any edit invalidates the approval). Consent is keyed to the actual directory being scanned: capability_bootstrap passes the effective workspace into ToolDiscovery.scan(workspace), so a first-setup workspace different from PWD cannot bypass the gate (a boot-then-task worker reuses its boot instance and never rescans a wire workspace). The user ~/.luna/tools dir remains unconditional.

Load-time code is PURE DATA: tool files are loaded text-only (load(..., "t")) in an environment with NO Tools, os, io, or require binding — a top-level effect raises and is contained. Only the returned handler is given a restricted Tools dispatcher (installed after validation): nested dispatch is allowed only when the inner tool’s declared class is at or below the custom tool’s own (none < read < write < execute), and execute-class nesting additionally requires an explicit sandbox config — a handler can never silently spawn a bare shell.

Stdio grant parity

Both task transports apply the same permission rule (client/core/wire_permissions.lua): an absent/invalid permissions field is explicit-empty (deny-default), and a wire permission_mode paired with a grant that has no execute grade clamps to read-only. The stdio worker previously read neither field.

CORS preflight contract

A genuine CORS preflight is OPTIONS with BOTH an Origin and an Access-Control-Request-Method request header and no body. The auth middleware answers it directly with 204 + the configured CORS headers (the sol_http_infra:reply_headers/2 chokepoint, limon_origin-gated) in every auth posture — the handler is never reached and no identity is ever attached, so a browser preflight cannot trip a verb-agnostic mutation.

Everything else is not a preflight: a bare OPTIONS probe takes the normal auth path (401/403 with auth on) and is never handed an anonymous identity; the generic dispatch clause answers any OPTIONS it still sees with a typed 405 instead of dispatching. The one mutation the sweep found verb-agnostic — telemetry clear — is now POST-only at the handler (GET/OPTIONS → typed 405), pinned by ci/get_mutation_lint.py (clear in the corpus).

Canonical request path

Sol authorizes the SAME path the Cowboy router dispatches. The middleware computes one canonical path (sol_auth_middleware:canonical_path/1) with the router’s algorithm — split on /, percent-decode each segment, RFC 2396 dot-segment removal — and every decision (API version, exemptions, metrics gate, anonymous grants, RBAC, ownership, rate-limit keying, WS handshake matching, maintenance, SLO class) consumes it. Paths the router would represent ambiguously are refused 400 invalid_request_path: encoded separators (%2F/%5C), empty internal segments (//), invalid percent escapes, control bytes, and non-absolute paths. A raw /health/../api/v1/skills is therefore authorized as /api/v1/skills, and %XX can never resolve a different route than the one that was checked.

HEAD and OPTIONS

HEAD carries GET’s authority and nothing else: permission and resource scope resolution map it to GET, so it can never read a resource the equivalent GET would deny. A HEAD on a path whose only rules are for other methods answers 405. A bare OPTIONS (not a genuine preflight) never reaches a known handler: the RBAC chokepoint answers 405 with the route’s Allow set. Only the genuine preflight branch answers 204.

Release-binary obfuscation (not encryption)

The secure Luna and CLI builds (client/build/build.sh, zerg-cli/build/build.sh) XOR the embedded Lua blobs, add a CRC32 integrity check, strip, and (for Luna) UPX-pack the result. This is Obfuscation, not encryption: the key is deterministic from the shipped sources. client/build/encrypt_blobs.py:derive_key_from_sources/3 computes SHA-256 over the sorted module list, updating with each .lua file’s bytes plus a NUL separator, and truncates the digest to 32 bytes. The build splits that key into two arrays stored in different parts of the generated C file; the runtime reconstructs it as half_a XOR half_b. Anyone holding the same sources can derive the same key, so the binary gains no confidentiality and protects no secret — it only raises the effort of casual inspection. Use --plain --no-upx when debugging.

Worker Path Validation

The worker_path configuration is validated against a configurable prefix. This prevents arbitrary binary execution:

%% sys.config — only binaries under /opt/sol/bin/ are allowed
{worker_path, "/opt/sol/bin/luna"}

Workers spawned via the HTTP API are also validated.

Error Sanitization

HTTP error responses never contain internal Erlang terms. All errors are mapped to generic strings:

{"ok": false, "error": {"code": "model_not_found", "message": "model not found"}}

The /api/v1/* family answers the Zerg {ok, error:{code, message}} envelope; the catalog of error codes is stable and documented. Internal details like process IDs, supervisor references, and stack traces are logged server-side but not exposed to clients.

Method Enforcement

Mutation endpoints require POST method. Other methods receive 405 Method Not Allowed:

/api/v1/start, /api/v1/stop, /api/v1/stop-all /api/v1/discover /api/v1/agents/spawn, /api/v1/agents/:id/kill /api/v1/cluster/join, /api/v1/cluster/leave /api/v1/lua/eval, /api/v1/lua/workers/spawn /api/v1/zmq/dispatch /api/v1/circuits/reset /api/v1/schedule/spawn, /api/v1/schedule/:id/run /api/v1/channels/spawn, /api/v1/channels/:id/message /api/v1/orchestrate /api/v1/telemetry/clear

Root User Safety

Sol uses erlexec to manage OS processes (llama.cpp, workers). When running as root:

Effective user is downgraded to nobody (configurable) Command arguments are passed as lists, not shell strings — preventing shell injection Process monitoring uses Erlang monitors, not polling

Plugin Sandbox

Lua plugins run in a sandboxed Luerl VM with restricted standard libraries:

LibraryStatusReason
osRemovedPrevent OS command execution
ioRemovedPrevent file system access
debugRemovedPrevent VM inspection
packageRemovedPrevent module loading
stringAvailableString operations
tableAvailableTable operations
mathAvailableMath operations
coroutineAvailableCoroutine support

Additional protections:

Eval timeout: 3000 ms per lifecycle call by default (plugin_lifecycle_timeout_ms, — the old 15 s constant kept a hostile plugin inside the caller for a quarter minute) — prevents runaway computation; lifecycle Lua runs off the manager’s critical path Periodic GC: Luerl VM garbage collected between calls Network access: Only via sol.http bridge (mediated by Sol) No filesystem access: No way to read or write files from Lua

ETS Heir Protection

Critical ETS tables survive owner process crashes via {heir, Pid}:

TableOwnerData
sol_modelssol_registry_ownerModel registry
sol_global_catalogsol_catalog_ownerCluster catalog
sol_metricssol_metrics_ownerMetrics counters
sol_task_resultssol_task_store_ownerTask results
sol_task_tokenssol_task_store_ownerTask tokens
sol_scheduled_jobssol_scheduler_store_ownerScheduled jobs
sol_circuitssol_circuit_ownerCircuit breaker state
sol_provider_poolsol_provider_pool_ownerProvider keys
sol_channelssol_channel_ownerChannel instances

Graceful Shutdown

prep_stop drains in-flight requests before the VM shuts down. This prevents data loss during rolling upgrades.

Known Security Issues

The historical server findings below are fixed:

IDIssueFix
SRV-8Plugin HTTP bridge sends HTTPS over plain HTTPFIXED (S52) — TLS verification enabled for plugin HTTP requests
SRV-9DNS resolution failure bypasses SSRF checkFIXED (S36) — resolution failures now reject the request

This page is not a claim of zero open security work. The live open/accepted register — including wild-owned legs (crash-dump hygiene, fleet key rotation/CD) and the accepted provider-key-at-rest posture — is docs/known-security-gaps.md; the hardening program is docs/production-flip-checklist.md. See also §Audit history and docs/archive/AGENTS-decisions-archive.md.

Limon bearer storage — accepted residual

Posture (RECORD — accepted, no auth rework). The Limon SPA holds the session bearer in sessionStorage (TOKEN_STORAGE_KEY in limon/src/stores/auth.ts; guarded by the shared storage helper with an in-memory fallback for storage-disabled browsers). Any script executing in the SPA origin can read it: this is XSS-exfiltratable by architecture. The posture reduces — it does not eliminate — that class; the mitigations below are the layered defense, and the alternatives are recorded for the roadmap rather than silently assumed safe.

Layered mitigations (verified real).

CSP script-src 'self' — the enforced production policy is single-sourced in limon/src/csp.ts (CSP_HEADER_VALUE) and served as an HTTP response header by the deployment layer (the meta tag in index.html cannot enforce frame-ancestors, hence the header contract). No inline script, no unsafe-eval, no third-party script origins; object-src/frame-src/frame-ancestors are 'none'. An injected <script>/event-handler payload is blocked at the parser. Single DOMPurify chokepoint — every rendered-HTML sink routes through sanitizeMarkdownHtml in limon/src/composables/useMarkdown.ts (markdown-it html:false as the first belt, DOMPurify with an explicit forbid-tag profile as the second). The two v-html sinks are ChatMessage.vue (rendered LLM content) and SkillDetailModal.vue (marketplace bodies); ci/limon_sink_lint.py freezes them to those two sanitized bindings (shrink-only; a new v-html/innerHTML/ dangerouslySetInnerHTML sink is RED). No token in URLs or logs — the bearer travels only in the Authorization header; the chat WS authenticates via the REST-minted one-time ticket subprotocol (never a query-string token), and HTTP request logging never records the header value.

Roadmap options (not implemented — each is a real trade, not a free win).

  1. Cookie realm (HttpOnly/Secure/SameSite) for same-host deployments. Removes JS readability, so XSS can no longer exfiltrate the credential — but it does not stop an XSS payload from acting in-session, and it converts every state-changing request into a CSRF surface (the double-submit zerg_csrf contract already covers Mango’s cookie-authenticated legs, not the whole API). It also assumes the API is same-origin: the supported air-gap/private-network topologies point the SPA at a different host, where SameSite cookies need SameSite=None; Secure and credentialed CORS, and the WS ticket flow would need rework. Requires a cookie realm in Mango plus a migration window.
  2. Short-TTL bearer + silent refresh. Keep the header-only transport (no CORS/CSRF change) but shrink the exfiltration window to the token TTL and the blast radius of a leaked value; a refresh credential held outside JS (or a re-auth prompt) completes the loop. Costs: a refresh endpoint + rotation/revocation semantics, more 401/retry churn, clock skew in air-gapped deployments, and the token is still readable during its TTL.

Either option is a deliberate architecture change with its own review; the current posture is accepted knowingly, with the sink lint and CSP as the enforcement floor.

Implemented Security Features

API key authentication — Bearer token via Authorization: Bearer <key> header; sol_auth validates against local keys or Mango service Per-key rate limiting — sol_rate_limiter enforces 60 RPM per key (configurable) ZMQ state caps — worker_cap=100, listener_cap=1000, pid_cap=10000 as shipped in sys.config (code fallbacks 256/1024/1024 in server/include/sol_zmq.hrl; configurable via zmq_worker_cap/zmq_listener_cap/zmq_pid_cap) Error sanitization — internal Erlang terms never leaked to HTTP clients SSRF prevention — webhook URL validation blocks private IPs; DNS rebinding protection Landlock sandbox — Linux 5.13+ kernel-enforced filesystem ACL; a WRITE-DENY layer only (read enforcement stays with bwrap’s ro-binds — Landlock’s allowlist model cannot deny arbitrary read paths). Landlock↔bwrap composition is a measured FINAL DECLINE: a live Landlock write-domain refuses bwrap’s user-namespace setup (the /proc/self/{setgroups,uid_map,gid_map} writes EPERM), and after a user namespace is pre-created bwrap’s mount stage still fails (Failed to make / slave: Operation not permitted) — a live domain refuses mount(2) outright with EPERM at both granted and ungranted targets. The only ordering that works is namespaces + mounts first, Landlock after (probe: post-mount granted write OK, outside write EACCES), which requires an applier running inside the bwrap namespace that bwrap does not expose and Luna does not ship. So when bwrap wraps the spawn the fork layer STANDS DOWN with a loud one-time warning, and Landlock remains the write-deny layer for bwrap-less spawns (bwrap=off or bwrap unavailable) — never both layers, never none silently. Decision record: client/core/sandbox.lua (LANDLOCK_BWRAP_COMPOSITION); pinned by the real-kernel suite client/tests/test_sandbox_composition_truth.lua Bwrap/seatbelt sandbox — user-space sandbox wrappers (bwrap on Linux, seatbelt on macOS — one wrapper per spawn, NOT stacked with the Landlock fork layer; see above): workspace isolation; custom /etc/hosts injection; --die-with-parent; --unshare-net Bwrap namespaces + env allowlist — --unshare-pid --unshare-ipc --unshare-uts (same-uid process enumeration/kill isolation; SysV IPC isolation; hostname spoofing isolation) + --clearenv with an explicit env allowlist (PATH HOME LANG LC_ALL TMPDIR USER LOGNAME SHELL + per-tool env_passthrough extras) so SOL_API_KEY / provider keys / *KEY*/*TOKEN*/*SECRET* vars never cross the namespace boundary; the _spawn_popen fallback and io.popen sites (configure wizard) scrub the same key-shaped vars via env -u; MCP/LSP stdio servers run with a Landlock-only config and a child env rebuilt from the allowlist Sandbox layer matrix — authoritative layer ownership (keep in sync with the client/core/sandbox.lua header): Bwrap: namespaces (pid/ipc/uts/net) + env allowlist + read-deny (tmpfs//dev/null shadows over credential paths) + ro-bind root + workspace rw binds + network isolation Landlock: fork-layer write-deny only (WRITE_FILE|REMOVE_FILE|MAKE_DIR beneath workspace root + rw grants); NEVER EXECUTES a ruleset containing EXECUTE Landlock↔bwrap composition: the two layers cannot wrap one exec — a live Landlock domain EPERMs bwrap’s userns setup and mount stage and refuses mount(2) outright; the working order (namespaces/mounts first, Landlock after) needs an in-namespace applier bwrap does not expose. Wrapped spawns therefore run under bwrap only with Landlock stood down (loud one-time warn); sandbox_layers_effective reports the APPLIED composition (bwrap), sandbox_layers_available reports the capability probe (bwrap+landlock-abi<N>) — the telemetry never claims bwrap+landlock. Evidence pinned by client/tests/test_sandbox_composition_truth.lua Seatbelt: macOS SBPL profile (write-deny + ssh/gnupg read-deny); no namespace/env controls Bwrap=off residual (documented): no read-deny and no network isolation — the Landlock fork layer still applies (write-deny is not disabled); execution.sandbox.bwrap = off/auto/required semantics verified real Read_only_dirs overlap rule: a read_only_dirs entry nested UNDER a granted write root (workspace root / allowed_write_paths / rw_dirs) is unenforceable by the Landlock fork layer — path-beneath rules are ADDITIVE and no rule can carve an exception out of a parent grant. Such a config is REFUSED in the landlock-only postures (every mode, including auto) with the typed landlock_ro_overlap:<ro>:<root> error — the spawn exits 127 rather than silently running with the “read-only” path writable. A read_only_dirs entry that is an ancestor of (or equal to) a write root is fine: the write grant is dropped and the subtree stays read-only. Use bwrap’s ro-binds for subtractive read-only semantics. Zero-active-layer posture: when enabled=true but NEITHER bwrap NOR Landlock is active (posture none), the spawn gate (sandbox.zero_layer_spawn_gate, called from both ffi.init gates) refuses with the typed sandbox_unavailable error when execution.sandbox.require_effective_layer=true, or when the Sol session is NON-LOOPBACK and execution.sandbox.effective_layer_ack is unset; loopback/TTY sessions keep the warn-only posture (sandbox.zero_layer_spawns + one-time loud warning). Refusals are counted (sandbox.zero_layer_refusals, require_effective_layer_refusals, non_loopback_unacked_refusals) and the APPLIED composition travels to Sol as sandbox_layers_effective (absolute gauge; SolLunaSandboxInert pages on the inert posture) Filesystem sandbox — worker path validation; binary_to_existing_atom guards; path traversal prevention Role-based access control — Mango RBAC roles propagated via ZMQ user_uuid Header injection prevention — HTTP header values validated to reject CR/LF characters Path traversal prevention — file paths normalized and checked for .. traversal sequences Timing-safe token comparison — API key validation uses constant-time comparison Session fixation prevention — session identifiers regenerated after authentication state changes

Prompt Injection Detection (L43)

Client-side prompt injection detection is applied to all user input before LLM processing:

35 patterns across 11 categories — client/core/injection_detector.lua PATTERNS.

Patterns by category: system_override — “ignore previous instructions”-style prompt overrides memory_injection, memory_override — attempts to poison or replace stored memory context_manipulation — attempts to override system-prompt instructions role_override, role_manipulation — attempts to reassign the assistant’s role (“you are now…”, “disregard instructions”) instruction_smuggle — hidden instructions in comments/markup (<!--[SYSTEM]-->) encoding_evasion — URL/hex/unicode-encoded payloads exfiltration — attempts to send data to external endpoints capability_escalation — attempts to disable security or bypass the sandbox tool_abuse — piping fetched content into a shell 3 severity levels: info — logged but allowed (low-confidence matches) warning — logged and surfaced to user (moderate-confidence matches) block — request rejected before reaching LLM (high-confidence matches) Implemented in client/core/injection_detector.lua (PATTERNS; the live count is the generated block above, gated by ci/docs_constant_parity_lint.py)

Air-Gapped Deployment (S79)

Sol supports fully air-gapped deployment with no outbound network connections:

WILDZERG blueprint — the canonical on-prem deploy (runit + podman, air-gap capable) is provisioned via wild/AGENTS.md + wild/scripts/provision/; the legacy deployment/infra/scripts/setup.sh was archived with the old on-host model Docker Compose profiles (legacy, archived) — --profile mango for optional services; core stack runs without internet access Local routing — all inter-service communication stays within the cluster network; no external DNS or API calls required Production configuration — environment variables for all endpoints, no hardcoded external URLs

Egress inventory

The egress points below are the complete inventory: worker/CLI gates, plus Sol deployment-configured endpoints. “Complete” means no other shipped background caller exists; it does not mean the configured endpoints are inert.

Egress pointGateDefault
LLM provider endpoints (by design)provider config (per-provider key + base URL)on
osv_check.lua + mcp_osv.lua (MCP package-vuln lookup to api.osv.dev, via the single osv_gate.lua)LUNA_ALLOW_OSV_CHECKoff
auto_install.lua tool downloads (curl of pinned release assets), package-manager installs, and install_via_pip (via the single egress_gate.lua)LUNA_ALLOW_TOOL_INSTALLoff. sudo package installs additionally require explicit caller consent
zerg update check + SHA256 fetchZERG_ALLOW_EGRESS_UPDATEon
Sol license/seat refresh (seats_url) — background HTTP(S) fetch every seats_refresh_ms (default 30000) with peer verificationseats_enabled + seats_url (empty URL = no timer)off unless configured
Sol OAuth token refresh for declarative providers (token_url; zerg oauth login)provider oauth sub-mapoff unless configured
Local model server (localhost:11434, ollama)loopback only — not egress—

Set the gates to 0/false for a strict air-gap posture; the Sol/Luna frontend trees (limon/toronja/starfruit, Luna core) contain NO third-party CDN/analytics references — asserted by ci/egress_assert_lint.py (born required, ).

OAuth/PKCE for MCP Providers

OAuth PKCE (Proof Key for Code Exchange) authentication is supported for MCP servers that require OAuth2 authorization. The flow uses FFI raw sockets for the callback server, crypto-random state generation, and the standard authorization code + token exchange flow.

(AUTH-13) endpoint hygiene: authorize_url and token_url must be https, public (not private/loopback), and carry no userinfo; token requests refuse redirects. The callback listener stays loopback (RFC 8252), and the redirect URI is single-sourced (get_redirect_uri(port) feeds the authorize URL and the token request). Token persistence is checked: a failed save_token fails the flow typed (failed to persist OAuth token) instead of returning an unpersisted token.

Implemented in client/core/mcp_oauth.lua.

OAuth PKCE for declarative model providers

zerg oauth login <provider> completes a PKCE browser flow for a provider whose JSON declares an oauth sub-map: Sol returns the authorize URL + CSRF state (POST /api/v1/oauth/login, admin), the CLI binds the loopback redirect (oauth_redirect_uri, default 127.0.0.1:21337/callback — only loopback redirect URIs are bindable), the operator consents, and Sol exchanges the code at the provider token_url (POST /api/v1/oauth/login/complete, admin; PKCE S256, verifier never leaves Sol). Access + refresh tokens persist under ~/.sol/oauth_tokens.json (0600-from-birth); resolve_api_key consumes them, a provider 401 signals a refresh through the pool’s auth-class report path, and a background tick renews tokens inside a 5-minute window. zerg oauth status lists connected providers; zerg oauth logout <provider> deletes one (strict-audited).

Air-gap: the flow requires the operator’s browser + the IdP token_url to be reachable — on a fully air-gapped fleet it cannot run. Keyring/env API keys (zerg keyring-set, api_key_env) remain the canonical air-gap credential path; nothing in the OAuth machinery is on the boot or request critical path when unused.

DNS Rebinding Protection

DNS rebinding SSRF attacks are blocked via FFI getaddrinfo resolution. Before making HTTP requests to user-supplied URLs, the hostname is resolved and all resulting IP addresses are checked against private ranges. This prevents attackers from bypassing SSRF protections using DNS rebinding techniques.

Implemented in client/ffi/dns.lua (is_safe_hostname) and enforced in client/core/ssrf.lua (shared is_private_host).

Write Deny List

The filesystem tool enforces a deny list of sensitive paths that can never be written or overwritten:

.ssh/, .gnupg/, .aws/, .env, .bashrc, .zshrc/, .netrc, .pgpass, .profile, .gitconfig, authorized_keys

Adds the ~/.luna write-deny root (data-dir exception only) — the auto-loaded/config/credential surface (hooks.lua, policies/*, config.json, mcp.json, settings*.json, agents/*, approvals/*, keys/*, tools, extensions) is never model-writable, including missing leaves. Implemented in client/core/write_policy.lua; the undo replay uses the same gate.

Session share capability model

Session shares (POST /api/v1/sessions, GET /api/v1/shares/:share_id) use a capability-token model: the opaque share_id IS the capability and the secret. The public view endpoint is unauthenticated BY DESIGN — this is the recorded LOW adjudication, accepted because the id is a 256-bit random token (unguessable) and no separate ACL exists; possessing the id is the authorization. There is no expires_at emission — expiry is internal state. Compensating controls:

TTL clamp — ttl_days is clamped server-side to min(ttl_days, 365); larger requests are capped loudly (server warning share ttl_days N clamped to 365), never silent forever-shares . Per-user create quota — share_quota_per_user (default 100 live shares); at quota the create answers 429 share_quota_exceeded with retry-after: 3600, never a 500. Per-IP read rate limit + read logging — the public endpoint is rate limited per IP (share_rate_limit_per_min) and every read is logged at notice level with share id + peer IP (; sol_http_shares.erl).

Mango credential class

Mango computes the credential class BEFORE its CSRF decision. Only a syntactically valid explicit Authorization: Bearer <non-empty> credential suppresses the zerg_csrf double-submit check; Basic, an empty Bearer, a bare token, or any other scheme does not. A mutating request carrying a present-but-not-Bearer Authorization header is refused 401 and never silently falls back to the ambient zerg_session cookie. Logout applies the same predicate, revokes every credential actually presented (Bearer + cookie, deduped), and clears cookies only after every revoke succeeds. Login requires Content-Type: application/json (forcing a CORS preflight), closing the text/plain login-CSRF leg.

CLI credential origin binding

zerg login records the token origin (token_origin) in the config/profile. A stored token is sent only to that origin: an explicit --api-url override never receives an origin-bound token for a different host, and a legacy token with no recorded origin is never sent to an override at all. Explicit credentials (--bearer, --token, ZERG_TOKEN) remain operator-supplied overrides. --profile NAME login/logout writes and clears only profiles[NAME], including the per-profile keyring entry.

The zerg_session cookie is not a bearer. It is ambient — a browser attaches it to every cross-site request — so the credential CLASS drives the auth decision (sol_auth_middleware:extract_credential/1, the single zerg_session reader in the route path; the logout leg and the WS handshake are the other two sanctioned readers, pinned by ci/cookie_csrf_lint.py):

Safe methods (GET/HEAD/OPTIONS) — the cookie is accepted as a bearer-equivalent credential. Mutating methods (POST/PUT/PATCH/DELETE/…) — a cookie-authenticated request must present the zerg_csrf double-submit pair (the zerg_csrf header equal to the zerg_csrf cookie — the Mango pattern, single-sourced in sol_auth_middleware:csrf_pair_valid/1; the logout leg delegates there). Absent/mismatched → typed 403 csrf_required (one uniform body — no oracle), counted (cookie_csrf_refused_total). A cross-site form post can carry the ambient cookie but can never set the header, so every mutating route is covered at this single chokepoint — there is no cookie-consuming mutating route outside the gate. Authorization: Bearer and ?token= (when allow_token_query=true) are explicit credentials — the CSRF class does not apply. The Authorization header’s mere presence proves not-CSRF.

Nothing sets a live zerg_session cookie in this release (logout clears it); the gate is the load-bearing contract for the first surface that does.

WS-handshake Origin binding

The “GET is safe” CSRF rule does NOT hold for a websocket upgrade: a cross-site page can open wss://host/api/v1/chat/<id>/ws and the browser attaches the ambient zerg_session cookie to the handshake (cross-site WebSocket hijack — on success the hostile page can DRIVE the victim’s agent session). At the same middleware chokepoint, every WS-handshake route (sol_auth_middleware:is_ws_handshake_path/1, derived from the route table) authenticated by the cookie class must present a trusted Origin header BEFORE the upgrade — mismatch/missing answers the typed 403 origin_required, counted (ws_origin_refused_total), pinned by ci/ws_origin_lint.py.

The trusted-Origin anchor (sol_http_infra:ws_origin_allowed/1) mirrors the CORS posture:

the configured limon_origin (exact match; * = operator wildcard); Same-host — the Origin authority equals the request Host authority (a first-party page; a hostile page’s Origin names its own host and never matches); the loopback dev posture — both Origin host and request Host host classify loopback (localhost:5173 → 127.0.0.1:8080 dev consoles); auth_enabled=false loopback dev never reaches the gate (the dev identity branch precedes the credential arms).

Exempt classes: ticket-authenticated upgrades (the single-use 60s zerg_ticket subprotocol — proof no third party holds) and every explicit credential (Bearer/?token= — an attacker cannot set those cross-origin). Non-browser clients can forge Origin, but they are not the ambient- credential class; a cookie-carrying non-browser client should use the ticket.

Remaining (Not Yet Implemented)

(No remaining unimplemented security features. The trust-plane posture program’s residual legs are tracked in docs/known-security-gaps.md + docs/production-flip-checklist.md, not here.)

Trust-plane posture program

Erlang distribution TLS contract

Distribution TLS is a VM-flag activation, deliberately NOT an app-env key (the lesson: comment-only keys imply wiring that does not exist). The full contract — -proto_dist inet_tls + -ssl_dist_optfile in the wild-rendered vm.args, per-node certs with SAN = node FQDN, verify_peer + fail_if_no_peer_cert on both legs, the cluster cookie STAYING the admission credential, the cluster-probe/remsh same-window update, and the epmd-plaintext residual lives in server/config/ssl_dist.conf.example and docs/production-flip-checklist.md. Activation is a wild maintenance-window drill: probe 3/3 over TLS, a plain peer refused, rollback tested once.

Secret lifecycle decisions

Provider keys: declarative keys are never persisted; operator-added pool keys ARE persisted encrypted. Declarative configs carry api_key_env names and the pool holds those values in gen_server state only. Since provider_key_store=true (the shipped default) persists OPERATOR-added keys (sol_provider_pool:add_key/3) AES-256-GCM at <data_dir>/provider_keys.bin (0600, atomic) so a pool crash does not lose them; a corrupt store fails OPEN (the pool boots) and is counted. The real residual for declarative keys remains crash dumps (docs/known-security-gaps.md §Secret lifecycle — the ERL_CRASH_DUMP ask is wild-owned). Audit-chain key rotation shipped in (key-epoch ring + typed cross-rotation verdicts) — the “rotation = evidence loss” gap is closed on the Mango leg. Revocation-journal retention — Closed (,; S-13; ). RevocationRing.compact prunes a bounded prefix (MANGO_REVOCATION_JOURNAL_KEEP, default RING_SIZE) in bounded chunks, recording the in-tx revocation_journal_pruned_floor and surviving-min frontier in audit_chain_meta. Boot refuses a tail/prefix/wipe regression; legal burnt epochs stay gap-tolerant. MAX(epoch) monotonicity is the invariant either way. The same row is recorded in known-security-gaps.md.

Luna Policy System

Luna enforces a 3-layer security model on all command execution, including both sequential and concurrent (parallel) tool paths.

Execute-grade split

The server-grant gate distinguishes execute authority from write authority: execute-class tools (bash, code_exec, task spawns, background/ team spawns — anything that can run shell on the worker) and the permission-mode elevation (allow-all/auto) require tasks:execute (or *). The coarse write⇒execute rule lives ONLY behind legacy_write_implies_execute (default true — existing installs keep the behavior; new installs set it false via SOL_LEGACY_WRITE_IMPLIES_EXECUTE=false / LUNA_LEGACY_WRITE_IMPLIES_EXECUTE=false on BOTH sides — Sol and Luna mirror the flag; the shared matrix fixture server/test/fixtures/permission_mode_clamp_matrix.json pins the semantics on both mirrors). With the flag off, a workspace:write-only user cannot raise worker posture or run execute-class tools.

Layer 1: Permission System

Module: client/core/permission_checker.lua

Gates ALL tool invocations. Checks tool name against configured permission mode (6 modes: default, allow-all, deny-all, read-only, plan, auto — see permissions.md). Integrates with danger_detector (45 regex patterns: 26 dangerous + 19 caution, plus 3 AST-derived dangerous findings) to gate risky operations.

Layer 2: Command Policy

Module: client/core/command_policy.lua

Gates bash tool specifically. Three profiles with increasing permissiveness:

ProfileDeny PrefixesNetworkask_destructive
strict25 patternsblockedyes
standard25 patternsallowedyes
permissive9 patternsallowedno

Deny prefixes include: rm -rf /, mkfs, dd if=/dev/zero, curl | bash, shutdown, reboot, iptables -F, /etc/passwd, /etc/shadow, etc.

Ask_destructive — when enabled, commands flagged as dangerous or caution by danger_detector return {ask=true} for user confirmation via TUI modal.

User Rules (Lua Policy Files)

Users can define custom rules in ~/.luna/policies/*.lua. These provide programmable policy equivalent to Starlark:

~/.luna/policies/no-docker.lua
return {
  name = "no-docker",
  rules = {
    { pattern = "docker ", action = "deny", reason = "docker not allowed" },
    { pattern = "kubectl ", action = "deny", reason = "kubectl not allowed" },
    { pattern = "helm ", action = "allow", reason = "helm is ok" },
  }
}

Rules are evaluated after built-in deny prefixes. First match wins. Actions: deny (block) or allow (bypass further checks).

Audit Logging

Enable with command_policy.enable_audit(path). All policy decisions are logged as JSONL:

{"ts":1748300000,"command":"rm -rf /tmp/test","allowed":false,"reason":"denied prefix: rm -rf /","source":"command_policy:strict"}

Layer 3: OS-Level Sandbox

Module: client/core/sandbox.lua

When enabled via config.execution.sandbox.enabled, commands execute inside a bwrap sandbox:

Read-only bind of / (system files immutable) Read-write bind of workspace directory only /tmp tmpfs mount (TMPDIR is rewritten to /tmp inside the namespace — the host TMPDIR, e.g. /run/user/1000, does not exist there) Namespace isolation: --unshare-pid (same-uid host processes are unkillable — pid namespaces are kernel-enforced on signal delivery — and invisible in the fresh /proc), --unshare-ipc, --unshare-uts Env allowlist: --clearenv + --setenv for PATH HOME LANG LC_ALL TMPDIR USER LOGNAME SHELL + per-tool env_passthrough extras — SOL_API_KEY/provider keys/*KEY*/*TOKEN*/*SECRET* never cross the boundary; the scrub set now also covers the anchored PASSWORD/PASSPHRASE/_PASS/PWD/*_PWD/*_AUTH/*CREDENTIAL*/*PRIVATE* families and value-shaped URL userinfo (DATABASE_URL=postgres://user:pass@…), while XAUTHORITY and SSH_AUTH_SOCK survive; the _spawn_popen fallback, configure-wizard io.popen, and the macOS seatbelt leg splice the same set via env -u; MCP/LSP stdio servers get a Landlock-only config + allowlist-rebuilt child env Sensitive-path read-deny (tmpfs//dev/null shadows) from ONE single-source list shared by the bwrap and seatbelt builders: ~/.ssh, ~/.gnupg, ~/.aws, ~/.netrc, ~/.git-credentials, ~/.docker/config.json, ~/.config/gcloud, ~/.kube, ~/.npmrc, ~/.config/gh/hosts.yml, ~/.azure, ~/.pgpass, and the ~/.luna credential surface — keys, approvals, oauth_tokens.json, settings.json, mcp.json, sessions, sessions.db, memory.json, MEMORY.md, memory.db, profiles, logs, analytics.db (the ~/.luna/bin toolchain is the acknowledged, census-pinned exception); adds the podman/buildah/skopeo store ~/.config/containers/auth.json plus the XDG runtime copy $XDG_RUNTIME_DIR/containers/auth.json (canonically /run/user/<euid>/containers/auth.json) Socket deny shadows: container-daemon sockets (docker.sock/podman.sock/containerd.sock, system + per-user) plus the agent/keyring roots /run/user/<uid>/keyring, /run/user/<uid>/gnupg, /run/gnupg, and $SSH_AUTH_SOCK when set — resolved at build time, shadowed with /dev/null (files) or --tmpfs (directory roots). /tmp/ssh-*/agent is an accepted residual (not statically resolvable). deny_sockets={} disables the defaults only with deny_sockets_ack=true; otherwise the defaults apply Network isolation (--unshare-net) by default --die-with-parent ensures cleanup on crash

Backend selection: execution.sandbox.bwrap = off | auto (default) | required — semantics verified real: off runs the bare shell argv with the Landlock fork layer still applied (write-deny; documented residual: no read-deny, no network isolation); required refuses to run when bwrap is missing. On macOS the seatbelt profile applies. The macOS seatbelt posture is argv-verified only: the emitted SBPL profile is covered by render/parity tests, but the ZERG token has no macOS kernel-truth runner, so no kernel-enforcement claim is made until a real sandbox-exec drill is recorded. The drill is implemented and self-registers on a real Darwin host (client/tests/test_seatbelt_env_scrub.lua: outside-workspace write must be denied, workspace write must succeed); on Linux it does not register, so release claims about seatbelt enforcement stay gated on that macOS leg. allowed_write_paths is additive on BOTH backends: the workspace write allow is always emitted first, then each grant.

Default: ON. DEFAULT_CONFIG carries execution.sandbox.enabled = true — a prompt-injected agent must NOT get arbitrary unsandboxed shell by default. Consequences:

If the sandbox is enabled but unavailable (no bwrap / no sandbox-exec), FFI.spawn and FFI.spawn_async error with sandbox_unavailable instead of degrading to a bare shell. code_exec runs inside the sandbox like bash (it passes the agent’s real config through). The workspace is enforced by the file tools: reads/writes outside the configured workspace are denied, and denied entirely when no workspace is configured (fail-closed; the interactive TUI binds reads to the session cwd, or an operator may set workspace = "." explicitly). allow-all permission mode requires execution.sandbox.enabled = true. Process timeouts kill the process group (children setsid), so backgrounded grandchildren (sleep 9999 &) do not survive.

Operators who explicitly want the legacy insecure behavior set execution.sandbox.enabled = false (documented as the insecure option).

Configuration:

execution = {
  policy = "standard",
  sandbox = {
    enabled = true,
    network = false,
    allowed_paths = { "/data" },
  }
}

Managed Policy (Enterprise)

Server-side policy overrides via GET/PUT /api/v1/managed-settings (admin only, fleet-wide — the fleet push is the ZMQ managed_settings_update PUB). The schema is CLOSED:

{
  "execution.policy": "strict",
  "execution.max_iterations": 100,
  "execution.session_budget_usd": 5.0
}

Applied by Luna via managed_config.apply_managed with highest priority — overrides both user config and mode defaults.

Mango Identity Service Hardening

Mango (the identity/auth microservice) ships its own hardening surface; this section documents the contract.

Rate limiting: reserve/release/spend

RateLimiter.check is an atomic reserve — it decrements immediately when a token is available (no peek window). spend consumes the reservation on credential failure; release refunds it on success (capped at the rate). Burst admission is exactly the configured budget on both the memory and SQLite backends — N concurrent attempts can never multiply into N× the budget. Every auth limiter (login per-IP, per-account, validate, service-token, password-change) follows: check(reserve) → success: release; failure: spend. A DB-outage login (503) releases — infrastructure failures never burn the brute-force budget.

LDAP federation seam

MANGO_LDAP_TLS is a closed set {starttls, ldaps, none} validated at boot — an unknown value refuses boot (a typo previously fell through to plaintext binds with zero signal). Runtime path refuses plaintext too. A federated mail that collides with a local account refuses the LDAP login (uniform “invalid credentials”) unless MANGO_LDAP_ALLOW_ACCOUNT_OVERRIDE=true (documented dangerous). This closes the account-takeover seam where a crafted LDAP entry could mint the local user’s session token. Concurrent first-login races retry as update — never a raw UNIQUE 500. LDAP runs on a dedicated bounded executor (MANGO_LDAP_EXECUTOR_MAX, default 4); an LDAP outage cannot saturate the shared pool and starve local bcrypt logins (the break-glass path). Group → role mapping: MANGO_LDAP_GROUP_ROLE_MAP is a JSON object {group: role} mapping the entry’s memberOf claims to Mango roles (matched case-insensitively by full DN or CN); MANGO_LDAP_DEFAULT_ROLE (none default, or viewer) covers unmapped users. A malformed mapping refuses boot. Grants flow through the same user_teams → team_roles → roles machinery as every other grant — each mapped role owns a deterministic ldap-role-<role> team — and memberships are SYNCED on every login (a group removed in LDAP demotes on the next login). The users.role column is never written by federation; every mapping decision leaves an audit row (ldap.role_mapped) with the claim and role provenance.

LDAP TLS posture decision

Decision: glauth LDAPS with a provisioned cert is the target posture; plaintext-on-the-bridge is explicitly NOT adopted. The verified state (2026-09-19 audit + wild pin): the fleet’s glauth ships [ldap] enabled=true:3893 with [ldaps] enabled=false and no STARTTLS evidence, while Mango defaults MANGO_LDAP_TLS=starttls + verify — i.e. the live Mango→glauth leg either hard-fails or silently falls back to local accounts; “fixing” it with MANGO_LDAP_TLS=none would carry the service-bind password AND user passwords in cleartext across the shared podman bridge, and glauth currently publishes 3893 on the LAN IP (an A1 surface). Execution (wild, with the prod-flip drill): enable [ldaps] with a provisioned cert, set MANGO_LDAP_TLS=ldaps + MANGO_LDAP_CA_FILE, remove the LAN publish of the plaintext port, and verify one live LDAP login as the acceptance test. Until that lands, LDAP federation on the fleet stays de-facto-disabled rather than plaintext — that is the compensating control.

RBAC permission cache

A generation counter stamps cache entries at fetch start; any invalidation (invalidate_permission_cache / invalidate_all_caches) bumps the epoch, and a stale in-flight fill (started pre-revocation, finished post-) is rejected as a miss — the caller refetches. Revoke-then- read never serves pre-revocation permissions; the fast path is preserved when nothing changed.

Audit ordering

Privileged state-changing endpoints audit before responding and fail closed: the strict audit path re-raises on a write failure and the endpoint returns 503 “audit unavailable — retry operation” with Retry-After: 30 instead of a 2xx with no audit record (: finish_audit_unavailable honors AuditUnavailableError.status_code = 503; the legacy 500 path remains for other exception classes only). The success body is never flushed, so the failure status can never be mistaken for a confirmed state change. Informational events (failed-login, logout, locked-account attempts) deliberately stay fail-open (strict=False) — they must never break auth responses. In short: privileged state changes are audit-fail-closed; reads and login attempts are audit-best-effort. Operators should treat a 503 on a non-idempotent create as “not confirmed — retry” guidance.

Audit call-site classification

Every handler audit site in mango/handlers/, strict or not. ( 19,: the rows below were re-verified against the handlers; the login-success row, the 503 prose above, and the two added strict families were the drift.)

SiteAction(s)ModeWhy
users.py UsersHandler create/update/delete + org endpointscreate_user, update_user, delete_user, org equivalentsstrictprivileged state change
teams.py TeamsHandler create/update/delete + membershipscreate_team, update_team, delete_team, membership changesstrictprivileged state change
rbac.py RolesHandler create/update/delete + grantscreate_role, update_role, delete_role, permission grantsstrictprivilege escalation surface
tasks.py TasksHandler create/update/delete + assignmentscreate_task, update_task, delete_task, assignment changesstrictprivileged state change
auth.py change-passwordchange_passwordstrictcredential change; the split’s template
auth.py service-token issuanceservice_token.createdstrict“the most sensitive privileged action” — a minted token without a record is a worse failure than a 500
auth.py mass token revocationtokens.revoked_allstrictprivileged state change — a 200 “all revoked” without a record breaks the revocation trail
auth.py admin account unlockaccount.unlockedstrictprivileged state change — clearing a lockout is security-relevant
auth.py login successloginstrictthe strict arm with finish_strict_or_revoke: an audit outage revokes the just-minted token and refuses the login (a login that never returns is the misread this closes)
auth.py single-token revocationtokens.revokedstrictprivileged state change — a 200 “revoked” without a record breaks the revocation trail
orchestrator_lease.py lease transitionsorchestrator_lease_{acquired,stolen,taken_over}strictprivileged state change — takeover attribution rides the audit row
auth.py login failure (credential + locked-account)login_failednon-strictinformational; fail-open so auth never 500s under audit-store hiccups
auth.py logoutlogoutnon-strictinformational; the token is already revoked by AuthSystem.logout

Strict sites audit BEFORE finish via audit_then_finish or the revoke-in-arm finish_strict_or_revoke; non-strict sites use self.audit and degrade to a CRITICAL log + alert counter on failure. The service-token READ path is unaudited by design (read-only, derivable from the issuance rows).

Mango audit chain

Mango revocation journal signing

The revocation ring’s served epoch is now published only AFTER the journal row and ring entry are appended, under one lock (the pre-fix epoch bump before the awaited insert let a snapshot answer (N, []), so Sol adopted N and never replayed the revocation). PostgreSQL also takes a transaction-scoped advisory lock so revocations commit in epoch order. Journal rows are HMAC-signed and chained (signature / prev_signature, migration v0015); the high-water/floor/frontier markers are signed and monotonic in SQL, and boot verifies the signed chain (a deleted MIDDLE row is a chain break; a deleted tail is the high-water check; a modified row fails its HMAC). Pre-v0015 rows are TOFU-exempt via revocation_journal_signed_from.

Mango service-token mint, lease and secrets

POST /auth/service-token answers ONE uniform 403 {"error": "forbidden"} for every non-success credential/shape failure (wrong secret, missing/unknown user, allowlist denial, malformed fields); body-parse/rate-limit errors are identical regardless of the secret. This closes the secret-validity oracle. Service/bridge/audit/archive shared secrets must be >= 16 bytes or boot refuses (validate_boot_secrets). The orchestrator lease row is bound to the acquiring token’s user_uuid; a stale steal by a DIFFERENT principal requires takeover authority (admin binding or the RBAC-off allowlist), the optional request epoch is CAS-checked (lease_epoch_stale), and every transition is strictly audited.

Mango readiness and event-transport posture

/ready caches its DB/migration/instance verdict for ~1s for non-loopback callers (loopback stays live), so a health-check fan-out cannot amplify DB load. The ZMQ PUB bind must be loopback or ipc:///inproc:// unless MANGO_ZMQ_ALLOW_NONLOOPBACK=1 acknowledges a broader bind; the dead inbound PULL leg (no Sol sender — Decision #433) is retired and never bound, and the multipart discard path is bounded (an endless part stream tears the socket down instead of pinning the listener).

Mango’s audit_logs now carries the same tamper-evidence premise as Sol’s sol_audit_log (HMAC prev_signature chain + monotonic seq), implemented in mango/systems/audit.py with migrations v0003_audit_chain (columns) and v0007_audit_chain_checkpoint (the anchor table):

Fields: seq (monotonic, head+1 per write; the head is only advanced after COMMIT, so a failed write’s seq is never consumed), prev_signature (the previous sealed row’s signature, "" for the first), signature (hex HMAC-SHA256). Pre-v0003 rows keep seq=NULL and are outside the chain by construction. seq GAPS are seq_gap violations — there is no “gaps legal” posture. Material: canonical JSON (sort_keys, compact separators — the audit-archive canonicalization precedent) of the entry-minus-signature INCLUDING seq, prev_signature and (post-v0005) created_at. Both backends store created_at as DOUBLE PRECISION so the timestamp round-trips exactly (pre-v0005 rows verify under the legacy created_at-free material via the audit_chain_meta boundary). Head: in-memory (seq, signature), sound because of the single-process invariant (above); writes serialize on a module lock and, on PostgreSQL, on a pg_advisory_xact_lock held to COMMIT (so a concurrent transaction cannot derive a stale head — ). Boot head = SELECT seq, signature ORDER BY seq DESC LIMIT 1, derived lazily on the first write (including in-transaction writes in a fresh request context — ); a REAL head-read failure fails the write (never a silent fork at seq 0). Torn tails are free via single-statement INSERT atomicity. Anchor: audit_chain_checkpoint holds ONE signed row — (seq, signature) plus checkpoint_sig = HMAC(chain key, "mango-audit-checkpoint-v1|" + canonical JSON of {seq, signature}) — refreshed on EVERY chained write (the write-time anchor closes the verify-then-delete window). Verify compares the observed tail against it: a shorter tail (or a full wipe) is truncated_tail, a missing head is truncated_head, a swapped tail is sequence_rewind, a corrupted anchor is checkpoint_invalid (all typed, ok=false); a missing anchor is reported as unanchored (the chain may still verify — but never silently green). Secret: MANGO_AUDIT_CHAIN_SECRET (>=16 bytes as-is; shorter is SHA-256-derived with a warning). Unset with token auth on → CRITICAL + a RANDOM per-process key (fail-loud, not boot-blocking — mirroring sol_audit_log; cross-restart verification then honestly fails at the boundary until the operator sets the secret, and the verdict’s key_source says ephemeral). Strict split: the seal rides the SAME strict/unstrict discipline as the write — strict callers get AuditUnavailableError (503, fail-closed) on store OR chain failure; informational events fail loud-but-open. Verify is an OPERATOR surface, never per-write: Audit.verify_integrity(db, max_rows=, checkpoint=) recomputes the full ordered chain with hmac.compare_digest, checks adjacency (prev == previous row's signature when seqs are adjacent), reports seq gaps, is size-guarded (MANGO_AUDIT_VERIFY_MAX_ROWS, default 200000) and returns the verdict key set (ok / rows_checked / truncated / violations / reasons / anchored_to_seq / key_source). scripts/verify_audit_chain.py (--checkpoint <store|path>) exits non-zero on any reason, including a clean-but-unanchored chain. Log hygiene: the audit log lines are repr-capped (_logsafe, 128 chars) for action/resource_type/resource_uuid — raw %s of attacker-controlled URL segments was a log-injection vector. What is PERSISTED stays raw so the chain material is stable. The same-class LDAP-email log sites also route through _logsafe now the former residual is closed.

Anchor hardening

Every checkpoint MAC is mandatory. read_checkpoint treats an empty/missing checkpoint_sig as checkpoint_invalid (the pre-fix if mac skipped verification, so checkpoint_sig='' pointed the anchor at a surviving tail and verified green). Append-only checkpoint history (audit_chain_checkpoint_history, migration v0015): every write appends its signed (seq, signature, checkpoint_sig) pair. A singleton anchor that sits BEHIND the historical maximum is a truncated_tail (detail=checkpoint_rollback) verdict — restoring an older valid anchor after deleting the tail is refused. A stale anchor behind the observed tail is likewise truncated_tail (detail=checkpoint_behind_tail), with one re-read for a concurrent writer. ok means anchored: an unanchored chain or a row-bound-truncated scan now returns ok=false (pre-fix ok=true with reasons=["unanchored"]). The operator CLI keeps its explicit UNANCHORED/partial-scan messages and exits non-zero. Log/ingestion hygiene: _logsafe(actor) at both audit sinks, and _logsafe on LDAP exception text; the audit-archive POST validates timestamp/source/aggregate_id/event_type types and lengths (non-string timestamp → 400, never 500) and maps DB failures to a typed 503.

Audit log retention

Decision: RETAIN FOREVER for this cycle; the prune-floor design is recorded, owned, and not yet implemented. audit_logs has no retention path today. A naive DELETE is NOT an acceptable remedy: verify_integrity requires the first observed row to be seq 1 (truncated_head) and a bare prune also trips the adjacency seq_gap check — the integrity tool would flag the operator’s own hygiene as tampering. Growth is real (every login

  • privileged mutation writes 1–3 rows at ~0.5–1 KiB; a 1000-user fleet at 100 logins/user/day ≈ 10⁵ rows/day), so retention is a design decision, not a missing trim.

The designed successor reuses the revocation journal’s prune-floor machinery (revocation_journal_pruned_floor / surviving_min / high_water): a signed retained_from_seq marker advanced atomically with each bounded prune chunk, plus a verify mode that anchors the head to that floor (rows below it are legally pruned; a missing row above it stays seq_gap). Compaction must be operator-invoked with a keep bound, chunked like RevocationRing.compact — never date-bound auto-delete. Until that lands: back up the audit store with its chain key (a restore is unverifiable without MANGO_AUDIT_CHAIN_SECRET/the prior ring), size the volume for unbounded growth, and do not manually delete rows. Owner/check-date: `` in plan/residual-register-v0765.md (next Mango storage window, 2026-12-31).

Update: the prune-floor design above IS implemented Audit.prune(keep=, chunk_rows=) deletes a bounded prefix atomically with the signed retained_from_seq marker and now also writes its own chained audit_retention_prune audit row.

Dummy-verify cost parity

The unknown-account login dummy and the handler-side locked-account / budget-exhausted burns previously hashed at the import-time DEFAULT bcrypt cost while the real verify path derived its cost from MANGO_BCRYPT_COST — a cost-mismatch timing oracle for account enumeration. All four consumers now share dummy_bcrypt_verify, whose hash cache is keyed by the LIVE configured cost (computed inside the executor — ’s no-IOLoop-block is preserved).

Client IP resolution

Behind a trusted proxy, the client is the rightmost-untrusted XFF hop (skipping trusted proxies), validated with ipaddress (invalid values fall back to the TCP peer). trusted_proxies is live app config (list or comma-string, stripped entries) with MANGO_TRUSTED_PROXIES as fallback — client-chosen leftmost values can no longer forge limiter keys or audit ip_address fields.

Global-trust guard — a /0 CIDR entry (0.0.0.0/0, ::/0) trusts every peer and makes X-Forwarded-For/ X-Real-IP fully attacker-controlled, so it is DROPPED at parse with a once-per-process CRITICAL unless MANGO_ALLOW_GLOBAL_TRUST=true is set . Legit CIDR entries are unaffected; the guard also applies to direct ip_is_trusted callers (defense in depth).

(AUTH-20): trusted_proxies is now a real config-file option (trusted_proxies =... in mango.conf) threaded through init_app, not only the MANGO_TRUSTED_PROXIES env fallback. Direct loopback is no longer exempt from rate limiting by address alone: it gets its own bounded bucket (MANGO_LOOPBACK_RATE_LIMIT, default 3000/60s), and a configured MANGO_CONTROL_PLANE_TOKEN requires the matching X-Control-Plane-Token header before the unlimited exemption applies. Every security boolean (MANGO_ENABLE_TOKEN_AUTH, MANGO_REQUIRE_AUTH, MANGO_COOKIE_SECURE, MANGO_ALLOW_GLOBAL_TRUST, …) is parsed by one strict parser accepting on/off, true/false, 1/0, yes/no; any other value refuses boot (the pre-fix parser silently read on as false). MANGO_REQUIRE_AUTH is enforced centrally in prepare, so anonymous requests are refused before any handler (including the task list) runs.

Forwarded client IP — Sol vs Mango

Proxy contract (both services): a reverse proxy MUST emit and normalize X-Forwarded-For (append the peer it accepted the connection from; never pass a client-supplied chain through unchanged). Forwarding headers are hops, never an authority: a value the client invented before the proxy is not a client identity.

Sol treats X-Real-IP as one more unvalidated hop and only reads it when an XFF chain is present; a lone client-supplied X-Real-IP from a trusted proxy is Ignored (the TCP peer is used). The rightmost-untrusted walk and the anti-mint-loopback rule are unchanged, so a forwarded value can never mint a loopback bucket or bypass the loopback/admin gates.

Mango divergence (recorded, not yet migrated): Mango’s BaseHandler.resolve_client_ip still honours a trusted peer’s X-Real-IP (with the same anti-mint rule) when XFF is absent. Deployments that put a trusted proxy in front of BOTH services must therefore emit XFF; an X-Real-IP-only proxy gives Mango a client identity that Sol ignores, and the two limiter/audit keys can disagree. The parity fixture (server/test/fixtures/client_ip_resolution.json) pins ONLY the Sol resolver; it is not a cross-service mirror. Owner/check-date: the next Mango identity window (align Mango to the Sol rule or document the operator-level XFF requirement in the wild blueprint).

Public-read exposure gate: /metrics + /openapi

/metrics and /openapi extend the auth-skipping PublicBaseHandler — they are unauthenticated even when token auth is on. The shared PublicReadGateMixin now gates both:

Loopback clients: allowed (the historical, ops-compatible default); Non-loopback + bearer token: allowed when the request carries Authorization: Bearer <MANGO_METRICS_READ_TOKEN> (constant-time compare; empty token = no token path); Non-loopback, metrics_expose="any": allowed — the explicit broader-exposure lever (MANGO_METRICS_EXPOSE env); Otherwise: 403.

Defaults keep today’s behavior (metrics_expose="loopback", metrics_read_token="" → loopback-only). OPTIONS preflights are exempt.

Sol /metrics exposure posture

Sol’s /metrics (Prometheus exposition, sol_http:dispatch(prometheus_metrics, _)) is peer-gated, not anonymously exempt. The -era text below this section described a “hardening path … not yet a hard gate”; the gate landed in and the topology honesty followed in . The implemented posture:

/metrics is OFF the auth-exempt list. It sits beside its RBAC-documented sibling /api/v1/metrics; a bearer request needs the metrics:read permission ({GET, /metrics} => metrics:read in the route permission map). Tokenless scrapes are refused with 403 unless the loopback TOPOLOGY holds. metrics_gate_peer/1 requires BOTH legs of is_loopback_topology/2: the TCP peer is loopback and every X-Forwarded-For hop the request carries is itself loopback. A reverse proxy bound on loopback that forwards external traffic fails leg 2 and is refused — the previous peer-only check served the fleet exposition to the world through any on-host proxy. The refusal happens before sol_prometheus:format_metrics/0 (fail-closed; the response is a typed 403, never a 401 challenge). There is no metrics_expose lever on the Sol side — the loopback | any lever and metrics_read_token bearer leg documented in an earlier draft belong to Mango’s /metrics (see the Mango public-read gate above). Sol’s lever equivalents were never implemented and are not promised here.

For an off-loopback Prometheus agent, scrape through an authenticated bearer with metrics:read (or terminate at a proxy that presents it). The absent(sol_up) dead-man switch still works: the loopback leg keeps on-host scrapes anonymous, so a scrape failure is still visible as a gap.

Single-process invariant

Mango MUST run as exactly one process. The revocation ring + epoch, the RBAC permission cache, the rate limiters, the audit HMAC chain head, and the ZMQ PUB socket are single-process state — a second process would serve stale permissions, multiply brute-force budgets, fork the audit chain, and split the event bridge. tornado 6.5 removed --procs entirely (the option is rejected as unrecognized) and app.listen never forks, so the stock entrypoint starts one process. Mango HA L0 adds the missing Runtime config gate: MANGO_WORKERS>1 refuses boot unless it is explicitly opted into with MANGO_MULTI_PROCESS=1 AND backed by PostgreSQL; MANGO_MULTI_PROCESS=1 on SQLite also refuses boot (the L1 coherence work does not exist, so a partial-L1 boot is a config error, not a degraded mode). Production posture: one podman container under wild/runit; concurrency = the event loop + nginx. See docs/production-runbook.md “Mango identity-service L0”.

Revocation-bridge health surface

A bridge that boots but cannot bind used to look healthy while silently never delivering a revocation frame. Now:

ZMQTransport.pub_connected — live bound-state of the PUB leg; /health body carries "revocation_bridge": "up" | "degraded" | "disabled" (disabled = no zmq_pub_url; degraded = configured but not bound right now — bind failure, start crash, mid-reconnect); gauge mango_revocation_bridge_up (0/1), refreshed on every /metrics and /health scrape — a Mango-side family. (The previous text claimed it “feeds the Sol consumer” — no such consumer existed, BD-1106. Truth since then: Sol exports its OWN bridge transport gauge sol_mango_bridge_bind_up (1 = connected, 0 = failed/degraded, series absent when the bridge is disabled) from sol_mango_zmq_bridge state, consumed by the SolMangoBridgeDown alert; mango_revocation_bridge_up remains observable on the same scrape for the Mango half of the story.) a configured-but-failed bridge is CRITICAL-logged degraded, boot continues (an optional transport must not kill the identity service).

Password policy

The common-password list (mango/data/common_passwords.txt) is enforced — a missing list refuses boot in token-auth mode unless explicitly waived (MANGO_ALLOW_MISSING_COMMON_PASSWORDS=true).: the list is the pinned SecLists 10k-most-common (MIT, commit 3ccb6c3257ccabac92a639d435435cf09873b28e), sha256-indexed to keep the repo small (sha256: exact digests for the top 100, p: 4-byte prefixes for the rest — regenerate via mango/scripts/gen_common_passwords.py; see the file header for the pin and the documented supplement). Entries match case-insensitively, so Password123 and leet variants are rejected. Passwords are capped at 72 Bytes (bcrypt’s key length); existing longer accounts are unaffected (bcrypt truncates consistently on hash and check) but cannot choose new over-long passwords. Token entropy is 256-bit (secrets.token_urlsafe(32)).

Token storage decision: SHA-256, not bcrypt

Decision: DECLINE the deferred bcrypt token-hash migration; keep SHA-256 over uniformly random 256-bit tokens. This closes the -F1 “adopt or decline with evidence” item that had remained prose-only (plan/archive/phase--architecture-duplication-reduction.md M-G3 “DEFERRED”). Verified current posture:

generation is secrets.token_urlsafe(32) = 32 bytes (256 bits) of CSPRNG entropy at both mint funnels (session + service; the service token adds a fixed mango_srv_ prefix); storage is sha256(token).hexdigest (AuthSystem._hash_token); the raw credential is returned once and never persisted; lookups hash the presented value and compare the stored digest; every TTL is clamped (session 300 s..72 h, service 1 h..90 d), so the entropy floor — not the KDF — is the binding constraint.

Brute force against a dumped store therefore needs ~2²⁵⁶ preimages regardless of hash speed. Bcrypt would add ~100 ms per validate (the hot path for every request), require a dual-read migration and a second stored format, and buy nothing for a uniformly random secret. The risk that WOULD justify a slow KDF — a low-entropy, human-chosen token — is excluded by the single generation funnel; mango/test/test_token_hash_posture.py pins it (raw never stored, 32 decoded bytes, SHA-256 digest). Reopen only if a future token format becomes user-supplied or shorter.

ZMQ Trust Plane & Identity Propagation

Decisions – document the closure of the ownership matrix’s comment-vs-implementation seams.

batch: transport trust

CURVE transport: non-loopback ZMQ binds are CURVE-encrypted by default; plaintext requires an explicit ack or declared tunnel; the crypto backend is nacerl/tweetnacl (chumak’s own default, vendored + fixed for OTP 27+ — see the spacebeam/nacerl fork README, pinned in server/rebar.lock). The server keypair auto-generates to <data_dir>/curve_server.cert; workers provision LUNA_ZMQ_CURVE_SERVERKEY. Per-worker enrollment keys: key_id on ready selects the verification key from zmq_enrollment_keys; revoked/unknown/mismatched keys refused; fleet-secret compat window until 2026-11-01; registration-rate anomaly alarm. Sol→Mango TLS: mango_tls=true (verify_peer + system CAs, mango_ca_file to pin a custom CA); a non-loopback plaintext Mango hop refuses boot in prod. Mango inbound fail-closed: the ZMQ bridge refuses to bind PULL/PUB without MANGO_BRIDGE_HMAC_SECRET; _verify_inbound rejects unsigned frames. Luna wire trust: Luna refuses to register with a non-loopback server without a secret/CURVE key (LUNA_ZMQ_ALLOW_PLAINTEXT=1 escape hatch); wire workspace_root must match zmq.allowed_workspace_roots; a missing permissions field is deny-default ({}). Static Luna build precondition: the musl static Luna binary can only speak Curve when libzmq is built with libsodium. build/setup-musl.sh builds a hash-pinned libsodium 1.0.20 and configures libzmq WITH_LIBSODIUM=ON, then runs a fail-closed build-time Curve probe (a zmq_has("curve") + real loopback Curve round-trip) and writes the libzmq-curve-ok cache marker only on success; a deps cache from the pre-fix WITH_LIBSODIUM=OFF recipe is rebuilt automatically. ci/verify-static.sh <binary> --require-curve (wired into build/build-musl.sh for the luna artifact) re-proves the capability against the same deps tree and fails the build otherwise. On the Luna side the registration posture is applied-options truth: a configured LUNA_ZMQ_CURVE_SERVERKEY counts only when every setsockopt returned 0 (wire_trust.registration_posture/5); a valid key against a Curve-less libzmq refuses (or degrades loudly under the explicit plaintext ack) with a CRITICAL boot datum — it can no longer silently connect plaintext while the operator believes Curve is on. Shares hardening: /api/v1/shares/:id is per-IP rate-limited (default 30/min, share_rate_limit_per_min) and read-logged (id + ip, notice); expiry was already enforced at read. Revocation replay closure: Mango keeps a 1024-entry revocation ring + epoch; Sol pulls /auth/revocations?since_epoch=N on bridge (re)connect + every zmq_mango_resync_ms (60s) and applies entries idempotently. The pull is not authorized by service-token class alone Mango requires the revocations:read permission, an admin binding or a uuid on the MANGO_REVOCATIONS_READ_USERS allowlist (mango/mango/handlers/auth.py:1574-1583). A zero-permission service token gets 403; the permission is declared in the Mango classification fixture and is not seeded to any default role. Logout CSRF: cookie-authenticated logout requires the X-CSRF-Token header matching the zerg_csrf cookie (Bearer logout unchanged). Air-gap egress gates: LUNA_ALLOW_OSV_CHECK / LUNA_ALLOW_TOOL_INSTALL / ZERG_ALLOW_EGRESS_UPDATE (see the egress inventory above); ci/egress_assert_lint.py asserts the frontend/Luna trees stay free of third-party CDN/analytics references (born required).

Ownership matrix: queued seats & liveness

Queued tasks enter the ownership index at enqueue with a reserved <<"queued">> sentinel identity — a KNOWN task with NO eligible sender (result/token/error always fail for any sender identity). On an index miss, the sender must equal the recorded executor stamped at dispatch; a frame with no recorded executor, or a foreign one, is refused and counted in sol_zmq_ownership_refused_total. The recorded-executor match grace is thereby restricted to the genuine post-restart window (the previous registered-sender grace is DELETED). The index sweep is liveness-aware: the 1h TTL means “idle 1h”, not “age 1h” — heartbeat/accepted result/token/error refresh the row timestamp, and rows are swept only when the task is not busy, queued, or store-pending; an unreachable gateway suspends the sweep (retention-fail-safe).

Reserved task-id namespace

zmq-<ms>-<counter> ids are SERVER-RESERVED. Caller-supplied ids with that prefix are rejected at the dispatch boundary ({error, reserved_task_id}) enforced structurally by ci/caller_task_id_prefix_lint.py (contract tested). Workflow-bridge correlation ids (non-zmq prefix) are unaffected.

Identity injection

Client-supplied identity keys never survive into deferred resources: inject_user_identity / inject_task_identity / orchestration opts STRIP user_uuid/permissions/listener/owner first, then stamp server identity unconditionally — including <<"system">> (an explicit stamp is the honest marker; empty permissions are stamped too, meaningful on the wire per.3).

Worker-registration HMAC & adoption

The registration HMAC binds the ROUTING IDENTITY (length-prefixed in the signed material, nonce || identity || worker_id || child_depth) in addition to nonce/worker_id/depth — a captured ready frame can no longer be replayed under a different routing identity (the nonce LRU is per-identity, so the fresh-victim window is closed). In-flight-task adoption additionally requires index-worker equality. Worker registration REQUIRES a secret on every non-loopback bind in every deployment mode except explicit dev (runtime refusal; the prod boot gate remains).

ACP replay protection

The ACP HMAC is deterministic over the payload, so replay protection is GLOBAL and freshness-checked: every verified frame’s digest is checked against a MAC-keyed global cache (sol_acp_replay_global, bounded LRU acp_replay_max = 65536, 1h expiry purge, fail-closed when the table is unavailable) — a captured frame replayed over a FRESH connection is refused + counted. The per-peer cache of survives only as the one-window acp_replay_scope=peer rollback lever (CRITICAL boot banner). Frames of type request/response/discover additionally validate the protocol timestamp/ttl fields at ingress (refusing stale, >30s future, zero/absurd ttl — typed, counted); capability/notify/broadcast carry ttl=0 by contract and rely on the global digest cache. Frame caps (acp_packet_size, clamped at 16 MiB) refuse oversized declared lengths in the driver before allocation; HMAC failures and oversize frames are counted. Capability registration binds to the verified key identity, not the socket . A non-loopback ACP bind requires the explicit acp_listener_plaintext_ack=true acknowledgement (; the plane is HMAC-only raw TCP).

ACP registration key binding

ACP capability registrations over the TCP leg bind to the verified KEY identity (acp_key_id, the HMAC shared-secret plane) instead of the ephemeral {tcp, Socket} term: same key + new socket rebinds (reconnect allowed), a different key for a taken AgentId is refused (key_mismatch, counted), and revoke_key/1 drops every registration bound to the key. Registration is a real call — the router returns typed verdicts (ok | {error, already_registered | key_mismatch}) instead of the former unconditional {ok, registered}. TCP disconnects drop the socket-owned registrations; the ZMQ leg keeps its enrollment-verified identity-bound semantics.

ZMQ transport posture

: CURVE is now the default posture on every non-loopback bind (see docs/zmq-security.md). The old plaintext rule below remains the loopback/dev posture. What the HMAC/ownership layers protect: frame integrity + sender binding at the application plane. What CURVE now adds: confidentiality + active-tamper resistance at the TCP plane (the tweetnacl CURVE handshake — a wrong-key peer never completes it). Deployment rule: every non-loopback bind boots with CURVE, a declared tunnel, or an explicit plaintext acknowledgement (zmq_transport_plaintext_ack; CRITICAL banner in staging/qa; boot REFUSAL in prod).

The cluster cookie rotates from crypto:strong_rand_bytes(32) (hex-encoded, 256-bit class) — rand:uniform is banned from security-sensitive generation (the old 44-char alphabet draw described ~264 bits of ENCODING, not entropy source).

Mango validate-path limiting

Mango’s validate limiter is per-account post-validate: valid tokens bucket per account/uuid (reserve/release — a garbage flood can never 401 a valid user through Sol’s loopback funnel); garbage tokens bucket a separate fail-closed (ip, invalid) limiter that throttles itself. A Sol-forwarded x-zerg-user-uuid header is honored ONLY from trusted (loopback) peers.

Luna safety classes & denial circuit breaker

Bypass-immune safety classes

Four exact, data-driven classes sit at the top-level result of core.permission_checker.check (client/core/safety_classes.lua). They are evaluated after the normal mode/rules/RBAC walk: a DENY stays deny, an ask stays ask, but an evaluator ALLOW matching a safety class is escalated to the ask flow regardless of the permission mode — including allow-all, auto, the built-in general/leader overrides, and a server admin ["*"] grant. The speculative classifier is suppressed for safety-class calls, so a classifier verdict can never collapse the ask. With no ask hook the result is false (fail closed).

ClassTriggers
dangerous_commandDangerDetector.analyze rates the shell command dangerous (execute tools: bash, execute_command, shell; code_exec code for any language)
secret_accessRead-tool path or shell token resolves to a credential/secret path (~/.ssh, ~/.aws, ~/.netrc, ~/.git-credentials, .env*, id_rsa/.pem/.key, ~/.luna/keys, …)
credential_writeWrite/edit/delete/redirect into a credential path, private key, env file, shell rc file (.bashrc, .zshrc, .profile, .gitconfig), or the project security-config files (.luna.json, .luna/settings.json, .luna/settings.local.json — the files carrying SECURITY_FAMILIES keys)
destructive_deleteA recursive + force rm (-rf, -fr, --recursive --force) outside the danger detector’s root/home patterns, or delete_file targeting / or the home directory

Sensitive path names are reused from core.sandbox.CREDENTIAL_READ_DENY_NAMES (the single-source credential list); project config paths correspond to core.repo_config_security.SECURITY_FAMILIES. Path matching is normalized (quotes/backslashes stripped, ~/$HOME expanded, duplicate slashes collapsed) and segment-anchored, so /tmp/fake.ssh/notes.txt is not a credential path.

Mode × class outcome (ASK means the ask hook runs; no hook ⇒ deny):

Mode / posturedangerous_commandsecret_accesscredential_writedestructive_delete
defaultASKASKASKASK
plan (read-only override)DENY (write/execute denied by the mode)ASKDENY (write denied)DENY (execute denied)
read-onlyDENYASKDENYDENY
allow-all (sandbox boundary present)ASKASKASKASK
deny-allDENYDENYDENYDENY
autoDENY (danger detector denies before the ask)ASKASKASK
server admin ["*"] / allow-all mode overrideASKASKASKASK

Safety-class decisions are never cached (permission_checker.check_cached re-evaluates any safety-class match), so a user “Always allow” answer cannot permanently bypass the class for the TTL window.

Permission-denial circuit breaker

tool_executor._dispatch_allowed — the one shared pre-dispatch funnel for the sequential, concurrent, and speculative paths — counts consecutive permission denials. A permission ALLOW resets the run. At the configured limit (permission_denial_limit, default 3, clamped 1..20) the breaker latches, emits an agent.diagnostic event (kind=permission_denial_limit, with count/limit/tool), and after the current tool batch the executor yields a typed terminal:

{ type = "turn_done", success = false, error = "permission_denial_limit",
  denials = N, limit = L, tool = "<last denied tool>" }

The denied tools still render their normal tool_done events first. The terminal rides the existing event contract (no new wire type); agent.ended is emitted through the shared terminal funnel. Agent:reset_permission_breaker clears the counter and latch, and every turn start calls it automatically, so the breaker never leaks across turns. _permission_denial_limit and _permission_breaker are per-agent fields — no process-global breaker state is shared between concurrent agents.

Editor proposal turns

A headless editor edit turn runs with --propose-edits (config.edit_proposals). The dispatch funnel refuses side effects before the permission walk, so no mode, classifier verdict, mode override, or server admin grant can widen it:

Tool classProposal-turn outcome
read/noneexecutes normally (workspace inspection)
write-classone validated tool_use proposal frame (the editor’s diff review contract); refused edit_proposal_unreviewed; no write
execute-class (bash, code_exec, task spawns, …)refused proposal_mode_denied; no proposal
safety-class write/execute (credential_write, secret_access, dangerous_command, destructive_delete)refused edit_proposal_refused; no proposal — a safety class never reaches the editor apply path
schema-invalid writerefused edit_proposal_invalid; no proposal

The editor applies a proposal only after :ZergAccept (diff review), with a stale-buffer check (changed tick + expected text + path identity) and a pre-apply snapshot (~/.luna/editor-snapshots/, plus a git blob when inside a worktree) that :ZergUndoEdit restores. The full contract lives in client/docs/vim-integration.md §.

When a ask is raised during an editor turn, the permission_request frame opens the editor confirm UI (Allow once / Always / Deny, default Deny) and the answer rides the correlated permission_reply line.

Permission ask round-trip

A permission ask is an operator decision, never a silent default. The worker emits a bounded ask (tool name + command/path summary + danger level/pattern labels — the raw tool input and its secrets never ride the wire, the registry, or the audit chain), Sol registers it in sol_permission_registry and pushes it to the chat session’s WebSocket (Limon PermissionPrompt). Only the ask OWNER or an admin (*) may decide; every decision (operator, timeout, client disconnect, task terminal) writes a STRICT audit row with a sha256 input_hash instead of input content. A 1..300s server timeout and the worker’s own local deadline both deny typed, and the worker’s 600s decision cache only persists an explicit always (one-shot allow/deny never replay).