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.

ZMQ Security Posture

Current State

Transport encryption: CURVE by default. ZMQ communication between Sol and Luna workers runs over the CURVE security model (ZMTP): the ROUTER (task plane) and PUB (event plane) sockets act as CURVE servers whenever the bind is non-loopback (zmq_curve_enabled=auto — the default; loopback binds keep the plaintext dev posture since nothing leaves the host). The server keypair is generated on first boot and persisted to <data_dir>/curve_server.cert (chumak_cert z85 format, mode 0600); workers provision the server’s PUBLIC key as LUNA_ZMQ_CURVE_SERVERKEY (or auto-discover the same-host keyfile). A non-loopback plaintext bind refuses boot in prod unless the operator explicitly acknowledges it (zmq_transport_plaintext_ack=true, CRITICAL-logged) or declares an encrypted tunnel (zmq_transport_tunnel=wireguard|mtls-sidecar) — one gate family for ROUTER + PUB. A curve-enabled node whose crypto backend is missing (a build where the chumak override was lost) also refuses boot — it never silently binds plaintext.

The CURVE crypto backend is nacerl (tweetnacl) — chumak’s own documented default, vendored as the self-hosted spacebeam/nacerl fork (branch zerg/main, pinned in server/rebar.lock; see the fork README.md for the full “what was fixed and why”). tweetnacl is the exact crypto libzmq itself vendors for CURVE, so both sides of a curve connection implement the identical NaCl construction. Zero system dependencies.

Registration authentication: per-worker enrollment keys. The shared fleet secret (SOL_ZMQ_WORKER_SECRET) remains supported during the legacy-compat window but the recommended posture is per-worker keys: the ready frame carries key_id, Sol verifies the HMAC with the named registry key (zmq_enrollment_keys, provisioned per worker — config map or SOL_ZMQ_ENROLLMENT_KEYS JSON), and refuses unknown/revoked keys. A registry entry bound to a specific worker_id refuses a ready claiming a different worker — a stolen key cannot re-register under a fresh identity. Registration-rate anomalies (default >60 registrations/min) fire a CRITICAL alarm (zmq_register_rate_anomaly_total); the anonymous/fleet-legacy bucket paces at max(zmq_register_rate_limit, zmq_worker_cap) so a cap-sized restart storm converges, while per-credential buckets keep the configured rate. The raw enrollment/local-mint secrets are held by the private sol_zmq_secret_store owner’s process state — the public ETS registries carry metadata only; a session key is re-derived from the store on a gateway restore.

Locally-spawned workers are first-class enrollment clients. With the compat window closed, a fleet-secret-only provisioning refuses EVERY registration — the live-fleet defect this closes (init-wkr-N was spawned with only the shared secret and heartbeated against fleet_secret_deprecated forever; sol_zmq_registered_workers stuck at 0). Now the spawn path (sol_worker:worker_env/1, used by sol_worker spawns and the gateway’s init-wkr-N) mints — or reuses — a per-worker enrollment key in the reserved local: namespace, bound to the exact worker id, and the worker env carries LUNA_ZMQ_KEY_ID + the minted secret INSTEAD of the shared fleet secret (least privilege: locally-spawned workers no longer hold the fleet-wide credential at all). The minted keys persist at <data_dir>/zmq_enrollment_local.json (0600, atomic tmp→rename; a corrupt store is moved aside and re-minted, CRITICAL-logged) so a Sol restart re-issues the same key to the same worker id. The local: id namespace is refused for operator-provisioned keys. The lever zmq_local_enrollment (default true; SOL_ZMQ_LOCAL_ENROLLMENT=false) restores the legacy env. A fleet secret set with NO other provisioning and local minting disabled is a knowably dead registration plane and refuses boot (zmq_registration_plane_dead; ack lever SOL_ZMQ_REGISTRATION_PLANE_ACK=true CRITICAL-banners instead); with minting enabled the same shape CRITICAL-banners that EXTERNAL fleet-secret workers cannot register and names the provisioning requirement (SOL_ZMQ_ENROLLMENT_KEYS). The compat window, when explicitly reopened, is bounded: SOL_ZMQ_FLEET_LEGACY_COMPAT_UNTIL (ISO YYYY-MM-DD) CRITICAL-banners with the remaining days and refuses (fleet_compat_window_expired) once past; its use is counted (sol_zmq_fleet_legacy_ready_total), paired with the labeled refusal family sol_zmq_registration_refused_total{reason="fleet_secret_deprecated"}. On the worker side, ANY registration refusal (registration_hmac_failed, with the enrollment reason in details) now de-registers and schedules the full-jitter re-ready instead of heartbeat-looping in a never-registered “connected” state.

All ZMQ traffic is therefore: Encrypted (CURVE) on every non-loopback bind by default; plaintext only with an explicit operator acknowledgement or declared tunnel Authenticated at registration (fleet secret or per-worker enrollment key, nonce-bound HMAC with replay protection) Protected against replay at the application level (nonce LRU with TTL + identity binding)

Message-level ownership enforcement. The transport gap is mitigated by per-message authorization on the Sol control plane:

result / token / error frames require the worker the task was dispatched to (sol_zmq_indexes task index) and current registration. On an index miss the gate answers from durable DATA, not from registration: only a registered sender whose identity equals the recorded executor (sol_task_store:get_last_executor/1, stamped at dispatch and re-stamped by the boot reconcile) rides the bounded post-restart grace, attributed <<"system">> and WARNING-logged. No recorded executor, or a foreign one, is refused and counted. The previous “currently registered sender” grace is DELETED — a registered worker can no longer claim an executor-less index miss. A forged frame from a never-registered DEALER is dropped, logged CRITICAL, and counted in sol_zmq_auth_failures_total (Prometheus). A registered worker cannot create synthetic “completed” tasks: writes for task ids with no ownership-index entry, no sol_task_results pending row and no dispatch-queue seat are rejected. Terminal states (ok/completed/cancelled/timeout) reject all later writes — a late worker result cannot resurrect a cancelled or timed-out task. event frames require a registered worker identity and the worker-emittable event namespace is closed: only telemetry.* and agent.* diagnostics are accepted. Core state events (task.*, workflow.*, team.*, scheduler.*, model.*) from ZMQ workers are dropped + counted — they are HTTP/internally sourced by definition. Caller-supplied user_uuid is stripped. spawn frames require the parent task to have been dispatched to the sending worker — closing cross-session RBAC inheritance via a forged parent_task_id. Child spawns also consume a license seat. acp, acp_reply and plugin_tool_call frames all require a registered sender; acp/acp_reply attribution always uses the socket-bound routing identity (frame-supplied from is discarded), and an acp_reply may only satisfy a request that was actually ZMQ-forwarded to that identity. : the ACP plane carries NO user principal — user_uuid is stripped at the handler and in the forward builder, and Luna’s idle agent always uses its per-connection anon:<worker_id> scope. A ZMQ acp_type=capability AgentId MUST equal the verified routing identity (agent_id_mismatch otherwise — no squatting a well-known name); every routed/delivered request refreshes the registry last_seen so a continuously used agent never expires; the legacy programmatic register/3 is guarded (same-pid refresh only; explicit register/4 overwrite). team_heartbeat / team_directive / team_mail require registration and team membership of the sender’s registered worker_id (server-side mapping); team_mail’s from is derived server-side; heartbeat liveness is recorded for the sender’s own member record, never the frame-supplied member_id.

All gates are behind zmq_ownership_enforced (default true; rollback via SOL_ZMQ_OWNERSHIP_ENFORCED=false).

Worker Registration

Enrollment keys: zmq_enrollment_keys configures #{KeyId => #{worker_id => WorkerId | "*", secret => Secret}}. A ready carrying key_id is verified against the named key (same HMAC material below); unknown, revoked (zmq_enrollment_revoked) or worker-mismatched keys are refused with a CRITICAL log + zmq_auth_failures_total. The "fleet-legacy" key name (or an absent key_id) selects the shared fleet secret while zmq_fleet_legacy_compat=true — **the compat window defaults CLOSED as of **; new installs provision enrollment keys.

Secret strength: every enrollment secret must be a binary of ≥ 16 bytes. A blank/<<>> or short secret is an INVALID entry: it is dropped from the normalized registry with a CRITICAL log and counted, and validate_configured_keys/0 refuses the boot ({invalid_enrollment_entries, N}) unless the explicit ack lever zmq_enrollment_allow_invalid downgrades it loudly. resolve_key/1 also enforces the floor at runtime (a short secret injected into the live table refuses typed with weak_secret), and the ready funnel sends the worker an error frame — the pre-fix shape accepted <<>>, then crashed session_key/1 inside the handler, leaving the worker knocking forever with no feedback.

Runtime revocation input: the revocation set is not restart-only even without the Mango bridge. From the operator remote shell / sol_console:

sol_zmq_enrollment:revoke_key(<<"worker-7">>).    %% immediate
sol_zmq_enrollment:unrevoke_key(<<"worker-7">>).  %% rollback

revoke_key/1 writes the authoritative ETS set that resolve_key/1 and key_active/1 read directly, so the next registration (and the gateway’s 10s liveness key sweep, which evicts live sessions of inactive keys)

Enrollment↔CURVE binding + provisioning surface. Enrollment records MAY carry the optional curve_pubkey field (40-char z85 or 64-char hex) — the operator-collected binding of worker ↔ CURVE client key per the amended key-distribution migration (plan/curve-key-distribution-migration.md, Option A′). A malformed value makes the entry invalid (dropped + counted; the boot refuses enrollment_keys_invalid unless zmq_enrollment_allow_invalid is set). Under A′ the flip posture keeps zmq_curve_clientkeys unset (any): CURVE supplies confidentiality + server authentication; per-worker authorization stays with the enrollment HMAC + identity binding + the per-frame MAC plane. The operator provisioning surface — everything a worker needs to connect — is one remote-shell call:

sol_zmq_curve:provisioning_info().
%% #{keyfile => ..., server_public_key_z85 => <<"...">>,
%%   curve_enabled => ..., bind_addr => ..., worker_env_hint => ...}

refuses immediately — no Mango resync tick, no restart. Config-file edits to zmq_enrollment_revoked still take effect on the ~60s resync (refresh_from_config/0) when the bridge is live, and on restart otherwise; a later refresh_from_config/0 re-reads config and can therefore re-add a config-listed key, so make a runtime revocation durable by removing the key from config too.

Credential rotation: DRAIN BEFORE ROTATING. A worker’s enrollment key may be rotated (revoke the old id, provision the new one) — but adoption across a reconnect requires SESSION-KEY CONTINUITY: the derived MAC key of the presented credential must equal the key recorded on the existing registration. A rotation performed while the worker has an in-flight task therefore refuses adoption and resolves that task as worker_reconnected (the error strategy decides retry vs terminal). Operational procedure: (1) stop accepting new work for the worker / let it drain (zerg status shows its in-flight task), (2) revoke the old key and provision the new one, (3) let the worker reconnect and re-READY. The rotation is visible: a verified re-registration under a different key_id bumps zmq_credential_rotation_inflight_total (ZMQ dashboard panel “Credential Refresh Refusals”; alert on an unexpected increase) and logs the old/new key ids. A fleet-legacy sentinel session (key_id = "fleet-legacy") stays active only while zmq_fleet_legacy_compat=true; the 10s key sweep reads the sentinel through that lever instead of treating it as a removed key.

When SOL_ZMQ_WORKER_SECRET (SOL_ZMQ_WORKER_SECRET env → binary via secret_val/1) is configured (≥ 16 bytes), every ready frame must carry a fresh nonce plus:

hmac = HMAC-SHA256(secret, nonce || u16(len(identity)) || identity
                            || u16(len(worker_id)) || worker_id
                            || u32(child_depth) || u64(ctr))

Field binding: the MAC covers the ROUTING identity (length-prefixed, before worker_id) + worker_id + child_depth — a captured ready frame cannot be re-signed-replayed against a different routing identity (a rogue DEALER replaying a captured frame under a victim’s identity fails the HMAC). Luna sets the DEALER identity to worker_id, so its builder emits the worker_id in both slots. Monotonic counter: the material ends with ctr, a u64 big-endian wall-clock millisecond counter that is strictly increasing per identity and freshness-bounded (10 min default, zmq_ready_ctr_max_age_ms). Sol refuses ctr <= last accepted (counter_replayed) and stale counters (counter_stale) independently of the nonce LRU — the LRU (kept as the hostile-churn DoS bound; the 1024-identity cap can no longer re-open a replay window) is no longer the replay defense. ** (WIRE-03):** the ctr freshness bounds are ONE clock domain with the frame-tx plane — 10 minutes in the past and the shared 24-hour FUTURE window. A ctr beyond the future window is refused without persisting; recovery from a worker-PERSISTED future floor is the signed sol_zmq_indexes:retire_identity/2 server reset plus a Luna restart with LUNA_RESET_REPLAY_WATERMARKS=1 (the idle reaper also drops absurd-future rows). A missing/non-integer ctr refuses with missing_counter; the explicit legacy-material lever is zmq_enrollment_ctr_required=false (mixed-fleet escape hatch — the legacy 4-arity material via registration_signed_material/4, nonce-LRU replay bound only). The canonical v2 builder is registration_signed_material/5. Freshness: Sol keeps a per-identity nonce LRU (last 64, records timestamped with a 60s TTL) — any replayed nonce is refused (nonce_replayed). The LRU survives gateway restarts via the index heir (node restarts lose it by design — it is the DoS bound, not the primary replay defense); identities are evicted when their worker is evicted and the table is size-capped (1024 identities, oldest-identity eviction). The monotonic ready-counter AND frame-tx watermarks are additionally journaled into the durable replay fence so they survive node restarts too; a READY-ctr admission fsyncs the journal before it returns. In-flight adoption proof: a duplicate-identity ready arriving while the record holds an active task is adopted ONLY when the ready was VERIFIED by any configured credential (the verification outcome — auth_class — is carried out of verify_worker_registration, never inferred from env presence) AND the frame names the exact task_id it resumes (matching the record’s current_task AND the ownership-index owner). Anything else falls back to the orphan path (task terminally errored with worker_reconnected) — an open-registration peer can no longer hijack an in-flight task by claiming the victim’s identity, and enrollment-only fleets no longer discard executed work on reconnect. Boot gate: prod + non-loopback zmq_bind_addr + empty zmq_worker_secret refuses boot ({refuse_boot, zmq_secret_required} — the same fail-closed pattern as the HTTP auth boundary). Loopback binds keep the open dev posture; non-prod external binds boot with a WARNING. The secret is provisioned by wild (SOL_ZMQ_WORKER_SECRET / LUNA_ZMQ_WORKER_SECRET on workers).

Loss Policy

The wire-level loss policy (critical-frame set, droppable classes, paused-gateway NACK behavior) is specified in the canonical wire reference — see the Loss Policy section of docs/zmq-protocol-reference.md. The security-relevant summary: only true diagnostics (telemetry.-prefixed event frames) and the abandoned-reply class (acp_reply, whose caller-side timeout governs) are ever shed; result/token/error (content), heartbeat (liveness) and the coordination frames (team_directive/team_mail/team_heartbeat/acp/ plugin_tool_call — ) are never dropped, and any frame a paused gateway still sheds is NACKed with an explicit error frame. : the acp_reply shed classification is now consistent across BOTH pause layers — sol_zmq_recv_dispatcher: droppable_under_load/2 explicitly sheds it too (the pre-fix shape forwarded it at the mailbox-HWM layer while the gateway’s paused gate shed it), and the boot drift check is bidirectional so the two layers and the shared manifest can never fork silently again.

PUB Plane PII

The PUB socket (5556) has no per-subscriber auth, so it carries correlation metadata only: task.created publishes task_id (never the prompt), task.completed publishes {task_id, status, tokens_used, workflow_id} (never result content), and session.message_pushed payloads are stripped of message bodies. Both encoder paths (the event-forwarder Path A and the sync-event-router Path B) produce the same canonical shape per topic.

The authoritative per-event transport matrix (store ingress, SSE, PUB-to-Luna Path A/B, Mango bridge) is generated in event-reference.md by ci/event_transport_matrix_gen.py; do not hand-copy event counts or per-topic rows into this doc.

: task.failed publishes error_code — a server-reason allowlist (task_timeout, worker_timeout, worker_reconnected, send_timeout, gateway_paused, cancelled); anything worker-supplied collapses to <<"worker_error">>. Worker free-text error strings (which embed prompt fragments and paths) are UNREACHABLE from the PUB plane. task.dispatched/task.started publish worker_hint — the 16-hex-char SHA-256 prefix of the worker id — instead of the raw worker_id: stable for ops correlation, non-invertible, not a routing key.

: the PUB scrub (sol_zmq_events:strip_pub_pii/1) is now a bounded recursive scrub (depth ≤ 4): the content keys plus config — a team config can embed provider API keys — and the known-sensitive subkey family (api_key, secret*, *token, password, credentials, private_key, bearer, authorization, cookie, hmac, mac_key, signing/encryption keys) are removed at every level, and the Path A generic team/workflow encoders run it too (the pre-fix top-level-only strip shipped team_created’s config map intact on one path). Nested opts maps are scrubbed as well; a planted-secret regression asserts the bytes never reach the encoded frame.

Per-Frame MAC Plane

The ROUTER routing identity is client-declared, so identity alone can never authenticate a frame. Every worker-plane frame (token, result, error, heartbeat, and — since then — team_directive, the recorded acceptance) and every frame on the extended agent/team plane (spawn, event, acp, acp_reply, team_heartbeat, team_mail — ) from a CREDENTIALED session carries a trailing multipart MAC frame:

DEALER multipart : [payload, mac_hex]
mac_hex          = hex(HMAC-SHA256(session_key, "Z3" || u16be(len(identity))
                                       || identity || u64be(tx) || payload_bytes))
session_key      = hex(HMAC-SHA256(credential_secret, "zerg-session-mac-v1"))
tx               = per-session monotonic frame counter (u64, max(last+1, epoch-ms))

The payload bytes are MAC’d verbatim (no canonical-encoding ambiguity); the routing identity — the one field NOT inside the payload — is bound in explicitly. session_key is the 64-char lowercase-hex STRING (both sides derive identically; Luna’s AgeCrypto.hmac_sha256_hex is byte-exact). The cross-language vector table docs/fixtures/zmq_frame_mac_vectors.json pins the material + MAC bytes across both languages (server/test/sol_zmq_frame_mac_vector_tests.erl + client/tests/test_zmq_frame_mac.lua). Material v3: the per-session tx counter is bound INTO the MAC material and stamped on the frame as the additive msgpack key tx (no multipart shape change). Sol enforces strict monotonicity per identity (sol_zmq_indexes:frame_tx_ok — an identity-lifetime tombstone that eviction NEVER purges within the node, and which the durable replay fence below persists across node restarts — one journal append per accepted frame plus the 256-record snapshot cadence): a replayed frame fails {refuse, replayed_tx} and bumps sol_zmq_frame_mac_replay_total. This closes the replay defense the material had none of — captured heartbeat/spawn/ team_directive frames no longer replay cleanly. Worker plane + the new planes moved together in the ONE material bump. Durable replay fence: both watermark stores (sol_zmq_frame_tx and sol_zmq_ready_ctr) are memory-only ETS with the index heir — they survive a gateway restart but NOT a node restart. They are persisted by <data_dir>/zmq_replay_fence.term (full snapshot — sol_durable_file tmp→fsync→rename, mode 0600, one atomic write per 256 recorded watermarks OR 5s) plus an append journal (zmq_replay_fence.journal): every accepted watermark row is appended (one write syscall, no per-frame fsync) before the frame is dispatched, and a READY-ctr admission fsyncs the journal before it returns (one fsync per accepted READY, which also commits every earlier tx append). The snapshot flush rotates the journal (journal → journal.prev); boot (sol_zmq_replay_fence:load/0) MAX-merges snapshot + both journal generations and compacts them back into the snapshot before the transport tail accepts frames. A captured frame or READY replayed after a node restart therefore still fails replayed_tx / counter_replayed. A journal append/sync failure REFUSES the frame/READY fail-closed (typed refusal; a READY advances no ETS row, a tx CAS may already have advanced in memory but the frame is still refused) and bumps sol_zmq_fence_journal_write_failed_total (paged by SolZmqLossCounters) — a frame is never admitted with an unrecorded watermark. The snapshot-cadence check runs on the next recorded watermark, NOT on a timer: a POWER/OS loss therefore loses at most the last ≤256 un-fsynced tx rows since the last snapshot flush — wall-time unbounded if the fleet goes idle below the 256-record threshold (READY rows are always fsynced, so they never sit in that tail). A process/VM death (kill -9) loses no accepted row. Of the affected classes, a replayed result/token is neutralized downstream — settlement settle_once, the token seq-gap detector and the per-attempt gates make the replayed work exactly-once; the sharpest leg was a stale ready re-registration for an OFFLINE worker (re-registering a captured READY), which the READY fsync closes. The signed identity-retire operation either purges the snapshot+journal (when it owns the journal handle) or fsyncs an ordered {retire, Identity} tombstone that boot applies after the snapshot and earlier journal frames; if NEITHER artifact can be written the retire returns {error, {fence_purge_failed, _}} instead of claiming a durable reset. The v1 legacy-material READY (zmq_enrollment_ctr_required=false) has no counter plane and remains nonce-LRU-bound only (node-lifetime) — the lever is the documented mixed-fleet escape hatch, not the default. A missing/corrupt fence file is CRITICAL-logged and moved aside, and the READY ctr freshness bound (10 min) keeps refusing stale READYs independently. Luna send-side fail-closed: a credentialed session NEVER sends a worker-plane frame bare. If the per-frame MAC cannot be computed (frame_mac_v3 → nil: a crypto-backend failure after the session key was derived), Luna refuses the send with a typed frame_mac_unavailable (critical frames stay in the retransmit lane); the pre-fix shape fell through to the anonymous single-frame send, silently re-opening the unsigned class under prefer/legacy windows. The Luna decoder also enforces Sol’s structural budget (65536 elements / 64 containers) and refuses trailing bytes (WIRE-08) — both ends now agree on the exact-consumption + budget contract. Worker event aggregate truth: agent.child_completed is emitted with the SERVER child task id (the client-local background id rides as client_task_id). A child executed by a different worker than its parent is accepted through the server-recorded child→parent relationship when the sender owns the parent; legacy client-local ids are re-stamped to the verified parent. A legitimate child no longer trips SolZmqAuthFailures. Sol→Luna direction — the documented asymmetry (, B3-): the MAC + tx replay binding above covers the worker→Sol direction only. Outbound Sol→Luna frames carry the skew-aware v stamp and ride the CURVE-pinned pipe, but they carry No per-frame MAC and no freshness/nonce/replay binding. An adversary who can record and re-deliver outbound frames — control of the pinned transport, the loopback plaintext posture, or the null mechanism — can replay task/lane_control/cancel_task frames at Luna. The blast radius is bounded by Luna-side idempotency, not cryptography: the pending-task queue is keyed by task_id and the highest attempt wins (an equal/lower redelivery is a duplicate), an already-terminal task is not re-executed (terminal journal/spool), and the lane-control plane is holder/lease-gated (stale_grant / lease_lane_mismatch refusals). The residual is a replayed coordination frame whose effect is not task-keyed (e.g. a duplicate lane start/stop against a still-live lease); the transport trust boundary (CURVE pin + the plaintext refusal gates) is the defense. Closing the asymmetry needs a Luna-side inbound nonce/epoch accepted on the solver→worker plane — tracked by the B4 successor rows, never silently implied by the worker-plane MAC. Fleet-legacy window (, — the legacy-decay pattern): lever zmq_frame_mac_legacy, default OPEN at, CUTOVER SHIPPED in (default false — the window is CLOSED; sys.prod.config pins it explicitly). While it was open: missing MACs on the extended set were accepted + counted into sol_zmq_frame_mac_legacy_total, and a tx-less v2 MAC ("Z1" material) verified under the window. CLOSED posture: missing MACs on the extended set and v2 (tx-less) MACs REFUSE under zmq_frame_mac=required (rollback lever = flip the config to true). A PRESENT but invalid MAC is refused in every posture. ** straggler window (,; CUTOVER, SEV1 SOLZMQ-01):** the completion added cancel_task and plugin_tool_call (plus plugin_tool_result, later retired inbound with /) to the MAC plane AFTER the cutover had closed the window — with NO window and NO pairing note, so required silently began refusing the UNSIGNED versions of those frames from every Luna whose send side predates. These types are worker→Sol CONTROL traffic: a refused cancel_task strands the child running, a refused plugin_tool_call breaks every plugin tool on the lagging worker. Opened a TYPE-SCOPED window (lever zmq_frame_mac_d1542_legacy, formerly default OPEN) under which a missing MAC on exactly the completion types was accepted + counted into sol_zmq_frame_mac_straggler_total (a PRESENT but invalid MAC was still refused). ** CLOSED the window: the default is now false.** A missing MAC on ANY plane type refuses under required; the straggler counter must sit at ZERO in a healthy fleet. The SEV1 SOLZMQ-01 chain the window left open: a peer presenting a registered identity (client-declared, and duplicate arbitration is not instantaneous) could send UNSIGNED plugin tool calls executed under the victim task’s stored grant, or cancel a victim’s children. Rollback is the EXPLICIT config lever ({zmq_frame_mac_d1542_legacy, true}) — no silent default. The mixed-fleet matrix (every plane class × every posture, counters included) is pinned by server/test/sol_zmq_frame_mac_set_tests.erl (mixed_fleet_matrix_test_); the credentialed real-wire drill is server/test/sol_zmq_credentialed_wire_SUITE.erl. ** ** the reference Python worker (example/python/zmq_worker.py, WORKER_PLANE_TYPES) is machine-checked against the same fixture (worker_plane ∪ extended_plane) by ci/wire_doc_parity_lint.py — a worker extended from the example signs every current plane type (the pre-fix set omitted lane_control/cancel_task/plugin_tool_call, so those frames refused missing_mac; the / retirement of the worker→Sol log/plugin_tool_result frames shrank the set). Sol verifies the MAC in the frame router BEFORE any handler runs; a refusal drops the frame + bumps zmq_frame_mac_missing_total / zmq_frame_mac_failures_total / zmq_auth_failures_total. The mac gate itself is crash-wrapped — one malformed frame cannot take the gateway down. : the gate is fail-CLOSED for a credentialed record whose session key is missing or non-binary ({refuse, session_key_missing}; the pre-fix shape fell into the “no session key” arm and skipped verification), and the no-wire gateway arities dispatch_zmq_async/3 + /4 are DELETED — every in-process frame now carries its wire metadata, so no direct caller can bypass the gate. : the frame router’s legacy no-wire dispatch_zmq/4 and /5 arities are now -ifdef(TEST) (test-build only); a production compile exports ONLY the wire-carrying dispatch_zmq/6. The prefer/off levers below are unchanged. Per-pipe registration binding: the vendored chumak patch surfaces the DELIVERING pipe pid (recv_multipart_with_pipe/1 → {ok, Multipart, PipePid}); an ACCEPTED ready BINDS its routing identity to that pipe and every later frame for the identity arriving on a DIFFERENT pipe is dropped + counted (zmq_pipe_binding_drop_total) before any handler runs (sol_zmq_pipe_binding:allow/4). This is a second, transport-level binding next to the CURVE identity pin. LEGACY POSTURE (documented): a worker record without a bound pipe (restored registers, pre-upgrade rows, pipe-less test surfaces) and unregistered identities stay ALLOWED — the binding strengthens the live path, it never retro-drops a fleet. ready re-binds on every accepted registration (the identity arbitration owns duplicate claims). Registration HMAC ordering: the fleet-secret READY path now verifies the HMAC BEFORE consulting nonce_seen/ready_counter_ok (mirroring the enrollment path) — an unauthenticated peer can no longer probe or consume the replay stores; the identity binding runs after consumption, exactly like enrollment. Mode lever zmq_frame_mac: required (default — a credentialed session’s worker-plane frame without a valid MAC is refused; extended set governed by the legacy window above), prefer (verify when present, count missing — closed the silent pass; the mixed-fleet window is observable), off (rollback lever). Anonymous sessions (no credential configured — loopback dev posture) stay MAC-optional. The owner-match leg of the ownership gate additionally requires CURRENT registration (sol_zmq_ownership:allow_result_frame/4). Duplicate routing identities at the transport floor (identity pinning, ): the vendored chumak detects a second DEALER declaring a live identity and notifies Sol with the NEWCOMER pipe’s pid. The registration is PINNED to the CURVE peer key captured at READY (chumak:peer_public_key/2 — stored on the #worker{} record and in the sender’s pinned map). Conflict policy, in order:

  1. Pinned + the newcomer’s pipe key matches the pin (constant-time) the newcomer provably speaks for the SAME host (completing a CURVE handshake with a public key requires the private key): legit reconnect. The stale incumbent pipes are evicted, the registration stays, and the newcomer’s READY rides the adoption gate. Proof beats the temp ban.
  2. Pinned + mismatch (or the newcomer presents no key) — the UNPROVEN newcomer pipe alone is evicted; the victim’s registration, pipe and in-flight task are untouched. The knock loop (one connect per knock, unauthenticated) no longer evicts anyone but its own pipe.
  3. No pin (unregistered identity, CURVE off / null mechanism, or a pre-pin registration) — the fail-closed evict-BOTH fallback registration dies, the in-flight task orphans through error_strategy, all pipes disconnect (zmq_identity_conflict_total alarm). Knock-loop bound: every conflict is recorded per identity into a 60s window; at 10 conflicts the identity is TEMP-BANNED for 300s — further unproven conflicts land a CRITICAL + the existing zmq_register_rate_anomaly_total anomaly alarm + sol_zmq_identity_conflict_banned_total, and the offender’s future connects are evicted on sight. A key-matching reconnect is exempt (proof beats the ban). A registered victim’s egress is restored by the bounded heal above; only a continued knock storm can extend the aggregate refusal window (never the 60s ledger per knock). : the sender now CONSULTS identity_banned/1 (sol_zmq_sender:arbitrate_decision/4) — a banned identity’s unproven newcomer is evicted ALONE instead of the evict-BOTH fallback (the pre-fix shape let every knock on a banned identity still evict the victim’s registration; the doc claim was unimplemented code-side). The pinned-key clause is evaluated first, so the key-matching reconnect exemption is preserved. Residual (honest): under the acknowledged plaintext posture (zmq_curve_enabled=false / loopback, or zmq_curve_clientkeys=any with null-mechanism peers), there is no peer key to pin: step 3’s evict-BOTH applies and a knock still evicts a victim that is itself unproven. The documented mitigations remain zmq_curve_clientkeys allowlists (a knock’s handshake then fails before the identity layer), firewalling the ZMQ port, and CURVE-on — identity pinning is the identity-layer bound, not a transport-floor ACL. (With the ban consultation, once the knock loop crosses the threshold the victim registration survives.) Egress TTL: a duplicate-identity knock makes the sender cache {refuse, unverified_conflict} BEFORE arbitration (so the next send cannot round-robin onto a competing pipe). On an evict_newcomer verdict where the registered victim survives, that cached refusal is now CLEARED after a bounded 250 ms settle window (?EGRESS_HEAL_MS): new sends to the victim egress again 250 ms after the attacker pipe is closed instead of remaining blacked out for the full 60s conflict ledger. The settle window keeps the transport’s eviction/reconnect visibility from racing the heal. Sustained knocks (review fix): once a heal is GRANTED for a registered victim, later knocks inside the ledger window keep egress open while the single-pipe proof holds — CURVE: exactly one live peer key on the registered pipe; plaintext/null mechanism: the registered pipe is alive (chumak omits unsigned pipes, so there is no pid to enumerate). The gateway’s post-eviction reconcile consults the SAME grant + proof before unpinning, so a >=4 conns/s knock loop cannot sustain a blackout. A registration eviction prunes the grant. The 60s window still exists and still rate-limits/bans repeated knocks; it no longer blacks out a registered victim’s new dispatch. In-flight work was never affected. CURVE-with-pin reconnects keep the adopt_newcomer heal (window/ban cleared, stale incumbents evicted). Pre-auth frame bucket: unregistered heartbeats spend a per-delivering-pipe + global 60s bucket (zmq_preauth_pipe_limit default 20, zmq_preauth_global_limit default 2000) before any ready_required control reply. A dropped frame is counted on zmq_preauth_heartbeat_dropped_total and never reaches the sender’s per-identity budget map; the sender’s control-budget drop log is rate-limited. Client-key fail-closed: the allowlist no longer fails open. zmq_curve_clientkeys=any is the documented confidentiality-only form and means UNRESTRICTED; ANY configured list must decode entry-for-entry, otherwise the bind is REFUSED with a typed error (curve_clientkeys_empty, curve_clientkeys_undecodable, curve_clientkeys_shape) — a typo can neither silently drop an allowed key nor silently become any. Every security-relevant set_socket_option return is checked and a rejected option refuses the bind (the ROUTER/PUB init stops rather than binding with the allowlist absent). Proven-reconnect exemption: the conflict window/ban counts UNPROVEN pipes only. A duplicate identity whose newcomer presents the pinned CURVE key (only the same host holds that private key) is a legitimate reconnect: it is not recorded, and any active temp ban + window is CLEARED so the verified re-READY is admitted. The pre-fix shape counted legitimate reconnects, so a flapping worker self-banned after 10 reconnects inside 60s.

Team-Mail Content Signatures

Every team_mail_push to a credentialed session carries a mail-integrity stamp keyed with the RECIPIENT’s derived session key. Luna verifies it BEFORE injecting the mail into agent context; a missing/mismatched stamp QUARANTINES the mail (counted, never delivered to a box).

V1 envelope stamp (hmac) — HMAC-SHA256(session_key, 'zerg-team-mail-v1' || u16be(team_id) || u16be(from_id) || u16be(to_worker_id) || u16be(recipient routing identity)) (sol_zmq_frame_mac:mail_hmac/5). Binds WHERE the mail came from, not what it says. V2 content stamp (hmac2, hmac_v=2) — frame_mac(identity, 'zerg-team-mail-v2' || u16be(team_id) || u16be(from_kind) || u16be(from_id) || u16be(to_worker_id) || u16be(recipient routing identity) || u16be(priority) || u16be(timestamp) || u16be(subject) || u16be(sha256(canonical-JSON body))) (sol_zmq_frame_mac:mail_v2_material/9, mail_hmac_v2/10). canonical-JSON is OTP json:encode field-value form (sorted object keys, no whitespace, shortest float form; the current server atom fallback hashes a JSON null as the STRING "null").

Verification rule on Luna (client/core/zmq_team_plane.lua + client/core/team_mail_hmac.lua): hmac_v present → it MUST be 2 and hmac2 MUST verify over the full content material (body/priority/timestamp/ subject included); a wrong/unknown version or a malformed frame is refused. hmac_v absent → the v1 envelope stamp is verified (the documented One-window compatibility posture). The v2 tamper battery lives in client/tests/test_team_plane_hmac.lua; the cross-language vectors are docs/fixtures/team_plane_hmac_vectors.json (mail_v2, mail_v2_canonical, mail_v2_wire).

Documented window residual: while v1-only frames are still accepted, an on-path attacker who can STRIP hmac_v/hmac2 can downgrade a captured push to the v1 envelope check, so a body-only mutation would verify. The TRANSPORT PRECONDITION is explicit: this requires the attacker to modify a Sol→Luna frame in transit, and there is no per-frame MAC on the Sol→Luna direction (the frame-MAC plane is Luna→Sol only; client/core/zmq_worker.lua records the deliberate posture). In a supported deployment the direction is protected by the CURVE transport handshake (or a tunnel); a plaintext non-loopback posture is refused without an explicit dev-only ack. So payload modification is impossible under CURVE, and the downgrade is directly exploitable only in the acknowledged plaintext/dev postures. Impact is bounded to arbitrary content in the RECIPIENT’s mailbox marked hmac_ok=true (prompt-injection grade) — the downgrade cannot retarget another recipient or sender, because v1 still binds {team, from, to} + the recipient routing identity.

Close condition (machine-checkable): Sol’s v2 sender is present on every configured node AND a measured fleet window shows zero v1-window deliveries (_mail_v1_window_deliveries on the worker; a v1 deliver is counted, a v2 deliver is not) → set LUNA_TEAM_MAIL_V2_ONLY=1 fleet-wide. That lever refuses any push without hmac_v; the client test flips the compat-window leg to quarantine under it. The dated owner/check obligation is the `` row in plan/residual-register-v0856.md.

Canonical fail-closed edges: the v2 body hash is wire-type-stable for the shapes OTP’s json:encode can sign — empty array/object, float vs integer, -0.0, an explicit JSON null (as a value, an array element and an object value), 2^53 (both integer and float), the subnormal/top-range float forms, and the fixed/scientific cut. The typed decoder (MessagePack.unpack_typed) carries the pre-msgpack distinction and docs/fixtures/team_plane_hmac_vectors.json (mail_v2_wire) pins every row with a FULL server-signed frame consumed by BOTH ends. Remaining edges are availability-only, never admission bypasses: an integer beyond 2^53: the NORMAL decode refuses the frame (LuaJIT doubles cannot represent it exactly); the TYPED decode verifies the server signature and the sanitized delivery carries the exact decimal string Only for the unrepresentable value. An exactly-representable integer in the SAME body (even when encoded as msgpack uint64) is converted back to a Lua number, so one large integer cannot stringify the rest of the body (; the mixed_int_recovery fixture row pins both delivered types). an explicit null OBJECT VALUE / array element: verified typed; the delivered Lua table cannot carry a null value (a map value is dropped, an array element is a hole) — the signature still bound the exact bytes. non-finite (inf/NaN) or invalid-UTF-8 bodies: not producible by the server’s JSON signer; the typed canonicalization refuses them typed. a body key literally equal to the wire-tag key (\0msgpack_wire) could only ever cause a canonical mismatch (quarantine), never an admission. an untagged canonical gives the integer form for an integral number; the typed path is what makes 1.0/-0.0 exact — both ends consume the fixture, and a mismatch fails CLOSED (quarantine).

Mango→Sol Event Channel Authentication

The Mango→Sol cache-invalidation channel (sol_mango_zmq_bridge SUB ↔ Mango PUB) previously subscribed to all topics with no signature/HMAC/CURVE/ZAP — any host that could TCP-connect to Mango’s PUB socket could publish a forged token.revoked/user.updated, forcing cache flushes (idempotent-safe, so DoS-flavor rather than privilege escalation).

** fix:** Mango signs every PUB frame with an HMAC-SHA256 over the canonical v2 material (same pattern Mango already uses for audit-archive ingestion, audit_archive.py). Sol verifies the signature with a constant-time compare before forwarding the event:

Wire format (v2, contract; Mango sender cutover ): 5-part multipart [Type, Payload, Nonce, Ts, Sig] with

Material = u16be(len(Type)) || Type || Nonce || Ts || Payload
Sig      = hex(HMAC-SHA256(Secret, Material))   (64-char lowercase hex;
                                                  Sol also accepts raw 32)
Nonce    = 32 lowercase hex ASCII (16 random bytes)
Ts       = ASCII decimal of wall-clock MILLISECONDS

Freshness: |now − Ts| ≤ zmq_bridge_ts_window_ms (default 120000, inclusive both directions; Mango’s knob is MANGO_BRIDGE_TS_WINDOW_MS MUST match Sol’s, a mismatch silently refuses legitimate frames). Replay: a nonce already seen in sol_bridge_nonce_lru is refused (nonce_replay). : the seen-set is durable — every accepted nonce is appended + fsynced to <data_dir>/mango_bridge_nonce.journal BEFORE the event is forwarded, and start_bridge loads/compacts it before the socket admits, so a captured HMAC-valid frame replayed within the ts window after a NODE restart is refused (the signed material carries no seq; the journal is the durable floor). A journal write failure fails CLOSED (the frame is refused, no reservation is left behind). Mango signs at enqueue and re-signs at drain with a FRESH nonce AND fresh ts — a re-sign with the original nonce would replay at Sol’s LRU, and keeping the original ts would age a ring-buffered frame past the window (Sol refuses those and ticks zmq_bridge_ts_stale_total). The shared vector table docs/fixtures/bridge_hmac_vectors.json pins the bytes across both languages (mango/test/test_bridge_hmac_vectors.py + server/test/sol_bridge_hmac_vector_tests.erl). Legacy cutover: Mango NO LONGER SENDS the legacy 3-part type‖payload material — the sender cutover is one-way, and its inbound leg now requires v2 as well. Sol’s counted legacy-accept clause was **REMOVED in **: any 3-part frame is DROPPED (never forwarded, signature irrelevant) and bumps zmq_bridge_legacy_hmac_total — the counter’s meaning flipped from “counted accept” to straggler observation, and it must sit at zero in a healthy fleet. A straggler count means a sender is still previous and must be upgraded. The 2-part unsigned shape stays deliverable only in the acknowledged no-secret posture (below). Secret: Mango reads MANGO_BRIDGE_HMAC_SECRET (or mango_bridge_hmac_secret config); Sol reads SOL_MANGO_BRIDGE_SECRET (or mango_bridge_hmac_secret app env). They MUST match. Fail-closed posture: **** boot-refuses any Mango bridge socket without MANGO_BRIDGE_HMAC_SECRET, _verify_inbound rejects unsigned frames, and Sol boot-refuses a configured mango_pub_url without its secret (ack lever: zmq_bridge_allow_unsigned). : Mango’s sign path also fails closed — a secret-less _sign_v2 raises, so a misconfigured transport can never emit frames. The PULL (Sol→Mango) inbound leg remains on its older wire shape deliberately: it has no Sol counterpart sender ( — Sol does not publish to Mango).

See server/src/sol_mango_zmq_bridge.erl (verify + drop) and mango/mango/events/zmq_transport.py (sign).

Revocation propagation

token.revoked events are PUB-broadcast; events lost during Sol downtime are re-pulled from Mango’s revocation ring (GET /auth/revocations? since_epoch=N — {epoch, entries:[user_uuid], oldest_epoch}; oldest_epoch is the versioned field: the oldest epoch the ring can still answer, null when empty). The pull is Bearer-authenticated and authorized: the service token needs revocations:read, the bare * admin binding, or the uuid on MANGO_REVOCATIONS_READ_USERS; a zero-permission service token answers 403 (least privilege — the shape let any service token enumerate the revoked-UUID oracle). The bridge resyncs on (re)connect and on a periodic cadence (zmq_mango_resync_ms, default 60s) and applies the entries idempotently (the same action as a live token.revoked), advancing its epoch only on success.

Wrap-gap invariant: the ring serves only the last RING_SIZE (1024) entries. If Sol’s watermark fell further behind than the ring can answer — detected via oldest_epoch (watermark + 1 < oldest answerable) with an arithmetic fallback for older Mango responses (NewEpoch − Epoch > len(entries)), — the resync escalates: every Sol-side auth cache is flushed (the one-time repair covering the dropped window), the ring epoch is ADOPTED, and the event is CRITICAL-logged + counted (sol_zmq_bridge_resync_gap_total, the SolZmqResyncGap alert). A watermark REGRESSION (Mango restart behind a journaled ring —, ) keeps its separate full-flush-and-resync-from-0 path.

Non-revocation auth events: role/team/user change events ride lossy PUB/SUB only — a bridge disconnect delays a privilege change to the per-user cache TTL. Bounded by the reconnect resync, the per-user cache TTL, and auth_flush_on_reconnect (Sol, Default true since then -: one full auth-cache flush per bridge reconnect, so a DEMOTION made during an outage lands within the reconnect window; an explicit false restores the previous costed posture). The generic ?since= auth-event journal (the revocation-journal pattern generalized) stays the tracked successor if the flush cost proves operationally painful.

: the ring is durably journaled. Every revocation path (logout, mass revoke, self-service password change, admin password reset, user delete) appends to the append-only revocation_journal table INSIDE its revocation transaction, and Mango’s boot reloads MAX(epoch) + the last RING_SIZE rows before serving (a reload failure refuses boot — a silent empty ring would make every pre-restart revocation unreplayable while Sol trusts the watermark). A Mango restart no longer resets the ring; Sol’s epoch-regression full-flush fallback stays as the last resort. The revoke-all legs (password mutations, user deletion) additionally emit token.revoked live (byte-identical to logout’s shape) and journal the revocation, so a Sol that missed the PUB replays it within one resync tick.

Justification (Air-Gapped)

In the project’s primary deployment model:

  1. Same-host deployment: Sol and Luna workers run on the same physical host (wild blueprint: runit + podman on the operator’s hardware)
  2. Private network isolation: ZMQ ports (5555 ROUTER, 5556 PUB) bind to the private podman bridge network, not exposed to the host interface
  3. No cross-network ZMQ: All ZMQ traffic stays within the operator’s private network (podman bridge / LAN)

Under these conditions: Network-level access is controlled by podman’s network isolation An attacker who can reach the ZMQ port already has breached the podman network Loopback binds keep the plaintext dev posture (nothing leaves the host)

: cross-network ZMQ now defaults to CURVE-encrypted — the boot gate refuses an unencrypted non-loopback bind unless the operator explicitly acknowledges plaintext or declares an encrypted tunnel. The message-level gates above close the residual in-network threats (a compromised worker or a peer on a non-loopback bind forging frames into other users’ sessions).

Operational Requirements

When deploying ZMQ across network boundaries:

  1. Distribute the CURVE server key — the server public key lives in <data_dir>/curve_server.cert (the public-key line, z85); workers set LUNA_ZMQ_CURVE_SERVERKEY to it (same-host workers auto-discover the keyfile). Provision per-worker enrollment keys (zmq_enrollment_keys/SOL_ZMQ_ENROLLMENT_KEYS + LUNA_ZMQ_KEY_ID) rather than the shared fleet secret.
  2. Restrict client keys — zmq_curve_clientkeys (Z85 list) restricts WHICH clients can complete the handshake (the ZAP-equivalent authorization); default any provides confidentiality only.
  3. Firewall rules — restrict ZMQ port access to known Luna worker IP ranges (defense in depth).

Transport posture config reference

ConfigDefaultMeaning
zmq_curve_enabledautoauto = CURVE on when the bind is non-loopback; true = always; false = never
zmq_curve_secretkey—Server key (Z85 or 32-byte binary); unset → generated + persisted to zmq_curve_keyfile
zmq_curve_keyfile<data_dir>/curve_server.certchumak_cert-format keypair file (z85), mode 0600, gitignored
zmq_curve_clientkeysanyAllowed client public keys (Z85 list). any = unrestricted (confidentiality only); a CONFIGURED list must decode entry-for-entry or the bind REFUSES
zmq_transport_plaintext_ackfalseOperator acknowledgement for non-loopback plaintext (CRITICAL-logged)
zmq_transport_tunnel""Declared encrypted tunnel (wireguard/mtls-sidecar) — satisfies the posture
zmq_enrollment_keys#{}Per-worker keys: #{KeyId => #{worker_id, secret}} (config map or SOL_ZMQ_ENROLLMENT_KEYS JSON); secret ≥ 16 bytes or the boot refuses
zmq_enrollment_revoked[]Revoked key ids (or SOL_ZMQ_ENROLLMENT_REVOKED, comma-separated); runtime add/remove via sol_zmq_enrollment:revoke_key/1 / unrevoke_key/1
zmq_fleet_legacy_compatfalseFleet-secret registration window (deprecation 2026-11-01)
zmq_register_rate_limit60Successful registrations/min before the anomaly alarm fires
zmq_frame_mac_legacyfalseFleet-legacy window for the extended agent/team MAC plane + the v2 (tx-less) material — missing/v2 legs REFUSE while closed; true is the recorded rollback lever
zmq_frame_mac_d1542_legacyfalseType-scoped window for the completion types: while true, required accepts + counts missing MACs on exactly those two types; missing MACs on every other type REFUSE. Rollback lever only — the default is fail-closed

Implementation

See server/src/sol_zmq_sender.erl for the ROUTER socket setup (CURVE server options from sol_zmq_curve:socket_opts/0) and client/core/zmq_worker.lua for the DEALER socket connection (CURVE client options + registration posture). Ownership gates live in server/src/sol_zmq_ownership.erl (gate helpers incl. allow_result_frame/4), server/src/sol_zmq_handler_worker.erl (registration HMAC + enrollment keys + result/token/error + adoption proof), server/src/sol_zmq_handler_agent.erl (event allowlist / acp / plugin frames), server/src/sol_zmq_handler_team.erl (team frame gates), and server/src/sol_zmq_bg_task.erl (spawn parent binding + seat gate). The per-pipe registration binding lives in sol_zmq_pipe_binding.erl (the frame router consults it pre-handler; chumak:recv_multipart_with_pipe/1 is the vendored transport surface); the durable replay fence in sol_zmq_replay_fence.erl (loaded by sol_zmq_indexes:ensure_tables/1). The boot refusals live in sol_app:zmq_auth_boundary/0 + sol_app:mango_auth_boundary/0 + sol_app:http_plaintext_boundary/0 (the HTTP plaintext mirror); the loss policy in sol_zmq_recv_dispatcher (droppable_under_load/1 / is_critical_type/1); the PUB-plane canonical shapes in sol_zmq_events.erl.

Execute-grade authority stamp: the legacy_write_implies_execute lever was independently configured on both sides of the wire; the task frame now carries Sol’s EFFECTIVE value (additive key) and Luna applies min(Sol, Luna) at its no-escalation clamp, so a split config (Sol off / Luna on) can no longer let a bare :write grant authorize allow-all/auto on the worker. The field is registered in ci/wire_field_provenance_lint.py.

Ownership matrix & index lifecycle

The result/token/error matrix is the code’s decision table in sol_zmq_ownership:allow_result_frame/4 (all rows gated by zmq_ownership_enforced). The decisive split is index hit vs index miss; on a miss the eligible sender is derived from the recorded executor, never from registration alone. The previous “currently registered sender” grace has no row and no code path:

Index stateEligible senderCode branch / note
Owner identity matches sender, sender registeredyestask_sender/2 {ok, Identity} + is_registered/2
Owner identity matches sender, sender not registerednoowner-match leg requires current registration → auth_failure/3
<<"queued">> sentinel rownone{error, queued_task}; a queue seat has no eligible sender
Index miss, sender unregisterednois_registered/2 false → auth_failure/3 (a never-registered DEALER can never forge a predictable id)
Index miss, sender registered, recorded executor == senderyes (WARNING)sol_task_store:get_last_executor/1 match → bounded post-restart grace, attributed <<"system">>; the synthetic-task guard still applies
Index miss, sender registered, no recorded executorno_ -> refusal + auth_failure/3
Index miss, sender registered, foreign recorded executorno (CRITICAL)mismatch arm: “grace-leg rewrite rejected” + auth_failure/3

The ownership-index sweep is liveness-aware: ?TASK_TTL_MS (1h) means “idle 1h”. Heartbeat and accepted result/token/error frames refresh the row timestamp (sol_zmq_indexes:touch_task/1); the sweep deletes only rows that are older than the TTL AND not a busy worker’s current task AND not queued AND not store-pending. An unreachable gateway suspends the sweep (retention-fail-safe). Boot reconcile repopulates the index for every outstanding dispatch receipt inside gateway init — before the transport tail accepts a single worker frame — and re-stamps the receipt’s executor snapshot into the requeued task row. The warning-grace row above therefore only fires for a matching recorded executor; an outbox-known task with no matching executor is refused, not waved through.

The zmq-<ms>-<counter> task-id namespace is server-reserved ({error, reserved_task_id} for caller-supplied collisions); the registration HMAC binds nonce || identity || worker_id || child_depth || u64(ctr).

Caller-supplied task-id collision gate: ANY caller-supplied id already present in the ownership index, the task store (pending OR terminal) or the dispatch queue refuses with the typed {error, task_id_in_use} + sol_zmq_task_id_in_use_total — the pre-fix shape only guarded the zmq- prefix, so a caller id colliding with another user’s live/queued/terminal task overwrote the ownership-index row and the queue/pending state (user A’s results resolving to user B’s ownership). The check runs inside the single gateway dispatch writer, so of two concurrent duplicates exactly one wins; the original ownership stays intact in every case.

Frame bounds: the encoder-side cap mirrors the 10 MB recv bound on BOTH ends: sol_zmq_protocol:encode_message/1 refuses any frame over sol_zmq_protocol:max_msg_size/0 with {error, {message_too_large, Size}} (typed, nothing on the wire), and Luna’s ffi/zmq.lua drains the remaining RCVMORE parts of an oversize message before erroring (no false reconnect, no multipart desync) with the same 10 MB aggregate multipart budget (the pre-fix shape materialized up to 1024×10 MB). The default Luna worker id gained a pid + per-process suffix (luna-<epoch>-<pid>-<seq>-<rand>), killing the same-second self-collision that fired the duplicate-identity path on innocent launches.