From fbcdef32e6b8823b616a1f20399db14a3834abe4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 22:39:05 -0600 Subject: [PATCH] id-core+hosted-worker: universal signed-and-validated admission gate (A9120-signature-gate, #10275) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One gate on every admission path for both cores, per design part A cross-cutting invariant 1 (S1.12-S1.20): semantic validation, signature + payload verification (digest recomputed on receipt), signer binding against a directory and the authenticated principal, namespace/tenant authorization through the A9116 seam pattern, and policy (admitted domains, payload budget). Local producers sign before entering; no unsigned-local exception. The AdmissionReceipt is the only accepted state transition and has no constructor outside the gate — no route bypass. - pkgs/id/crates/id-core/src/admission_gate.rs (new) - pkgs/id/crates/id-core/tests/admission_gate.rs (new) — model oracle: generated operations vs an independent reference model - pkgs/id/hosted-worker/src/admission-gate.ts (new) — TS mirror, same pipeline/stages/rejection classes; compiles the atlas SHA-256 profile verifier (blake3 admissions stay with the Rust core and refuse `unsupported` here, as an excluding dispatch does in Rust) - pkgs/id/hosted-worker/test/admission-gate.test.ts (new) No crate-root/manifest changes (owned by 9110-02); the test includes the module by path, per the sibling-slice pattern. Oracle: cargo test -p id-core --test admission_gate → 6 passed; bun test admission-gate.test.ts → 8 pass. --- pkgs/id/crates/id-core/src/admission_gate.rs | 566 ++++++++++++++++++ .../id/crates/id-core/tests/admission_gate.rs | 403 +++++++++++++ pkgs/id/hosted-worker/src/admission-gate.ts | 482 +++++++++++++++ .../hosted-worker/test/admission-gate.test.ts | 308 ++++++++++ 4 files changed, 1759 insertions(+) create mode 100644 pkgs/id/crates/id-core/src/admission_gate.rs create mode 100644 pkgs/id/crates/id-core/tests/admission_gate.rs create mode 100644 pkgs/id/hosted-worker/src/admission-gate.ts create mode 100644 pkgs/id/hosted-worker/test/admission-gate.test.ts diff --git a/pkgs/id/crates/id-core/src/admission_gate.rs b/pkgs/id/crates/id-core/src/admission_gate.rs new file mode 100644 index 0000000000..ff1af1cee6 --- /dev/null +++ b/pkgs/id/crates/id-core/src/admission_gate.rs @@ -0,0 +1,566 @@ +//! Universal signed-and-validated admission gate for both cores +//! (slice A9120-signature-gate, issue #10275; design part A, +//! cross-cutting invariants 1, 6 and 7 — statements S1.12–S1.20, +//! S3.4–S3.10, S4.19–S4.28). +//! +//! Every admission path — a remote producer's canonical bytes or a +//! local producer's already-constructed envelope — passes this one +//! gate before any state transition is accepted. Local producers +//! sign before entering; there is no unsigned-local exception +//! (invariant 1). The gate runs, in order: +//! +//! 1. **Semantic validation** — the body must encode under the +//! canonical profile (labels bounded, strict field set) and the +//! envelope must survive a canonical decode/encode round trip, so +//! a hand-constructed value gets exactly the checks wire bytes +//! get (invariant 7: malformed encodings and unknown critical +//! fields reject). +//! 2. **Signature and payload verification** — the A9114 envelope +//! verifies its detached signature against the body's key and the +//! payload against the committed payload ID and length (the +//! A9120 content core's digest-before-commit rule, recomputed on +//! receipt per invariant 2). +//! 3. **Signer binding** — the body's `signer_id` must resolve in +//! the signer directory to exactly the body's key, and the +//! authenticated principal must be that signer. +//! 4. **Namespace/tenant authorization** — the injected +//! [`AdmissionAuthorizer`] seam (the A9116-registry-state pattern) +//! judges the authenticated context against the body's requested +//! scope; the shipped [`ScopeBindingAuthorizer`] requires the +//! body's context to equal the authenticated tenant scope +//! (invariant 6). This slice consumes the #9083 authenticated +//! tenant/scope context contract; it does not define tenancy. +//! 5. **Policy** — the body's domain must be admitted by the gate +//! policy and the payload must fit the policy size budget. +//! +//! The only artifact of acceptance is an [`AdmissionReceipt`]. Its +//! fields are private and it has no constructor outside this +//! module: holding a receipt is proof the gate ran every check — +//! no route bypass exists. +//! +//! The crate-root export of this module belongs to slice 9110-02; +//! the model test includes it by path, per the sibling-slice +//! pattern. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; + +use crate::hash_profile::{ProfileDispatch, DEFAULT_MAX_CONTENT_BYTES}; +use crate::id_shape::{HashProfile, IdShapeError}; +use crate::signed_envelope::{Body, Envelope, EnvelopeError, EnvelopeId, PayloadId}; + +/// Longest admitted context field, in bytes. Mirrors the +/// A9116 registry-state context bound. +pub const MAX_CONTEXT_BYTES: usize = 255; + +/// The authenticated tenant/scope context an admission is judged +/// against (the #9083 contract shape, mirroring A9116's +/// `MutationContext` field for field). Authentication itself +/// happens outside the gate; the gate consumes its result. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdmissionContext { + principal: String, + tenant_scope: String, + authorization_scope: String, +} + +fn checked_context(field: &'static str, text: &str) -> Result<(), AdmissionRejection> { + if !text.is_empty() + && text.len() <= MAX_CONTEXT_BYTES + && text.bytes().all(|byte| byte.is_ascii_graphic()) + { + Ok(()) + } else { + Err(AdmissionRejection::InvalidContext { + field, + problem: "is not 1 to 255 visible ASCII characters", + }) + } +} + +impl AdmissionContext { + /// A validated context. + /// + /// # Errors + /// + /// [`AdmissionRejection::InvalidContext`] when any field is + /// empty, over [`MAX_CONTEXT_BYTES`], or not visible ASCII. + pub fn new( + principal: impl Into, + tenant_scope: impl Into, + authorization_scope: impl Into, + ) -> Result { + let principal = principal.into(); + let tenant_scope = tenant_scope.into(); + let authorization_scope = authorization_scope.into(); + checked_context("principal", &principal)?; + checked_context("tenant_scope", &tenant_scope)?; + checked_context("authorization_scope", &authorization_scope)?; + Ok(Self { + principal, + tenant_scope, + authorization_scope, + }) + } + + /// The authenticated principal (the signer identity admissions + /// are bound to). + #[must_use] + pub fn principal(&self) -> &str { + &self.principal + } + + /// The tenant scope the context is authenticated for. + #[must_use] + pub fn tenant_scope(&self) -> &str { + &self.tenant_scope + } + + /// The authorization scope the context presents (for example + /// `admission:write`). + #[must_use] + pub fn authorization_scope(&self) -> &str { + &self.authorization_scope + } +} + +/// Gate policy: which signing domains are admitted and how large a +/// payload may be. Mechanism, not behaviour — a deployment narrows +/// it, never widens it past the hard budget compiled into the +/// profile dispatch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GatePolicy { + admitted_domains: BTreeSet, + max_payload_bytes: u64, +} + +impl Default for GatePolicy { + /// Admits every domain; payload budget is the profile + /// dispatch's default content budget. + fn default() -> Self { + Self { + admitted_domains: BTreeSet::new(), + max_payload_bytes: DEFAULT_MAX_CONTENT_BYTES, + } + } +} + +impl GatePolicy { + /// A policy admitting only `domains` (an empty set admits + /// every domain) with the default payload budget. + #[must_use] + pub fn admitting(domains: impl IntoIterator) -> Self { + Self { + admitted_domains: domains.into_iter().collect(), + max_payload_bytes: DEFAULT_MAX_CONTENT_BYTES, + } + } + + /// Narrows the payload budget. + #[must_use] + pub const fn with_max_payload_bytes(mut self, max_payload_bytes: u64) -> Self { + self.max_payload_bytes = max_payload_bytes; + self + } + + /// Whether `domain` is admitted (every domain is, when the + /// admitted set is empty). + #[must_use] + pub fn admits_domain(&self, domain: &str) -> bool { + self.admitted_domains.is_empty() || self.admitted_domains.contains(domain) + } + + /// The payload size budget in bytes. + #[must_use] + pub const fn max_payload_bytes(&self) -> u64 { + self.max_payload_bytes + } +} + +/// Signer binding source: resolves a signer identity to the key +/// registered for it. The gate refuses any signer the directory +/// does not know, and any body whose key is not the registered one. +pub trait SignerDirectory: Send + Sync { + /// The registered Ed25519 public key for `signer_id`, if any. + fn key_for(&self, signer_id: &str) -> Option<[u8; 32]>; +} + +/// A [`SignerDirectory`] over a fixed registration table. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct StaticSignerDirectory { + keys: BTreeMap, +} + +impl StaticSignerDirectory { + /// An empty directory. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Registers `signer_id` with its public key. + pub fn register(&mut self, signer_id: impl Into, key: [u8; 32]) { + self.keys.insert(signer_id.into(), key); + } + + /// Whether `signer_id` is registered. + #[must_use] + pub fn contains(&self, signer_id: &str) -> bool { + self.keys.contains_key(signer_id) + } +} + +impl SignerDirectory for StaticSignerDirectory { + fn key_for(&self, signer_id: &str) -> Option<[u8; 32]> { + self.keys.get(signer_id).copied() + } +} + +/// Namespace/tenant authorization seam. Implementations judge the +/// authenticated context against the body's requested scope and +/// refuse with [`AdmissionRejection::Unauthorized`]. +pub trait AdmissionAuthorizer: Send + Sync { + /// Authorizes, or refuses, this admission. + /// + /// # Errors + /// + /// [`AdmissionRejection::Unauthorized`] when the context does + /// not hold authority over the body's scope. + fn authorize(&self, context: &AdmissionContext, body: &Body) -> Result<(), AdmissionRejection>; +} + +/// The shipped authorizer: the body's context (its requested +/// namespace/tenant scope) must equal the authenticated tenant +/// scope exactly (invariant 6 — requested tenant/scope must match +/// authenticated context). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ScopeBindingAuthorizer; + +impl AdmissionAuthorizer for ScopeBindingAuthorizer { + fn authorize(&self, context: &AdmissionContext, body: &Body) -> Result<(), AdmissionRejection> { + if body.context == context.tenant_scope() { + Ok(()) + } else { + Err(AdmissionRejection::Unauthorized { + problem: format!( + "body context {:?} is not the authenticated tenant scope {:?}", + body.context, + context.tenant_scope() + ), + }) + } + } +} + +/// Why an admission was refused. Each variant is one gate stage; +/// [`AdmissionRejection::class`] is the stable failure class the +/// model oracle compares. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AdmissionRejection { + /// A context field failed validation at construction. + InvalidContext { + /// The field name. + field: &'static str, + /// What was wrong. + problem: &'static str, + }, + /// The envelope is not a well-formed canonical record. + Malformed(EnvelopeError), + /// The version, suite or content profile is not one this gate + /// verifies. + Unsupported(EnvelopeError), + /// The payload is not what the body commits (length or digest). + Payload(EnvelopeError), + /// The signature does not verify against the body's key. + BadSignature, + /// The signer is unknown, its registered key differs from the + /// body's key, or the authenticated principal is not the signer. + SignerBinding { + /// The body's signer identity. + signer_id: String, + /// What was wrong. + problem: &'static str, + }, + /// The authenticated context does not hold authority over the + /// body's requested scope. + Unauthorized { + /// What was refused, with the scopes involved. + problem: String, + }, + /// The gate policy refuses this domain or payload size. + Policy { + /// What the policy refused. + problem: String, + }, +} + +impl AdmissionRejection { + /// A stable failure class: `malformed`, `unsupported`, + /// `payload`, `bad_signature`, `signer_binding`, + /// `unauthorized` or `policy`. + #[must_use] + pub const fn class(&self) -> &'static str { + match self { + Self::InvalidContext { .. } | Self::Malformed(_) => "malformed", + Self::Unsupported(_) => "unsupported", + Self::Payload(_) => "payload", + Self::BadSignature => "bad_signature", + Self::SignerBinding { .. } => "signer_binding", + Self::Unauthorized { .. } => "unauthorized", + Self::Policy { .. } => "policy", + } + } +} + +impl fmt::Display for AdmissionRejection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidContext { field, problem } => { + write!(f, "context field {field}: {problem}") + } + Self::Malformed(error) => write!(f, "malformed envelope: {error}"), + Self::Unsupported(error) => write!(f, "unsupported envelope: {error}"), + Self::Payload(error) => write!(f, "payload rejected: {error}"), + Self::BadSignature => write!(f, "signature does not verify"), + Self::SignerBinding { signer_id, problem } => { + write!(f, "signer {signer_id:?}: {problem}") + } + Self::Unauthorized { problem } => write!(f, "unauthorized: {problem}"), + Self::Policy { problem } => write!(f, "policy refusal: {problem}"), + } + } +} + +impl std::error::Error for AdmissionRejection {} + +/// Maps an envelope verification failure onto the gate stage that +/// owns it. +fn map_verify_error(error: EnvelopeError, signer_id: &str) -> AdmissionRejection { + match error { + EnvelopeError::BadSignature => AdmissionRejection::BadSignature, + EnvelopeError::BadKey | EnvelopeError::KeyMismatch => AdmissionRejection::SignerBinding { + signer_id: signer_id.to_owned(), + problem: "the body key is not a valid Ed25519 public key", + }, + EnvelopeError::UnsupportedVersion(_) | EnvelopeError::UnsupportedSuite(_) => { + AdmissionRejection::Unsupported(error) + } + EnvelopeError::Id(IdShapeError::UnsupportedProfile { .. }) => { + AdmissionRejection::Unsupported(error) + } + EnvelopeError::PayloadLength { .. } => AdmissionRejection::Payload(error), + EnvelopeError::Id(IdShapeError::DigestMismatch) + | EnvelopeError::Id(IdShapeError::InvalidProfileParameters { .. }) + | EnvelopeError::Id(IdShapeError::ResourceLimit { .. }) => { + AdmissionRejection::Payload(error) + } + other => AdmissionRejection::Malformed(other), + } +} + +/// Proof of admission. Minted only by [`AdmissionGate::admit`] / +/// [`AdmissionGate::admit_canonical`] after every check passed; +/// the fields are private and there is no other constructor, so a +/// receipt cannot be forged by a route that skipped the gate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdmissionReceipt { + envelope_id: EnvelopeId, + payload_id: PayloadId, + signer_id: String, + tenant_scope: String, + payload_length: u64, +} + +impl AdmissionReceipt { + /// The admitted envelope's identity. + #[must_use] + pub const fn envelope_id(&self) -> &EnvelopeId { + &self.envelope_id + } + + /// The admitted payload's identity. + #[must_use] + pub const fn payload_id(&self) -> &PayloadId { + &self.payload_id + } + + /// The signer the admission is bound to. + #[must_use] + pub fn signer_id(&self) -> &str { + &self.signer_id + } + + /// The tenant scope the admission was authorized under (the + /// body's context, checked against the authenticated context). + #[must_use] + pub fn tenant_scope(&self) -> &str { + &self.tenant_scope + } + + /// The admitted payload length in bytes. + #[must_use] + pub const fn payload_length(&self) -> u64 { + self.payload_length + } +} + +/// The admission gate. One gate, every path: [`Self::admit`] for +/// constructed envelopes (local producers) and +/// [`Self::admit_canonical`] for wire bytes run the identical +/// pipeline. +pub struct AdmissionGate { + policy: GatePolicy, + directory: Box, + authorizer: Box, + dispatch: ProfileDispatch, +} + +impl AdmissionGate { + /// A gate with the default profile dispatch (every compiled + /// profile admitted, default content budget). + #[must_use] + pub fn new( + policy: GatePolicy, + directory: impl SignerDirectory + 'static, + authorizer: impl AdmissionAuthorizer + 'static, + ) -> Self { + Self { + policy, + directory: Box::new(directory), + authorizer: Box::new(authorizer), + dispatch: ProfileDispatch::default(), + } + } + + /// A gate with an explicit profile dispatch. + #[must_use] + pub fn with_dispatch( + policy: GatePolicy, + directory: impl SignerDirectory + 'static, + authorizer: impl AdmissionAuthorizer + 'static, + dispatch: ProfileDispatch, + ) -> Self { + Self { + policy, + directory: Box::new(directory), + authorizer: Box::new(authorizer), + dispatch, + } + } + + /// Admits wire bytes: canonical decode, then the full + /// pipeline. This is the remote-producer path; it shares every + /// check with the local path. + /// + /// # Errors + /// + /// [`AdmissionRejection::Malformed`] for undecodable bytes, + /// then as [`Self::admit`]. + pub fn admit_canonical( + &self, + bytes: &[u8], + context: &AdmissionContext, + ) -> Result { + let envelope = Envelope::decode(bytes).map_err(AdmissionRejection::Malformed)?; + self.admit(&envelope, context) + } + + /// Runs the full admission pipeline over a constructed + /// envelope (the local-producer path — the producer signed + /// before entering, and the gate re-checks everything wire + /// bytes would face). + /// + /// # Errors + /// + /// The first failing stage's [`AdmissionRejection`], in + /// pipeline order: semantic validation, signature/payload + /// verification, signer binding, authorization, policy. + pub fn admit( + &self, + envelope: &Envelope, + context: &AdmissionContext, + ) -> Result { + let body = &envelope.body; + + // Stage 1 — semantic validation. `to_value` enforces the + // label bounds decode enforces; the canonical round trip + // then proves the constructed value is byte-identical to + // what the wire path would decode, so no field can smuggle + // past the strict field set. + body.to_value().map_err(AdmissionRejection::Malformed)?; + let canonical = envelope + .canonical_bytes() + .map_err(AdmissionRejection::Malformed)?; + let decoded = Envelope::decode(&canonical).map_err(AdmissionRejection::Malformed)?; + if decoded != *envelope { + return Err(AdmissionRejection::Malformed(EnvelopeError::Field { + field: "envelope", + problem: "is not in canonical form", + })); + } + + // Stage 2 — signature and payload verification (digest + // recomputed on receipt; the signature covers the exact + // canonical body). + envelope + .verify(&self.dispatch) + .map_err(|error| map_verify_error(error, &body.signer_id))?; + + // Stage 3 — signer binding: the signer must be registered + // with exactly this key, and the authenticated principal + // must be the signer. + match self.directory.key_for(&body.signer_id) { + None => { + return Err(AdmissionRejection::SignerBinding { + signer_id: body.signer_id.clone(), + problem: "signer is not registered in the directory", + }); + } + Some(registered) if registered != body.key => { + return Err(AdmissionRejection::SignerBinding { + signer_id: body.signer_id.clone(), + problem: "registered key does not match the body key", + }); + } + Some(_) => {} + } + if context.principal() != body.signer_id { + return Err(AdmissionRejection::SignerBinding { + signer_id: body.signer_id.clone(), + problem: "the authenticated principal is not the signer", + }); + } + + // Stage 4 — namespace/tenant authorization (injected seam). + self.authorizer.authorize(context, body)?; + + // Stage 5 — policy: admitted domain and payload budget. + if !self.policy.admits_domain(&body.domain) { + return Err(AdmissionRejection::Policy { + problem: format!("domain {:?} is not admitted by policy", body.domain), + }); + } + if body.payload_length > self.policy.max_payload_bytes() { + return Err(AdmissionRejection::Policy { + problem: format!( + "payload of {} bytes exceeds the policy maximum of {} bytes", + body.payload_length, + self.policy.max_payload_bytes() + ), + }); + } + + // Every check passed: mint the receipt — the only accepted + // state transition this slice produces. + let envelope_id = envelope + .id(HashProfile::RawBlake3_256) + .map_err(AdmissionRejection::Malformed)?; + Ok(AdmissionReceipt { + envelope_id, + payload_id: body.payload_id, + signer_id: body.signer_id.clone(), + tenant_scope: body.context.clone(), + payload_length: body.payload_length, + }) + } +} diff --git a/pkgs/id/crates/id-core/tests/admission_gate.rs b/pkgs/id/crates/id-core/tests/admission_gate.rs new file mode 100644 index 0000000000..c01c9c16cf --- /dev/null +++ b/pkgs/id/crates/id-core/tests/admission_gate.rs @@ -0,0 +1,403 @@ +//! Universal signed-and-validated admission gate +//! (slice A9120-signature-gate, issue #10275). +//! +//! Oracle: **model** — ingress model: every accepted state +//! transition has verified signature and all validation decisions; +//! no route bypass exists. The proptest generates admission +//! operations (valid local producers, tampered payloads, forged +//! signatures, unknown and rebound signers, wrong principals, +//! wrong scopes, oversized payloads, unadmitted domains, garbage +//! wire bytes, non-canonical constructions, duplicate admissions) +//! against an independent reference model over plain values; every +//! resulting accepted set and rejection class must match. Targeted +//! tests pin the receipt fields, the no-unsigned-local-exception +//! rule, the wire/constructed path equivalence and the context +//! validation the generator is unlikely to hit. +//! +//! The crate-root export of `admission_gate` belongs to slice +//! 9110-02, so this test includes it, and the modules it builds +//! on, by path. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[path = "../src/canonical_cbor.rs"] +#[allow(dead_code)] +mod canonical_cbor; + +#[path = "../src/id_shape.rs"] +#[allow(dead_code)] +mod id_shape; + +#[path = "../src/hash_profile.rs"] +#[allow(dead_code)] +mod hash_profile; + +#[path = "../src/signed_envelope.rs"] +#[allow(dead_code)] +mod signed_envelope; + +#[path = "../src/admission_gate.rs"] +#[allow(dead_code)] +mod admission_gate; + +use std::collections::BTreeSet; + +use admission_gate::{ + AdmissionContext, AdmissionGate, AdmissionReceipt, AdmissionRejection, GatePolicy, + ScopeBindingAuthorizer, StaticSignerDirectory, +}; +use ed25519_dalek::{Signer as _, SigningKey}; +use id_shape::HashProfile; +use proptest::prelude::*; +use signed_envelope::{signature_preimage, Body, Envelope, PayloadId, SUITE_ED25519}; + +const RAW: HashProfile = HashProfile::RawBlake3_256; +const DOMAIN: &str = "id/atlas"; +const OTHER_DOMAIN: &str = "id/other"; +const TENANTS: [&str; 2] = ["tenant-a", "tenant-b"]; +const SIGNERS: [(&str, u8); 2] = [("alice", 11), ("bob", 22)]; +const MALLORY: (&str, u8) = ("mallory", 33); +const MAX_PAYLOAD: u64 = 64; + +fn signing_key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) +} + +fn public_key(seed: u8) -> [u8; 32] { + signing_key(seed).verifying_key().to_bytes() +} + +fn context(principal: &str, tenant: &str) -> AdmissionContext { + AdmissionContext::new(principal, tenant, "admission:write").unwrap() +} + +fn directory() -> StaticSignerDirectory { + let mut directory = StaticSignerDirectory::new(); + for (signer_id, seed) in SIGNERS { + directory.register(signer_id, public_key(seed)); + } + directory +} + +fn gate() -> AdmissionGate { + AdmissionGate::new( + GatePolicy::admitting([DOMAIN.to_string()]).with_max_payload_bytes(MAX_PAYLOAD), + directory(), + ScopeBindingAuthorizer, + ) +} + +/// A gate whose directory binds alice to bob's key: every alice +/// admission must fail signer binding even though her envelopes +/// are self-consistent. +fn poisoned_gate() -> AdmissionGate { + let mut directory = StaticSignerDirectory::new(); + directory.register("alice", public_key(22)); + directory.register("bob", public_key(22)); + AdmissionGate::new( + GatePolicy::admitting([DOMAIN.to_string()]).with_max_payload_bytes(MAX_PAYLOAD), + directory, + ScopeBindingAuthorizer, + ) +} + +fn make_envelope( + signer_id: &str, + seed: u8, + tenant: &str, + domain: &str, + payload: Vec, +) -> Envelope { + let key = signing_key(seed); + let body = Body { + domain: domain.to_string(), + context: tenant.to_string(), + subject: None, + graph: None, + predecessor: None, + signer_id: signer_id.to_string(), + key: key.verifying_key().to_bytes(), + suite: SUITE_ED25519.to_string(), + payload_id: PayloadId::of(RAW, &payload).unwrap(), + payload_length: payload.len() as u64, + }; + Envelope::sign(body, payload, &key).unwrap() +} + +fn valid_envelope(signer: usize, tenant: usize, seed: u8) -> Envelope { + let (signer_id, key_seed) = SIGNERS[signer]; + make_envelope(signer_id, key_seed, TENANTS[tenant], DOMAIN, vec![seed; 8]) +} + +fn receipt_digest(receipt: &AdmissionReceipt) -> Vec { + receipt.envelope_id().content_id().digest().to_vec() +} + +fn envelope_digest(envelope: &Envelope) -> Vec { + envelope.id(RAW).unwrap().content_id().digest().to_vec() +} + +/// A gate outcome reduced to what the model predicts: the +/// admitted envelope digest, or the rejection's class. +fn outcome(result: Result) -> Result, &'static str> { + result + .map(|receipt| receipt_digest(&receipt)) + .map_err(|rejection| rejection.class()) +} + +// --------------------------------------------------------------------- +// Targeted tests +// --------------------------------------------------------------------- + +#[test] +fn valid_local_producer_is_admitted_with_a_full_receipt() { + let envelope = valid_envelope(0, 0, 7); + let receipt = gate() + .admit(&envelope, &context("alice", "tenant-a")) + .unwrap(); + assert_eq!(receipt_digest(&receipt), envelope_digest(&envelope)); + assert_eq!( + receipt.payload_id(), + &PayloadId::of(RAW, &vec![7u8; 8]).unwrap() + ); + assert_eq!(receipt.signer_id(), "alice"); + assert_eq!(receipt.tenant_scope(), "tenant-a"); + assert_eq!(receipt.payload_length(), 8); +} + +#[test] +fn unsigned_envelope_is_rejected_no_local_exception() { + // Invariant 1: local producers sign before entering the gate; + // an unsigned envelope is refused like any forgery. + let mut envelope = valid_envelope(0, 0, 7); + envelope.signature = [0u8; 64]; + let rejection = gate() + .admit(&envelope, &context("alice", "tenant-a")) + .unwrap_err(); + assert_eq!(rejection, AdmissionRejection::BadSignature); + assert_eq!(rejection.class(), "bad_signature"); +} + +#[test] +fn canonical_wire_path_matches_the_constructed_path() { + // No route bypass: wire bytes and constructed envelopes face + // the identical pipeline and mint identical receipts. + let gate = gate(); + let envelope = valid_envelope(1, 1, 9); + let ctx = context("bob", "tenant-b"); + let via_constructed = gate.admit(&envelope, &ctx).unwrap(); + let via_wire = gate + .admit_canonical(&envelope.canonical_bytes().unwrap(), &ctx) + .unwrap(); + assert_eq!(via_constructed, via_wire); + + let bytes = envelope.canonical_bytes().unwrap(); + let truncated = &bytes[..bytes.len() - 3]; + let rejection = gate.admit_canonical(truncated, &ctx).unwrap_err(); + assert_eq!(rejection.class(), "malformed"); +} + +#[test] +fn default_policy_admits_any_domain_within_the_default_budget() { + let gate = AdmissionGate::new(GatePolicy::default(), directory(), ScopeBindingAuthorizer); + let envelope = make_envelope("alice", 11, "tenant-a", OTHER_DOMAIN, vec![3u8; 8]); + let receipt = gate + .admit(&envelope, &context("alice", "tenant-a")) + .unwrap(); + assert_eq!(receipt.tenant_scope(), "tenant-a"); +} + +#[test] +fn context_fields_are_validated() { + assert_eq!( + AdmissionContext::new("", "tenant-a", "admission:write") + .unwrap_err() + .class(), + "malformed" + ); + assert_eq!( + AdmissionContext::new("alice", "tenant a", "admission:write") + .unwrap_err() + .class(), + "malformed" + ); + assert_eq!( + AdmissionContext::new("alice", "tenant-a", "x".repeat(256)) + .unwrap_err() + .class(), + "malformed" + ); + assert!(AdmissionContext::new("alice", "tenant-a", "x".repeat(255)).is_ok()); +} + +// --------------------------------------------------------------------- +// Model proptest +// --------------------------------------------------------------------- + +/// One generated admission operation, as raw indices the harness +/// interprets against the fixed actor table. +type Op = (u8, u8, u8, u8); + +fn op_strategy() -> impl Strategy { + (any::(), any::(), any::(), any::()) +} + +/// The reference model: the set of envelope digests the gate may +/// have accepted, over plain values. The harness computes each +/// operation's expected outcome from the model's own rules, runs +/// the gate, and compares outcome and accepted set after every +/// operation. +struct Model { + admitted: BTreeSet>, + last_valid: Option<(Envelope, AdmissionContext)>, +} + +impl Model { + fn new() -> Self { + Self { + admitted: BTreeSet::new(), + last_valid: None, + } + } +} + +fn run_ops(ops: Vec) -> Result<(), TestCaseError> { + let gate = gate(); + let poisoned = poisoned_gate(); + let mut model = Model::new(); + + for (kind, a, b, c) in ops { + let signer = usize::from(a % 2); + let tenant = usize::from(b % 2); + let (signer_id, _) = SIGNERS[signer]; + match kind % 12 { + 0 => { + // Valid local producer admission. + let envelope = valid_envelope(signer, tenant, c); + let ctx = context(signer_id, TENANTS[tenant]); + let digest = envelope_digest(&envelope); + let result = gate.admit(&envelope, &ctx); + prop_assert_eq!(outcome(result), Ok(digest.clone())); + model.admitted.insert(digest); + model.last_valid = Some((envelope, ctx)); + } + 1 => { + // Tampered payload: digest no longer matches. + let mut envelope = valid_envelope(signer, tenant, c); + envelope.payload[0] ^= 0xff; + let result = gate.admit(&envelope, &context(signer_id, TENANTS[tenant])); + prop_assert_eq!(outcome(result), Err("payload")); + } + 2 => { + // Forged signature: another key signed the preimage. + let mut envelope = valid_envelope(signer, tenant, c); + let other_seed = SIGNERS[1 - signer].1; + envelope.signature = signing_key(other_seed) + .sign(&signature_preimage(&envelope.body).unwrap()) + .to_bytes(); + let result = gate.admit(&envelope, &context(signer_id, TENANTS[tenant])); + prop_assert_eq!(outcome(result), Err("bad_signature")); + } + 3 => { + // Unknown signer: self-consistent, unregistered. + let envelope = + make_envelope(MALLORY.0, MALLORY.1, TENANTS[tenant], DOMAIN, vec![c; 8]); + let result = gate.admit(&envelope, &context(MALLORY.0, TENANTS[tenant])); + prop_assert_eq!(outcome(result), Err("signer_binding")); + } + 4 => { + // Rebound key: the directory binds alice to bob's key. + let envelope = valid_envelope(0, tenant, c); + let result = poisoned.admit(&envelope, &context("alice", TENANTS[tenant])); + prop_assert_eq!(outcome(result), Err("signer_binding")); + } + 5 => { + // Wrong principal: a different registered signer + // presents alice's envelope. + let envelope = valid_envelope(signer, tenant, c); + let other = SIGNERS[1 - signer].0; + let result = gate.admit(&envelope, &context(other, TENANTS[tenant])); + prop_assert_eq!(outcome(result), Err("signer_binding")); + } + 6 => { + // Wrong scope: authenticated for the other tenant. + let envelope = valid_envelope(signer, 0, c); + let result = gate.admit(&envelope, &context(signer_id, TENANTS[1])); + prop_assert_eq!(outcome(result), Err("unauthorized")); + } + 7 => { + // Oversized payload: valid in every way except the + // policy budget. + let (sid, seed) = SIGNERS[signer]; + let envelope = make_envelope(sid, seed, TENANTS[tenant], DOMAIN, vec![c; 65]); + let result = gate.admit(&envelope, &context(sid, TENANTS[tenant])); + prop_assert_eq!(outcome(result), Err("policy")); + } + 8 => { + // Unadmitted domain. + let (sid, seed) = SIGNERS[signer]; + let envelope = make_envelope(sid, seed, TENANTS[tenant], OTHER_DOMAIN, vec![c; 8]); + let result = gate.admit(&envelope, &context(sid, TENANTS[tenant])); + prop_assert_eq!(outcome(result), Err("policy")); + } + 9 => { + // Garbage wire bytes never decode. + let result = gate.admit_canonical(&[0xff; 24], &context("alice", "tenant-a")); + prop_assert_eq!(outcome(result), Err("malformed")); + } + 10 => { + // Non-canonical construction: empty domain label. + let payload = vec![c; 8]; + let body = Body { + domain: String::new(), + context: TENANTS[tenant].to_string(), + subject: None, + graph: None, + predecessor: None, + signer_id: signer_id.to_string(), + key: public_key(SIGNERS[signer].1), + suite: SUITE_ED25519.to_string(), + payload_id: PayloadId::of(RAW, &payload).unwrap(), + payload_length: payload.len() as u64, + }; + let envelope = Envelope { + body, + payload, + signature: [9u8; 64], + }; + let result = gate.admit(&envelope, &context(signer_id, TENANTS[tenant])); + prop_assert_eq!(outcome(result), Err("malformed")); + } + _ => { + // Duplicate admission of the last valid envelope: + // idempotent acceptance, same receipt, set unchanged. + if let Some((envelope, ctx)) = &model.last_valid { + let digest = envelope_digest(envelope); + let result = gate.admit(envelope, ctx); + prop_assert_eq!(outcome(result), Ok(digest.clone())); + prop_assert!(model.admitted.contains(&digest)); + } else { + let envelope = valid_envelope(signer, tenant, c); + let ctx = context(signer_id, TENANTS[tenant]); + let digest = envelope_digest(&envelope); + let result = gate.admit(&envelope, &ctx); + prop_assert_eq!(outcome(result), Ok(digest.clone())); + model.admitted.insert(digest); + model.last_valid = Some((envelope, ctx)); + } + } + } + } + Ok(()) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(48))] + + #[test] + fn generated_operations_match_the_model( + ops in prop::collection::vec(op_strategy(), 0..=24) + ) { + run_ops(ops)?; + } +} diff --git a/pkgs/id/hosted-worker/src/admission-gate.ts b/pkgs/id/hosted-worker/src/admission-gate.ts new file mode 100644 index 0000000000..42ad0afeb2 --- /dev/null +++ b/pkgs/id/hosted-worker/src/admission-gate.ts @@ -0,0 +1,482 @@ +// Universal signed-and-validated admission gate for both cores +// (slice A9120-signature-gate, #10275; design part A, cross-cutting +// invariants 1, 6 and 7 — statements S1.12–S1.20, S3.4–S3.10, +// S4.19–S4.28). +// +// TypeScript mirror of crates/id-core/src/admission_gate.rs: the +// same pipeline, the same stage order, the same typed rejection +// classes, so an admission decision is identical across the Rust +// core and this hosted worker. Every admission path passes this +// gate before any state transition is accepted; local producers +// sign before entering — there is no unsigned-local exception. +// +// Pipeline: (1) semantic validation of the canonical record, +// (2) signature and payload verification (digest recomputed on +// receipt), (3) signer binding against the directory and the +// authenticated principal, (4) namespace/tenant authorization +// through the injected seam, (5) policy (admitted domains, +// payload budget). +// +// Profile dispatch mirrors the Rust compiled-verifier registry: +// this build compiles the atlas-chunk-sha256-utf8 verifier +// (WebCrypto SHA-256). A payload ID under raw-blake3-256 — or any +// unknown profile — is refused `unsupported`, exactly as a Rust +// node whose dispatch excludes the profile refuses it; the Rust +// core remains the authority for blake3 admissions. + +import { + CborError, + decodeCanonical, + encodeCanonical, + type CborValue, +} from "./canonical-cbor.ts"; + +/** The stable failure class of a rejection (mirrors the Rust `class()`). */ +export type AdmissionRejectionClass = + | "malformed" + | "unsupported" + | "payload" + | "bad_signature" + | "signer_binding" + | "unauthorized" + | "policy"; + +/** Typed admission refusal; `rejectionClass` names the gate stage. */ +export class AdmissionRejection extends Error { + readonly rejectionClass: AdmissionRejectionClass; + constructor(rejectionClass: AdmissionRejectionClass, message: string) { + super(message); + this.rejectionClass = rejectionClass; + } +} + +const malformed = (message: string) => new AdmissionRejection("malformed", message); + +/** Longest admitted context field, in bytes (mirrors the Rust bound). */ +export const MAX_CONTEXT_BYTES = 255; + +/** + * The authenticated tenant/scope context an admission is judged + * against (the #9083 contract shape, mirroring A9116's mutation + * context field for field). Authentication happens outside the + * gate; the gate consumes its result. + */ +export interface AdmissionContext { + principal: string; + tenantScope: string; + authorizationScope: string; +} + +function checkContextField(field: string, text: string): void { + const bytes = new TextEncoder().encode(text); + const visible = [...text].every((ch) => { + const code = ch.codePointAt(0) ?? 0; + return code >= 0x21 && code <= 0x7e; + }); + if (bytes.length === 0 || bytes.length > MAX_CONTEXT_BYTES || !visible) { + throw malformed(`context field ${field}: is not 1 to 255 visible ASCII characters`); + } +} + +/** A validated admission context; throws `malformed` on a bad field. */ +export function admissionContext( + principal: string, + tenantScope: string, + authorizationScope: string, +): AdmissionContext { + checkContextField("principal", principal); + checkContextField("tenant_scope", tenantScope); + checkContextField("authorization_scope", authorizationScope); + return { principal, tenantScope, authorizationScope }; +} + +/** Gate policy: admitted signing domains and the payload budget. */ +export interface GatePolicy { + /** Admitted domains; an empty or absent set admits every domain. */ + admittedDomains?: ReadonlySet; + /** Payload budget in bytes; defaults to the Rust default content budget. */ + maxPayloadBytes?: number; +} + +const DEFAULT_MAX_PAYLOAD_BYTES = 64 * 2 ** 30; + +/** + * Signer binding source: resolves a signer identity to the key + * registered for it. Unknown signers and key mismatches refuse. + */ +export interface SignerDirectory { + keyFor(signerId: string): Uint8Array | undefined; +} + +/** A {@link SignerDirectory} over a fixed registration table. */ +export class StaticSignerDirectory implements SignerDirectory { + readonly #keys = new Map(); + + register(signerId: string, key: Uint8Array): void { + this.#keys.set(signerId, new Uint8Array(key)); + } + + keyFor(signerId: string): Uint8Array | undefined { + return this.#keys.get(signerId); + } +} + +/** The body fields the authorization seam judges. */ +export interface BodyView { + domain: string; + context: string; + signerId: string; +} + +/** + * Namespace/tenant authorization seam. Implementations judge the + * authenticated context against the body's requested scope and + * throw an `unauthorized` {@link AdmissionRejection} to refuse. + */ +export interface AdmissionAuthorizer { + authorize(context: AdmissionContext, body: BodyView): void; +} + +/** + * The shipped authorizer: the body's context (its requested + * namespace/tenant scope) must equal the authenticated tenant + * scope exactly (invariant 6). + */ +export class ScopeBindingAuthorizer implements AdmissionAuthorizer { + authorize(context: AdmissionContext, body: BodyView): void { + if (body.context !== context.tenantScope) { + throw new AdmissionRejection( + "unauthorized", + `body context ${JSON.stringify(body.context)} is not the authenticated tenant scope ${JSON.stringify(context.tenantScope)}`, + ); + } + } +} + +/** Proof of admission, minted only by the gate after every check. */ +export interface AdmissionReceipt { + signerId: string; + tenantScope: string; + payloadLength: number; + payloadProfile: string; + /** Hex digest of the payload under its profile. */ + payloadDigestHex: string; + /** Hex SHA-256 of the canonical envelope bytes (this build's receipt digest). */ + envelopeDigestHex: string; +} + +const SIGNATURE_DOMAIN_PREFIX = new TextEncoder().encode("id/signed-body/v1\0"); +const SUITE_ED25519 = "ed25519"; +const BODY_VERSION = 1n; +const MAX_LABEL_BYTES = 256; +const PROFILE_ATLAS_SHA256_UTF8 = "atlas-chunk-sha256-utf8"; + +const BODY_FIELDS = new Set([ + "v", + "domain", + "context", + "subject", + "graph", + "predecessor", + "signer_id", + "key", + "suite", + "payload_id", + "payload_length", +]); + +type MapEntries = [CborValue, CborValue][]; + +function mapField(entries: MapEntries, name: string): CborValue | undefined { + for (const [key, value] of entries) { + if (key.kind === "text" && key.value === name) return value; + } + return undefined; +} + +function requireMap(value: CborValue, what: string): MapEntries { + if (value.kind !== "map") throw malformed(`${what}: is not a map`); + return value.value; +} + +function requireText(value: CborValue | undefined, field: string): string { + if (value === undefined || value.kind !== "text") { + throw malformed(`field ${field}: missing or not text`); + } + return value.value; +} + +function requireBytes(value: CborValue | undefined, field: string): Uint8Array { + if (value === undefined || value.kind !== "bytes") { + throw malformed(`field ${field}: missing or not bytes`); + } + return value.value; +} + +function requireUint(value: CborValue | undefined, field: string): bigint { + if (value === undefined || value.kind !== "uint") { + throw malformed(`field ${field}: missing or not an unsigned integer`); + } + return value.value; +} + +function checkLabel(field: string, label: string): void { + const bytes = new TextEncoder().encode(label); + if (bytes.length === 0) throw malformed(`field ${field}: must not be empty`); + if (bytes.length > MAX_LABEL_BYTES) throw malformed(`field ${field}: is too long`); +} + +function bytesEqual(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + return a.every((byte, i) => byte === b[i]); +} + +function toHex(data: Uint8Array): string { + return [...data].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +interface ParsedEnvelope { + bodyValue: CborValue; + domain: string; + context: string; + signerId: string; + key: Uint8Array; + suite: string; + payloadProfile: string; + payloadDigest: Uint8Array; + payloadLength: bigint; + payload: Uint8Array; + signature: Uint8Array; +} + +/** Strict structural extraction, mirroring the Rust `Fields` discipline. */ +function parseEnvelope(decoded: CborValue): ParsedEnvelope { + const envelope = requireMap(decoded, "envelope"); + for (const [key] of envelope) { + if (key.kind === "text" && !["body", "payload", "signature"].includes(key.value)) { + throw malformed(`envelope: unknown field ${key.value}`); + } + } + const bodyValue = mapField(envelope, "body"); + if (bodyValue === undefined) throw malformed("field body: missing"); + const body = requireMap(bodyValue, "body"); + for (const [key] of body) { + if (key.kind === "text" && !BODY_FIELDS.has(key.value)) { + throw malformed(`body: unknown field ${key.value}`); + } + } + const version = requireUint(mapField(body, "v"), "v"); + if (version !== BODY_VERSION) { + throw new AdmissionRejection("unsupported", `unsupported body version ${version}`); + } + const payloadId = requireMap( + (() => { + const value = mapField(body, "payload_id"); + if (value === undefined) throw malformed("field payload_id: missing"); + return value; + })(), + "payload_id", + ); + return { + bodyValue, + domain: requireText(mapField(body, "domain"), "domain"), + context: requireText(mapField(body, "context"), "context"), + signerId: requireText(mapField(body, "signer_id"), "signer_id"), + key: requireBytes(mapField(body, "key"), "key"), + suite: requireText(mapField(body, "suite"), "suite"), + payloadProfile: requireText(mapField(payloadId, "profile"), "payload_id.profile"), + payloadDigest: requireBytes(mapField(payloadId, "digest"), "payload_id.digest"), + payloadLength: requireUint(mapField(body, "payload_length"), "payload_length"), + payload: requireBytes(mapField(envelope, "payload"), "payload"), + signature: requireBytes(mapField(envelope, "signature"), "signature"), + }; +} + +/** The exact bytes the body signature covers (mirrors the Rust preimage). */ +function signaturePreimage(bodyValue: CborValue, domain: string): Uint8Array { + const encoded = encodeCanonical(bodyValue); + const domainBytes = new TextEncoder().encode(domain); + const out = new Uint8Array( + SIGNATURE_DOMAIN_PREFIX.length + 4 + domainBytes.length + encoded.length, + ); + let pos = 0; + out.set(SIGNATURE_DOMAIN_PREFIX, pos); + pos += SIGNATURE_DOMAIN_PREFIX.length; + new DataView(out.buffer).setUint32(pos, domainBytes.length, false); + pos += 4; + out.set(domainBytes, pos); + pos += domainBytes.length; + out.set(encoded, pos); + return out; +} + +/** The admission gate. One gate, every path. */ +export class AdmissionGate { + readonly #policy: GatePolicy; + readonly #directory: SignerDirectory; + readonly #authorizer: AdmissionAuthorizer; + + constructor( + policy: GatePolicy, + directory: SignerDirectory, + authorizer: AdmissionAuthorizer, + ) { + this.#policy = policy; + this.#directory = directory; + this.#authorizer = authorizer; + } + + /** + * Runs the full admission pipeline over canonical envelope + * bytes. Resolves with the receipt on acceptance; rejects with + * an {@link AdmissionRejection} naming the failing stage. + */ + async admitCanonical( + bytes: Uint8Array, + context: AdmissionContext, + ): Promise { + // Stage 1 — semantic validation: canonical decode, strict + // field sets, label bounds, canonical round trip. + let decoded: CborValue; + try { + decoded = decodeCanonical(bytes); + } catch (error) { + if (error instanceof CborError) throw malformed(`envelope encoding: ${error.message}`); + throw error; + } + const parsed = parseEnvelope(decoded); + checkLabel("domain", parsed.domain); + checkLabel("context", parsed.context); + if (!bytesEqual(encodeCanonical(decoded), bytes)) { + throw malformed("envelope: is not in canonical form"); + } + if (parsed.key.length !== 32) throw malformed("field key: has the wrong length"); + if (parsed.signature.length !== 64) { + throw malformed("field signature: has the wrong length"); + } + if (parsed.payloadDigest.length !== 32) { + throw malformed("field payload_id.digest: has the wrong length"); + } + + // Stage 2 — signature and payload verification. + if (parsed.suite !== SUITE_ED25519) { + throw new AdmissionRejection("unsupported", `unsupported signature suite ${JSON.stringify(parsed.suite)}`); + } + if (BigInt(parsed.payload.length) !== parsed.payloadLength) { + throw new AdmissionRejection( + "payload", + `payload is ${parsed.payload.length} bytes but the body commits ${parsed.payloadLength}`, + ); + } + await this.#verifyPayloadDigest(parsed); + await this.#verifySignature(parsed); + + // Stage 3 — signer binding. + const registered = this.#directory.keyFor(parsed.signerId); + if (registered === undefined) { + throw new AdmissionRejection( + "signer_binding", + `signer ${JSON.stringify(parsed.signerId)}: signer is not registered in the directory`, + ); + } + if (!bytesEqual(registered, parsed.key)) { + throw new AdmissionRejection( + "signer_binding", + `signer ${JSON.stringify(parsed.signerId)}: registered key does not match the body key`, + ); + } + if (context.principal !== parsed.signerId) { + throw new AdmissionRejection( + "signer_binding", + `signer ${JSON.stringify(parsed.signerId)}: the authenticated principal is not the signer`, + ); + } + + // Stage 4 — namespace/tenant authorization (injected seam). + this.#authorizer.authorize(context, { + domain: parsed.domain, + context: parsed.context, + signerId: parsed.signerId, + }); + + // Stage 5 — policy: admitted domain and payload budget. + const admitted = this.#policy.admittedDomains; + if (admitted !== undefined && admitted.size > 0 && !admitted.has(parsed.domain)) { + throw new AdmissionRejection( + "policy", + `domain ${JSON.stringify(parsed.domain)} is not admitted by policy`, + ); + } + const maxPayload = this.#policy.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES; + if (parsed.payloadLength > BigInt(maxPayload)) { + throw new AdmissionRejection( + "policy", + `payload of ${parsed.payloadLength} bytes exceeds the policy maximum of ${maxPayload} bytes`, + ); + } + + const envelopeDigest = new Uint8Array( + await crypto.subtle.digest("SHA-256", bytes as BufferSource), + ); + return { + signerId: parsed.signerId, + tenantScope: parsed.context, + payloadLength: parsed.payload.length, + payloadProfile: parsed.payloadProfile, + payloadDigestHex: toHex(parsed.payloadDigest), + envelopeDigestHex: toHex(envelopeDigest), + }; + } + + async #verifyPayloadDigest(parsed: ParsedEnvelope): Promise { + if (parsed.payloadProfile === PROFILE_ATLAS_SHA256_UTF8) { + // The atlas profile is defined over UTF-8 text. + try { + new TextDecoder("utf-8", { fatal: true }).decode(parsed.payload); + } catch { + throw new AdmissionRejection( + "payload", + "atlas-chunk-sha256-utf8 is defined over UTF-8 text", + ); + } + const digest = new Uint8Array( + await crypto.subtle.digest("SHA-256", parsed.payload as BufferSource), + ); + if (!bytesEqual(digest, parsed.payloadDigest)) { + throw new AdmissionRejection("payload", "payload digest does not match the payload ID"); + } + return; + } + // raw-blake3-256 has no compiled verifier in this build; an + // unknown profile is unsupported on any build. + throw new AdmissionRejection( + "unsupported", + `unsupported content profile ${JSON.stringify(parsed.payloadProfile)}`, + ); + } + + async #verifySignature(parsed: ParsedEnvelope): Promise { + let key: CryptoKey; + try { + key = await crypto.subtle.importKey( + "raw", + parsed.key as BufferSource, + "Ed25519", + false, + ["verify"], + ); + } catch { + throw new AdmissionRejection( + "signer_binding", + `signer ${JSON.stringify(parsed.signerId)}: the body key is not a valid Ed25519 public key`, + ); + } + const ok = await crypto.subtle.verify( + "Ed25519", + key, + parsed.signature as BufferSource, + signaturePreimage(parsed.bodyValue, parsed.domain) as BufferSource, + ); + if (!ok) throw new AdmissionRejection("bad_signature", "signature does not verify"); + } +} diff --git a/pkgs/id/hosted-worker/test/admission-gate.test.ts b/pkgs/id/hosted-worker/test/admission-gate.test.ts new file mode 100644 index 0000000000..639a3cddf3 --- /dev/null +++ b/pkgs/id/hosted-worker/test/admission-gate.test.ts @@ -0,0 +1,308 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + AdmissionGate, + AdmissionRejection, + ScopeBindingAuthorizer, + StaticSignerDirectory, + admissionContext, + type AdmissionContext, +} from "../src/admission-gate.ts"; +import { encodeCanonical, type CborValue } from "../src/canonical-cbor.ts"; + +// Mirror of crates/id-core/tests/admission_gate.rs: the same +// actor table and the same scenario → rejection-class table, so +// the hosted worker's gate is held to the Rust gate's decisions. +// Payloads use the atlas-chunk-sha256-utf8 profile — the profile +// this build compiles a verifier for. + +const DOMAIN = "id/atlas"; +const OTHER_DOMAIN = "id/other"; +const PROFILE = "atlas-chunk-sha256-utf8"; + +const text = (value: string): CborValue => ({ kind: "text", value }); +const bytes = (value: Uint8Array): CborValue => ({ kind: "bytes", value }); +const uint = (value: bigint): CborValue => ({ kind: "uint", value }); +const map = (entries: [CborValue, CborValue][]): CborValue => ({ + kind: "map", + value: entries, +}); + +const encoder = new TextEncoder(); + +function toHex(data: Uint8Array): string { + return [...data].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +async function sha256(data: Uint8Array): Promise { + return new Uint8Array(await crypto.subtle.digest("SHA-256", data as BufferSource)); +} + +interface Actor { + signerId: string; + pair: CryptoKeyPair; + publicRaw: Uint8Array; +} + +async function makeActor(signerId: string): Promise { + const pair = (await crypto.subtle.generateKey("Ed25519", true, [ + "sign", + "verify", + ])) as CryptoKeyPair; + const publicRaw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey)); + return { signerId, pair, publicRaw }; +} + +const alice = await makeActor("alice"); +const bob = await makeActor("bob"); +const mallory = await makeActor("mallory"); + +function directory(): StaticSignerDirectory { + const dir = new StaticSignerDirectory(); + dir.register("alice", alice.publicRaw); + dir.register("bob", bob.publicRaw); + return dir; +} + +function gate(policy?: { admittedDomains?: Set; maxPayloadBytes?: number }): AdmissionGate { + return new AdmissionGate( + policy ?? { admittedDomains: new Set([DOMAIN]), maxPayloadBytes: 64 }, + directory(), + new ScopeBindingAuthorizer(), + ); +} + +function context(principal: string, tenant: string): AdmissionContext { + return admissionContext(principal, tenant, "admission:write"); +} + +/** The signature preimage, built independently of the gate's own copy. */ +function signaturePreimage(body: CborValue, domain: string): Uint8Array { + const prefix = encoder.encode("id/signed-body/v1\0"); + const domainBytes = encoder.encode(domain); + const encoded = encodeCanonical(body); + const out = new Uint8Array(prefix.length + 4 + domainBytes.length + encoded.length); + let pos = 0; + out.set(prefix, pos); + pos += prefix.length; + new DataView(out.buffer).setUint32(pos, domainBytes.length, false); + pos += 4; + out.set(domainBytes, pos); + pos += domainBytes.length; + out.set(encoded, pos); + return out; +} + +interface EnvelopeOptions { + actor: Actor; + tenant: string; + domain: string; + payload: Uint8Array; + profile?: string; + digestOverride?: Uint8Array; + signWith?: CryptoKey; + signatureOverride?: Uint8Array; +} + +async function buildEnvelope(opts: EnvelopeOptions): Promise { + const digest = opts.digestOverride ?? (await sha256(opts.payload)); + const body = map([ + [text("v"), uint(1n)], + [text("domain"), text(opts.domain)], + [text("context"), text(opts.tenant)], + [text("signer_id"), text(opts.actor.signerId)], + [text("key"), bytes(opts.actor.publicRaw)], + [text("suite"), text("ed25519")], + [ + text("payload_id"), + map([ + [text("digest"), bytes(digest)], + [text("profile"), text(opts.profile ?? PROFILE)], + ]), + ], + [text("payload_length"), uint(BigInt(opts.payload.length))], + ]); + const signature = + opts.signatureOverride ?? + new Uint8Array( + await crypto.subtle.sign( + "Ed25519", + opts.signWith ?? opts.actor.pair.privateKey, + signaturePreimage(body, opts.domain) as BufferSource, + ), + ); + return encodeCanonical( + map([ + [text("body"), body], + [text("payload"), bytes(opts.payload)], + [text("signature"), bytes(signature)], + ]), + ); +} + +async function rejectionClass(promise: Promise): Promise { + try { + await promise; + } catch (error) { + assert.ok(error instanceof AdmissionRejection, `expected AdmissionRejection, got ${error}`); + return error.rejectionClass; + } + assert.fail("expected the admission to be rejected"); +} + +const payload = encoder.encode("hello atlas"); + +test("valid producer is admitted with a full receipt", async () => { + const envelope = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: DOMAIN, + payload, + }); + const receipt = await gate().admitCanonical(envelope, context("alice", "tenant-a")); + assert.equal(receipt.signerId, "alice"); + assert.equal(receipt.tenantScope, "tenant-a"); + assert.equal(receipt.payloadLength, payload.length); + assert.equal(receipt.payloadProfile, PROFILE); + assert.equal(receipt.payloadDigestHex, toHex(await sha256(payload))); +}); + +test("tampered payload is refused at the payload stage", async () => { + const envelope = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: DOMAIN, + payload: encoder.encode("forged payload"), + digestOverride: await sha256(payload), + }); + assert.equal( + await rejectionClass(gate().admitCanonical(envelope, context("alice", "tenant-a"))), + "payload", + ); +}); + +test("forged and unsigned envelopes are refused as bad signatures", async () => { + const forged = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: DOMAIN, + payload, + signWith: bob.pair.privateKey, + }); + assert.equal( + await rejectionClass(gate().admitCanonical(forged, context("alice", "tenant-a"))), + "bad_signature", + ); + + // Invariant 1: no unsigned-local exception. + const unsigned = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: DOMAIN, + payload, + signatureOverride: new Uint8Array(64), + }); + assert.equal( + await rejectionClass(gate().admitCanonical(unsigned, context("alice", "tenant-a"))), + "bad_signature", + ); +}); + +test("unknown signer and wrong principal fail signer binding", async () => { + const unknown = await buildEnvelope({ + actor: mallory, + tenant: "tenant-a", + domain: DOMAIN, + payload, + }); + assert.equal( + await rejectionClass(gate().admitCanonical(unknown, context("mallory", "tenant-a"))), + "signer_binding", + ); + + const alices = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: DOMAIN, + payload, + }); + assert.equal( + await rejectionClass(gate().admitCanonical(alices, context("bob", "tenant-a"))), + "signer_binding", + ); +}); + +test("wrong tenant scope is unauthorized", async () => { + const envelope = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: DOMAIN, + payload, + }); + assert.equal( + await rejectionClass(gate().admitCanonical(envelope, context("alice", "tenant-b"))), + "unauthorized", + ); +}); + +test("oversized payload and unadmitted domain are policy refusals", async () => { + const oversized = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: DOMAIN, + payload: encoder.encode("123456789"), + }); + const smallGate = gate({ admittedDomains: new Set([DOMAIN]), maxPayloadBytes: 8 }); + assert.equal( + await rejectionClass(smallGate.admitCanonical(oversized, context("alice", "tenant-a"))), + "policy", + ); + + const otherDomain = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: OTHER_DOMAIN, + payload, + }); + assert.equal( + await rejectionClass(gate().admitCanonical(otherDomain, context("alice", "tenant-a"))), + "policy", + ); +}); + +test("garbage bytes are malformed; the blake3 profile is unsupported in this build", async () => { + assert.equal( + await rejectionClass( + gate().admitCanonical(new Uint8Array(24).fill(0xff), context("alice", "tenant-a")), + ), + "malformed", + ); + + const blake3 = await buildEnvelope({ + actor: alice, + tenant: "tenant-a", + domain: DOMAIN, + payload, + profile: "raw-blake3-256", + digestOverride: new Uint8Array(32), + }); + assert.equal( + await rejectionClass(gate().admitCanonical(blake3, context("alice", "tenant-a"))), + "unsupported", + ); +}); + +test("context fields are validated", () => { + assert.throws( + () => admissionContext("", "tenant-a", "admission:write"), + (error: unknown) => + error instanceof AdmissionRejection && error.rejectionClass === "malformed", + ); + assert.throws( + () => admissionContext("alice", "tenant a", "admission:write"), + (error: unknown) => + error instanceof AdmissionRejection && error.rejectionClass === "malformed", + ); + assert.ok(admissionContext("alice", "tenant-a", "x".repeat(255))); +});