diff --git a/atomic-cli/src/commands/git/hooks.rs b/atomic-cli/src/commands/git/hooks.rs index 1062a53c..615e972f 100644 --- a/atomic-cli/src/commands/git/hooks.rs +++ b/atomic-cli/src/commands/git/hooks.rs @@ -879,12 +879,7 @@ fn gate_config( repo: &atomic_repository::Repository, ) -> atomic_repository::repository::provenance_gate::PublicationGateConfig { atomic_repository::repository::provenance_gate::PublicationGateConfig::from_repo(repo) - .unwrap_or( - atomic_repository::repository::provenance_gate::PublicationGateConfig { - trust: Default::default(), - repository_identity: None, - }, - ) + .unwrap_or_default() } pub(crate) fn record_pre_commit(root: &Path) -> CliResult<()> { diff --git a/atomic-cli/src/commands/git/verify_receive.rs b/atomic-cli/src/commands/git/verify_receive.rs index 6aa58237..285158d1 100644 --- a/atomic-cli/src/commands/git/verify_receive.rs +++ b/atomic-cli/src/commands/git/verify_receive.rs @@ -273,12 +273,7 @@ fn gate_config( repo: &Repository, ) -> atomic_repository::repository::provenance_gate::PublicationGateConfig { atomic_repository::repository::provenance_gate::PublicationGateConfig::from_repo(repo) - .unwrap_or( - atomic_repository::repository::provenance_gate::PublicationGateConfig { - trust: Default::default(), - repository_identity: None, - }, - ) + .unwrap_or_default() } /// Walk first-parent history from `tip` to the nearest projection commit and diff --git a/atomic-cli/tests/it/agent_hook_publication_gate_test.rs b/atomic-cli/tests/it/agent_hook_publication_gate_test.rs new file mode 100644 index 00000000..29162d90 --- /dev/null +++ b/atomic-cli/tests/it/agent_hook_publication_gate_test.rs @@ -0,0 +1,410 @@ +//! Regression coverage for atomicdotdev/atomic#330: changes recorded by the +//! Claude Code agent hooks ("managed-session" changes) must be publishable +//! through the trusted provenance gate once their session has been attested +//! by the user's own identity. +//! +//! Each test drives the real `atomic agent hooks claude-code ` entry +//! points the way `atomic agent enable` installs them, in a Git repository +//! imported with `atomic git import`, under an isolated `HOME` / +//! `ATOMIC_CONFIG_DIR` so the identity store is private to the test. +//! +//! Before the fix: +//! +//! * After `SessionEnd`, the attestation is signed by the user's default +//! identity, yet the gate reports that signer as "unknown (not +//! configured)", so both `atomic git push` and `atomic insert` into a +//! shared view refuse every hook-recorded change. +//! * A repository that names its identity in `[author] identity` (by +//! identity name, as `atomic org set` writes it) still never trusts it, +//! because the name is compared verbatim against the signer DID. +//! * Refusals do not say how to recover: the in-session refusal does not say +//! that attestations are written at session end, and the untrusted-signer +//! refusal does not say how to configure `[git.trust]`. + +// The hooks drive the Git shim, which is Unix-only for now. +#![cfg(unix)] + +use std::fs; +use std::io::Write as _; +use std::path::Path; +use std::process::{Command, Output, Stdio}; + +use serde_json::Value; +use tempfile::TempDir; + +const ATOMIC_BIN: &str = env!("CARGO_BIN_EXE_atomic"); + +const USER: &str = "repro"; +const AGENT: &str = "repro-claude"; + +struct Fixture { + home: TempDir, + repository: TempDir, + session: String, +} + +impl Fixture { + /// The issue's setup: a default user identity, a delegated claude-code + /// agent identity selected for the hooks, and a Git repository imported + /// into Atomic. + fn new() -> Self { + let fixture = Self { + home: TempDir::new().expect("home tempdir"), + repository: TempDir::new().expect("repository tempdir"), + session: format!("issue-330-{}", std::process::id()), + }; + fixture.atomic_ok(&[ + "identity", + "new", + USER, + "-e", + "repro@example.invalid", + "--set-default", + ]); + fixture.atomic_ok(&[ + "identity", + "agent", + "create", + AGENT, + "--agent-type", + "claude-code", + "--local", + "--expires", + "1d", + ]); + fixture.atomic_ok(&["agent", "identity", "set", &format!("{USER}+{AGENT}")]); + + fixture.git_ok(&["init", "-q", "-b", "main"]); + fixture.git_ok(&["config", "user.name", USER]); + fixture.git_ok(&["config", "user.email", "repro@example.invalid"]); + fixture.git_ok(&["config", "commit.gpgsign", "false"]); + fixture.git_ok(&["config", "maintenance.auto", "false"]); + fs::write(fixture.root().join("README.md"), b"hello\n").expect("write README"); + fixture.git_ok(&["add", "-A"]); + fixture.git_ok(&["commit", "-q", "-m", "init"]); + fixture.atomic_ok(&["git", "import", "--no-vault"]); + fixture + } + + fn root(&self) -> &Path { + self.repository.path() + } + + fn config_dir(&self) -> std::path::PathBuf { + self.home.path().join(".atomic") + } + + fn atomic_with_stdin(&self, args: &[&str], input: Option<&[u8]>) -> Output { + let mut command = Command::new(ATOMIC_BIN); + command + .args(args) + .current_dir(self.root()) + .env("HOME", self.home.path()) + .env("ATOMIC_HOME", self.config_dir()) + .env("ATOMIC_CONFIG_DIR", self.config_dir()) + .env("ATOMIC_NONINTERACTIVE", "1") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("NO_COLOR", "1") + .env("CLICOLOR", "0") + .env("TERM", "dumb") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if input.is_some() { + command.stdin(Stdio::piped()); + } + let mut child = command.spawn().expect("spawn atomic"); + if let Some(input) = input { + child + .stdin + .take() + .expect("atomic stdin") + .write_all(input) + .expect("write atomic stdin"); + } + child.wait_with_output().expect("wait for atomic") + } + + fn atomic(&self, args: &[&str]) -> Output { + self.atomic_with_stdin(args, None) + } + + fn atomic_ok(&self, args: &[&str]) -> Output { + let output = self.atomic(args); + assert_success(&output, &format!("atomic {}", args.join(" "))); + output + } + + fn git_ok(&self, args: &[&str]) -> Output { + let output = Command::new("git") + .args(args) + .current_dir(self.root()) + .env("HOME", self.home.path()) + .env("GIT_CONFIG_NOSYSTEM", "1") + .output() + .expect("run git"); + assert_success(&output, &format!("git {}", args.join(" "))); + output + } + + /// Pipe one Claude Code hook event into `atomic agent hooks claude-code`. + fn hook(&self, verb: &str, event: Value) { + let mut payload = serde_json::json!({ + "session_id": self.session, + "cwd": self.root(), + "transcript_path": self.home.path().join("transcript.jsonl"), + }); + payload + .as_object_mut() + .expect("hook payload object") + .extend(event.as_object().expect("hook event object").clone()); + let output = self.atomic_with_stdin( + &["agent", "hooks", "claude-code", verb], + Some(payload.to_string().as_bytes()), + ); + assert_success(&output, &format!("hook {verb}")); + } + + /// One agent turn that edits a file; the Stop hook records it into the + /// session's draft view. Returns the recorded change hash. + fn agent_turn(&self) -> String { + fs::write(self.home.path().join("transcript.jsonl"), b"").expect("write transcript"); + self.hook( + "session-start", + serde_json::json!({"hook_event_name": "SessionStart", "source": "startup"}), + ); + self.hook( + "user-prompt-submit", + serde_json::json!({ + "hook_event_name": "UserPromptSubmit", + "prompt": "edit the readme", + }), + ); + fs::write(self.root().join("README.md"), b"hello\nworld\n").expect("edit README"); + self.hook( + "stop", + serde_json::json!({"hook_event_name": "Stop", "stop_hook_active": false}), + ); + let change = self.latest_change(); + assert_eq!( + change["message"].as_str().map(str::trim), + Some("edit the readme"), + "the Stop hook must have recorded the agent turn: {change}" + ); + change["hash"] + .as_str() + .expect("recorded change hash") + .to_string() + } + + fn end_session(&self) { + self.hook( + "session-end", + serde_json::json!({ + "hook_event_name": "SessionEnd", + "reason": "prompt_input_exit", + }), + ); + } + + fn latest_change(&self) -> Value { + let log = self.atomic_ok(&["log", "-n", "1", "-f", "json", "--full-hash"]); + let log: Value = serde_json::from_slice(&log.stdout).expect("log JSON"); + first_entry(&log).clone() + } + + fn current_view(&self) -> String { + let status = self.atomic_ok(&["status"]); + String::from_utf8_lossy(&status.stdout) + .lines() + .find_map(|line| line.strip_prefix("On view ")) + .expect("status names the current view") + .trim() + .to_string() + } + + /// The `did:atomic:` DID of a stored identity. + fn did_of(&self, identity: &str) -> String { + let shown = self.atomic_ok(&["identity", "show", identity]); + let id = String::from_utf8_lossy(&shown.stdout) + .lines() + .find_map(|line| line.trim().strip_prefix("ID:")) + .map(|id| id.trim().to_string()) + .expect("identity show prints the identity ID"); + format!("did:atomic:{id}") + } + + fn append_repo_config(&self, toml: &str) { + let path = self.root().join(".atomic/config.toml"); + let mut config = fs::read_to_string(&path).expect("read repo config"); + config.push('\n'); + config.push_str(toml); + fs::write(&path, config).expect("write repo config"); + } + + fn git_push_dry(&self) -> Output { + self.atomic(&["git", "push", "--no-push", "-b", "feature"]) + } +} + +fn first_entry(log: &Value) -> &Value { + match log { + Value::Array(entries) => entries.first().expect("at least one log entry"), + Value::Object(object) => object + .get("changes") + .or_else(|| object.get("entries")) + .and_then(Value::as_array) + .and_then(|entries| entries.first()) + .expect("at least one log entry"), + other => panic!("unexpected log JSON shape: {other}"), + } +} + +fn assert_success(output: &Output, operation: &str) { + assert!( + output.status.success(), + "{operation} failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn output_text(output: &Output) -> String { + format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) +} + +/// #330: after `SessionEnd`, the attestation is signed by the user's own +/// default identity — the identity that delegated the hook's agent identity. +/// That is this machine's own signing key, so the change is publishable +/// through `atomic git push`. +#[test] +fn hook_recorded_change_is_git_pushable_after_session_end() { + let fixture = Fixture::new(); + fixture.agent_turn(); + fixture.end_session(); + + let push = fixture.git_push_dry(); + assert_success( + &push, + "atomic git push --no-push -b feature after session end", + ); +} + +/// #330: the same refusal blocked promoting the hook-recorded change into the +/// shared `main` view with `atomic insert`. +#[test] +fn hook_recorded_change_inserts_into_shared_view_after_session_end() { + let fixture = Fixture::new(); + let change = fixture.agent_turn(); + fixture.end_session(); + + let draft = fixture.current_view(); + assert_ne!(draft, "main", "the Stop hook records into a draft view"); + fixture.atomic_ok(&["view", "switch", "main"]); + let insert = fixture.atomic(&["insert", "view", &draft]); + assert_success(&insert, &format!("atomic insert view {draft} into main")); + + let main_tip = fixture.latest_change(); + assert_eq!( + main_tip["hash"].as_str(), + Some(change.as_str()), + "main must now carry the hook-recorded change" + ); +} + +/// #330: a repository identity named in `[author] identity` by identity +/// *name* (the form `atomic org set` writes) is the repository's stated +/// trust root and must be resolved to its DID — even when this machine's +/// default identity has since changed. +#[test] +fn author_identity_name_is_resolved_as_the_repository_trust_root() { + let fixture = Fixture::new(); + fixture.agent_turn(); + fixture.end_session(); + + // Move this machine's default to a different identity, so only the + // repository's configured identity can vouch for the attestation. + fixture.atomic_ok(&[ + "identity", + "new", + "someone-else", + "-e", + "else@example.invalid", + "--set-default", + ]); + fixture.append_repo_config(&format!("[author]\nidentity = \"{USER}\"\n")); + + let push = fixture.git_push_dry(); + assert_success( + &push, + "atomic git push with the signer named as [author] identity", + ); +} + +/// #330: while the session is still open there is no attestation yet — they +/// are written at session end. The refusal must say so instead of leaving the +/// user to guess. +#[test] +fn in_session_refusal_says_attestations_are_written_at_session_end() { + let fixture = Fixture::new(); + fixture.agent_turn(); + + let push = fixture.git_push_dry(); + assert!( + !push.status.success(), + "an unattested in-session change must still be refused" + ); + let text = output_text(&push); + assert!( + text.contains("no same-session attestation"), + "refusal names the missing attestation:\n{text}" + ); + assert!( + text.contains("still active") && text.contains("session ends"), + "refusal must explain that the session is still active and attestations \ + are written when the session ends:\n{text}" + ); +} + +/// #330: an attestation signed by an identity that is neither this machine's +/// default nor the repository identity stays untrusted, and the refusal must +/// say how to trust it. Following that advice makes the push succeed. +#[test] +fn untrusted_signer_refusal_explains_how_to_configure_trust() { + let fixture = Fixture::new(); + fixture.agent_turn(); + fixture.end_session(); + let signer = fixture.did_of(USER); + + // A different default identity: the attestation's signer is now foreign. + fixture.atomic_ok(&[ + "identity", + "new", + "someone-else", + "-e", + "else@example.invalid", + "--set-default", + ]); + + let refused = fixture.git_push_dry(); + assert!( + !refused.status.success(), + "a foreign signer must not satisfy the gate" + ); + let text = output_text(&refused); + assert!( + text.contains(&format!("signer '{signer}'")), + "refusal names the untrusted signer {signer}:\n{text}" + ); + assert!( + text.contains("[git.trust]") && text.contains(".atomic/config.toml"), + "refusal must say how to configure trust ([git.trust] in .atomic/config.toml):\n{text}" + ); + + fixture.append_repo_config(&format!("[git.trust]\nsigners = [\"{signer}\"]\n")); + let push = fixture.git_push_dry(); + assert_success(&push, "atomic git push after trusting the signer"); +} diff --git a/atomic-cli/tests/it/main.rs b/atomic-cli/tests/it/main.rs index d3b2a435..491b187d 100644 --- a/atomic-cli/tests/it/main.rs +++ b/atomic-cli/tests/it/main.rs @@ -9,6 +9,7 @@ mod adaptation_regression_test; mod agent_capture_oracle_cb12a_test; mod agent_error_integration_test; +mod agent_hook_publication_gate_test; mod agent_repair_cb12a_test; mod bridge_agent_workflow_regression_test; mod build_version_integration_test; diff --git a/atomic-config/src/lib.rs b/atomic-config/src/lib.rs index 99b079bf..991d8be2 100644 --- a/atomic-config/src/lib.rs +++ b/atomic-config/src/lib.rs @@ -811,6 +811,12 @@ impl GitIdentityConfig { /// independently of the signer (RFC §5.2), so an unknown signer can supply /// correct content but can never satisfy a publication gate. /// +/// The publication gate evaluates a second self-root the same way: the +/// host's default identity, which signs agent session attestations +/// (`PublicationGateConfig::signer_trust` in `atomic-repository`). It is +/// passed to [`GitTrustConfig::evaluate`] as a root, so revocation still +/// wins over it. +/// /// Web-of-trust via delegation certificates was considered and **deferred**: /// it broadens who can satisfy gates without a repository-local decision, and /// enabling it later requires an explicit policy decision (delegation diff --git a/atomic-repository/src/repository/provenance_gate.rs b/atomic-repository/src/repository/provenance_gate.rs index 1c3d0347..1a3132a9 100644 --- a/atomic-repository/src/repository/provenance_gate.rs +++ b/atomic-repository/src/repository/provenance_gate.rs @@ -20,8 +20,11 @@ //! provider: without the key (e.g. on a receiving remote) the attestation //! is **unverifiable and fails closed** — it is never silently accepted. //! 5. **Trusted signer** — the attestation signer is evaluated against the -//! explicitly configured `[git.trust]` policy (`SignerTrust::Trusted`). -//! Revocation always wins; unknown signers are untrusted. +//! explicitly configured `[git.trust]` policy (`SignerTrust::Trusted`) +//! plus the two self-roots: the repository identity (`[author] identity`, +//! resolved to its DID) and this host's default identity — the key +//! session attestations are signed with. Revocation always wins; any +//! other signer is unknown and untrusted. //! 6. **No unexplained Git commit** — a change with //! `ChangeOrigin::GitSynthesized` attributed to a managed session whose //! ledger does not carry the corresponding incomplete marker is unexplained @@ -41,8 +44,16 @@ //! operation ancestry and leases are absent (F4/F5). A passing gate //! therefore proves *configured-policy enforcement over the available //! evidence*, nothing stronger. RFC §19 Q4 (open-source trust default) is -//! UNRESOLVED: no default trust is granted or invented here; only -//! explicitly configured signers ever satisfy the trust check. +//! UNRESOLVED: no third-party default trust (web of trust, delegation +//! chains, content inference) is granted or invented here; only the +//! self-roots and explicitly configured signers satisfy the trust check. +//! +//! The host's default identity is a self-root for the same reason the +//! repository identity is: an attestation that verifies under that key was +//! signed with this machine's own secret key — the key +//! `create_session_attestation` signs with when an agent session ends. +//! Without it, every hook-recorded change was refused at every boundary +//! with the user's own DID reported as "unknown" (atomicdotdev/atomic#330). //! //! # Content vs provenance separation (RFC §5.2/§12.8) //! @@ -86,30 +97,98 @@ pub type MacKeyProvider<'a> = &'a dyn Fn(&str) -> Option; pub type DidKeyProvider<'a> = &'a dyn Fn(&str) -> Option<[u8; 32]>; /// Configuration for one gate evaluation. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct PublicationGateConfig { /// Explicitly configured binding signer trust policy (`[git.trust]`). pub trust: GitTrustConfig, /// The repository's own signer DID (stated default trust root), if any. pub repository_identity: Option, + /// DID of this host's default identity, if any: the key session + /// attestations are signed with, and therefore a self-root alongside + /// the repository identity. + pub local_identity: Option, } impl PublicationGateConfig { /// Load the gate configuration from the repository's `.atomic/config.toml`. + /// + /// `[author] identity` may name the repository identity by DID, identity + /// name, or identity ID; names and IDs are resolved to the DID through + /// the repository-local identity store, then the host's default store. + /// The host's default identity is read from the default store without + /// creating it. pub fn from_repo(repo: &Repository) -> Result { let config = atomic_config::RepoConfig::load(&repo.dot_dir().join("config.toml")).map_err( |error| RepositoryError::InvalidOperation { message: error.to_string(), }, )?; + let repository_identity = config + .author + .as_ref() + .and_then(|author| author.identity.as_deref()) + .map(str::trim) + .filter(|reference| !reference.is_empty()) + .map(|reference| { + resolve_identity_did(repo, reference).unwrap_or_else(|| reference.to_string()) + }); Ok(Self { - repository_identity: config - .author - .as_ref() - .and_then(|author| author.identity.clone()), + repository_identity, + local_identity: local_default_identity_did(), trust: config.git.trust, }) } + + /// Evaluate one attestation signer against the configured policy and + /// both self-roots. Revocation wins over either root. + pub fn signer_trust(&self, signer: &str) -> SignerTrust { + match self + .trust + .evaluate(signer, self.repository_identity.as_deref()) + { + SignerTrust::Unknown => self.trust.evaluate(signer, self.local_identity.as_deref()), + decided => decided, + } + } +} + +/// Resolve an identity reference (DID, identity name, or identity ID) to +/// its `did:atomic` DID through the repository-local store, then the host's +/// default store. `None` when no store knows the reference. +fn resolve_identity_did(repo: &Repository, reference: &str) -> Option { + if reference.starts_with("did:") { + return Some(reference.to_string()); + } + let lookup = |store: atomic_identity::IdentityStore| { + store + .load_by_name(reference) + .ok() + .or_else(|| { + atomic_identity::IdentityId::from_base32(reference) + .ok() + .and_then(|id| store.load(&id).ok()) + }) + .map(|identity| atomic_canonical::did::did_for_public_key(&identity.public_key)) + }; + atomic_identity::IdentityStore::open_existing(&repo.dot_dir().join("identities")) + .ok() + .and_then(lookup) + .or_else(|| { + atomic_identity::IdentityStore::open_default_existing() + .ok() + .and_then(lookup) + }) +} + +/// The DID of the host's default identity — the identity +/// `create_session_attestation` signs session attestations with. Read-only: +/// a missing store yields `None` and is never created. +fn local_default_identity_did() -> Option { + let store = atomic_identity::IdentityStore::open_default_existing().ok()?; + let identity = store.get_default().ok()??; + Some(atomic_canonical::did::did_for_public_key( + &identity.public_key, + )) } /// A single reason the gate refused one change. @@ -131,8 +210,14 @@ pub enum GateBlocker { unbound_commits: Vec, paths: Vec, }, - /// No same-session attestation covers this change. - MissingAttestation { change: String, session: String }, + /// No same-session attestation covers this change. `session_active` is + /// set while the session ledger still reports the session as active: + /// session attestations are only written when the session ends. + MissingAttestation { + change: String, + session: String, + session_active: bool, + }, /// A same-session attestation exists but its signature does not verify. AttestationNotVerifying { change: String, @@ -235,11 +320,24 @@ impl std::fmt::Display for GateBlocker { } Ok(()) } - Self::MissingAttestation { change, session } => { + Self::MissingAttestation { + change, + session, + session_active, + } => { write!( f, "change {change}: no same-session attestation for session {session}" - ) + )?; + if *session_active { + write!( + f, + "; the session is still active and its attestation is written when \ + the session ends (the agent's SessionEnd hook): end the agent session, \ + then retry" + )?; + } + Ok(()) } Self::AttestationNotVerifying { change, @@ -265,11 +363,37 @@ impl std::fmt::Display for GateBlocker { attestation, signer, verdict, - } => write!( - f, - "change {change}: attestation {attestation} (session {session}) signer '{signer}' \ - is {verdict} under the configured trust policy and cannot satisfy a publication gate" - ), + } => { + write!( + f, + "change {change}: attestation {attestation} (session {session}) signer \ + '{signer}' is {verdict} under the configured trust policy and cannot satisfy \ + a publication gate" + )?; + if *verdict != trust_label(SignerTrust::Unknown) { + // Revoked: deliberately not configurable from here. + } else if signer.starts_with("session-mac:") { + // MAC-signed evidence is what a session produces when no + // default identity exists to sign it; allowlisting a + // per-session MAC is not the remedy. + write!( + f, + "; the attestation was signed with the session MAC because no default \ + identity was available when the session ended — create one with \ + `atomic identity new --set-default` so future sessions are \ + signed by it" + )?; + } else { + write!( + f, + "; trusted signers are the repository identity ([author] identity), this \ + host's default identity, and the DIDs listed under [git.trust] signers \ + in .atomic/config.toml — to trust this signer, add \ + `signers = [\"{signer}\"]` to the [git.trust] section" + )?; + } + Ok(()) + } Self::UnexplainedGitCommit { change, session } => write!( f, "change {change}: Git-synthesized change attributed to session {session} without \ @@ -321,8 +445,9 @@ fn default_limitations() -> Vec { "full boundary/manifest/ref/operation ancestry and repair leases are not yet enforced \ (CB-12A review F4/F5)" .to_string(), - "RFC section 19 Q4 (open-source trust default) is unresolved: only explicitly configured \ - signers satisfy the trust check; no default trust is granted" + "RFC section 19 Q4 (open-source trust default) is unresolved: only the repository \ + identity, this host's default identity, and explicitly configured [git.trust] signers \ + satisfy the trust check; no third-party default trust is granted" .to_string(), "this verdict enforces configured policy over available evidence; content correctness is \ verified independently of signatures" @@ -333,7 +458,10 @@ fn default_limitations() -> Vec { /// Cached per-session ledger status. enum LedgerStatus { Missing, - Ok, + /// The session is still running: attestations arrive at session end. + Active, + /// The session ended normally. + Ended, Incomplete { reason: String, unbound_commits: Vec, @@ -599,7 +727,7 @@ impl Repository { }); false } - LedgerStatus::Ok => false, + LedgerStatus::Active | LedgerStatus::Ended => false, LedgerStatus::Incomplete { reason, unbound_commits, @@ -634,8 +762,12 @@ impl Repository { }); true } - _ => { - vacant.insert(LedgerStatus::Ok); + SessionStatus::Active => { + vacant.insert(LedgerStatus::Active); + false + } + SessionStatus::Ended => { + vacant.insert(LedgerStatus::Ended); false } }, @@ -659,6 +791,7 @@ impl Repository { status } }; + let session_active = matches!(ledger_cache.get(&session), Some(LedgerStatus::Active)); // Unexplained Git commit: synthesized origin attributed to a // managed session whose ledger never recorded the incompleteness. @@ -778,6 +911,7 @@ impl Repository { verdict.blocks.push(GateBlocker::MissingAttestation { change: change_b32.clone(), session: session.clone(), + session_active, }); } Some(AttestationCheck { @@ -802,9 +936,7 @@ impl Repository { } else { // Signature authenticates; now the trust policy. let signer = signer.unwrap_or_default(); - let trust = config - .trust - .evaluate(&signer, config.repository_identity.as_deref()); + let trust = config.signer_trust(&signer); if trust != SignerTrust::Trusted { verdict .blocks @@ -907,6 +1039,7 @@ mod tests { revoked: Vec::new(), }, repository_identity: None, + local_identity: None, } } @@ -1314,6 +1447,7 @@ mod tests { &PublicationGateConfig { trust: GitTrustConfig::default(), repository_identity: None, + local_identity: None, }, Some(&no_provider), Some(&did_provider), @@ -1438,6 +1572,7 @@ mod tests { &PublicationGateConfig { trust: GitTrustConfig::default(), repository_identity: None, + local_identity: None, }, Some(&provider), None, @@ -1452,6 +1587,7 @@ mod tests { revoked: vec!["session-mac:sess-gate".to_string()], }, repository_identity: None, + local_identity: None, }; let verdict = repo .evaluate_publication_gate(&[hash], &revoked_config, Some(&provider), None) @@ -1681,6 +1817,237 @@ mod tests { None => std::env::remove_var("ATOMIC_CONFIG_DIR"), } } + + // --------------------------------------------------------------------- + // atomicdotdev/atomic#330: the host's default identity — the key + // session attestations are signed with — is a self-root; refusals say + // how to recover. + // --------------------------------------------------------------------- + + /// A gate config that trusts nothing but the given host identity. + fn config_with_local_identity(did: &str) -> PublicationGateConfig { + PublicationGateConfig { + local_identity: Some(did.to_string()), + ..PublicationGateConfig::default() + } + } + + /// A DID-signed managed change, fully evidenced except for trust. + fn did_attested_change(repo: &Repository, keypair: &atomic_identity::KeyPair) -> Hash { + let change = managed_change("did signed by the host identity"); + let hash = repo.save_change(&change).expect("save"); + install_provenance_root_and_ledger(repo, &hash); + install_did_attestation(repo, &hash, keypair); + hash + } + + #[test] + fn host_default_identity_is_a_trust_root() { + let (_dir, repo) = create_temp_repo(); + let (keypair, did) = agent_keypair(); + let hash = did_attested_change(&repo, &keypair); + + let public = *keypair.public.as_bytes(); + let did_provider = move |_signer: &str| Some(public); + let verdict = repo + .evaluate_publication_gate( + &[hash], + &config_with_local_identity(&did), + Some(&no_provider), + Some(&did_provider), + ) + .expect("gate runs"); + assert!( + verdict.allowed(), + "an attestation signed by this host's default identity must pass: {}", + verdict.refusal_report() + ); + } + + #[test] + fn revoked_host_default_identity_cannot_satisfy_the_gate() { + let (_dir, repo) = create_temp_repo(); + let (keypair, did) = agent_keypair(); + let hash = did_attested_change(&repo, &keypair); + + let public = *keypair.public.as_bytes(); + let did_provider = move |_signer: &str| Some(public); + let config = PublicationGateConfig { + trust: GitTrustConfig { + signers: Vec::new(), + revoked: vec![did.clone()], + }, + ..config_with_local_identity(&did) + }; + assert_eq!(config.signer_trust(&did), SignerTrust::Revoked); + let verdict = repo + .evaluate_publication_gate(&[hash], &config, Some(&no_provider), Some(&did_provider)) + .expect("gate runs"); + assert_eq!(blocker_kinds(&verdict), vec!["signer"], "{verdict:?}"); + let report = verdict.refusal_report(); + assert!(report.contains("is revoked"), "{report}"); + assert!( + !report.contains("to trust this signer"), + "a revoked signer must not be advertised as configurable: {report}" + ); + } + + #[test] + fn host_default_identity_does_not_vouch_for_other_signers() { + let (_dir, repo) = create_temp_repo(); + let (keypair, signer) = agent_keypair(); + let (_host, host_did) = agent_keypair(); + let hash = did_attested_change(&repo, &keypair); + + let public = *keypair.public.as_bytes(); + let did_provider = move |_signer: &str| Some(public); + let verdict = repo + .evaluate_publication_gate( + &[hash], + &config_with_local_identity(&host_did), + Some(&no_provider), + Some(&did_provider), + ) + .expect("gate runs"); + assert_eq!(blocker_kinds(&verdict), vec!["signer"], "{verdict:?}"); + let report = verdict.refusal_report(); + assert!( + report.contains(&format!("signer '{signer}' is unknown (not configured)")), + "{report}" + ); + assert!( + report.contains("[git.trust]") + && report.contains(".atomic/config.toml") + && report.contains(&format!("signers = [\"{signer}\"]")), + "an unknown signer's refusal must say how to trust it: {report}" + ); + } + + #[test] + fn session_mac_signer_refusal_points_at_creating_a_default_identity() { + let (_dir, repo) = create_temp_repo(); + let change = managed_change("mac signed without an identity"); + let hash = repo.save_change(&change).expect("save"); + install_provenance_root_and_ledger(&repo, &hash); + install_attestation(&repo, &hash, true); + + let verdict = repo + .evaluate_publication_gate( + &[hash], + &PublicationGateConfig::default(), + Some(&provider), + None, + ) + .expect("gate runs"); + assert_eq!(blocker_kinds(&verdict), vec!["signer"], "{verdict:?}"); + let report = verdict.refusal_report(); + assert!( + report.contains("signed with the session MAC") + && report.contains("atomic identity new"), + "{report}" + ); + assert!( + !report.contains("signers = ["), + "a per-session MAC must not be suggested for the allowlist: {report}" + ); + } + + #[test] + fn active_session_without_attestation_says_it_is_written_at_session_end() { + let (_dir, repo) = create_temp_repo(); + let change = managed_change("attested only at session end"); + let hash = repo.save_change(&change).expect("save"); + install_provenance_root_and_ledger(&repo, &hash); + repo.upsert_session_lifecycle(SESSION, None, None, None) + .expect("session marked active"); + + let verdict = repo + .evaluate_publication_gate( + &[hash], + &config_with_signer("session-mac:sess-gate"), + Some(&provider), + None, + ) + .expect("gate runs"); + assert_eq!(blocker_kinds(&verdict), vec!["attestation"], "{verdict:?}"); + assert!(matches!( + &verdict.blocks[0], + GateBlocker::MissingAttestation { + session_active: true, + .. + } + )); + let report = verdict.refusal_report(); + assert!( + report.contains("still active") && report.contains("session ends"), + "{report}" + ); + + // Once the session has ended, a missing attestation is a genuine + // evidence hole: no "end the session" advice. + repo.upsert_session_lifecycle(SESSION, None, None, Some(1)) + .expect("session marked ended"); + let verdict = repo + .evaluate_publication_gate( + &[hash], + &config_with_signer("session-mac:sess-gate"), + Some(&provider), + None, + ) + .expect("gate runs"); + assert_eq!(blocker_kinds(&verdict), vec!["attestation"], "{verdict:?}"); + assert!( + !verdict.refusal_report().contains("still active"), + "{}", + verdict.refusal_report() + ); + } + + #[test] + fn from_repo_resolves_author_identity_names_to_dids() { + use atomic_identity::{Identity, IdentityStore, KeyPair}; + + let (_dir, repo) = create_temp_repo(); + let keypair = KeyPair::generate(); + let identity = Identity::new("repo-owner", &keypair); + let did = atomic_canonical::did::did_for_public_key(&keypair.public); + IdentityStore::open(&repo.dot_dir().join("identities")) + .expect("repo-local identity store opens") + .save(&identity) + .expect("identity saved into the repository"); + + let config_path = repo.dot_dir().join("config.toml"); + let write_author = |reference: &str| { + std::fs::write( + &config_path, + format!("[author]\nname = \"Owner\"\nidentity = \"{reference}\"\n"), + ) + .expect("write repo config"); + }; + + // By name, as `atomic org set` writes it. + write_author("repo-owner"); + let config = PublicationGateConfig::from_repo(&repo).expect("config loads"); + assert_eq!(config.repository_identity.as_deref(), Some(did.as_str())); + assert_eq!(config.signer_trust(&did), SignerTrust::Trusted); + + // By identity ID. + write_author(&identity.id.to_base32()); + let config = PublicationGateConfig::from_repo(&repo).expect("config loads"); + assert_eq!(config.repository_identity.as_deref(), Some(did.as_str())); + + // A DID is used verbatim; an unresolvable reference is kept as-is + // (it simply matches no signer). + write_author(&did); + let config = PublicationGateConfig::from_repo(&repo).expect("config loads"); + assert_eq!(config.repository_identity.as_deref(), Some(did.as_str())); + write_author("nobody-by-this-name"); + let config = PublicationGateConfig::from_repo(&repo).expect("config loads"); + assert_eq!( + config.repository_identity.as_deref(), + Some("nobody-by-this-name") + ); + } } #[cfg(test)] @@ -1735,6 +2102,7 @@ mod privacy_tests { &PublicationGateConfig { trust: GitTrustConfig::default(), repository_identity: None, + local_identity: None, }, Some(&|_| Some("dd44dd44".to_string())), None, diff --git a/atomic-repository/src/triage/report.rs b/atomic-repository/src/triage/report.rs index 2bb96f9f..53d1f5c4 100644 --- a/atomic-repository/src/triage/report.rs +++ b/atomic-repository/src/triage/report.rs @@ -710,10 +710,7 @@ pub fn build_report( match repo.evaluate_publication_gate( &candidate_hashes, &crate::repository::provenance_gate::PublicationGateConfig::from_repo(repo) - .unwrap_or(crate::repository::provenance_gate::PublicationGateConfig { - trust: Default::default(), - repository_identity: None, - }), + .unwrap_or_default(), Some(&provider), Some(&did_provider), ) { diff --git a/docs/shim-operating-guide.md b/docs/shim-operating-guide.md index 6bf9c10d..28ded526 100644 --- a/docs/shim-operating-guide.md +++ b/docs/shim-operating-guide.md @@ -376,6 +376,29 @@ an unknown signer trusted. Repository trust settings live under `[git.trust]`: explicitly revoked signers remain revoked, and unknown signers' provenance is not trusted for publication. +The publication gate (`atomic git push`, `atomic push`, and `atomic insert` +into a shared view) trusts an attestation signer when it is one of: + +- the repository identity, `[author] identity` in `.atomic/config.toml` + (a DID, identity name, or identity ID); +- this machine's default identity (`atomic identity default`), the key that + signs agent session attestations when the session ends; +- a DID listed under `[git.trust] signers`. + +A revoked signer stays revoked even when it is also one of these. To trust a +collaborator's attestations, add their DID: + +```toml +# .atomic/config.toml +[git.trust] +signers = ["did:atomic:…"] +revoked = [] +``` + +Agent sessions write their attestation when the session ends (the agent's +SessionEnd hook). Until then, a change recorded during the session is refused +with "the session is still active". End the session, then publish. + Signed Anchor bindings use the supplied Ed25519 key. Managed-session capture currently uses a session MAC, not an agent-DID signature; its signature coverage has limits recorded in the RFC tracker.