Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
resolver = "2"
members = [
"atomic-agent",
"atomic-audit",
"atomic-canonical",
"atomic-cli",
"atomic-client",
Expand Down Expand Up @@ -30,6 +31,7 @@ rust-version = "1.90"
[workspace.dependencies]
# Core
atomic-agent = { path = "atomic-agent" }
atomic-audit = { path = "atomic-audit" }
atomic-canonical = { path = "atomic-canonical" }
atomic-client = { path = "atomic-client" }
atomic-core = { path = "atomic-core" }
Expand Down
122 changes: 112 additions & 10 deletions atomic-agent/src/turn/orchestrator/attestation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,27 +59,38 @@ pub(crate) fn capture_root(
Ok(atomic_core::types::Hash::of(&buf))
}

fn did_signing_identity_from_store(
store: &atomic_identity::IdentityStore,
selected_name: Option<&str>,
) -> Option<(String, atomic_identity::KeyPair)> {
let identity = match selected_name {
Some(name) => store.load_by_name(name).ok()?,
None => store.get_default().ok()??,
};
// Verify the secret matches this identity's public key. An unavailable
// explicit signer must never fall back to a different identity.
let keypair = store.load_keypair(&identity.id, None).ok()?;
Some((
atomic_canonical::did::did_for_public_key(&identity.public_key),
keypair,
))
}

impl TurnOrchestrator {
/// Load the configured agent DID identity for attestation signing
/// (CB-12A AC3).
///
/// Returns the signer DID (`did:atomic:<base32>` from
/// `atomic_canonical::did`) plus the store-verified keypair when a
/// default identity with a loadable secret key exists. Any failure — no
/// store, no default identity, encrypted/locked key, secret/public
/// selected agent identity (or the default when none is selected) has a
/// loadable secret key. Any failure — no store, missing identity,
/// encrypted/locked key, secret/public
/// mismatch — yields `None` and the attestation falls back to the
/// session MAC, which [`atomic_core::change::attestation::TrustPolicy`]
/// then refuses as trusted evidence.
pub(crate) fn load_did_signing_identity(&self) -> Option<(String, atomic_identity::KeyPair)> {
let store = atomic_identity::IdentityStore::open_default().ok()?;
// get_default resolves the configured default identity directly.
let identity = store.get_default().ok()??;
// load_keypair verifies the secret matches the identity's public key.
let keypair = store.load_keypair(&identity.id, None).ok()?;
Some((
atomic_canonical::did::did_for_public_key(&identity.public_key),
keypair,
))
did_signing_identity_from_store(&store, self.agent_identity.as_deref())
}

// =========================================================================
Expand Down Expand Up @@ -496,3 +507,94 @@ impl TurnOrchestrator {
}
}
}

#[cfg(test)]
mod signing_identity_tests {
use super::did_signing_identity_from_store;
use atomic_identity::{Identity, IdentityStore, KeyPair};

fn store_with_default() -> (tempfile::TempDir, IdentityStore, Identity) {
let temp = tempfile::tempdir().unwrap();
let mut store = IdentityStore::open(temp.path()).unwrap();
let keypair = KeyPair::generate();
let human = Identity::new("human", &keypair);
store.save_with_keypair(&human, &keypair, None).unwrap();
store.set_default(&human.id).unwrap();
(temp, store, human)
}

#[test]
fn selected_reviewer_uses_its_own_did_and_key() {
let (_temp, store, human) = store_with_default();
let reviewer_key = KeyPair::generate();
let reviewer = Identity::new("reviewer", &reviewer_key);
store
.save_with_keypair(&reviewer, &reviewer_key, None)
.unwrap();

let (did, keypair) = did_signing_identity_from_store(&store, Some("reviewer")).unwrap();
assert_eq!(
did,
atomic_canonical::did::did_for_public_key(&reviewer.public_key)
);
assert_eq!(keypair.public, reviewer_key.public);
assert_ne!(keypair.public, human.public_key);
}

#[test]
fn no_selection_retains_default_signer() {
let (_temp, store, human) = store_with_default();

let (did, keypair) = did_signing_identity_from_store(&store, None).unwrap();
assert_eq!(
did,
atomic_canonical::did::did_for_public_key(&human.public_key)
);
assert_eq!(keypair.public, human.public_key);
}

#[test]
fn missing_selected_reviewer_does_not_use_default() {
let (_temp, store, _human) = store_with_default();
assert!(did_signing_identity_from_store(&store, Some("missing-reviewer")).is_none());
}

#[test]
fn keyless_selected_reviewer_does_not_use_default() {
let (_temp, store, _human) = store_with_default();
store.save(&Identity::generate("reviewer")).unwrap();
assert!(did_signing_identity_from_store(&store, Some("reviewer")).is_none());
}

#[test]
fn mismatched_selected_reviewer_key_does_not_use_default() {
let (_temp, store, _human) = store_with_default();
let reviewer = Identity::generate("reviewer");
store
.save_with_keypair(&reviewer, &KeyPair::generate(), None)
.unwrap();
assert!(did_signing_identity_from_store(&store, Some("reviewer")).is_none());
}

#[test]
fn locked_selected_reviewer_key_does_not_use_default() {
let (_temp, store, _human) = store_with_default();
let reviewer_key = KeyPair::generate();
let reviewer = Identity::new("reviewer", &reviewer_key);
store
.save_with_keypair(&reviewer, &reviewer_key, None)
.unwrap();
let secret_path = store
.root()
.join(format!("reviewer-{}", reviewer.id.short()))
.join("secret.key");
let secret = std::fs::read_to_string(&secret_path).unwrap();
std::fs::write(
secret_path,
secret.replace("encryption = \"none\"", "encryption = \"locked\""),
)
.unwrap();

assert!(did_signing_identity_from_store(&store, Some("reviewer")).is_none());
}
}
84 changes: 84 additions & 0 deletions atomic-audit/AUDITS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Executable anti-slop audits — ruleset 2

All ten audit cards have executable checks. The seven substantive families are
no longer guidance-only: matches flow through the same recorded before/after
adapter into numbered findings, with source locations, concrete observations,
introduction attribution and proposed corrections. Nothing here runs tests,
fixes code, rewrites acceptance criteria or grants approval.

These checks inspect specific source constructs. Completing a check means its
documented patterns were inspected, not that the entire behavioral concern was
proved absent. Unsupported languages, syntax recovery and budget exhaustion
remain explicit. The parser registry and its trees are reused; there is no new
parser, whole-project scan, global-name caller join or compiler/type resolver.

## Implemented checks

| Audit | Executable evidence | Languages | Important exclusions |
|---|---|---|---|
| Syntax | Error/missing syntax nodes | All nine registered syntax modes | Parser evidence, not compiler proof |
| Unfinished behavior | Actual `todo!`/`unimplemented!` invocations | Rust | Comments/strings are not invocations; macro shadowing and deliberate scaffolds need judgment |
| Undocumented empty catch | Empty catch AST body without comments | TS/TSX | An explanatory comment or executable handler is not an empty-catch match |
| Failure masking | `Err` match/if-let branch constructs `Ok`; catch ends with `return true` | Rust, TS/TSX | Error propagation, ordinary successful branches and explicit `std::io::ErrorKind::NotFound`-guarded `Ok(None)` absence contracts are excluded; other intentional fallbacks may be justified by their contract |
| Duplicated behavior | Nonempty if/else bodies have identical syntax tokens, with literal content preserved | Rust, TS/TSX | Comments/formatting do not change comparison; Rust let/let-chain name bindings are excluded; condition effects must be preserved |
| Unnecessary machinery | At least two same-module private forwarding layers, unchanged arguments and identical first-layer parameter/return contracts | Rust | Excludes single naming wrappers, public/attributed/generic/receiver boundaries, transformed arguments and direct cycles; architectural naming intent still needs judgment |
| Manageability | Joint long-body/control-flow concentration, new or worsened relative to the recorded baseline | All nine modes | Unique named functions only; standalone large length/parameter/complexity values do not produce a finding |
| Async/resource safety | Known synchronous std/parking_lot guard remains live across same-block await; async executor passed to unshadowed standard Promise | Rust, TS/TSX | Explicit drop/completed inner scopes and Tokio mutexes are excluded. Rust binding recognition is limited to qualified constructors/simple parameter types; indirect aliases, complex paths, possible ownership transfers and type inference are not guessed. Shadowing does not incorrectly count as releasing the old guard |
| Weak verification | Empty test without should_panic; test asserts literal true or compares an identical simple expression with itself | Rust | Does not classify every assertion-free test as weak. Result-returning tests and framework behavior can verify real contracts; side-effecting self-calls are excluded |
| Unsafe shortcuts | Selected qualified unsafe memory operation without local SAFETY argument; blanket warnings/clippy::all suppression without local reason | Rust | Narrow lint exceptions and locally explained operations are excluded; absence of a safety argument is not proof of undefined behavior |

Unnecessary-machinery, duplication and manageability matches are Low-severity
review concerns, not declarations that an abstraction is forbidden or a bug
exists. Other source-pattern matches are Medium review findings. Every result
states the observed construct and its potential contract consequence so a
reviewer can accept/reject the concern with relevant context. No finding invents
a governing criterion or marks an acceptance criterion unmet.

The Rust constructors/macros in these patterns are source-syntax observations;
unusual local shadowing or generated code can require contextual rejection of a
match. In particular, this is not proof of a compiled `Result` type, runtime
reachability, external API compatibility, executed tests or complete cleanup.

## Joint manageability policy

`atomic.manageability.v1` is explicit Atomic review policy, not a universal
scientific cutoff or a metric-quality pass/fail gate. It requires:

- at least **100 code-bearing function-body lines**, **and**
- cyclomatic complexity at least **15** or control-flow nesting at least **4**.

Both use the existing `atomic.metrics.syntax.v1` counting implementation, with
comments and nested-function bodies excluded according to that convention.
Long straight-line tables alone and small branch-heavy dispatchers alone do not
trigger it. For an already-triggering named function, a new finding requires at
least **three additional decision points or a new nesting level**, not merely
one more line, formatting, straight-line growth or an unchanged count. This is
also Atomic policy, not a calibrated defect predictor. New/worsened joint burden
reports the actual after factors and, when present, before factors. An unavailable
baseline yields Unknown introduction, never an invented zero baseline.

An isolated metric value, metric count or risk-rule trigger still does not create
a defect finding. This audit's finding is the specific combination of long body
and branching/nesting in an identified recorded function, qualified as increased
review/maintenance burden rather than proof of missing tests or runtime failure.

## Scope, attribution and bounds

The adapter inspects selected recorded content and its actual before snapshot.
Later/dirty source is not used. Ordinary matches use exact rule/source-text
multisets: line shifts alone are preexisting; additional identical occurrences
can be new; an edited existing same-rule match has Unknown introduction rather
than a fabricated regression. Manageability additionally compares the named
subject's joint evidence as described above.

The existing 1 MiB source limit and 100-issue limit remain. AST inventory is capped
at 300,000 nodes / nesting depth 256 and substantive subtree work is capped at 32 MiB of inspected
source spans per file. Budget exhaustion produces an explicit incomplete check,
not a truncated clean result. A syntax-recovered tree runs syntax diagnostics
only, never substantive checks on unreliable nodes.

Tests include positive evidence for every substantive family, nearby negative
cases, attribution of new/preexisting/unknown concerns, scope-pinned recorded
inspection and a real CLI invocation producing all seven families without a
supplied findings file. Those fixtures validate detector execution; they do not
claim exhaustive detection of every problem in each audit category.
Loading
Loading