diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index e8c7719..c52065a 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -280,7 +280,7 @@ pub(crate) async fn run(state_root_binding: Option) -> anyhow::Result<( require_no_runtime_custody_failure(&mut fatal_events)?; let (revisions, _) = broadcast::channel(32); let cover_budget = configured_cover_budget()?; - let consumers = Arc::new(open_consumer_registry()); + let consumers = Arc::new(open_consumer_registry()?); let mut state = AppState { consumer: ConsumerPort::new(world.clone()), consumers, @@ -452,20 +452,15 @@ async fn cultnet_world_patch( } /// Read once at startup. A missing or unset path means no configured -/// consumers, which is the fail-closed default; a malformed file is fatal to -/// the registry rather than silently empty, so a mistyped credential cannot -/// read as "no consumers configured". -fn open_consumer_registry() -> ConsumerRegistry { +/// consumers, which is the fail-closed default; a malformed file fails +/// startup outright, so a mistyped credential cannot silently read as "no +/// consumers configured". +fn open_consumer_registry() -> anyhow::Result { let Ok(path) = std::env::var(crate::world::CONSUMER_CREDENTIALS_ENVIRONMENT) else { - return ConsumerRegistry::empty(); + return Ok(ConsumerRegistry::empty()); }; - match ConsumerRegistry::from_secret_file(&path) { - Ok(registry) => registry, - Err(error) => { - tracing::warn!(%error, "consumer credentials are unreadable; no consumer is configured"); - ConsumerRegistry::empty() - } - } + ConsumerRegistry::from_secret_file(&path) + .map_err(|error| anyhow::anyhow!("consumer credentials at {path} are unreadable: {error}")) } async fn cultnet_snapshot( @@ -3112,4 +3107,44 @@ mod tests { "every cell in the tick must carry the same tick index" ); } + + /// A missing credentials path is the fail-closed default: no consumer is + /// configured, and startup proceeds. A path that names a file that exists + /// but does not decode is a different situation entirely -- a mistyped or + /// corrupted credential -- and must not be swallowed into the same empty + /// registry. It fails startup instead. + #[test] + fn a_malformed_consumer_credentials_file_refuses_the_registry_rather_than_starting_empty() { + // Serialize against any other test in this binary that touches the + // same process-wide environment variable. + static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _guard = ENV_LOCK.lock().unwrap_or_else(|poison| poison.into_inner()); + + let previous = std::env::var(crate::world::CONSUMER_CREDENTIALS_ENVIRONMENT).ok(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("consumers.cc"); + std::fs::write(&path, b"not a consumer credentials file").unwrap(); + // SAFETY: serialized by ENV_LOCK above; no other thread in this test + // binary reads or writes this variable concurrently. + unsafe { + std::env::set_var( + crate::world::CONSUMER_CREDENTIALS_ENVIRONMENT, + path.as_os_str(), + ); + } + let result = open_consumer_registry(); + // SAFETY: same lock, restoring (or clearing) the prior value. + unsafe { + match &previous { + Some(value) => { + std::env::set_var(crate::world::CONSUMER_CREDENTIALS_ENVIRONMENT, value) + } + None => std::env::remove_var(crate::world::CONSUMER_CREDENTIALS_ENVIRONMENT), + } + } + assert!( + result.is_err(), + "a malformed credentials file must refuse the registry, not start empty" + ); + } } diff --git a/crates/ghostlight-dungeon/src/world/consumer.rs b/crates/ghostlight-dungeon/src/world/consumer.rs index c1528a3..991de0b 100644 --- a/crates/ghostlight-dungeon/src/world/consumer.rs +++ b/crates/ghostlight-dungeon/src/world/consumer.rs @@ -35,7 +35,7 @@ pub(crate) const CONSUMER_BODY_LIMIT: usize = patch::MAX_PATCH_BYTES + CONSUMER_ /// The environment variable naming the credentials file. pub(crate) const CONSUMER_CREDENTIALS_ENVIRONMENT: &str = "GHOSTLIGHT_CONSUMER_CREDENTIALS"; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub(crate) struct ConsumerPatchDocument { /// Pinned to `CONSUMER_PATCH_SCHEMA`; any other value is refused before the @@ -63,6 +63,26 @@ pub(crate) struct ConsumerPatchDocument { pub(crate) patch: Vec, } +/// `derive(Debug)` would print `secret` in plaintext into any log, panic +/// message, or test failure that formats this document. `Debug` is for +/// diagnostics, not custody, so the field is redacted here rather than left to +/// callers to remember not to print it. +impl std::fmt::Debug for ConsumerPatchDocument { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ConsumerPatchDocument") + .field("schema", &self.schema) + .field("world_id", &self.world_id) + .field("consumer", &self.consumer) + .field("secret", &"") + .field("idempotency_key", &self.idempotency_key) + .field("expected_revision", &self.expected_revision) + .field("answers", &self.answers) + .field("patch", &self.patch) + .finish() + } +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub(crate) struct ConsumerReceiptDocument { @@ -110,6 +130,15 @@ pub(crate) enum ConsumerOutcome { pub(crate) enum ConsumerRefusal { Schema, TooLarge, + /// The byte-decoded patch held more declarations than + /// `patch::MAX_PATCH_DECLARATIONS`. + TooManyDeclarations, + /// The byte-decoded patch held more operations than + /// `patch::MAX_PATCH_OPERATIONS`. + TooManyOperations, + /// The byte-decoded patch cited more evidence than + /// `patch::MAX_PATCH_EVIDENCE`. + TooManyEvidence, NotCanonical, Malformed, Unauthenticated, @@ -277,10 +306,10 @@ fn decode_document(bytes: &[u8]) -> Result ConsumerRefusal { match error { - PatchDecodeError::TooLarge { .. } - | PatchDecodeError::TooManyDeclarations { .. } - | PatchDecodeError::TooManyOperations { .. } - | PatchDecodeError::TooManyEvidence { .. } => ConsumerRefusal::TooLarge, + PatchDecodeError::TooLarge { .. } => ConsumerRefusal::TooLarge, + PatchDecodeError::TooManyDeclarations { .. } => ConsumerRefusal::TooManyDeclarations, + PatchDecodeError::TooManyOperations { .. } => ConsumerRefusal::TooManyOperations, + PatchDecodeError::TooManyEvidence { .. } => ConsumerRefusal::TooManyEvidence, PatchDecodeError::NotCanonical => ConsumerRefusal::NotCanonical, PatchDecodeError::Malformed => ConsumerRefusal::Malformed, } @@ -1204,36 +1233,6 @@ mod tests { assert_eq!(candidate, kernel.state); } - #[test] - fn journal_replay_refuses_a_forged_consumer_row() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, mirror) = mirror_kernel(directory.path(), "Forged"); - // A state whose event claims the mirror acted: the mirror's assignment - // has no controller id, so the shape check cannot match one. - let mut forged = kernel.state.clone(); - let event = forged.events.first().cloned(); - if let Some(mut event) = event { - event.scope = DecisionScope { - subject_id: mirror.first, - }; - forged.events = vec![event]; - assert!( - super::super::journal::verify_state_shape(&forged).is_err(), - "a forged consumer row replayed" - ); - } - // And a mirror carrying an affordance grant is refused by the same - // shape check, both ways. - let mut granted = kernel.state.clone(); - let scope = DecisionScope { - subject_id: mirror.first, - }; - granted - .affordance_grants - .insert(scope, BTreeSet::from([AffordanceId::issue()])); - assert!(super::super::journal::verify_state_shape(&granted).is_err()); - } - // ---- confinement, per row -------------------------------------------- #[test] @@ -1781,11 +1780,9 @@ mod tests { // ---- Soul: falsification of the pass's own claims ---------------------- - /// A committed decision under the forgery. `journal_replay_refuses_a_forged_consumer_row` - /// guards its first half behind `if let Some(event) = state.events.first()` - /// and the mirror fixture commits no decision, so that half never runs. - /// This is the same claim with a real event beneath it, and it also proves - /// the honest state — a mirror with no controller and no grant — passes. + /// A committed decision under the forgery, with a real event beneath it, + /// and proof that the honest state — a mirror with no controller and no + /// grant — passes the same shape check. #[test] fn soul_a_forged_decision_event_on_a_mirror_is_refused_at_replay() { let directory = tempfile::tempdir().unwrap(); @@ -1997,7 +1994,7 @@ mod tests { ConsumerRefusal::Unauthenticated, ), ( - "a patch frame over the item cap", + "a patch frame over the declaration cap", encode_document( &build_document( world_id, @@ -2011,7 +2008,7 @@ mod tests { .unwrap(), ) .unwrap(), - ConsumerRefusal::TooLarge, + ConsumerRefusal::TooManyDeclarations, ), ( "a stale expected revision", @@ -2266,4 +2263,30 @@ mod tests { assert!(registry.authenticate(OTHER, SECRET).is_none()); assert!(!format!("{registry:?}").contains(SECRET)); } + + /// The registry's own `Debug` carries only digests to begin with, but the + /// document that arrives off the wire carries the secret in plaintext, and + /// its `derive(Debug)` would have printed it. This is the document-side + /// sibling of `soul_no_secret_reaches_a_registry_error_or_a_registry_debug`. + #[test] + fn soul_no_secret_reaches_a_consumer_patch_document_debug() { + let empty = WorldPatch { + declarations: Vec::new(), + operations: Vec::new(), + evidence: Vec::new(), + }; + let document = build_document( + WorldId::nil_for_test(), + CONSUMER, + SECRET, + "idempotency-key", + 1, + None, + &empty, + ) + .unwrap(); + let rendered = format!("{document:?}"); + assert!(!rendered.contains(SECRET), "{rendered}"); + assert!(rendered.contains(""), "{rendered}"); + } } diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index 7bb69e0..01ffe89 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -60,8 +60,8 @@ const CELL_TOOL_STEP_BUDGET: usize = 2; /// carried by tool identity, never by a model-written argument. const HANDLE_SEPARATOR: &str = "__"; const PERSONA_WORD_BUDGET: usize = 180; -const CONTROLLER_WORK_ROW: &str = "controller_work.v8"; -const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v8"; +const CONTROLLER_WORK_ROW: &str = "controller_work.v9"; +const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v9"; /// The Interpreter's byte-span capture tool. It is not the generated `speak` /// affordance tool: one captures an utterance out of preserved prose, the other @@ -4944,8 +4944,11 @@ mod tests { /// `open` walks every row and demands both the row type and the schema id /// match the current constants, so a row left over from before the bump is /// an open-time error, not a quietly dropped or reinterpreted checkpoint. + /// v8 is the version that predates the pass-10 `session_command_id` + /// derivation change, so a v8 row is exactly the checkpoint this bump + /// exists to refuse. #[test] - fn a_controller_work_row_from_a_prior_schema_is_refused_at_open() { + fn a_controller_work_row_from_schema_v8_is_refused_at_open() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("controller-work.cc"); let command_id = CommandId::new(); @@ -4961,15 +4964,15 @@ mod tests { let mut store = OwnedRedbMessagePackBackingStore::new(&path).unwrap(); let row = CultCacheEnvelope { key: store_key(command_id).unwrap(), - r#type: "controller_work.v5".into(), + r#type: "controller_work.v8".into(), payload: rmp_serde::to_vec_named(&work).unwrap(), stored_at: Utc::now().to_rfc3339(), - schema_id: Some("ghostlight.controller_work.v5".into()), + schema_id: Some("ghostlight.controller_work.v8".into()), }; store.push(&row).unwrap(); } let Err(error) = CultCacheControllerWorkStore::open(&path) else { - panic!("a v5 row was accepted by the v6 store"); + panic!("a v8 row was accepted by the v9 store"); }; assert!(matches!(error, ControllerWorkStoreError::Fault { .. })); } @@ -8187,7 +8190,7 @@ mod tests { .unwrap(); } let Err(error) = CultCacheControllerWorkStore::open(&path) else { - panic!("a v7 row was accepted by the v8 store"); + panic!("a v7 row was accepted by the v9 store"); }; assert!(matches!(error, ControllerWorkStoreError::Fault { .. })); } diff --git a/crates/ghostlight-dungeon/src/world/elaboration.rs b/crates/ghostlight-dungeon/src/world/elaboration.rs index 0478a5a..59045da 100644 --- a/crates/ghostlight-dungeon/src/world/elaboration.rs +++ b/crates/ghostlight-dungeon/src/world/elaboration.rs @@ -426,6 +426,18 @@ impl ElaborationRunner { }) .await?; let draft = filter_evidence(capture.draft, &allowed); + // `check_patch_caps` is the one enforcement site for the + // three item caps on a `WorldPatch` value; the consumer + // ingress reaches it through `decode_patch`, and this is + // the elaboration lane's own call into the same function, + // so `MAX_PATCH_EVIDENCE` (never checked per-tool-call + // above, unlike declarations and operations before this + // pass) is bound here too. + if let Err(error) = patch::check_patch_caps(&draft) { + return Err(ControllerError::Serialization(format!( + "elaboration draft exceeded a patch item cap: {error:?}" + ))); + } let submitted = self .mailbox .submit_elaboration( @@ -919,14 +931,6 @@ fn apply_tool_call( } }, PatchToolShape::Declare { variant, fixed } => { - if draft.declarations.len() >= patch::MAX_PATCH_DECLARATIONS { - gaps.push(tool_decode_need( - name, - arguments, - "the draft is at its declaration cap", - )); - return "the draft is full".into(); - } let mut value = fields; value.insert("type".into(), Value::String(variant.into())); for (key, fixed_value) in fixed { @@ -949,14 +953,6 @@ fn apply_tool_call( } } PatchToolShape::Operate { variant } => { - if draft.operations.len() >= patch::MAX_PATCH_OPERATIONS { - gaps.push(tool_decode_need( - name, - arguments, - "the draft is at its operation cap", - )); - return "the draft is full".into(); - } let mut value = fields; value.insert("op".into(), Value::String(variant.into())); match serde_json::from_value::(Value::Object(value)) { @@ -1027,6 +1023,16 @@ pub(super) fn elaboration_request( /// mailbox's idempotency probe sees the same command. The derivation itself is /// `CommandId::derived`, which is the one recipe every derived command key /// uses. +/// +/// Pass 10 moved this derivation onto `CommandId::derived`, which hashes a +/// different byte stream than the pass-9 spelling did (see +/// `soul_the_session_command_id_derivation_moved_under_the_refactor`). There is +/// no migration for command ids computed under the old spelling: a session +/// checkpointed before this pass would resume under an id the mailbox has +/// never seen, which is exactly the silent-resume failure a bumped schema is +/// for. The `controller_work` row and schema constants carry v9 for the same +/// reason the `consumer.v1` bump exists — a pre-refactor checkpoint refuses to +/// open rather than resuming under a mismatched id. fn session_command_id(session: &ElaboratorSession) -> Result { let scope = digest_of(&(session.world_id, session.jurisdiction))?; Ok(CommandId::derived( @@ -1160,7 +1166,11 @@ mod tests { /// The author owns the size of what it authors. The kernel gets no cap. #[test] - fn a_draft_past_the_size_cap_becomes_a_gap() { + fn a_draft_past_the_declaration_cap_is_refused_by_the_shared_cap_check() { + // The elaboration lane no longer caps a declaration mid-round: one + // enforcement site, `check_patch_caps`, catches an over-cap draft + // before it reaches submission (see `step`), so at this layer the + // draft grows past the cap uncapped. let mut calls: Vec<(&str, Value)> = (0..=patch::MAX_PATCH_DECLARATIONS) .map(|index| { ( @@ -1177,11 +1187,44 @@ mod tests { let capture = capture(&vec![output(calls)]); assert_eq!( capture.draft.declarations.len(), - patch::MAX_PATCH_DECLARATIONS + patch::MAX_PATCH_DECLARATIONS + 1 ); - assert!( - capture.gaps.iter().any(|gap| gap.detail.contains("cap")), - "the call past the cap was not recorded as a gap" + assert_eq!( + patch::check_patch_caps(&capture.draft), + Err(patch::PatchDecodeError::TooManyDeclarations { + count: patch::MAX_PATCH_DECLARATIONS + 1 + }) + ); + } + + /// `MAX_PATCH_EVIDENCE` has no pre-append check at all: every admitted + /// citation is pushed to the draft unconditionally as it is captured. + /// `check_patch_caps` is the one place that bites, and it bites at the same + /// function every other cap goes through -- there is no separate, + /// unenforced evidence path on the elaboration lane. + #[test] + fn an_over_evidence_draft_is_refused_by_the_shared_cap_check() { + let mut calls: Vec<(&str, Value)> = (0..=patch::MAX_PATCH_EVIDENCE) + .map(|index| { + ( + "admit", + serde_json::json!({ + "holder": {"ref": "existing", "value": "00000000-0000-0000-0000-000000000001"}, + "resource": {"ref": "existing", "value": "00000000-0000-0000-0000-000000000002"}, + "qty": 1, + "evidence": format!("vault:harvest-{index}"), + }), + ) + }) + .collect(); + calls.push((SUBMIT_PATCH_TOOL, serde_json::json!({}))); + let capture = capture(&vec![output(calls)]); + assert_eq!(capture.draft.evidence.len(), patch::MAX_PATCH_EVIDENCE + 1); + assert_eq!( + patch::check_patch_caps(&capture.draft), + Err(patch::PatchDecodeError::TooManyEvidence { + count: patch::MAX_PATCH_EVIDENCE + 1 + }) ); } diff --git a/crates/ghostlight-dungeon/src/world/patch.rs b/crates/ghostlight-dungeon/src/world/patch.rs index 3838093..86e8e4b 100644 --- a/crates/ghostlight-dungeon/src/world/patch.rs +++ b/crates/ghostlight-dungeon/src/world/patch.rs @@ -1144,8 +1144,10 @@ pub(crate) struct WorldPatch { /// The one byte bound on a `WorldPatch` frame from any external source, and /// the three item bounds on a `WorldPatch` as a value. One owner, two -/// consumers: the consumer ingress decodes against them, and the elaboration -/// lane checks its own draft against the same two item caps. +/// consumers: the consumer ingress decodes against them through +/// `decode_patch`, and the elaboration lane checks its own assembled draft +/// against the same three item caps through `check_patch_caps`, before +/// submission. pub(crate) const MAX_PATCH_BYTES: usize = 256 * 1024; pub(crate) const MAX_PATCH_DECLARATIONS: usize = 64; pub(crate) const MAX_PATCH_OPERATIONS: usize = 128;