//! Local desired-state store for cloud-managed JavaScript policies. //! //! Cloud transport deliberately does not live here. A caller supplies an //! [`ArtifactFetcher`], while this module owns the security-sensitive local //! transaction: validate the manifest, verify SHA-256, write immutable cache //! objects, materialize a complete deployment, then switch `active.json` //! atomically. The hook hot path never downloads or partially activates policy. use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::HashSet; use std::fs::{self, File, OpenOptions}; use std::io::{self, Read, Write}; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::{AtomicU64, Ordering}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; /// What this daemon WRITES, and what the server emits today. /// /// 2, because the v1 payload named these fields `generation` and `revision` /// and neither appears any more. Same endpoint, same version number, different /// shape is precisely what a schema version exists to prevent — see the note at /// the emit site in AgentEye's `enforcement.rs`. pub const DESIRED_STATE_SCHEMA_VERSION: u32 = 2; pub const SCOPED_DESIRED_STATE_SCHEMA_VERSION: u32 = 3; /// What this daemon ACCEPTS when reading. /// /// 1 is here for files on DISK, never for a server: a machine that ran an /// earlier beta has a `desired-state.json` and an `active.json` written at /// version 1, and both structs carry `deny_unknown_fields`, so refusing the /// version would make the daemon unable to read its own persisted state — it /// would silently stop enforcing cloud policy until a poll re-materialised /// everything. The field aliases on `ActiveDeployment` exist for the same /// files and the same reason. pub const SUPPORTED_SCHEMA_VERSIONS: &[u32] = &[ 1, DESIRED_STATE_SCHEMA_VERSION, SCOPED_DESIRED_STATE_SCHEMA_VERSION, ]; const MANAGED_FILE_MODE: u32 = 0o600; static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0); /// NOT `deny_unknown_fields`, deliberately, unlike the locally-authored /// manifest below. This is parsed from a SERVER response, and daemons update on /// their own schedule — so strictness here means the first field cloud adds /// makes every older daemon reject desired-state and silently stop pulling, /// stranding fleets on whatever deployment they happened to hold. Strictness /// belongs on files we write ourselves, not on a remote payload. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct DesiredState { pub schema_version: u32, pub deployment: u64, pub policies: Vec, /// `off | observe | enforce` when FailproofAI Cloud sets this machine's /// Jev mode. With `observe`/`enforce` the CLI sends every gated tool call's /// metadata to FailproofAI Cloud, which asks the machine's deployed Jev /// checks and returns their verdict; `off` switches Jev off. Absent means /// Cloud does not override (the server stores its `local` choice as NULL /// and emits nothing), and the machine's own `jev.json` decides. Any other /// value rejects the whole state rather than being guessed at, like an /// unknown `effect`. /// /// Jev checks themselves never reach the machine (CONTRACT C10): they live /// on FailproofAI Cloud. A `semanticPolicies` key from a server that still /// sends one is ignored here, like any other field this build does not know. #[serde(default, skip_serializing_if = "Option::is_none")] pub jev_mode: Option, /// The `jev` and `both` assignments whose Jev checks FailproofAI Cloud asks /// for this machine: id, version, effect and agent scope only — never a /// declaration (CONTRACT C10). The CLI reads it to skip the Cloud Jev call /// for an agent no Cloud check targets, and to record an `observe` /// assignment's answers as observed. Absent (a server that predates it) /// means unknown: the CLI asks Cloud on every gated call, as before. #[serde(default, skip_serializing_if = "Option::is_none")] pub jev_policies: Option>, } /// One Cloud Jev assignment as the machine sees it: no question, no digest. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct JevAssignment { pub id: String, pub version: u64, /// Absent means `enforce`, like a JS assignment's. #[serde(default)] pub effect: PolicyEffect, /// Only schema 3 may carry this. Absent means all agents. #[serde(default, skip_serializing_if = "Option::is_none")] pub agent_targets: Option>, } /// The Jev modes FailproofAI Cloud may set. `local` is the server's word for /// "stop overriding" and is never sent — it is stored as NULL. pub const JEV_MODES: &[&str] = &["off", "observe", "enforce"]; /// The authorities an assignment may declare. Mirrors `PolicyAuthority` in the /// CLI's `policy-types.ts`. pub const AUTHORITIES: &[&str] = &["hard", "reviewable"]; /// A `desired-state.json` as a PRE-RENAME daemon wrote it — disk only. /// /// `DesiredState` above decodes bytes from a server we version in lockstep, so it /// deliberately refuses the old `generation`/`revision` spelling: an alias there /// would be dead code guarding a case no server can produce, and a /// silently-tolerated old field is how two sides drift back apart. /// /// That reasoning is right about the wire and incomplete about the FILE. The axis /// is *who wrote these bytes*, and `desired-state.json` is written by a daemon /// that may be older than the one now reading it — exactly like `active.json`, /// which is why that struct carries aliases. One struct was decoding bytes from /// two different writers, so the strictness the wire needs made the disk read /// fail: a v1 file does not trip the unknown `generation` key (this family has no /// `deny_unknown_fields`, on purpose) — it fails on `deployment` being MISSING. /// /// The consequence was not cosmetic. `repair_active_from_cache()` swallows that /// parse error, and if `active.json` is also gone or corrupt while OFFLINE it /// returns without rebuilding — so cloud policy stops being enforced until a poll /// succeeds, on a machine that has no way to poll. /// /// So: two types, one per writer, rather than one lenient type. The wire keeps its /// hard edge; the disk read falls back to this and converts. No `schema_version` /// is checked here — `read_desired()` validates after the conversion, through the /// same path the current shape takes. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] struct LegacyDesiredState { schema_version: u32, generation: u64, policies: Vec, } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] struct LegacyDesiredPolicy { id: String, revision: u64, sha256: String, artifact_url: String, #[serde(default)] effect: PolicyEffect, } impl From for DesiredState { fn from(old: LegacyDesiredState) -> Self { DesiredState { schema_version: old.schema_version, deployment: old.generation, policies: old.policies.into_iter().map(DesiredPolicy::from).collect(), // A pre-rename daemon predates the Cloud Jev mode. jev_mode: None, jev_policies: None, } } } impl From for DesiredPolicy { fn from(old: LegacyDesiredPolicy) -> Self { DesiredPolicy { id: old.id, version: old.revision, sha256: old.sha256, artifact_url: old.artifact_url, effect: old.effect, authority: None, reviewed_by: None, agent_targets: None, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct DesiredPolicy { pub id: String, pub version: u64, pub sha256: String, /// Opaque locator interpreted only by the cloud transport implementation. pub artifact_url: String, /// Defaults to `enforce` so a server that predates observe mode, or omits /// the field, keeps behaving exactly as before. The safe default is the /// one that keeps enforcing. #[serde(default)] pub effect: PolicyEffect, /// `hard | reviewable`, derived by the SERVER from the policy's kind: a /// `both` policy's JS half is `reviewable` by its own Jev checks. Carried /// verbatim into `active.json`, where the CLI already reads it /// (`cloud-managed-policies.ts`) — code inside the artifact cannot grant /// itself this. Absent means hard. #[serde(default, skip_serializing_if = "Option::is_none")] pub authority: Option, /// The Jev check names that may clear this policy's verdict. Carried /// verbatim; the CLI decides which of them this machine can actually ask. #[serde(default, skip_serializing_if = "Option::is_none")] pub reviewed_by: Option>, /// Only schema 3 may carry this. Absent means all agents. #[serde(default, skip_serializing_if = "Option::is_none")] pub agent_targets: Option>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AgentTarget { pub integration: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub instance_id: Option, } const INTEGRATIONS: &[&str] = &[ "claude", "codex", "copilot", "cursor", "opencode", "pi", "hermes", "openclaw", "factory", "devin", "antigravity", "goose", ]; fn valid_instance_id(id: &str) -> bool { let Some(hex) = id.strip_prefix("agt_") else { return false; }; (16..=32).contains(&hex.len()) && hex .bytes() .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) } fn validate_targets(targets: &[AgentTarget]) -> bool { if !(1..=32).contains(&targets.len()) { return false; } let mut seen = HashSet::new(); targets.iter().all(|target| { INTEGRATIONS.contains(&target.integration.as_str()) && target.instance_id.as_deref().is_none_or(valid_instance_id) && seen.insert(target) }) } /// What an assignment does when it matches. /// /// `observe` is the design's observe-before-enforce step: the policy is /// downloaded, verified and EVALUATED exactly like any other, but its verdict /// never changes what the agent is allowed to do. It exists so a rollout can be /// measured on real traffic before it can break anyone's work. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] #[serde(rename_all = "lowercase")] pub enum PolicyEffect { #[default] Enforce, Observe, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ActiveDeployment { pub schema_version: u32, /// `generation` is what every daemon before the rename wrote here. /// /// The alias is load-bearing rather than tidy: this struct carries /// `deny_unknown_fields`, so without it an upgraded daemon fails to parse /// its OWN `active.json` on three counts at once — `generation` unrecognised, /// `deployment` missing, and the same again for every policy's `revision`. /// A machine would silently lose the deployment it was enforcing until a /// poll succeeded, which on a fail-closed machine is the gap this whole /// subsystem exists to prevent. #[serde(alias = "generation")] pub deployment: u64, pub policies: Vec, /// Carried from `DesiredState::jev_mode` in the same atomic write as the /// policies. Skipped when unset, so a deployment with no Cloud Jev mode /// writes the exact `active.json` it wrote before this field existed, and /// defaulted on read, so a file written before it still parses under /// `deny_unknown_fields`. #[serde(default, skip_serializing_if = "Option::is_none")] pub jev_mode: Option, /// Carried from `DesiredState::jev_policies` in the same write. Skipped /// when unset, so an older server's deployment writes the same bytes. #[serde(default, skip_serializing_if = "Option::is_none")] pub jev_policies: Option>, } /// The `active.json` key a pre-release build of this branch wrote when it /// still delivered Jev checks to the machine (removed by CONTRACT C10). Dropped /// on read — see [`PolicyStore::read_active`] — and never written. const RETIRED_ACTIVE_KEYS: &[&str] = &["semanticPolicies"]; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ActivePolicy { pub id: String, /// `revision` is the pre-rename spelling. See `ActiveDeployment::deployment`. #[serde(alias = "revision")] pub version: u64, pub sha256: String, /// Relative to the cloud-managed root. Never supplied by the server. pub path: String, /// Carried through from the desired state so the evaluator does not have to /// re-consult cloud to know whether a policy may act. #[serde(default)] pub effect: PolicyEffect, /// Carried through from `DesiredPolicy::authority`; skipped when absent so /// a hard policy's entry is byte-identical to what it has always been. #[serde(default, skip_serializing_if = "Option::is_none")] pub authority: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub reviewed_by: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub agent_targets: Option>, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ReconcileOutcome { pub deployment: u64, pub downloaded: usize, pub repaired: usize, pub activated: bool, } #[derive(Debug)] pub enum ReconcileError { Io(io::Error), Json(serde_json::Error), InvalidDesiredState(String), HashMismatch { policy_id: String, expected: String, actual: String, }, Fetch { policy_id: String, message: String, }, NoVerifiedCopy { policy_id: String, }, /// The machine stopped being enrolled while this reconcile was running /// (`config --disconnect` during a poll). Nothing was persisted. Withdrawn, } impl std::fmt::Display for ReconcileError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Io(err) => write!(f, "cloud policy I/O error: {err}"), Self::Json(err) => write!(f, "cloud policy JSON error: {err}"), Self::InvalidDesiredState(message) => { write!(f, "invalid cloud desired state: {message}") } Self::HashMismatch { policy_id, expected, actual, } => write!( f, "cloud policy {policy_id} hash mismatch: expected {expected}, got {actual}" ), Self::Fetch { policy_id, message } => { write!(f, "failed to fetch cloud policy {policy_id}: {message}") } Self::NoVerifiedCopy { policy_id } => write!( f, "cloud policy {policy_id} has no verified artifact or deployment copy" ), Self::Withdrawn => write!( f, "this machine stopped being enrolled while the deployment was being applied; nothing was written" ), } } } impl std::error::Error for ReconcileError {} impl ReconcileError { /// The policy an error is about, when it is about one. pub fn policy_id(&self) -> Option<&str> { match self { Self::HashMismatch { policy_id, .. } | Self::Fetch { policy_id, .. } | Self::NoVerifiedCopy { policy_id } => Some(policy_id), _ => None, } } } // ── Error report (the `policyErrors` poll parameter) ───────────────────────── // // What this machine could not apply from its deployment, reported to // FailproofAI Cloud on the poll it already makes. Two writers, two files, one // wire list: the CLI writes `errors.json` (what it could not LOAD or RUN — a // JS policy that failed to import, a Cloud Jev mode this machine cannot act on // because it has no Cloud Jev credential (`jev_unconfigured`) or was connected // for decisions only (`transcripts_disabled`), an installed pack's Jev check // FailproofAI Cloud dropped for the question budget), and the daemon keeps its // own reconcile errors in `daemon-errors.json`. Neither ever writes the other's // file, so there is no read-modify-write race between two processes. /// One reported problem. The wire shape is exactly this, compact JSON. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct PolicyErrorEntry { pub id: String, pub version: Option, /// `regex | jev | both | daemon`. pub kind: String, pub message: String, } /// The kinds the wire accepts. An entry naming any other is dropped on read. pub const POLICY_ERROR_KINDS: &[&str] = &["regex", "jev", "both", "daemon"]; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] pub struct PolicyErrorFile { pub errors: Vec, } /// Lenient: the file is written by another program (the CLI) and read by this /// one on its own schedule, so an entry this build cannot read is skipped, not /// fatal — the rest of the report still reaches the server. fn parse_policy_error_file(bytes: &[u8]) -> Option> { let raw: serde_json::Value = serde_json::from_slice(bytes).ok()?; let list = raw.get("errors")?.as_array()?; Some( list.iter() .filter_map(|value| serde_json::from_value::(value.clone()).ok()) .filter(|entry| POLICY_ERROR_KINDS.contains(&entry.kind.as_str())) .collect(), ) } impl PolicyStore { /// The CLI's report, or None when it has never written one (or wrote /// something unreadable — which is then simply not reported, never guessed). pub fn read_cli_policy_errors(&self) -> Option> { parse_policy_error_file(&fs::read(self.cli_errors_path()).ok()?) } /// The daemon's own persisted reconcile error state, or None when it has /// never had one. pub fn read_daemon_policy_errors(&self) -> Option> { parse_policy_error_file(&fs::read(self.daemon_errors_path()).ok()?) } /// Persists the daemon's error state, only when it changed. pub fn write_daemon_policy_errors( &self, errors: &[PolicyErrorEntry], ) -> Result<(), ReconcileError> { if self.read_daemon_policy_errors().as_deref() == Some(errors) { return Ok(()); } let file = PolicyErrorFile { errors: errors.to_vec(), }; write_atomic(&self.daemon_errors_path(), &serde_json::to_vec(&file)?) } } impl From for ReconcileError { fn from(value: io::Error) -> Self { Self::Io(value) } } impl From for ReconcileError { fn from(value: serde_json::Error) -> Self { Self::Json(value) } } /// Transport boundary. Production cloud HTTP and tests both implement this; /// fetched bytes are untrusted until the reconciler verifies their digest. pub trait ArtifactFetcher { fn fetch(&self, policy: &DesiredPolicy) -> Result, String>; } impl ArtifactFetcher for F where F: Fn(&DesiredPolicy) -> Result, String>, { fn fetch(&self, policy: &DesiredPolicy) -> Result, String> { self(policy) } } #[derive(Debug, Clone)] pub struct PolicyStore { root: PathBuf, /// Highest deployment this process has seen the SERVER offer. /// /// The rollback guard used to compare against `active.json`'s deployment. /// That file is a derived local pointer owned by the user — which this /// module's own comment says — so on the product's stated threat model (a /// rogue agent running as the user) it was an attacker-controlled veto over /// the control plane: write a high number, and every real deployment is /// refused for good. Combined with corrupting the artifacts it points at, /// the machine cannot repair locally, cannot accept the server, and fails /// closed on every tool call — a permanent denial of service costing one /// file write. /// /// Anchoring on what the server said instead keeps the guard where it /// actually means something (a replayed or out-of-order response inside one /// session, which is the realistic transport failure) and gives up only /// cross-restart rollback protection — which is already carried by TLS, a /// bearer token and SHA-256 pinning of every artifact. Tampering now costs /// an attacker nothing more than a delay until the next poll. /// /// `Arc` rather than a bare atomic because `PolicyStore` is `Clone` and the /// maintenance lane holds its own handle: a per-clone counter would reset /// the floor to zero for whichever clone happened to be asked, quietly /// removing the guard it exists to provide. server_high_water: Arc, } impl PolicyStore { pub fn new(root: PathBuf) -> Self { Self { root, server_high_water: Arc::new(AtomicU64::new(0)), } } pub fn root(&self) -> &Path { &self.root } /// Forgets the highest deployment the server has offered this process. /// /// The deployment counter is the server's per (org, machine) — a different /// org, a re-registered machine or a fresh enrolment starts again at 0. A /// floor carried over from the previous identity would refuse every /// deployment the new one legitimately sends ("deployment rollback from 3 /// to 0") until the daemon restarted, while the previous org's policies /// went on enforcing. The maintenance lane calls this when, and only when, /// the cloud identity it polls with changes; within one identity the /// replay guard is untouched. pub fn reset_high_water(&self) { self.server_high_water.store(0, Ordering::Relaxed); } /// Stops enforcing cloud-managed policy: removes `desired-state.json`, then /// `active.json`. Returns whether anything was removed. /// /// Both files, in that order. Removing only `active.json` (what the CLI's /// `--disconnect` does) is undone on the next maintenance tick, because /// `repair_active_from_cache` rebuilds the pointer from the desired state /// still on disk. Desired first, so a crash between the two leaves nothing /// that repair could resurrect. The content-addressed artifacts stay: they /// are inert without a pointer, and a reconnect may reuse them. pub fn deactivate(&self) -> Result { let mut removed = false; for path in [self.desired_state_path(), self.active_manifest_path()] { match fs::remove_file(&path) { Ok(()) => removed = true, Err(err) if err.kind() == io::ErrorKind::NotFound => {} Err(err) => return Err(err.into()), } } Ok(removed) } pub fn active_manifest_path(&self) -> PathBuf { self.root.join("active.json") } pub fn desired_state_path(&self) -> PathBuf { self.root.join("desired-state.json") } pub fn read_active(&self) -> Result, ReconcileError> { let path = self.active_manifest_path(); if !path.exists() { return Ok(None); } let bytes = fs::read(path)?; // A file a pre-release build wrote may still name the Jev checks that // build delivered (`semanticPolicies`, CONTRACT C10 retired it). Under // `deny_unknown_fields` that key would make the whole deployment // unreadable — a machine enforcing nothing until a poll rewrote the file // — so it is dropped here, before the strict parse, and nothing else is // loosened. The file keeps it until the next write; nothing reads it. let mut value: serde_json::Value = serde_json::from_slice(&bytes)?; if let Some(object) = value.as_object_mut() { for key in RETIRED_ACTIVE_KEYS { object.remove(*key); } } Ok(Some(serde_json::from_value(value)?)) } pub fn read_desired(&self) -> Result, ReconcileError> { let path = self.desired_state_path(); if !path.exists() { return Ok(None); } let bytes = fs::read(path)?; // Current shape first, so the common path pays nothing. A pre-rename file // falls through to `LegacyDesiredState` rather than failing — see its note // for why this file needs the leniency `DesiredState` must not have. let desired: DesiredState = match serde_json::from_slice::(&bytes) { Ok(desired) => desired, Err(current_err) => match serde_json::from_slice::(&bytes) { Ok(legacy) => legacy.into(), // The CURRENT error is reported, not the legacy one: a genuinely // corrupt file is far likelier than a pre-rename one, and // "missing field `generation`" would send someone hunting the // wrong spelling. Err(_) => return Err(current_err.into()), }, }; validate_desired_state(&desired)?; Ok(Some(desired)) } /// Installs a complete desired deployment. Any error before the final /// `active.json` rename leaves the previous deployment authoritative. pub fn reconcile( &self, desired: &DesiredState, fetcher: &impl ArtifactFetcher, ) -> Result { self.reconcile_unless(desired, fetcher, &|| false) } /// [`reconcile`](Self::reconcile), abandoned with /// [`ReconcileError::Withdrawn`] — before `desired-state.json` or /// `active.json` is written — when `withdrawn()` says the machine is no /// longer enrolled. /// /// Asked after every artifact is fetched and verified, because that is the /// slow part: a poll is a request and then one fetch per new artifact, and a /// `config --disconnect` landing in that window used to be undone by this /// function's own writes. Artifacts already written are content-addressed /// and inert once nothing names them, so abandoning after them costs nothing. pub fn reconcile_unless( &self, desired: &DesiredState, fetcher: &impl ArtifactFetcher, withdrawn: &dyn Fn() -> bool, ) -> Result { validate_desired_state(desired)?; // active.json is a derived local pointer, not authority. If it was // truncated or otherwise corrupted, rebuild it from desired state // instead of making the corruption permanent. Non-JSON I/O failures // still surface. let previous = match self.read_active() { Ok(active) => active, Err(ReconcileError::Json(_)) => None, Err(err) => return Err(err), }; // Rollback guard, anchored on what the SERVER has said this session — // never on the local pointer. See `server_high_water`. let floor = self.server_high_water.load(Ordering::Relaxed); if desired.deployment < floor { return Err(ReconcileError::InvalidDesiredState(format!( "deployment rollback from {} to {} is not allowed", floor, desired.deployment ))); } // Recorded before the work below so a mid-reconcile failure cannot let // an immediately-following lower deployment through. self.server_high_water .fetch_max(desired.deployment, Ordering::Relaxed); // A local pointer AHEAD of the server is not authority, but it is worth // saying out loud: it means either a restored/re-registered control // plane, or that something edited this machine's state. if let Some(active) = &previous && active.deployment > desired.deployment { tracing::warn!( "local active deployment {} is ahead of the server's {}; \ taking the server's state (the local pointer is not authority)", active.deployment, desired.deployment ); } // ONE copy of every policy, addressed by its own hash. // // Layout 2 kept two: `artifacts/` plus a per-deployment copy under // `deployments//.mjs`. The second copy bought two things, and // neither survives contact with content addressing: // // • Staging. A deployment was materialised whole under its own number // before `active.json` pointed at it, so a half-downloaded set could // not go live. But an artifact path CONTAINS its hash, so a new // deployment only ever writes new files — it cannot disturb the ones // the current `active.json` names. Nothing needs staging away from a // live set it is structurally incapable of touching. // // • Mutual repair. A tampered artifact was rebuilt from the deployment // copy and vice versa. That is a cache repairing a cache; the server // is the authority, the hash is known, and a re-fetch is both simpler // and correct even when BOTH copies are bad — the case the old scheme // could not recover from at all. // // `active.json` is still the single atomic activation point, and the flip // is still last. fs::create_dir_all(self.root.join("artifacts"))?; let mut downloaded = 0; let mut repaired = 0; let mut active_policies = Vec::with_capacity(desired.policies.len()); for policy in &desired.policies { let artifact_path = self.artifact_path(&policy.sha256); match self.ensure_artifact(&artifact_path, policy, fetcher)? { Ensured::Present => {} Ensured::Downloaded => downloaded += 1, Ensured::Repaired => repaired += 1, } active_policies.push(ActivePolicy { id: policy.id.clone(), version: policy.version, effect: policy.effect, sha256: policy.sha256.clone(), path: self.relative_to_root(&artifact_path)?, authority: policy.authority.clone(), reviewed_by: policy.reviewed_by.clone(), agent_targets: policy.agent_targets.clone(), }); } let active = ActiveDeployment { schema_version: desired.schema_version, deployment: desired.deployment, policies: active_policies, jev_mode: desired.jev_mode.clone(), jev_policies: desired.jev_policies.clone(), }; let manifest_bytes = serde_json::to_vec_pretty(&active)?; // The per-deployment `manifest.json` is gone with `deployments//`. It // duplicated `active.json` for a directory that no longer exists, and a // second copy of the pointer is a second thing that can disagree. if withdrawn() { return Err(ReconcileError::Withdrawn); } // Persist the cloud snapshot before switching active.json. A crash in // between is recoverable: the maintenance loop reconstructs the active // pointer from this snapshot and the artifacts already verified on disk. write_atomic( &self.desired_state_path(), &serde_json::to_vec_pretty(desired)?, )?; let activated = previous.as_ref() != Some(&active); if activated { write_atomic(&self.active_manifest_path(), &manifest_bytes)?; } // AFTER the flip, never before. A machine upgrading from layout 2 has a // per-deployment tree whose files the OLD `active.json` still named; once // the new pointer is live nothing reads it, and leaving it behind means // carrying a full copy of every policy set the machine has ever had. // // `generations` FIRST, and that is the whole point: layout 2 wrote // `cloud-policies/generations//`, and the generation→deployment rename // swept this string literal along with the code. But a literal naming an // ON-DISK artifact written by an OLDER build is not a symbol to rename — // it is data, exactly like the `generation`/`revision` field names that // needed aliases. Checking only `deployments` tested for a directory // nothing has ever written, so the cleanup never ran on any real machine // and the tree it exists to remove was kept forever. The comment above // said "has a `deployments/` tree", which was the same mistake in prose. // // `deployments` is still checked, for a daemon built from this branch // between the rename and the flattening. Costs one `exists()` on a path // that is absent everywhere else. // // Best-effort: a directory we cannot remove is dead weight, not a reason // to fail a reconcile that has already succeeded. for legacy in ["generations", "deployments"] { let path = self.root.join(legacy); if activated && path.exists() { match fs::remove_dir_all(&path) { Ok(()) => tracing::info!("removed the layout-2 {legacy}/ tree"), Err(err) => { tracing::warn!(?err, "could not remove the layout-2 {legacy}/ tree") } } } } if activated { self.remove_semantic_leftovers(); } Ok(ReconcileOutcome { deployment: desired.deployment, downloaded, repaired, activated, }) } /// Verifies every artifact the active deployment names, and reports what it /// cannot fix. /// /// WHAT THIS LOST WHEN `deployments//` WENT AWAY, stated plainly because /// it is a real capability and not an implementation detail: layout 2 kept /// two copies of every policy, so a tampered one could be rebuilt from the /// other WITHOUT the network. There is one copy now, and a corrupt copy has /// no local source of truth — the fix is a re-fetch, which needs the server. /// /// What is NOT lost is the safety property. The hook path verifies each /// artifact's digest before importing it, so a tampered file is refused, not /// executed. The cost is availability: on a machine that cannot reach the /// control plane, that one policy stops enforcing until it can, and this /// function's error is what says so. For a tool whose job is refusing /// dangerous things, failing closed and loudly beats self-healing quietly. /// /// active.json is left unchanged either way, so the worker keeps its last /// known-good decision set. pub fn repair_active_from_cache(&self) -> Result { self.repair_active_from_cache_unless(&|| false) } /// A repair after a Cloud poll must use the same enrolment guard as the /// poll itself. A disconnect may remove both state files after we read /// desired-state.json; that snapshot must not restore the old deployment. pub fn repair_active_from_cache_unless( &self, withdrawn: &dyn Fn() -> bool, ) -> Result { if withdrawn() { return Ok(0); } // A corrupted `desired-state.json` must not disable repair. // // `self.read_desired()?` propagated any parse error straight out, // short-circuiting before the `active.json`-driven branch below — the // one that rebuilds a tampered `deployments//.mjs` from the // still-valid, content-addressed `artifacts/.mjs` copy. So one bad // byte in a file this branch does not even need permanently disabled // deployment-copy self-healing, and per `CLOUD_POLICIES.md` the only // thing that rewrites it is a successful cloud poll — which never // happens on an unenrolled or unreachable machine. // // `reconcile()` already tolerates exactly this for `active.json` // (`Err(ReconcileError::Json(_)) => None`); the two are now symmetric. let desired = match self.read_desired() { Ok(desired) => desired, Err(ReconcileError::Json(err)) => { tracing::warn!( %err, "desired-state.json is unreadable; repairing from active.json alone" ); None } Err(err) => return Err(err), }; if let Some(desired) = desired { let outcome = self.reconcile_unless( &desired, &|policy: &DesiredPolicy| { Err(format!( "no verified cached bytes remain for {}; cloud refetch required", policy.id )) }, withdrawn, ); return match outcome { Ok(outcome) => Ok(outcome.repaired + usize::from(outcome.activated)), Err(ReconcileError::Withdrawn) => Ok(0), Err(err) => Err(err), }; } if withdrawn() { return Ok(0); } let Some(active) = self.read_active()? else { return Ok(0); }; if !SUPPORTED_SCHEMA_VERSIONS.contains(&active.schema_version) { return Err(ReconcileError::InvalidDesiredState(format!( "unsupported active schema version {} (supported: {:?})", active.schema_version, SUPPORTED_SCHEMA_VERSIONS ))); } let mut repaired = 0; for policy in &active.policies { if withdrawn() { return Ok(repaired); } validate_policy_identity(&policy.id)?; validate_sha256(&policy.sha256)?; let deployment_path = safe_join_relative(&self.root, &policy.path)?; let artifact_path = self.artifact_path(&policy.sha256); let artifact_valid = file_matches_hash(&artifact_path, &policy.sha256)?; let deployment_valid = file_matches_hash(&deployment_path, &policy.sha256)?; match (artifact_valid, deployment_valid) { (true, true) => {} (true, false) => { write_atomic(&deployment_path, &fs::read(&artifact_path)?)?; repaired += 1; } (false, true) => { write_atomic(&artifact_path, &fs::read(&deployment_path)?)?; repaired += 1; } (false, false) => { return Err(ReconcileError::NoVerifiedCopy { policy_id: policy.id.clone(), }); } } } Ok(repaired) } /// Removes this machine's Cloud deployment: `desired-state.json` FIRST, /// then `active.json`, then both error reports. Returns how many files were /// actually removed. /// /// For a machine that has been put back on OSS (see `maintenance_tick`), and /// the same order `config --disconnect` uses: with the snapshot gone first, /// nothing can rebuild the pointer from it in between. Artifacts stay — they /// are content-addressed, verified on use and inert once nothing names them. pub fn clear_deployment(&self) -> io::Result { let mut removed = 0; for path in [ self.desired_state_path(), self.active_manifest_path(), self.cli_errors_path(), self.daemon_errors_path(), ] { match fs::remove_file(&path) { Ok(()) => removed += 1, Err(err) if err.kind() == io::ErrorKind::NotFound => {} Err(err) => return Err(err), } } Ok(removed) } fn artifact_path(&self, sha256: &str) -> PathBuf { self.root.join("artifacts").join(format!("{sha256}.mjs")) } /// Removes `artifacts/.json`: Jev check declarations a pre-release /// build of this branch delivered to the machine. Since CONTRACT C10 Jev /// checks live only on FailproofAI Cloud and nothing writes or reads these, /// but they held an org's check text. Run after an activation, like the /// layout-2 cleanup above; best-effort, and only files named exactly like /// one (64 lowercase hex + `.json`) — the JS artifacts are `.mjs`. fn remove_semantic_leftovers(&self) { let Ok(entries) = fs::read_dir(self.root.join("artifacts")) else { return; }; for entry in entries.flatten() { let name = entry.file_name(); let Some(stem) = name.to_str().and_then(|n| n.strip_suffix(".json")) else { continue; }; if stem.len() != 64 || !stem.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) { continue; } match fs::remove_file(entry.path()) { Ok(()) => tracing::info!("removed a pre-release Jev check artifact"), Err(err) => { tracing::warn!(?err, "could not remove a pre-release Jev check artifact") } } } } /// Where `errors.json` lives: the CLI's report of what it could not load /// from the active deployment (see `read_cli_policy_errors`). pub fn cli_errors_path(&self) -> PathBuf { self.root.join("errors.json") } /// Where the daemon persists its OWN reconcile error state, so a restart /// neither forgets an error the server is still showing nor starts /// reporting on a machine that never had one. pub fn daemon_errors_path(&self) -> PathBuf { self.root.join("daemon-errors.json") } /// Makes `path` hold bytes hashing to `request.sha256`, fetching and /// verifying them when it does not. Nothing unverified is ever written. fn ensure_artifact( &self, path: &Path, request: &DesiredPolicy, fetcher: &impl ArtifactFetcher, ) -> Result { if file_matches_hash(path, &request.sha256)? { return Ok(Ensured::Present); } // Present-but-wrong and absent are different events, and the metric is // worth keeping honest: one means somebody or something modified a // verified file, the other is a first download. let existed = path.exists(); let bytes = fetcher .fetch(request) .map_err(|message| ReconcileError::Fetch { policy_id: request.id.clone(), message, })?; verify_bytes(request, &bytes)?; write_atomic(path, &bytes)?; Ok(if existed { Ensured::Repaired } else { Ensured::Downloaded }) } fn relative_to_root(&self, path: &Path) -> Result { Ok(path .strip_prefix(&self.root) .map_err(|_| { ReconcileError::InvalidDesiredState("deployment path escaped policy root".into()) })? .to_string_lossy() .into_owned()) } } enum Ensured { Present, Downloaded, Repaired, } /// Starts the maintenance-lane integrity loop. It performs one pass /// immediately, then periodically, and wakes in short slices so daemon /// shutdown never waits for the full reconciliation interval. pub fn spawn_integrity_monitor( store: PolicyStore, shutdown: Arc, interval: Duration, ) -> JoinHandle<()> { std::thread::spawn(move || { while !shutdown.load(Ordering::Relaxed) { match store.repair_active_from_cache() { Ok(0) => {} Ok(repaired) => { tracing::info!("repaired {repaired} cloud-managed policy artifact(s)") } Err(err) => tracing::warn!("cloud policy integrity error: {err}"), } let deadline = Instant::now() + interval; while !shutdown.load(Ordering::Relaxed) && Instant::now() < deadline { let remaining = deadline.saturating_duration_since(Instant::now()); std::thread::sleep(remaining.min(Duration::from_millis(50))); } } }) } fn validate_desired_state(desired: &DesiredState) -> Result<(), ReconcileError> { if !SUPPORTED_SCHEMA_VERSIONS.contains(&desired.schema_version) { return Err(ReconcileError::InvalidDesiredState(format!( "unsupported schema version {} (supported: {:?})", desired.schema_version, SUPPORTED_SCHEMA_VERSIONS ))); } let mut ids = HashSet::new(); for policy in &desired.policies { if let Some(targets) = &policy.agent_targets && (desired.schema_version < SCOPED_DESIRED_STATE_SCHEMA_VERSION || !validate_targets(targets)) { return Err(ReconcileError::InvalidDesiredState(format!( "policy {} has invalid agentTargets for schema {}", policy.id, desired.schema_version ))); } validate_policy_identity(&policy.id)?; validate_sha256(&policy.sha256)?; if policy.artifact_url.trim().is_empty() { return Err(ReconcileError::InvalidDesiredState(format!( "policy {} has an empty artifactUrl", policy.id ))); } if !ids.insert(policy.id.as_str()) { return Err(ReconcileError::InvalidDesiredState(format!( "duplicate policy id {}", policy.id ))); } // Refused rather than dropped, like an unknown `effect`: the server // derives this from the policy's kind, so a value outside the two it // can produce is a stale or forged payload, not a typo to shrug off. if let Some(authority) = &policy.authority && !AUTHORITIES.contains(&authority.as_str()) { return Err(ReconcileError::InvalidDesiredState(format!( "policy {} has authority {authority:?} (expected one of {AUTHORITIES:?})", policy.id ))); } } if let Some(mode) = &desired.jev_mode && !JEV_MODES.contains(&mode.as_str()) { return Err(ReconcileError::InvalidDesiredState(format!( "jevMode {mode:?} is not one of {JEV_MODES:?}" ))); } let mut jev_ids = HashSet::new(); for assignment in desired.jev_policies.iter().flatten() { validate_policy_identity(&assignment.id)?; if let Some(targets) = &assignment.agent_targets && (desired.schema_version < SCOPED_DESIRED_STATE_SCHEMA_VERSION || !validate_targets(targets)) { return Err(ReconcileError::InvalidDesiredState(format!( "Jev policy {} has invalid agentTargets for schema {}", assignment.id, desired.schema_version ))); } if !jev_ids.insert(assignment.id.as_str()) { return Err(ReconcileError::InvalidDesiredState(format!( "duplicate Jev policy id {}", assignment.id ))); } } Ok(()) } fn validate_policy_identity(id: &str) -> Result<(), ReconcileError> { let valid = !id.is_empty() && id.len() <= 128 && id .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) && id != "." && id != ".."; if !valid { return Err(ReconcileError::InvalidDesiredState(format!( "unsafe policy id {id:?}" ))); } Ok(()) } fn validate_sha256(value: &str) -> Result<(), ReconcileError> { if value.len() != 64 || !value .bytes() .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) { return Err(ReconcileError::InvalidDesiredState(format!( "invalid lowercase SHA-256 digest {value:?}" ))); } Ok(()) } fn safe_join_relative(root: &Path, relative: &str) -> Result { let path = Path::new(relative); if path.is_absolute() || path .components() .any(|component| !matches!(component, std::path::Component::Normal(_))) { return Err(ReconcileError::InvalidDesiredState(format!( "unsafe active policy path {relative:?}" ))); } Ok(root.join(path)) } fn verify_bytes(policy: &DesiredPolicy, bytes: &[u8]) -> Result<(), ReconcileError> { let actual = sha256_hex(bytes); if actual != policy.sha256 { return Err(ReconcileError::HashMismatch { policy_id: policy.id.clone(), expected: policy.sha256.clone(), actual, }); } Ok(()) } fn file_matches_hash(path: &Path, expected: &str) -> Result { let mut file = match File::open(path) { Ok(file) => file, Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(false), Err(err) => return Err(err.into()), }; let mut hasher = Sha256::new(); let mut buffer = [0_u8; 8192]; loop { let read = file.read(&mut buffer)?; if read == 0 { break; } hasher.update(&buffer[..read]); } Ok(hex_encode(&hasher.finalize()) == expected) } fn sha256_hex(bytes: &[u8]) -> String { hex_encode(&Sha256::digest(bytes)) } fn hex_encode(bytes: &[u8]) -> String { const HEX: &[u8; 16] = b"0123456789abcdef"; let mut encoded = String::with_capacity(bytes.len() * 2); for &byte in bytes { encoded.push(HEX[(byte >> 4) as usize] as char); encoded.push(HEX[(byte & 0x0f) as usize] as char); } encoded } fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), ReconcileError> { let parent = path .parent() .ok_or_else(|| io::Error::other("managed policy path has no parent"))?; fs::create_dir_all(parent)?; let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed); let file_name = path .file_name() .and_then(|name| name.to_str()) .unwrap_or("managed-policy"); let temp = parent.join(format!(".{file_name}.tmp-{}-{counter}", std::process::id())); let mut file = OpenOptions::new() .write(true) .create_new(true) .open(&temp)?; file.set_permissions(fs::Permissions::from_mode(MANAGED_FILE_MODE))?; file.write_all(bytes)?; file.sync_all()?; drop(file); fs::rename(&temp, path)?; File::open(parent)?.sync_all()?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn desired_state_tolerates_fields_this_daemon_does_not_know() { // Daemons update on their own schedule. If this struct rejected unknown // fields, the first thing cloud added would make every older daemon // fail to parse desired-state and silently stop pulling — a fleet // stranded on whatever deployment it happened to hold, with no error // anyone would look for. let json = r#"{"schemaVersion":1,"deployment":4,"policies":[ {"id":"guard","version":2,"sha256":"aa","artifactUrl":"/a","effect":"observe", "someFutureField":{"nested":true}} ],"anotherFutureField":42}"#; let parsed: DesiredState = serde_json::from_str(json).expect("must parse"); assert_eq!(parsed.deployment, 4); assert_eq!(parsed.policies[0].effect, PolicyEffect::Observe); } #[test] fn a_policy_with_no_effect_enforces() { // The default has to be the one that keeps enforcing: a server that // predates observe mode must not silently downgrade a fleet to // observation. let json = r#"{"schemaVersion":1,"deployment":1,"policies":[ {"id":"g","version":1,"sha256":"aa","artifactUrl":"/a"}]}"#; let parsed: DesiredState = serde_json::from_str(json).unwrap(); assert_eq!(parsed.policies[0].effect, PolicyEffect::Enforce); } #[test] fn an_unreadable_effect_is_rejected_rather_than_guessed() { // Guessing would mean choosing between enforcing something cloud did // not ask to enforce, or observing something it wanted enforced. Both // are worse than refusing the deployment. let json = r#"{"schemaVersion":1,"deployment":1,"policies":[ {"id":"g","version":1,"sha256":"aa","artifactUrl":"/a","effect":"maybe"}]}"#; assert!(serde_json::from_str::(json).is_err()); } #[test] fn the_active_manifest_records_the_effect_it_activated() { // active.json is what the evaluator reads. If the effect were not // carried here, an observe-mode policy would enforce the moment the // daemon restarted and re-read its own manifest. let manifest = ActiveDeployment { schema_version: 1, deployment: 9, policies: vec![ActivePolicy { id: "g".into(), version: 1, sha256: "aa".into(), path: "deployments/9/g.mjs".into(), effect: PolicyEffect::Observe, authority: None, reviewed_by: None, agent_targets: None, }], jev_mode: None, jev_policies: None, }; let round_tripped: ActiveDeployment = serde_json::from_str(&serde_json::to_string(&manifest).unwrap()).unwrap(); assert_eq!(round_tripped.policies[0].effect, PolicyEffect::Observe); assert!( serde_json::to_string(&manifest) .unwrap() .contains("\"effect\":\"observe\"") ); } use std::sync::atomic::{AtomicUsize, Ordering}; fn temp_store(name: &str) -> PolicyStore { let root = std::env::temp_dir().join(format!( "failproofaid-cloud-policy-{name}-{}-{}", std::process::id(), TEMP_COUNTER.fetch_add(1, Ordering::Relaxed) )); PolicyStore::new(root) } fn desired(deployment: u64, id: &str, bytes: &[u8]) -> DesiredState { DesiredState { schema_version: DESIRED_STATE_SCHEMA_VERSION, deployment, policies: vec![DesiredPolicy { id: id.to_string(), version: deployment, sha256: sha256_hex(bytes), artifact_url: format!("https://cloud.invalid/{id}/{deployment}"), effect: PolicyEffect::Enforce, authority: None, reviewed_by: None, agent_targets: None, }], jev_mode: None, jev_policies: None, } } #[test] fn activates_a_complete_verified_deployment() { let store = temp_store("activate"); let bytes = b"export default 'cloud policy';\n"; let state = desired(7, "block-secrets", bytes); let fetches = AtomicUsize::new(0); let outcome = store .reconcile(&state, &|_: &DesiredPolicy| { fetches.fetch_add(1, Ordering::Relaxed); Ok(bytes.to_vec()) }) .unwrap(); assert_eq!(outcome.downloaded, 1); assert!(outcome.activated); assert_eq!(fetches.load(Ordering::Relaxed), 1); let active = store.read_active().unwrap().unwrap(); assert_eq!(active.deployment, 7); assert_eq!(active.policies[0].id, "block-secrets"); let active_path = store.root().join(&active.policies[0].path); assert_eq!(fs::read(active_path).unwrap(), bytes); fs::remove_dir_all(store.root()).ok(); } #[test] fn a_bad_download_never_replaces_last_known_good() { let store = temp_store("bad-download"); let good = b"export default 'good';\n"; store .reconcile(&desired(1, "guard", good), &|_: &DesiredPolicy| { Ok(good.to_vec()) }) .unwrap(); let before = fs::read(store.active_manifest_path()).unwrap(); let next = desired(2, "guard", b"export default 'expected';\n"); let err = store .reconcile( &next, &|_: &DesiredPolicy| Ok(b"tampered download".to_vec()), ) .unwrap_err(); assert!(matches!(err, ReconcileError::HashMismatch { .. })); assert_eq!(fs::read(store.active_manifest_path()).unwrap(), before); assert_eq!(store.read_active().unwrap().unwrap().deployment, 1); fs::remove_dir_all(store.root()).ok(); } /// The layout-2 tree is actually removed — under the name layout 2 wrote. /// /// This checked `deployments/` only, a name nothing has ever written: the /// generation→deployment rename swept up a string literal that names an /// ON-DISK artifact from an older build. So the cleanup never ran on any real /// machine, and the full copy of every policy set the machine had ever held /// was kept forever — the exact outcome the code's own comment says it exists /// to prevent. #[test] fn the_layout_two_generations_tree_is_removed_after_the_flip() { let store = temp_store("legacy-generations"); let bytes = b"export default 'x';\n".to_vec(); // Both names, so the test would catch a fix that swapped one for the other // rather than covering both. for legacy in ["generations", "deployments"] { std::fs::create_dir_all(store.root().join(legacy).join("4")).unwrap(); std::fs::write( store.root().join(legacy).join("4").join("old.mjs"), b"stale", ) .unwrap(); } let desired = desired(1, "p", &bytes); store .reconcile(&desired, &|_: &DesiredPolicy| Ok(bytes.clone())) .expect("reconcile"); assert!( !store.root().join("generations").exists(), "the layout-2 generations/ tree must be removed once the new pointer is live" ); assert!(!store.root().join("deployments").exists()); // And the live set is untouched by the cleanup. assert!(store.read_active().unwrap().is_some()); } #[test] fn a_tampered_artifact_is_reported_rather_than_silently_repaired() { // Layout 2 kept a second copy under `deployments//` and rebuilt one // from the other offline. There is one copy now, so a corrupt artifact // has no local source of truth and the honest outcome is an error the // caller logs — both callers already treat it as an integrity error. // // The safety property is unchanged: the hook path verifies the digest // before importing, so the tampered bytes are refused rather than run. let store = temp_store("tampered-artifact"); let bytes = b"export default 'verified';\n"; let state = desired(4, "guard", bytes); store .reconcile(&state, &|_: &DesiredPolicy| Ok(bytes.to_vec())) .unwrap(); let artifact_path = store.artifact_path(&state.policies[0].sha256); fs::write(&artifact_path, b"tampered").unwrap(); let err = store .repair_active_from_cache() .expect_err("a corrupt artifact with no second copy cannot be repaired locally"); assert!( format!("{err}").contains("refetch"), "the error must say a re-fetch is required, got: {err}" ); // active.json is untouched, so the worker keeps its last known-good set. assert!(store.read_active().unwrap().is_some()); fs::remove_dir_all(store.root()).ok(); } #[test] fn disconnect_during_cached_repair_cannot_restore_its_removed_deployment() { use std::cell::Cell; let store = temp_store("disconnect-mid-repair"); let bytes = b"export default 'verified';\n"; let state = desired(4, "guard", bytes); store .reconcile(&state, &|_: &DesiredPolicy| Ok(bytes.to_vec())) .unwrap(); let checks = Cell::new(0); let withdrawn = || { let count = checks.get(); checks.set(count + 1); if count == 0 { return false; // after the snapshot read, before activation } fs::remove_file(store.desired_state_path()).ok(); fs::remove_file(store.active_manifest_path()).ok(); true }; assert_eq!( store.repair_active_from_cache_unless(&withdrawn).unwrap(), 0 ); assert!( checks.get() >= 2, "the repair must recheck enrolment at activation" ); assert!(!store.desired_state_path().exists()); assert!(!store.active_manifest_path().exists()); fs::remove_dir_all(store.root()).ok(); } #[test] fn a_real_poll_refetches_what_local_repair_cannot() { // The other half of the same contract: the fix exists, it just needs the // server. With a working fetcher the tampered artifact is replaced and // counted as a repair rather than a first download. let store = temp_store("refetch-tampered"); let bytes = b"export default 'verified';\n"; let state = desired(4, "guard", bytes); store .reconcile(&state, &|_: &DesiredPolicy| Ok(bytes.to_vec())) .unwrap(); let artifact_path = store.artifact_path(&state.policies[0].sha256); fs::write(&artifact_path, b"tampered").unwrap(); let outcome = store .reconcile(&state, &|_: &DesiredPolicy| Ok(bytes.to_vec())) .unwrap(); assert_eq!(outcome.repaired, 1, "present-but-wrong counts as a repair"); assert_eq!(outcome.downloaded, 0, "not a first download"); assert_eq!(fs::read(artifact_path).unwrap(), bytes); fs::remove_dir_all(store.root()).ok(); } #[test] fn repairs_a_removed_or_rewritten_active_manifest_from_desired_state() { let store = temp_store("repair-active"); let bytes = b"export default 'verified';\n"; store .reconcile(&desired(11, "guard", bytes), &|_: &DesiredPolicy| { Ok(bytes.to_vec()) }) .unwrap(); fs::write( store.active_manifest_path(), br#"{"schemaVersion":1,"deployment":11,"policies":[]}"#, ) .unwrap(); assert_eq!(store.repair_active_from_cache().unwrap(), 1); assert_eq!(store.read_active().unwrap().unwrap().policies.len(), 1); fs::write(store.active_manifest_path(), b"not-json").unwrap(); assert_eq!(store.repair_active_from_cache().unwrap(), 1); assert_eq!( store.read_active().unwrap().unwrap().policies[0].id, "guard" ); fs::remove_dir_all(store.root()).ok(); } /// The floor belongs to one cloud identity. After a reset (org switch, /// re-registration) the new identity's deployment 0 — and its empty set — /// must activate; without one, the same 0 is still a rollback. #[test] fn a_reset_floor_accepts_the_next_identitys_lower_deployment() { let store = temp_store("reset-floor"); let bytes = b"policy"; store .reconcile(&desired(3, "guard", bytes), &|_: &DesiredPolicy| { Ok(bytes.to_vec()) }) .unwrap(); let empty = DesiredState { schema_version: DESIRED_STATE_SCHEMA_VERSION, deployment: 0, policies: vec![], jev_mode: None, jev_policies: None, }; let refuse = |_: &DesiredPolicy| -> Result, String> { Err("no fetch".into()) }; assert!( matches!( store.reconcile(&empty, &refuse), Err(ReconcileError::InvalidDesiredState(_)) ), "without a reset, a lower deployment is still a rollback" ); store.reset_high_water(); let outcome = store .reconcile(&empty, &refuse) .expect("a new identity's deployment 0 must be accepted after a reset"); assert!(outcome.activated); let active = store.read_active().unwrap().unwrap(); assert_eq!(active.deployment, 0); assert!(active.policies.is_empty()); // And the guard is live again for the new identity. store .reconcile(&desired(2, "guard", bytes), &|_: &DesiredPolicy| { Ok(bytes.to_vec()) }) .unwrap(); assert!(matches!( store.reconcile(&empty, &refuse), Err(ReconcileError::InvalidDesiredState(_)) )); fs::remove_dir_all(store.root()).ok(); } /// Deactivation must survive the next maintenance tick: repair rebuilds /// `active.json` from `desired-state.json`, so both have to go. #[test] fn deactivate_removes_what_repair_would_resurrect() { let store = temp_store("deactivate"); let bytes = b"policy"; store .reconcile(&desired(4, "guard", bytes), &|_: &DesiredPolicy| { Ok(bytes.to_vec()) }) .unwrap(); assert!(store.deactivate().unwrap()); assert!(store.read_active().unwrap().is_none()); assert!(store.read_desired().unwrap().is_none()); assert_eq!(store.repair_active_from_cache().unwrap(), 0); assert!(store.read_active().unwrap().is_none()); assert!(!store.deactivate().unwrap(), "idempotent"); fs::remove_dir_all(store.root()).ok(); } #[test] fn rejects_traversal_duplicate_ids_and_deployment_rollback() { let store = temp_store("validation"); let bytes = b"policy"; let mut traversal = desired(1, "../escape", bytes); assert!(matches!( store.reconcile(&traversal, &|_: &DesiredPolicy| Ok(bytes.to_vec())), Err(ReconcileError::InvalidDesiredState(_)) )); traversal.policies[0].id = "guard".to_string(); traversal.policies.push(traversal.policies[0].clone()); assert!(matches!( store.reconcile(&traversal, &|_: &DesiredPolicy| Ok(bytes.to_vec())), Err(ReconcileError::InvalidDesiredState(_)) )); store .reconcile(&desired(9, "guard", bytes), &|_: &DesiredPolicy| { Ok(bytes.to_vec()) }) .unwrap(); assert!(matches!( store.reconcile(&desired(8, "guard", bytes), &|_: &DesiredPolicy| Ok( bytes.to_vec() )), Err(ReconcileError::InvalidDesiredState(_)) )); fs::remove_dir_all(store.root()).ok(); } /// A tampered local deployment must not be able to veto the control plane. /// /// The guard used to compare against `active.json`, a 0600 file owned by /// the very user the product's threat model treats as compromised. Writing /// one large number there made every subsequent real deployment fail /// validation for good; corrupt the artifacts it points at as well and the /// machine can neither repair locally nor accept the server, and fails /// closed on every tool call. A permanent denial of service for one file /// write. #[test] fn a_tampered_local_deployment_cannot_permanently_veto_the_server() { let store = temp_store("tampered-deployment"); let bytes = b"policy"; store .reconcile(&desired(5, "guard", bytes), &|_: &DesiredPolicy| { Ok(bytes.to_vec()) }) .unwrap(); // The attack: one edit to a user-owned file. let manifest = store.active_manifest_path(); let raw = fs::read_to_string(&manifest).unwrap(); let mut active: serde_json::Value = serde_json::from_str(&raw).unwrap(); active["deployment"] = serde_json::json!(u64::MAX); fs::write(&manifest, serde_json::to_vec(&active).unwrap()).unwrap(); // A fresh process, as after any restart. It must take the server's // state rather than treating the local number as authority. let restarted = PolicyStore::new(store.root().to_path_buf()); let outcome = restarted .reconcile(&desired(6, "guard", bytes), &|_: &DesiredPolicy| { Ok(bytes.to_vec()) }) .expect("the server's state must win over a local pointer"); assert!(outcome.activated); assert_eq!(restarted.read_active().unwrap().unwrap().deployment, 6); // And replay protection still holds WITHIN the session, which is the // transport failure the guard actually exists for. assert!(matches!( restarted.reconcile(&desired(5, "guard", bytes), &|_: &DesiredPolicy| Ok( bytes.to_vec() )), Err(ReconcileError::InvalidDesiredState(_)) )); fs::remove_dir_all(store.root()).ok(); } #[test] fn the_background_monitor_detects_tampering_without_touching_the_hook_path() { // The monitor's job changed with the flattening. It used to REPAIR a // tampered copy from the other one; with a single content-addressed copy // it DETECTS and reports, and the fix comes from the next cloud poll. // // What it must still never do is disturb the hook path: `active.json` is // left exactly as it was, so the worker keeps enforcing its last // known-good set while the corruption is reported. let store = temp_store("monitor"); let bytes = b"export default 'verified';\n"; store .reconcile(&desired(10, "guard", bytes), &|_: &DesiredPolicy| { Ok(bytes.to_vec()) }) .unwrap(); let active_before = store.read_active().unwrap().unwrap(); let artifact = store.root().join(&active_before.policies[0].path); fs::write(&artifact, b"tampered").unwrap(); let shutdown = Arc::new(AtomicBool::new(false)); let handle = spawn_integrity_monitor(store.clone(), shutdown.clone(), Duration::from_millis(10)); std::thread::sleep(Duration::from_millis(60)); shutdown.store(true, Ordering::Relaxed); handle.join().unwrap(); // Still tampered — the monitor cannot fix this alone any more — but the // pointer the worker reads is untouched. assert_eq!(fs::read(&artifact).unwrap(), b"tampered"); assert_eq!(store.read_active().unwrap().unwrap(), active_before); fs::remove_dir_all(store.root()).ok(); } } #[cfg(test)] pub(crate) mod cloud_jev_tests { //! Cloud Jev mode and `both` policies on the daemon (CONTRACT C5 as amended //! by C10): the machine receives a `both` policy's JS half with its derived //! `authority`/`reviewedBy`, and the Cloud Jev MODE — never the Jev checks //! themselves, which live on FailproofAI Cloud. The fixtures are //! `pub(crate)` for the maintenance-lane tests in `cloud_client.rs`. use super::*; use std::sync::atomic::Ordering; pub(crate) fn temp_store(name: &str) -> PolicyStore { let root = std::env::temp_dir().join(format!( "fpaid-cloud-jev-{name}-{}-{}", std::process::id(), TEMP_COUNTER.fetch_add(1, Ordering::Relaxed) )); let _ = fs::remove_dir_all(&root); PolicyStore::new(root) } const JS: &[u8] = b"export default 'regex half';\n"; /// Review m8: `artifacts/.json` files left by the pre-release /// on-machine delivery hold an org's check text. The next activation /// removes them, and only them: the JS artifacts are `.mjs`. #[test] fn an_activation_removes_pre_release_jev_check_artifacts() { let store = temp_store("semantic-leftovers"); let artifacts = store.root().join("artifacts"); fs::create_dir_all(&artifacts).unwrap(); let leftover = artifacts.join(format!("{}.json", "a1".repeat(32))); let not_a_digest = artifacts.join("notes.json"); fs::write(&leftover, b"[{\"name\":\"acme-x\"}]").unwrap(); fs::write(¬_a_digest, b"{}").unwrap(); store.reconcile(&jev_state(12), &serve).unwrap(); assert!(!leftover.exists()); assert!( not_a_digest.exists(), "only digest-named declaration files go" ); assert!(store.artifact_path(&sha256_hex(JS)).exists()); fs::remove_dir_all(store.root()).ok(); } /// A `both` policy's JS half (reviewable by its own Cloud check) under a /// Cloud Jev mode. pub(crate) fn jev_state(deployment: u64) -> DesiredState { DesiredState { schema_version: DESIRED_STATE_SCHEMA_VERSION, deployment, policies: vec![DesiredPolicy { id: "no-prod-db".into(), version: 3, sha256: sha256_hex(JS), artifact_url: format!("/enforcement/v1/artifacts/{}", sha256_hex(JS)), effect: PolicyEffect::Enforce, authority: Some("reviewable".into()), reviewed_by: Some(vec!["acme-prod-db".into()]), agent_targets: None, }], jev_mode: Some("observe".into()), jev_policies: None, } } pub(crate) fn serve(request: &DesiredPolicy) -> Result, String> { if sha256_hex(JS) == request.sha256 { return Ok(JS.to_vec()); } Err(format!("no such artifact {}", request.sha256)) } /// `active.json` exactly as a daemon from before Cloud Jev wrote it /// (`to_vec_pretty` of the old struct). const TODAYS_ACTIVE: &str = r#"{ "schemaVersion": 2, "deployment": 42, "policies": [ { "id": "block-curl", "version": 3, "sha256": "732c6e780e183a15259688d858e4ec0db20c7dd13352601c73db5540122e2c30", "path": "artifacts/732c6e780e183a15259688d858e4ec0db20c7dd13352601c73db5540122e2c30.mjs", "effect": "enforce" } ] }"#; /// `desired-state.json` exactly as a daemon from before Cloud Jev wrote it. const TODAYS_DESIRED: &str = r#"{ "schemaVersion": 2, "deployment": 42, "policies": [ { "id": "block-curl", "version": 3, "sha256": "732c6e780e183a15259688d858e4ec0db20c7dd13352601c73db5540122e2c30", "artifactUrl": "/enforcement/v1/artifacts/732c6e780e183a15259688d858e4ec0db20c7dd13352601c73db5540122e2c30", "effect": "observe" } ] }"#; /// Today's machines must write the files they always wrote: every new field /// is optional on read and skipped when empty on write. #[test] fn todays_active_json_round_trips_byte_identical() { let parsed: ActiveDeployment = serde_json::from_str(TODAYS_ACTIVE).unwrap(); assert_eq!(parsed.jev_mode, None); assert_eq!(parsed.policies[0].authority, None); let written = String::from_utf8(serde_json::to_vec_pretty(&parsed).unwrap()).unwrap(); assert_eq!(written, TODAYS_ACTIVE); } #[test] fn todays_desired_state_round_trips_byte_identical() { let parsed: DesiredState = serde_json::from_str(TODAYS_DESIRED).unwrap(); assert_eq!(parsed.jev_mode, None); assert_eq!(parsed.policies[0].reviewed_by, None); let written = String::from_utf8(serde_json::to_vec_pretty(&parsed).unwrap()).unwrap(); assert_eq!(written, TODAYS_DESIRED); } /// And a reconcile of a deployment with no Cloud Jev mode and no `both` /// policy still writes the old shape, byte for byte. #[test] fn a_deployment_with_no_jev_writes_no_new_keys() { let store = temp_store("no-jev"); let mut state = jev_state(5); state.jev_mode = None; state.policies[0].authority = None; state.policies[0].reviewed_by = None; store.reconcile(&state, &serve).unwrap(); let active = fs::read_to_string(store.active_manifest_path()).unwrap(); for key in ["semanticPolicies", "jevMode", "authority", "reviewedBy"] { assert!(!active.contains(key), "{key} must be skipped: {active}"); } let desired = fs::read_to_string(store.desired_state_path()).unwrap(); for key in ["semanticPolicies", "jevMode", "authority", "reviewedBy"] { assert!(!desired.contains(key), "{key} must be skipped: {desired}"); } fs::remove_dir_all(store.root()).ok(); } #[test] fn the_wire_carries_the_mode_and_the_both_fields_in_camel_case() { let json = r#"{"schemaVersion":2,"deployment":43, "policies":[{"id":"no-prod-db","version":3,"sha256":"aa","artifactUrl":"/a", "effect":"enforce","authority":"reviewable","reviewedBy":["prod-db-write-intent"]}], "jevMode":"observe"}"#; let parsed: DesiredState = serde_json::from_str(json).unwrap(); assert_eq!(parsed.policies[0].authority.as_deref(), Some("reviewable")); assert_eq!( parsed.policies[0].reviewed_by.as_deref(), Some(&["prod-db-write-intent".to_string()][..]) ); assert_eq!(parsed.jev_mode.as_deref(), Some("observe")); } /// A server that still sends Jev checks (`semanticPolicies`, retired by /// CONTRACT C10) is not obeyed: the list is ignored like any unknown field, /// nothing is fetched for it, and nothing Jev-related reaches the disk. #[test] fn semantic_policies_from_a_server_are_ignored_and_never_fetched() { let json = format!( r#"{{"schemaVersion":2,"deployment":44, "policies":[{{"id":"no-prod-db","version":3,"sha256":"{js}","artifactUrl":"/a", "effect":"enforce","authority":"reviewable","reviewedBy":["acme-prod-db"]}}], "semanticPolicies":[{{"id":"no-prod-db","version":3,"sha256":"{other}","artifactUrl":"/b"}}], "jevMode":"enforce"}}"#, js = sha256_hex(JS), other = sha256_hex(b"[]"), ); let parsed: DesiredState = serde_json::from_str(&json).unwrap(); let store = temp_store("retired-semantic"); let fetched = std::cell::RefCell::new(Vec::new()); store .reconcile(&parsed, &|request: &DesiredPolicy| { fetched.borrow_mut().push(request.sha256.clone()); serve(request) }) .unwrap(); assert_eq!(fetched.into_inner(), vec![sha256_hex(JS)]); let active = fs::read_to_string(store.active_manifest_path()).unwrap(); let desired = fs::read_to_string(store.desired_state_path()).unwrap(); for text in [&active, &desired] { assert!(!text.contains("semanticPolicies"), "{text}"); assert!(text.contains("\"jevMode\": \"enforce\""), "{text}"); assert!(text.contains("\"reviewedBy\""), "{text}"); } let names: Vec<_> = fs::read_dir(store.root().join("artifacts")) .unwrap() .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) .collect(); assert_eq!(names, vec![format!("{}.mjs", sha256_hex(JS))]); fs::remove_dir_all(store.root()).ok(); } /// An `active.json` left by a pre-release build that still delivered Jev /// checks carries `semanticPolicies`. It must stay readable under /// `deny_unknown_fields` — or the machine would enforce nothing until a /// poll — with the key ignored, and repair must not trip over it either. #[test] fn a_leftover_semantic_policies_key_in_active_json_is_ignored_safely() { let store = temp_store("leftover-semantic"); store.reconcile(&jev_state(8), &serve).unwrap(); let good = store.read_active().unwrap().unwrap(); let mut raw: serde_json::Value = serde_json::from_slice(&fs::read(store.active_manifest_path()).unwrap()).unwrap(); raw["semanticPolicies"] = serde_json::json!([ {"id": "no-prod-db", "version": 3, "sha256": "ab".repeat(32), "path": "artifacts/gone.json"} ]); fs::write( store.active_manifest_path(), serde_json::to_vec_pretty(&raw).unwrap(), ) .unwrap(); assert_eq!(store.read_active().unwrap().unwrap(), good); // Repair reads it too, and finds nothing to rebuild — the named Jev // artifact is not a thing the daemon checks any more. assert_eq!(store.repair_active_from_cache().unwrap(), 0); // With the snapshot gone, the active.json-only branch reads it as well. fs::remove_file(store.desired_state_path()).unwrap(); assert_eq!(store.repair_active_from_cache().unwrap(), 0); // Any OTHER unknown key is still refused: only the retired one is dropped. raw["somethingNew"] = serde_json::json!(1); fs::write( store.active_manifest_path(), serde_json::to_vec(&raw).unwrap(), ) .unwrap(); assert!(matches!(store.read_active(), Err(ReconcileError::Json(_)))); fs::remove_dir_all(store.root()).ok(); } /// The JS half, the derived authority and the Jev mode, in one atomic write. #[test] fn jev_assignments_ride_into_active_json_with_effect_and_scope() { let store = temp_store("jev-assignments"); let mut state = jev_state(9); state.schema_version = SCOPED_DESIRED_STATE_SCHEMA_VERSION; state.jev_mode = Some("enforce".into()); state.jev_policies = Some( serde_json::from_str( r#"[{"id":"prod-db","version":2,"effect":"observe","agentTargets":[{"integration":"claude"}]}, {"id":"no-prod-db","version":3}]"#, ) .unwrap(), ); assert!(store.reconcile(&state, &serve).unwrap().activated); let active = store.read_active().unwrap().unwrap(); let jev = active.jev_policies.unwrap(); assert_eq!(jev[0].effect, PolicyEffect::Observe); assert_eq!( jev[0].agent_targets.as_ref().unwrap()[0].integration, "claude" ); assert_eq!( jev[1].effect, PolicyEffect::Enforce, "absent effect is enforce" ); let text = fs::read_to_string(store.active_manifest_path()).unwrap(); assert!(text.contains("\"jevPolicies\""), "{text}"); // Absent stays absent: an older server's deployment writes the same bytes. let plain = temp_store("jev-assignments-absent"); plain.reconcile(&jev_state(9), &serve).unwrap(); let text = fs::read_to_string(plain.active_manifest_path()).unwrap(); assert!(!text.contains("jevPolicies"), "{text}"); fs::remove_dir_all(store.root()).ok(); fs::remove_dir_all(plain.root()).ok(); } #[test] fn a_bad_jev_assignment_refuses_the_whole_state() { let parse = |json: &str| -> Vec { serde_json::from_str(json).unwrap() }; // Targets need schema 3. let mut scoped_on_2 = jev_state(4); scoped_on_2.jev_policies = Some(parse( r#"[{"id":"a","version":1,"agentTargets":[{"integration":"codex"}]}]"#, )); assert!(validate_desired_state(&scoped_on_2).is_err()); let mut dup = jev_state(4); dup.jev_policies = Some(parse(r#"[{"id":"a","version":1},{"id":"a","version":2}]"#)); assert!(validate_desired_state(&dup).is_err()); let mut unsafe_id = jev_state(4); unsafe_id.jev_policies = Some(parse(r#"[{"id":"../x","version":1}]"#)); assert!(validate_desired_state(&unsafe_id).is_err()); // An unknown effect does not even parse. assert!( serde_json::from_str::>( r#"[{"id":"a","version":1,"effect":"maybe"}]"# ) .is_err() ); let mut ok = jev_state(4); ok.jev_policies = Some(parse(r#"[{"id":"a","version":1,"effect":"observe"}]"#)); assert!(validate_desired_state(&ok).is_ok()); } #[test] fn a_both_policy_and_the_jev_mode_activate_in_one_write() { let store = temp_store("both"); let outcome = store.reconcile(&jev_state(7), &serve).unwrap(); assert!(outcome.activated); assert_eq!(outcome.downloaded, 1, "the JS half only"); let active = store.read_active().unwrap().unwrap(); assert_eq!(active.jev_mode.as_deref(), Some("observe")); assert_eq!(active.policies[0].authority.as_deref(), Some("reviewable")); assert_eq!( active.policies[0].reviewed_by.as_deref(), Some(&["acme-prod-db".to_string()][..]) ); let text = fs::read_to_string(store.active_manifest_path()).unwrap(); for key in ["\"jevMode\"", "\"authority\"", "\"reviewedBy\""] { assert!(text.contains(key), "{key} missing: {text}"); } assert!(!text.contains("semanticPolicies"), "{text}"); // A second identical poll changes nothing and downloads nothing. let again = store.reconcile(&jev_state(7), &serve).unwrap(); assert!(!again.activated); assert_eq!(again.downloaded, 0); // A mode-only change (the C9.1 route) is a new deployment that flips. let mut enforce = jev_state(8); enforce.jev_mode = Some("enforce".into()); assert!(store.reconcile(&enforce, &serve).unwrap().activated); assert_eq!( store.read_active().unwrap().unwrap().jev_mode.as_deref(), Some("enforce") ); fs::remove_dir_all(store.root()).ok(); } #[test] fn the_mode_and_the_authority_are_validated() { let store = temp_store("validate"); validate_desired_state(&jev_state(1)).expect("a both policy is valid"); for mode in ["off", "observe", "enforce"] { let mut ok = jev_state(1); ok.jev_mode = Some(mode.into()); validate_desired_state(&ok).unwrap_or_else(|e| panic!("{mode}: {e}")); } for mode in ["local", "OBSERVE", "shadow", ""] { let mut bad = jev_state(1); bad.jev_mode = Some(mode.into()); assert!( validate_desired_state(&bad).is_err(), "jevMode {mode:?} must reject the state" ); } let mut hard = jev_state(1); hard.policies[0].authority = Some("hard".into()); validate_desired_state(&hard).expect("hard is an authority"); let mut bad_authority = jev_state(1); bad_authority.policies[0].authority = Some("soft".into()); assert!(validate_desired_state(&bad_authority).is_err()); // And a rejected state never reaches disk. assert!(store.reconcile(&bad_authority, &serve).is_err()); assert!(!store.active_manifest_path().exists()); fs::remove_dir_all(store.root()).ok(); } /// A lost `active.json` is rebuilt from the snapshot with its Jev mode and /// the `both` fields. #[test] fn repair_from_cache_keeps_the_mode_and_the_both_fields() { let store = temp_store("repair-mode"); store.reconcile(&jev_state(9), &serve).unwrap(); let good = store.read_active().unwrap().unwrap(); fs::remove_file(store.active_manifest_path()).unwrap(); assert_eq!(store.repair_active_from_cache().unwrap(), 1); assert_eq!(store.read_active().unwrap().unwrap(), good); assert_eq!(good.jev_mode.as_deref(), Some("observe")); fs::remove_dir_all(store.root()).ok(); } /// A disconnect that lands while a poll is in flight (review M2): the /// reconcile is abandoned before it persists anything, so neither the /// snapshot nor the pointer comes back, and a machine that had a deployment /// keeps exactly the files it had. #[test] fn a_withdrawn_enrolment_persists_nothing() { let store = temp_store("withdrawn"); assert!(matches!( store.reconcile_unless(&jev_state(4), &serve, &|| true), Err(ReconcileError::Withdrawn) )); assert!(!store.desired_state_path().exists()); assert!(!store.active_manifest_path().exists()); store.reconcile(&jev_state(4), &serve).unwrap(); let active = fs::read(store.active_manifest_path()).unwrap(); let snapshot = fs::read(store.desired_state_path()).unwrap(); let mut next = jev_state(5); next.jev_mode = Some("enforce".into()); assert!(matches!( store.reconcile_unless(&next, &serve, &|| true), Err(ReconcileError::Withdrawn) )); assert_eq!(fs::read(store.active_manifest_path()).unwrap(), active); assert_eq!(fs::read(store.desired_state_path()).unwrap(), snapshot); // Still enrolled: the same state applies. assert!( store .reconcile_unless(&next, &serve, &|| false) .unwrap() .activated ); fs::remove_dir_all(store.root()).ok(); } /// `clear_deployment` removes what `config --disconnect` removes, snapshot /// first, and leaves nothing a repair could rebuild the pointer from. #[test] fn clear_deployment_leaves_nothing_to_rebuild_from() { let store = temp_store("clear"); store.reconcile(&jev_state(4), &serve).unwrap(); store .write_daemon_policy_errors(&[PolicyErrorEntry { id: "desired-state".into(), version: None, kind: "daemon".into(), message: "x".into(), }]) .unwrap(); fs::write(store.cli_errors_path(), br#"{"errors":[]}"#).unwrap(); assert_eq!(store.clear_deployment().unwrap(), 4); for path in [ store.desired_state_path(), store.active_manifest_path(), store.cli_errors_path(), store.daemon_errors_path(), ] { assert!(!path.exists(), "{} survived", path.display()); } // The content-addressed artifacts stay: inert, and a reconnect is cheap. assert_eq!( fs::read_dir(store.root().join("artifacts")) .unwrap() .count(), 1 ); assert_eq!(store.clear_deployment().unwrap(), 0); assert_eq!(store.repair_active_from_cache().unwrap(), 0); assert!(!store.active_manifest_path().exists()); fs::remove_dir_all(store.root()).ok(); } #[test] fn error_files_are_read_leniently_and_written_only_on_change() { let store = temp_store("errors"); assert_eq!(store.read_cli_policy_errors(), None); assert_eq!(store.read_daemon_policy_errors(), None); fs::create_dir_all(store.root()).unwrap(); fs::write( store.cli_errors_path(), br#"{"errors":[ {"id":"no-prod-db","version":3,"kind":"both","message":"reviewedBy names acme-x, which is not deployed"}, {"id":"x","version":null,"kind":"daemon","message":"jev_unconfigured"}, {"id":"y","version":1,"kind":"nonsense","message":"dropped: unknown kind"}, {"id":"z","message":"dropped: no kind"} ]}"#, ) .unwrap(); let cli = store.read_cli_policy_errors().unwrap(); assert_eq!(cli.len(), 2); assert_eq!(cli[1].version, None); fs::write(store.cli_errors_path(), b"not json").unwrap(); assert_eq!(store.read_cli_policy_errors(), None); let entry = PolicyErrorEntry { id: "desired-state".into(), version: None, kind: "daemon".into(), message: "boom".into(), }; store .write_daemon_policy_errors(std::slice::from_ref(&entry)) .unwrap(); let first = fs::metadata(store.daemon_errors_path()) .unwrap() .modified() .unwrap(); std::thread::sleep(Duration::from_millis(20)); store .write_daemon_policy_errors(std::slice::from_ref(&entry)) .unwrap(); let second = fs::metadata(store.daemon_errors_path()) .unwrap() .modified() .unwrap(); assert_eq!(first, second, "an unchanged state must not be rewritten"); assert_eq!(store.read_daemon_policy_errors().unwrap(), vec![entry]); fs::remove_dir_all(store.root()).ok(); } } #[cfg(test)] mod pre_rename_state_tests { use super::*; /// Byte-exact `active.json` written by a daemon before the /// generation→deployment / revision→version rename, captured from a live /// machine rather than hand-written. const PRE_RENAME_ACTIVE: &str = r#"{ "schemaVersion": 1, "generation": 1, "policies": [ { "id": "e2e-block-curl", "revision": 1, "sha256": "732c6e780e183a15259688d858e4ec0db20c7dd13352601c73db5540122e2c30", "path": "generations/1/e2e-block-curl.mjs", "effect": "enforce" } ] }"#; /// A byte-accurate `desired-state.json` as an earlier beta wrote it. /// /// The sibling of `PRE_RENAME_ACTIVE`, and the file that had no test. Note it /// carries `generation` / `revision` and NO `schemaVersion` field name change — /// the version is 1 and the field names are the v1 spelling. const PRE_RENAME_DESIRED: &str = r#"{ "schemaVersion": 1, "generation": 4, "policies": [ { "id": "e2e-block-curl", "revision": 2, "sha256": "732c6e780e183a15259688d858e4ec0db20c7dd13352601c73db5540122e2c30", "artifactUrl": "enforcement/v1/artifacts/e2e-block-curl/2", "effect": "enforce" } ] }"#; /// The other half of the upgrade case, which the rename missed. /// /// `SUPPORTED_SCHEMA_VERSIONS`'s own comment says version 1 is accepted "for /// files on DISK" and names `desired-state.json` as one of them — but the /// aliases went only on `ActiveDeployment`, so this file could not be read. /// It does not fail on the unknown `generation` key (this struct has no /// `deny_unknown_fields`, deliberately, since it also decodes a remote /// payload) — it fails on `deployment` being MISSING, which is the confusing /// shape of the same bug. /// /// The consequence is not cosmetic: `repair_active_from_cache()` swallows the /// parse error, and with `active.json` also gone or corrupt while offline it /// returns without rebuilding, so cloud policy stops being enforced until a /// poll succeeds. #[test] fn a_pre_rename_desired_state_converts_through_the_legacy_shape() { // NOT through `DesiredState` directly — that type keeps its hard edge, and // `the_wire_does_not_accept_the_pre_rename_spelling` below is what holds it // there. The leniency lives in a disk-only type instead, so the two // writers of this file each get the strictness they warrant. let legacy: LegacyDesiredState = serde_json::from_str(PRE_RENAME_DESIRED) .expect("a pre-rename desired-state.json must still be readable after an upgrade"); let converted: DesiredState = legacy.into(); assert_eq!(converted.schema_version, 1); assert_eq!(converted.deployment, 4, "`generation` becomes `deployment`"); assert_eq!(converted.policies.len(), 1); assert_eq!( converted.policies[0].version, 2, "`revision` becomes `version`" ); assert_eq!(converted.policies[0].effect, PolicyEffect::Enforce); } /// And it survives the round trip the daemon actually performs: written to /// disk by an older build, read back by this one. #[test] fn read_desired_accepts_a_v1_file_left_by_an_earlier_beta() { // Inlined rather than reusing `temp_store`, which lives in the sibling // `tests` module: these two belong beside the fixture they read. let root = std::env::temp_dir().join(format!("failproofaid-v1-desired-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let store = PolicyStore::new(root.clone()); std::fs::create_dir_all(store.desired_state_path().parent().unwrap()).unwrap(); std::fs::write(store.desired_state_path(), PRE_RENAME_DESIRED).unwrap(); let desired = store .read_desired() .expect("a v1 desired-state.json on disk must be readable") .expect("it exists"); assert_eq!(desired.deployment, 4); assert_eq!(desired.policies[0].version, 2); let _ = std::fs::remove_dir_all(&root); } /// The upgrade case. `ActiveDeployment` carries `deny_unknown_fields`, so /// without the aliases this fails on three counts at once: `generation` /// unrecognised, `deployment` missing, and `revision`/`version` likewise per /// policy. The machine would lose the deployment it was already enforcing /// until a poll succeeded — on a fail-closed machine, exactly the gap this /// subsystem exists to close. #[test] fn active_json_written_before_the_rename_still_parses() { let parsed: ActiveDeployment = serde_json::from_str(PRE_RENAME_ACTIVE) .expect("a pre-rename active.json must still be readable after an upgrade"); assert_eq!(parsed.schema_version, 1); assert_eq!(parsed.deployment, 1); assert_eq!(parsed.policies.len(), 1); assert_eq!(parsed.policies[0].version, 1); assert_eq!(parsed.policies[0].id, "e2e-block-curl"); assert_eq!(parsed.policies[0].effect, PolicyEffect::Enforce); } /// The WIRE deliberately does NOT accept the old spelling. /// /// The alias was there and was removed on purpose: AgentEye#559 emits only /// the new names and bumped the payload to `schemaVersion: 2`, so an alias /// here would be dead code guarding a case no server can produce — and a /// silently-tolerated old field is how two sides drift back apart. If a /// payload ever arrives with `generation`/`revision`, it is either a stale /// server or something forged, and both should fail loudly. /// /// This is the exact opposite choice from `ActiveDeployment` above, and the /// difference is *who wrote the bytes*: the wire comes from a server we /// version in lockstep, `active.json` comes from a daemon that may be older /// than the one now reading it. #[test] fn the_wire_does_not_accept_the_pre_rename_spelling() { let err = serde_json::from_str::( r#"{"schemaVersion":1,"generation":184, "policies":[{"id":"p","revision":7,"sha256":"a", "artifactUrl":"/enforcement/v1/artifacts/a"}]}"#, ) .expect_err("the old wire spelling must be refused, not silently accepted"); assert!( err.to_string().contains("missing field"), "expected a missing-field error, got: {err}" ); } /// Legacy disk files, unscoped responses and scoped responses are readable. #[test] fn supported_schema_versions_are_accepted() { assert!( SUPPORTED_SCHEMA_VERSIONS.contains(&1), "a beta daemon's files are v1" ); assert!( SUPPORTED_SCHEMA_VERSIONS.contains(&DESIRED_STATE_SCHEMA_VERSION), "what we write must be readable" ); assert_eq!(DESIRED_STATE_SCHEMA_VERSION, 2, "the server emits 2"); assert!(SUPPORTED_SCHEMA_VERSIONS.contains(&SCOPED_DESIRED_STATE_SCHEMA_VERSION)); // The version the server actually sends must validate. let desired: DesiredState = serde_json::from_str( r#"{"schemaVersion":2,"deployment":1, "policies":[{"id":"p","version":1, "sha256":"439735423d5d532041bccbbc62cafefacd2253d3a7c71ff99d6473b38acda0ee", "artifactUrl":"/enforcement/v1/artifacts/x","effect":"enforce"}]}"#, ) .expect("schemaVersion 2 is what AgentEye emits"); validate_desired_state(&desired).expect("v2 desired state must validate"); // ...and an unknown one is still refused. let bad = DesiredState { schema_version: 99, ..desired }; assert!( validate_desired_state(&bad).is_err(), "an unknown version must be refused" ); } #[test] fn scoped_assignments_require_schema_three_and_round_trip_to_active_manifest() { let store = PolicyStore::new(std::env::temp_dir().join(format!( "failproofaid-agent-scoped-{}-{}", std::process::id(), TEMP_COUNTER.fetch_add(1, Ordering::Relaxed) ))); let bytes = b"export default 'scoped';\n"; let mut state = scoped_fixture(bytes); state.deployment = 42; state.policies[0].agent_targets = Some(vec![AgentTarget { integration: "hermes".into(), instance_id: Some("agt_1234567890abcdef".into()), }]); assert!( validate_desired_state(&state).is_err(), "schema 2 must never ignore the scope" ); state.schema_version = SCOPED_DESIRED_STATE_SCHEMA_VERSION; store .reconcile(&state, &|_: &DesiredPolicy| Ok(bytes.to_vec())) .unwrap(); let active = store.read_active().unwrap().unwrap(); assert_eq!(active.schema_version, 3); assert_eq!( active.policies[0].agent_targets, state.policies[0].agent_targets ); let text = fs::read_to_string(store.root().join("active.json")).unwrap(); assert!(text.contains("\"agentTargets\"")); fs::remove_dir_all(store.root()).ok(); } #[test] fn malformed_scopes_never_activate() { let mut state = scoped_fixture(b"guard"); state.schema_version = SCOPED_DESIRED_STATE_SCHEMA_VERSION; for targets in [ vec![], vec![AgentTarget { integration: "unknown".into(), instance_id: None, }], vec![AgentTarget { integration: "codex".into(), instance_id: Some("wrong".into()), }], vec![ AgentTarget { integration: "codex".into(), instance_id: None, }, AgentTarget { integration: "codex".into(), instance_id: None, }, ], ] { state.policies[0].agent_targets = Some(targets); assert!(validate_desired_state(&state).is_err()); } state.policies[0].agent_targets = None; assert!(validate_desired_state(&state).is_ok()); } fn scoped_fixture(bytes: &[u8]) -> DesiredState { DesiredState { schema_version: DESIRED_STATE_SCHEMA_VERSION, deployment: 1, policies: vec![DesiredPolicy { id: "guard".into(), version: 1, sha256: sha256_hex(bytes), artifact_url: "/enforcement/v1/artifacts/guard".into(), effect: PolicyEffect::Enforce, authority: None, reviewed_by: None, agent_targets: None, }], jev_mode: None, jev_policies: None, } } /// The new spelling is what we WRITE, and must keep round-tripping — an /// alias that quietly became the canonical name would be its own bug. #[test] fn the_current_spelling_round_trips() { let state = ActiveDeployment { schema_version: 1, deployment: 9, policies: vec![ActivePolicy { id: "p".into(), version: 3, sha256: "a".into(), path: "deployments/9/p.mjs".into(), effect: PolicyEffect::Observe, authority: None, reviewed_by: None, agent_targets: None, }], jev_mode: None, jev_policies: None, }; let text = serde_json::to_string(&state).unwrap(); assert!( text.contains("\"deployment\":9"), "must serialize the NEW name: {text}" ); assert!( text.contains("\"version\":3"), "must serialize the NEW name: {text}" ); assert_eq!( serde_json::from_str::(&text).unwrap(), state ); } }