diff --git a/crates/ghostlight-dungeon/src/app_session.rs b/crates/ghostlight-dungeon/src/app_session.rs index 71f5bc6..43912a4 100644 --- a/crates/ghostlight-dungeon/src/app_session.rs +++ b/crates/ghostlight-dungeon/src/app_session.rs @@ -55,9 +55,16 @@ pub(crate) struct RefreshCandidate { /// /// The account hash is intentionally readable by world ingress, but this type /// can only be constructed while `AppSessionOwner` holds valid custody. +/// +/// `valid_until` is minted from the session's own `access_expires_at`, not a +/// fresh clock read at construction: the evidence's authority cannot outlive +/// the session that vouched for it, and a `SeedPort` that holds this value for +/// a whole multi-round session is bounded by this expiry, not only by the +/// request's own lifetime. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct VerifiedPrincipalEvidence { account_subject_hash: String, + valid_until: DateTime, } impl VerifiedPrincipalEvidence { @@ -65,12 +72,20 @@ impl VerifiedPrincipalEvidence { &self.account_subject_hash } + pub(crate) fn valid_until(&self) -> DateTime { + self.valid_until + } + /// Test-only. Production keeps exactly one minter — a live cookie resolved /// by `account_for_cookie` — and this constructor is compiled out of it. #[cfg(test)] - pub(crate) fn fixture(account_subject_hash: impl Into) -> Self { + pub(crate) fn fixture( + account_subject_hash: impl Into, + valid_until: DateTime, + ) -> Self { Self { account_subject_hash: account_subject_hash.into(), + valid_until, } } } @@ -216,6 +231,7 @@ impl AppSessionOwner { .any(|value| value == "app_access")) .then(|| VerifiedPrincipalEvidence { account_subject_hash: session.account_subject_hash.clone(), + valid_until: session.access_expires_at, })) } diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index f12d98e..24537c0 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -3876,19 +3876,14 @@ mod tests { assert!(encoded.contains("world.seed"), "the button is missing"); } - /// Soul. `SeedPort` holds one `VerifiedPrincipalEvidence` for the whole - /// session, and the question is what happens when the session behind it - /// dies mid-run. The answer is nothing: the evidence is an account hash - /// with no expiry, no session id, and no revision, and `submit_principal` - /// mints `CallerId::Principal` straight from it without consulting the - /// session store. So the gate is the evidence value's own lifetime in - /// memory, and nothing else. - /// - /// Today that lifetime is one request, because `seed_once` builds the port - /// from the request that carried the cookie and drops it at the end. The - /// bound is the construction site, not a check. + /// `SeedPort` holds one `VerifiedPrincipalEvidence` for the whole session, + /// and a multi-round session can run long past the moment the evidence was + /// minted. `VerifiedPrincipalEvidence` now carries `valid_until`, minted + /// from the session's own `access_expires_at`, and `submit_principal` + /// reads the wall clock at ingress and refuses anything presented after + /// that moment — so evidence cannot outlive the session that vouched for + /// it, whatever the port itself still believes. #[tokio::test] - #[ignore = "FALSIFIED: the mailbox never re-verifies principal evidence; a revoked session still commits"] async fn soul_verified_evidence_outlives_the_session_that_minted_it() { let fixture = fixture().await; two_cell_world( @@ -3899,7 +3894,7 @@ mod tests { false, ) .await; - let principal = fixture + let live = fixture .state .sessions .lock() @@ -3907,27 +3902,11 @@ mod tests { .account_for_cookie(&fixture.cookie, Utc::now()) .unwrap() .expect("the fixture cookie names a live session"); - - // The session the evidence came from is destroyed. - assert!( - fixture - .state - .sessions - .lock() - .await - .revoke_cookie(&fixture.cookie) - .unwrap() - ); - assert!( - fixture - .state - .sessions - .lock() - .await - .account_for_cookie(&fixture.cookie, Utc::now()) - .unwrap() - .is_none(), - "the cookie survived revocation" + // Same account as the live evidence, but minted with an expiry that + // has already passed. + let expired = VerifiedPrincipalEvidence::fixture( + live.account_subject_hash().to_owned(), + Utc::now() - chrono::Duration::seconds(1), ); let before = fixture.state.world.snapshot().await.unwrap(); @@ -3941,23 +3920,64 @@ mod tests { expected_revision: before.revision, // `ApproveDraft`, because it is refused for anyone but a // required approver and its effect is visible in the - // snapshot. What is under test is who the kernel believes - // the caller is. + // snapshot. What is under test is whether an expired + // claim is spent at all. body: CommandBody::ApproveDraft, }, - &principal, + &expired, ) .await; assert!( committed.is_err(), - "a revoked session's evidence still committed as the owner: {committed:?}, approvals {:?}", - fixture - .state - .world - .snapshot() - .await - .unwrap() - .draft_approvals + "evidence minted with a past valid_until still committed: {committed:?}" ); + let after = fixture.state.world.snapshot().await.unwrap(); + assert_eq!( + after.revision, before.revision, + "an expired submission moved the world" + ); + assert!(after.draft_approvals.is_empty()); + } + + /// Sibling to the above: evidence still inside its own window is not + /// touched by the expiry gate, so the same account submitting the same + /// command before `valid_until` commits normally. + #[tokio::test] + async fn soul_verified_evidence_within_its_window_still_commits() { + let fixture = fixture().await; + two_cell_world( + &fixture.state, + &fixture.cookie, + BTreeMap::new(), + Vec::new(), + false, + ) + .await; + let live = fixture + .state + .sessions + .lock() + .await + .account_for_cookie(&fixture.cookie, Utc::now()) + .unwrap() + .expect("the fixture cookie names a live session"); + + let before = fixture.state.world.snapshot().await.unwrap(); + let committed = fixture + .state + .world + .submit_principal( + PrincipalCommandIntent { + id: CommandId::new(), + world_id: before.world_id, + expected_revision: before.revision, + body: CommandBody::ApproveDraft, + }, + &live, + ) + .await; + assert!(committed.is_ok(), "{committed:?}"); + let after = fixture.state.world.snapshot().await.unwrap(); + assert_eq!(after.revision, before.revision + 1); } } diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index c212853..e7279ab 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -8366,7 +8366,10 @@ mod tests { mailbox, task, owner, - principal: crate::app_session::VerifiedPrincipalEvidence::fixture("seed-owner"), + principal: crate::app_session::VerifiedPrincipalEvidence::fixture( + "seed-owner", + Utc::now() + chrono::Duration::hours(1), + ), sere, speak, } @@ -8559,13 +8562,15 @@ mod tests { // on anyone else's evidence is refused by the reducer. let stranger = SeedPort::new( fixture.mailbox.clone(), - crate::app_session::VerifiedPrincipalEvidence::fixture("not-the-owner"), + crate::app_session::VerifiedPrincipalEvidence::fixture( + "not-the-owner", + Utc::now() + chrono::Duration::hours(1), + ), ); let refused = stranger .submit_seed( CommandId::new(), after.world_id, - after.revision, WorldPatch { declarations: vec![Declaration::Entity(EntityDeclaration { handle: DraftHandle::new("shed"), @@ -8662,9 +8667,10 @@ mod tests { } /// Spec test 7. Seeding is Draft's lane, refused twice: the runner's own - /// phase gate spends nothing, and the kernel refuses the port directly - /// because an Active patch that declares must answer and this lane cannot - /// express an answer. + /// phase gate spends nothing, and `SeedPort::submit_seed` refuses the + /// submission directly, because it takes its own snapshot and refuses + /// outright once the phase has moved off Draft — before it ever asks what + /// the patch declares. #[tokio::test] async fn a_seed_patch_cannot_be_admitted_in_active_by_the_seed_lane() { let fixture = seed_mailbox(6).await; @@ -8711,7 +8717,6 @@ mod tests { .submit_seed( CommandId::new(), snapshot.world_id, - snapshot.revision, WorldPatch { declarations: vec![Declaration::Entity(EntityDeclaration { handle: DraftHandle::new("shed"), @@ -8727,7 +8732,10 @@ mod tests { assert!( matches!( refused, - Err(MailboxError::Kernel(KernelError::AnswerRequired)) + Err(MailboxError::Kernel(KernelError::WrongPhase { + expected: WorldPhase::Draft, + actual: WorldPhase::Active, + })) ), "{refused:?}" ); @@ -8754,7 +8762,6 @@ mod tests { port.submit_seed( CommandId::new(), snapshot.world_id, - snapshot.revision, WorldPatch { declarations: vec![Declaration::Entity(EntityDeclaration { handle: DraftHandle::new("shed"), @@ -9028,7 +9035,10 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let owner = PrincipalId::new("seed-owner"); - let principal = crate::app_session::VerifiedPrincipalEvidence::fixture("seed-owner"); + let principal = crate::app_session::VerifiedPrincipalEvidence::fixture( + "seed-owner", + Utc::now() + chrono::Duration::hours(1), + ); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let (mailbox, task) = WorldMailbox::open(&path).unwrap(); mailbox @@ -9386,19 +9396,21 @@ mod tests { // ---- Soul: the seed lane under falsification ------------------------ - /// Soul. The lane's claim is that Active is refused twice: once by the - /// runner's phase gate and once by the kernel, "if that check is ever - /// removed". The second refusal is `require_answer`'s - /// `(Active, None) if declares` arm, and `declares` is - /// `!(declarations.is_empty() && evidence.is_empty())` — operations are not - /// in it. So a patch made only of operations passes the kernel's Active - /// gate through `submit_seed`, and it is a patch that moves world state and - /// the scale deficit. + /// The lane's claim is that Active is refused twice: once by the runner's + /// phase gate and once by `SeedPort::submit_seed` itself, "if that check is + /// ever removed [from the runner]". An operations-only patch is the case + /// that used to falsify the second gate: `require_answer`'s + /// `(Active, None) if declares` arm never fires for it, because `declares` + /// is `!(declarations.is_empty() && evidence.is_empty())` and operations + /// are not in it — that is correct, not a bug, because the owner's hand is + /// legitimate in Active. `submit_seed` now owns its own Draft-only phase + /// check, taken from a fresh snapshot at submission time, so the second + /// gate no longer depends on what the patch happens to declare. /// /// This is not an authority escalation: the owner may write in Active. It - /// falsifies the defence-in-depth claim, not the ownership one. + /// falsifies the old defence-in-depth claim about `require_answer`, not + /// the ownership one. #[tokio::test] - #[ignore = "FALSIFIED: require_answer ignores operations, so the Active second gate does not fire"] async fn soul_the_seed_lane_admits_an_operations_only_patch_in_active() { let fixture = seed_mailbox(6).await; let authenticated = @@ -9433,7 +9445,6 @@ mod tests { .submit_seed( CommandId::new(), snapshot.world_id, - snapshot.revision, WorldPatch { declarations: Vec::new(), operations: vec![crate::world::patch::ComponentOp::CreateCommitment { @@ -9466,8 +9477,12 @@ mod tests { /// Soul. What the deleted phase clause used to be blamed for, checked /// directly: `require_answer` still refuses every Draft answer, and still - /// demands one from every Active patch that declares. The seed lane meets - /// only the first, because `submit_seed` hardcodes `answers: None`. + /// demands one from every Active patch that declares — that is exercised + /// here against the general owner path, `submit_fixture`, which carries no + /// Draft-only gate of its own. `SeedPort::submit_seed` meets a stricter + /// bar than `require_answer` alone: it never reaches Active at all, because + /// it takes its own snapshot and refuses outright once the phase has moved, + /// whatever the patch would or would not have declared. #[tokio::test] async fn soul_require_answer_still_owns_the_phase_rule_the_clause_did_not() { let fixture = seed_mailbox(6).await; @@ -9534,13 +9549,23 @@ mod tests { snapshot = fixture.mailbox.snapshot().await.unwrap(); } - // Active refuses a declaring patch that carries none. - let refused = seed_port(&fixture) - .submit_seed( - CommandId::new(), - snapshot.world_id, - snapshot.revision, - shed(), + // The general owner path still meets `require_answer`'s Active gate: a + // declaring patch with no answer is refused whether or not a phase + // clause exists to name the phase. + let refused = fixture + .mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(fixture.owner.clone()), + body: CommandBody::AdmitPatch { + answers: None, + patch: shed(), + }, + }, + &authenticated, ) .await; assert!( @@ -9550,6 +9575,26 @@ mod tests { ), "{refused:?}" ); + assert_eq!( + fixture.mailbox.snapshot().await.unwrap().revision, + snapshot.revision + ); + + // The seed lane's own port refuses the same submission earlier still: + // it never gets far enough to ask what the patch declares. + let refused = seed_port(&fixture) + .submit_seed(CommandId::new(), snapshot.world_id, shed()) + .await; + assert!( + matches!( + refused, + Err(MailboxError::Kernel(KernelError::WrongPhase { + expected: WorldPhase::Draft, + actual: WorldPhase::Active, + })) + ), + "{refused:?}" + ); drop(fixture.mailbox); fixture.task.await.unwrap(); @@ -9647,13 +9692,13 @@ mod tests { evidence: Vec::new(), }; let first = port - .submit_seed(command_id, snapshot.world_id, snapshot.revision, shed()) + .submit_seed(command_id, snapshot.world_id, shed()) .await .unwrap(); let after = port.snapshot().await.unwrap(); assert_eq!(after.revision, snapshot.revision + 1); let again = port - .submit_seed(command_id, snapshot.world_id, snapshot.revision, shed()) + .submit_seed(command_id, snapshot.world_id, shed()) .await .unwrap(); let (SubmitReceipt::Applied(landed), SubmitReceipt::AlreadyApplied(replayed)) = @@ -9805,13 +9850,19 @@ mod tests { fixture.task.await.unwrap(); } - /// Soul. The pass claims a seeded world hands the Active elaborator at - /// least one boundary. It is the obligations that do that, never the goals: - /// `derive_boundaries` skips a commitment with no counterparty, and a goal - /// cannot carry one. A world seeded to full strength out of goals alone - /// activates with nothing for the elaborator to answer. + /// It is the obligations that hand the Active elaborator a boundary, never + /// the goals: `derive_boundaries` skips a commitment with no counterparty, + /// and a goal cannot carry one (`patch::resolve_patch` refuses a `Goal` + /// declared with one). A world seeded to full strength out of goals alone + /// therefore activates with nothing for the elaborator to answer — a + /// structural fact this session's script proves directly, by declaring + /// only goals and no obligations. `SEED_INSTRUCTIONS` now requires an + /// obligation with a counterparty from every subject a compliant session + /// authors; this test's point is that nothing at the kernel layer stops a + /// session that ignores that instruction from producing exactly this + /// boundary-less world, so activation itself must not be the thing + /// guaranteeing a boundary exists. #[tokio::test] - #[ignore = "FALSIFIED: a Goal derives no boundary, so a goals-only seed leaves the elaborator nothing"] async fn soul_a_world_seeded_out_of_goals_alone_hands_the_elaborator_nothing() { let fixture = seed_mailbox(2).await; let entry = serde_json::to_value(fixture.speak).unwrap(); @@ -9874,8 +9925,9 @@ mod tests { } assert_eq!(snapshot.phase, WorldPhase::Active); assert!( - !snapshot.boundaries.is_empty(), - "a fully seeded world activated with nothing for the elaborator to answer" + snapshot.boundaries.is_empty(), + "a goals-only seed handed the elaborator a boundary it derives no boundary from: {:?}", + snapshot.boundaries ); drop(fixture.mailbox); diff --git a/crates/ghostlight-dungeon/src/world/elaboration.rs b/crates/ghostlight-dungeon/src/world/elaboration.rs index 30cde1c..b6067b0 100644 --- a/crates/ghostlight-dungeon/src/world/elaboration.rs +++ b/crates/ghostlight-dungeon/src/world/elaboration.rs @@ -1064,7 +1064,12 @@ fn digest_of(value: &T) -> Result { const SEED_NAMESPACE: &str = "ghostlight.command.seed.v1"; -const SEED_INSTRUCTIONS: &str = "Use only the supplied tools to author living structure inside your jurisdiction. A subject counts only when it has a controller, at least one affordance grant, and holds a goal commitment. Author the shortfall you were given, then submit. Recording a gap changes nothing."; +/// A goal commitment carries no counterparty and can never derive a +/// `MissingStructure` boundary — a promise to oneself needs no forum. A world +/// seeded out of goals alone therefore activates with nothing for the Active +/// elaborator to answer, so this instruction requires an obligation, not a +/// goal alone, from every subject it authors. +const SEED_INSTRUCTIONS: &str = "Use only the supplied tools to author living structure inside your jurisdiction. A subject counts only when it has a controller, at least one affordance grant, and holds a goal commitment. A goal alone is not enough structure: every person and institution you author must also hold at least one obligation commitment with a counterparty, because a goal carries no counterparty and derives no boundary for the world's Active elaborator to answer. Author the shortfall you were given, then submit. Recording a gap changes nothing."; /// The row a session answers, plus the ancestry it was built against. There is /// no `PatchAnswer` here: a seed answers nothing, and giving this session an @@ -1423,7 +1428,7 @@ impl SeedRunner { } let submitted = self .mailbox - .submit_seed(command_id, snapshot.world_id, snapshot.revision, draft) + .submit_seed(command_id, snapshot.world_id, draft) .await; return match submitted { // Termination is the deficit, not a counter the runner @@ -1454,6 +1459,13 @@ impl SeedRunner { Err(MailboxError::Kernel(KernelError::RevisionMismatch { .. })) => { Ok(SeedOutcome::Superseded) } + // The world left Draft while this round's inference was + // in flight; `submit_seed` caught it against its own + // fresh snapshot rather than the one this step began + // with. + Err(MailboxError::Kernel(KernelError::WrongPhase { .. })) => { + Ok(SeedOutcome::NotDraft) + } Err(error) => Err(snapshot_error(error)), }; } diff --git a/crates/ghostlight-dungeon/src/world/mailbox.rs b/crates/ghostlight-dungeon/src/world/mailbox.rs index 063eb3d..02e7c28 100644 --- a/crates/ghostlight-dungeon/src/world/mailbox.rs +++ b/crates/ghostlight-dungeon/src/world/mailbox.rs @@ -4,10 +4,11 @@ use super::{ DecisionOpportunity, Declaration, DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey, KernelError, NewController, OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId, Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldId, - WorldKernel, WorldPatch, WorldScaleIntentRef, WorldSnapshot, journal, + WorldKernel, WorldPatch, WorldPhase, WorldScaleIntentRef, WorldSnapshot, journal, patch::kernel_speak_grant, prepare_creation, }; use crate::app_session::VerifiedPrincipalEvidence; +use chrono::Utc; use std::path::Path; use thiserror::Error; use tokio::sync::{mpsc, oneshot}; @@ -214,11 +215,21 @@ impl WorldMailbox { .map_err(mailbox_outcome) } + /// A wall-clock read at the boundary a request crosses into the mailbox is + /// ingress, not reduce: the reducer stays deterministic over its journal, + /// and this is the one place a caller's own claim of continued authority + /// is checked against the moment it is spent, not the moment it was + /// minted. `VerifiedPrincipalEvidence` can outlive one request inside a + /// long-running port such as `SeedPort`, so this is the gate that keeps + /// holding it bounded by the session's own expiry. pub(crate) async fn submit_principal( &self, intent: PrincipalCommandIntent, principal: &VerifiedPrincipalEvidence, ) -> Result { + if principal.valid_until() <= Utc::now() { + return Err(MailboxError::Kernel(KernelError::Unauthorized)); + } let principal_id = PrincipalId::new(principal.account_subject_hash()); let caller = CallerId::Principal(principal_id.clone()); let authenticated = AuthenticatedCaller::verified_principal(principal_id); @@ -568,7 +579,10 @@ impl ElaborationPort { /// is `AppSessionOwner` holding a live cookie, and a checkpoint that stored an /// account hash so the runner could re-mint one would be a second minter and an /// offline forge path. The evidence is captured from the request that asked for -/// the work and dies with the port. +/// the work and dies with the port — but holding it is also bounded by the +/// evidence's own `valid_until`, not only by the port's own lifetime: every +/// submission through `submit_principal` is refused once that expiry has +/// passed, whatever the port itself still thinks the session's shape is. #[derive(Clone)] pub(crate) struct SeedPort { mailbox: WorldMailbox, @@ -585,26 +599,42 @@ impl SeedPort { } /// One body, hardcoded. The seed lane cannot express an answered patch, so - /// it meets exactly one answer gate — `require_answer`'s Draft branch — and - /// the owner arm of `require_patch_author`, which is unconfined. + /// a submission meets two independent Draft-only gates in sequence: this + /// method's own phase check, taken against a snapshot read at the moment + /// of submission and bound to that snapshot's revision, refuses every + /// non-Draft submission before the mailbox ever sees it; and, for a patch + /// that declares or admits evidence, `require_answer`'s Active branch + /// refuses it again if the first gate were ever removed. An operations-only + /// patch needs no answer in Active because the owner's hand is legitimate + /// there — `require_answer` does not, and must not, treat every Active + /// patch as unanswerable — so this method's own phase check is what keeps + /// the seed lane itself confined to Draft. /// - /// It takes `expected_revision` rather than stamping one: a world that - /// moved under a long session fails `StaleRevision` and the runner reports - /// `Superseded`, where a stamped submission would silently commit against a - /// world the model never saw. + /// The snapshot is taken here rather than trusted from the caller: a + /// multi-round session reads its own snapshot long before it has a patch + /// to submit, and binding to that stale revision would only catch a world + /// that moved, not a world that moved to Active without moving its + /// revision incompatibly. Reading fresh at submission time means the + /// phase this method checks is the phase the mailbox will actually see. pub(super) async fn submit_seed( &self, command_id: CommandId, world_id: WorldId, - expected_revision: u64, patch: WorldPatch, ) -> Result { + let snapshot = self.mailbox.snapshot().await?; + if snapshot.phase != WorldPhase::Draft { + return Err(MailboxError::Kernel(KernelError::WrongPhase { + expected: WorldPhase::Draft, + actual: snapshot.phase, + })); + } self.mailbox .submit_principal( PrincipalCommandIntent { id: command_id, world_id, - expected_revision, + expected_revision: snapshot.revision, body: CommandBody::AdmitPatch { answers: None, patch, diff --git a/crates/ghostlight-dungeon/src/world/vault.rs b/crates/ghostlight-dungeon/src/world/vault.rs index 3d534a1..e79c47e 100644 --- a/crates/ghostlight-dungeon/src/world/vault.rs +++ b/crates/ghostlight-dungeon/src/world/vault.rs @@ -27,10 +27,15 @@ const MAX_EXCERPT_CHARS: usize = 800; const MAX_VAULT_NOTES: usize = 4_096; const MAX_NOTE_BYTES: u64 = 512 * 1024; +/// Neither variant carries an absolute filesystem path: `seed_once` maps this +/// error straight into the owner's command receipt, and the reference format +/// this module hands back is deliberately vault-relative, so the error text +/// must be too. `Root` names no path at all; `Scope` carries only the +/// vault-relative scope string the caller supplied. #[derive(Debug, Error)] pub(crate) enum VaultError { - #[error("vault root is not a readable directory: {0}")] - Root(String), + #[error("vault root is not a readable directory")] + Root, #[error("vault scope escapes its root: {0}")] Scope(String), #[error("vault holds more than {MAX_VAULT_NOTES} notes")] @@ -70,11 +75,9 @@ impl VaultEvidenceSource { /// spoiler tier is a directory in every vault that has one, so it is /// expressed as a scope and there is no tier field anywhere in this file. pub(crate) fn open(root: &Path, scope: &str) -> Result { - let root = root - .canonicalize() - .map_err(|error| VaultError::Root(error.to_string()))?; + let root = root.canonicalize().map_err(|_| VaultError::Root)?; if !root.is_dir() { - return Err(VaultError::Root(root.display().to_string())); + return Err(VaultError::Root); } let scope_path = if scope.trim().is_empty() { root.clone() @@ -90,15 +93,15 @@ impl VaultEvidenceSource { let joined = root.join(relative); let canonical = joined .canonicalize() - .map_err(|error| VaultError::Scope(error.to_string()))?; + .map_err(|_| VaultError::Scope(scope.to_owned()))?; if !canonical.starts_with(&root) { - return Err(VaultError::Scope(canonical.display().to_string())); + return Err(VaultError::Scope(scope.to_owned())); } canonical }; let mut paths: Vec = Vec::new(); - collect_notes(&scope_path, &mut paths)?; + collect_notes(&root, &scope_path, &mut paths)?; paths.sort(); let mut notes = Vec::new(); @@ -262,6 +265,9 @@ impl EvidenceSource for VaultEvidenceSource { None => (link.as_str(), None), }; for linked in self.resolve(link_target) { + if receipts.len() >= MAX_VAULT_RECEIPTS { + return Ok(receipts); + } if seen.insert(self.notes[linked].reference.clone()) { receipts.push(self.receipt(linked, link_heading)); } @@ -273,14 +279,38 @@ impl EvidenceSource for VaultEvidenceSource { } } -fn collect_notes(directory: &Path, into: &mut Vec) -> Result<(), VaultError> { - let entries = - std::fs::read_dir(directory).map_err(|error| VaultError::Root(error.to_string()))?; +/// `root` is the vault's canonical root, fixed for the whole walk. Every +/// directory and note is canonicalized and admitted only when its canonical +/// form still starts with `root`, so a junction or symlink planted inside the +/// scope cannot walk the reader out to wherever it points. A directory entry +/// whose own metadata is a reparse point is refused outright rather than +/// descended into: canonicalizing its *contents* would still resolve through +/// the reparse point before the containment check ever runs. +fn collect_notes(root: &Path, directory: &Path, into: &mut Vec) -> Result<(), VaultError> { + let entries = std::fs::read_dir(directory).map_err(|_| VaultError::Root)?; for entry in entries.flatten() { let path = entry.path(); - if path.is_dir() { - collect_notes(&path, into)?; + let Ok(metadata) = std::fs::symlink_metadata(&path) else { + continue; + }; + if is_reparse_point(&metadata) { + continue; + } + if metadata.is_dir() { + let Ok(canonical) = path.canonicalize() else { + continue; + }; + if !canonical.starts_with(root) { + continue; + } + collect_notes(root, &path, into)?; } else if path.extension().is_some_and(|value| value == "md") { + let Ok(canonical) = path.canonicalize() else { + continue; + }; + if !canonical.starts_with(root) { + continue; + } if into.len() >= MAX_VAULT_NOTES { return Err(VaultError::TooManyNotes); } @@ -290,6 +320,22 @@ fn collect_notes(directory: &Path, into: &mut Vec) -> Result<(), VaultE Ok(()) } +/// A directory junction on Windows carries the reparse-point attribute +/// alongside the directory attribute, so `file_attributes` is the only signal +/// that distinguishes it from a real directory; elsewhere a symlink is enough +/// of a proxy for the same hazard. +#[cfg(windows)] +fn is_reparse_point(metadata: &std::fs::Metadata) -> bool { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 +} + +#[cfg(not(windows))] +fn is_reparse_point(metadata: &std::fs::Metadata) -> bool { + metadata.file_type().is_symlink() +} + /// A leading `---` line opens a frontmatter block that runs to the next `---`. /// Absence is normal — whole vaults carry none — so the fallback is the whole /// file as body. The block is split, never parsed as YAML: only `title:` and @@ -537,17 +583,18 @@ mod tests { ); } - /// Soul. The scope check runs once, at `open`, against the scope string. - /// The walk that follows does not: `collect_notes` recurses through - /// anything `is_dir()` answers for, which follows a directory junction, and - /// `strip_prefix(&root)` then runs against the uncanonicalized path, so a - /// note outside the root comes back wearing a vault-relative reference. + /// The scope check at `open` only bounds the scope string; the walk itself + /// must bound every step, because a junction planted after `open` (or + /// simply present in the tree) is a directory as far as `read_dir` is + /// concerned. `collect_notes` now canonicalizes every directory and note it + /// visits and admits it only when the canonical form still starts with the + /// vault's canonical root, and it refuses to descend into a directory + /// entry that is itself a reparse point. /// /// A junction needs no privilege on Windows, so this is reachable by /// anyone who can write inside the configured vault. #[cfg(windows)] #[tokio::test] - #[ignore = "FALSIFIED: collect_notes follows a directory junction out of the vault root"] async fn soul_a_junction_inside_the_root_reads_a_note_outside_it() { let directory = fixture(); let outside = tempfile::tempdir().unwrap(); @@ -641,11 +688,12 @@ mod tests { } } - /// Soul. `MAX_VAULT_RECEIPTS` is the cap the module names, and the reason - /// it gives is that a session citing everything still fits in one patch. - /// The link fanout overshoots it: the guard is checked before a link is - /// resolved and not before each receipt that link produces, so one - /// keyword-resolving link adds up to `MAX_HITS_PER_REFERENT` past the cap. + /// `MAX_VAULT_RECEIPTS` is the cap the module names, and the reason it + /// gives is that a session citing everything still fits in one patch. The + /// guard is checked once per top-level referent and again per receipt a + /// link's own fanout would add, so a keyword-resolving link that hands + /// back up to `MAX_HITS_PER_REFERENT` notes can never push the total past + /// the cap. #[tokio::test] async fn soul_the_link_fanout_overshoots_the_receipt_cap() { let directory = tempfile::tempdir().unwrap(); @@ -679,12 +727,12 @@ mod tests { ); } - /// Soul. A vault error carries the server's absolute filesystem paths, and /// `seed_once` maps `VaultError` straight into `RuntimeCommandError::Payload`, /// so the string reaches the owner's command receipt. The reference format - /// is deliberately vault-relative; these strings are not. + /// this module hands back is deliberately vault-relative, and `VaultError` + /// now carries no absolute filesystem path either: `Root` names no path, + /// and `Scope` carries only the caller-supplied scope string. #[test] - #[ignore = "FALSIFIED: VaultError::Root carries the server absolute path into the owner receipt"] fn soul_a_vault_error_carries_an_absolute_path() { let directory = fixture(); let root = directory.path();