The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(guard): correct audit log entry for policy violations
Steven Enamakelac0e8e3b7db1
diff --git a/crates/openhuman-core/src/memory/guard/audit.rs b/crates/openhuman-core/src/memory/guard/audit.rsindex 28fa8e6428..4d8a3a62de 100644--- a/crates/openhuman-core/src/memory/guard/audit.rs+++ b/crates/openhuman-core/src/memory/guard/audit.rs@@ -1,13 +1,15 @@-//! Step 7: the guard's tracing span and its audit event.+//! Step 7, host half: the guard's log lines and its audit event.+//!+//! The span, the char-budget trace and `NO_NAMESPACE` live with the decorator in+//! `tinymemory_guard::audit`; what stays here is what needs the host — the+//! driver class in the log line and the bus.//!//! ## What may be logged, and what may never be//!-//! Memory content is the most sensitive data in the product. Nothing in this-//! module — span field, log line, or bus event — carries a memory body, a-//! recall query, a namespace *key*, or a document title. What it carries is-//! **shapes**: the driver id, the contract method, the namespace, char counts,-//! and hit counts. A namespace is an operator-chosen bucket name and is already-//! logged verbatim by the embedded driver; a key is caller data and is not.+//! Memory content is the most sensitive data in the product. Nothing here —+//! log line or bus event — carries a memory body, a recall query, a namespace+//! *key*, or a document title. What it carries is **shapes**: the driver id, the+//! contract method, the namespace, char counts, and hit counts.//!//! That is also why this module publishes a purpose-built//! [`DomainEvent::MemoryGuardDenied`] rather than reusing@@ -15,58 +17,21 @@//! that one from the guard would push user query text onto the bus on every//! call.//!-//! Where an identifier genuinely helps correlate a report — a key, a source id-//! — use [`redact`], which returns an 8-hex-char SHA-256 prefix: stable enough-//! to correlate two log lines, useless for recovering the value. Note that-//! [`redact`] is a **log** redactor only; the content-side scrubber for egress-//! is `memory::safety::sanitize_text`, selected in-//! [`GuardPolicy::redact_outbound`](super::GuardPolicy::redact_outbound).-//!//! ## Denials only on the bus//!//! Success is logged (at `debug`, into the file-only core log) but is **not**//! published. One bus event per memory read would flood every subscriber on the//! hot path for no operator benefit; a refusal is the rare, actionable event.-use crate::memory::api::capabilities::Capability;-use crate::core::bus::BUS;use crate::core::events::DomainEvent;-use crate::util::redact::redact;--use super::policy::GuardPolicy;--/// Grep prefix for every guard log line, matching `[memory:binding]` and-/// `[memory:driver:embedded]`.-pub const LOG_PREFIX: &str = "[memory:guard]";--/// The tracing span every guarded call runs inside.-///-/// Carries the three correlation fields the spec asks for — `driver_id`, the-/// capability family, and the namespace — plus the contract method, so two-/// calls into the same family are distinguishable in a trace.-pub fn guard_span(- policy: &GuardPolicy,- capability: Capability,- method: &str,- namespace: &str,-) -> tracing::Span {- tracing::debug_span!(- "memory_guard",- driver_id = policy.driver_id(),- capability = capability.as_str(),- method = method,- namespace = namespace,- )-}+use tinymemory_guard::audit::LOG_PREFIX;+use tinymemory_guard::GuardPolicy;-/// Namespace placeholder for the contract methods that address no namespace-/// (maintenance, portability, goals). Better than an empty field, which reads-/// as "the namespace was lost".-pub const NO_NAMESPACE: &str = "-";+use super::policy::HostGuardPolicy;/// Log a call the guard let through. Shapes only.-pub fn trace_allowed(policy: &GuardPolicy, method: &str, namespace: &str, chars: usize) {+pub(super) fn log_allowed(policy: &HostGuardPolicy, method: &str, namespace: &str, chars: usize) {log::debug!("{LOG_PREFIX} allowed driver={} class={} method={method} namespace={namespace} \content_chars={chars}",@@ -75,27 +40,14 @@ pub fn trace_allowed(policy: &GuardPolicy, method: &str, namespace: &str, chars:);}-/// Log the effect of a budget, when it actually bit. Silent when it did not, so-/// the log is a record of truncation rather than a per-call heartbeat.-pub fn trace_budget(policy: &GuardPolicy, method: &str, dropped: usize, trimmed_chars: usize) {- if dropped == 0 && trimmed_chars == 0 {- return;- }- log::debug!(- "{LOG_PREFIX} budget applied driver={} method={method} dropped={dropped} \- trimmed_chars={trimmed_chars}",- policy.driver_id(),- );-}-/// Log and publish a refusal.///-/// Called from [`GuardPolicy::denied`](super::GuardPolicy::denied), so every-/// deny path audits by construction rather than by each call site remembering-/// to. `publish_global` is synchronous and a no-op before the bus is-/// initialised, so this is safe pre-boot with no `#[cfg(test)]` guard — the-/// same property `binding::build` relies on.-pub fn publish_guard_denied(policy: &GuardPolicy, method: &str, reason: &str) {+/// Called from [`GuardPolicy::on_denied`], which the decorator's+/// `GuardPolicy::denied` runs, so every deny path audits by construction rather+/// than by each call site remembering to. `publish_global` is synchronous and a+/// no-op before the bus is initialised, so this is safe pre-boot with no+/// `#[cfg(test)]` guard — the same property `binding::build` relies on.+pub(super) fn publish_guard_denied(policy: &HostGuardPolicy, method: &str, reason: &str) {log::warn!("{LOG_PREFIX} DENIED driver={} class={} method={method}: {reason}",policy.driver_id(),@@ -107,10 +59,3 @@ pub fn publish_guard_denied(policy: &GuardPolicy, method: &str, reason: &str) {reason: reason.to_string(),});}--/// A caller-supplied identifier in a form that is safe to log: an 8-hex-char-/// digest, never the value. Use for keys, node ids, and source ids when a log-/// line genuinely needs to correlate two calls.-pub fn correlate(value: &str) -> String {- redact(value)-}diff --git a/crates/openhuman-core/src/memory/guard/policy.rs b/crates/openhuman-core/src/memory/guard/policy.rsindex 603b22a410..0506afc7c2 100644--- a/crates/openhuman-core/src/memory/guard/policy.rs+++ b/crates/openhuman-core/src/memory/guard/policy.rs@@ -1,5 +1,9 @@-//! [`GuardPolicy`] — the resolved policy bundle [`MemoryGuard`] and all ten-//! family decorators share.+//! [`HostGuardPolicy`] — OpenHuman's [`GuardPolicy`]: the resolved policy bundle+//! [`MemoryGuard`] and all its family decorators share.+//!+//! The decorator itself is `tinymemory_guard::GuardedProvider`; this is the+//! host half it consults — live `SecurityPolicy`, the task-local source scope,+//! the conservative sanitizer, egress disclosure and the bus audit event.//!//! [`MemoryGuard`]: super::MemoryGuard//!@@ -35,10 +39,10 @@use std::borrow::Cow;use std::sync::Arc;-use crate::memory::api::capabilities::Capability;use crate::memory::api::error::MemoryError;use crate::memory::api::provider::types::SourceScope;-use crate::memory::api::types::MemoryTaint;+use tinymemory_guard::GuardPolicy;+pub use tinymemory_guard::GUARD_DENIED_PREFIX;use crate::config::schema::MemoryHooksConfig;use crate::core::subsystem::DriverClass;@@ -48,26 +52,22 @@ use crate::security::egress::types::{DataKind, EgressDescriptor, EgressReason};use crate::security::live_policy;use crate::security::policy::ToolOperation;-/// Prefix on every guard-authored error message, so a refusal that surfaces to-/// a caller is attributable to the guard rather than to the driver underneath.-pub const GUARD_DENIED_PREFIX: &str = "memory guard: ";-/// The trust state an external driver must carry before the guard will let a/// call reach it. Matches the value `binding::admit` requires at bind time.pub const TRUSTED: &str = "trusted";-/// The policy bundle every guarded call consults.+/// The host policy bundle every guarded call consults.///-/// Cheap to clone-by-`Arc`: the guard holds one, and each of the ten family+/// Cheap to clone-by-`Arc`: the guard holds one, and each of its family/// decorators holds an `Arc` of the same value.-pub struct GuardPolicy {+pub struct HostGuardPolicy {driver_id: String,class: DriverClass,hooks: MemoryHooksConfig,trust_state: String,}-impl GuardPolicy {+impl HostGuardPolicy {/// Build the policy for a bound driver.pub fn new(driver_id: impl Into<String>,@@ -83,11 +83,6 @@ impl GuardPolicy {}}- /// The bound driver's stable id — appears in every span and audit event.- pub fn driver_id(&self) -> &str {- &self.driver_id- }-/// How the driver was reached. A host fact, never self-reported.pub fn class(&self) -> DriverClass {self.class@@ -103,52 +98,21 @@ impl GuardPolicy {&self.trust_state}- // ── The admission gate: steps 1, 5 and 7 in one call ─────────────────────-- /// Enter the guard's tracing span, run the tier (step 1) and egress- /// (step 5) checks inside it, and leave — all before the caller awaits- /// anything.- ///- /// The span is entered and exited **within this synchronous call** on- /// purpose. [`tracing::span::EnteredSpan`] is `!Send`, and every method on- /// the driver contract is an `#[async_trait]` method whose future must be- /// `Send`; holding an entered span across the `.await` of the forwarded- /// driver call makes the whole future `!Send` and fails to compile. Keeping- /// the span around the *decision* is also where it earns its keep — the- /// driver below emits its own instrumented line for the work itself.- ///- /// # Errors- ///- /// The first refusal, tier or egress.- pub fn admit_read(- &self,- capability: Capability,- method: &str,- namespace: &str,- carries_content: bool,- ) -> Result<(), MemoryError> {- let span = super::audit::guard_span(self, capability, method, namespace);- let _enter = span.enter();- self.enforce_read(method)?;- self.check_egress(method, carries_content)+ fn enforce(&self, op: ToolOperation, operation: &str) -> Result<(), MemoryError> {+ // Read live, never cached — see the module docs.+ let Some(policy) = live_policy::current() else {+ return Ok(());+ };+ policy+ .enforce_tool_operation(op, operation)+ .map_err(|reason| self.denied(operation, reason))}+}- /// [`Self::admit_read`] for a write, taking the `Act` tier check.- ///- /// # Errors- ///- /// The first refusal, tier or egress.- pub fn admit_write(- &self,- capability: Capability,- method: &str,- namespace: &str,- carries_content: bool,- ) -> Result<(), MemoryError> {- let span = super::audit::guard_span(self, capability, method, namespace);- let _enter = span.enter();- self.enforce_write(method)?;- self.check_egress(method, carries_content)+impl GuardPolicy for HostGuardPolicy {+ /// The bound driver's stable id — appears in every span and audit event.+ fn driver_id(&self) -> &str {+ &self.driver_id}// ── Step 1: SecurityPolicy tier ─────────────────────────────────────────@@ -164,7 +128,9 @@ impl GuardPolicy {/// # Errors////// Whatever the live policy refuses, prefixed with [`GUARD_DENIED_PREFIX`].- pub fn enforce_read(&self, operation: &str) -> Result<(), MemoryError> {+ ///+ /// [`SecurityPolicy::enforce_tool_operation`]: crate::security::policy::SecurityPolicy::enforce_tool_operation+ fn enforce_read(&self, operation: &str) -> Result<(), MemoryError> {self.enforce(ToolOperation::Read, operation)}@@ -184,7 +150,7 @@ impl GuardPolicy {/// budget with no agent having acted at all.////// So the guard takes the tier half only, via- /// [`SecurityPolicy::enforce_write_tier`]. That is the same shape the ~15+ /// `SecurityPolicy::enforce_write_tier`. That is the same shape the ~15/// acting tools which gate on bare `can_act()` already use/// (`tinytools_std::filesystem::FileWriteTool`,/// `tools/impl/system/python_exec.rs`, `cron/scheduler.rs`, …). Budget@@ -193,7 +159,7 @@ impl GuardPolicy {/// # Errors////// Whatever the live policy refuses, prefixed with [`GUARD_DENIED_PREFIX`].- pub fn enforce_write(&self, operation: &str) -> Result<(), MemoryError> {+ fn enforce_write(&self, operation: &str) -> Result<(), MemoryError> {// Read live, never cached — see the module docs.let Some(policy) = live_policy::current() else {return Ok(());@@ -203,37 +169,6 @@ impl GuardPolicy {.map_err(|reason| self.denied(operation, reason))}- fn enforce(&self, op: ToolOperation, operation: &str) -> Result<(), MemoryError> {- // Read live, never cached — see the module docs.- let Some(policy) = live_policy::current() else {- return Ok(());- };- policy- .enforce_tool_operation(op, operation)- .map_err(|reason| self.denied(operation, reason))- }-- /// Build the guard's canonical refusal error, publishing the audit event as- /// a side effect. Every deny path goes through here so a refusal can never- /// be raised without the operator seeing it.- pub fn denied(&self, method: &str, reason: impl Into<String>) -> MemoryError {- let reason = reason.into();- super::audit::publish_guard_denied(self, method, &reason);- MemoryError::Invalid(format!("{GUARD_DENIED_PREFIX}{reason}"))- }-- // ── Step 1b: path rules — deliberately a no-op ───────────────────────────- //- // `validate_memory_relative_path` / `resolve_writable_memory_path` in- // `memory/ops/helpers.rs` validate `<workspace>/memory/<relative>` *file*- // paths against the ambient workspace. Not one method on the driver- // contract carries a filesystem path: `MemoryCore` takes namespace/key,- // `MemoryTree` takes namespace/node_id, `MemoryDocuments` takes a- // `NamespaceDocumentInput`. There is nothing here to validate, and running- // a namespace string through a path validator would invent semantics- // neither side agreed to. The path half of step 1 belongs to whatever- // future family actually accepts a path.-// ── Step 2: source scope as a query predicate ────────────────────────────/// The ambient per-turn source allowlist, in contract form.@@ -241,91 +176,20 @@ impl GuardPolicy {/// `None` is unrestricted. `Some` — including `Some` over an empty set —/// restricts: [`SourceScope`]'s own docs make an empty allow list deny all/// source-attributed content, which matches- /// [`crate::memory::source_scope`]'s empty-allowlist semantics- /// exactly.- ///- /// This is read at the guard boundary and passed **down** into the driver- /// so the allowlist becomes part of the query, never a post-filter over- /// rows a `limit` already truncated.- pub fn ambient_scope(&self) -> Option<SourceScope> {+ /// [`crate::memory::source_scope`]'s empty-allowlist semantics exactly.+ fn ambient_scope(&self) -> Option<SourceScope> {current_source_scope().map(SourceScope::new)}- /// The scope a query actually runs under, given what the caller asked for.- ///- /// The ambient allowlist is an **upper bound**, never a default that an- /// argument replaces. An earlier version returned `requested.or(ambient)`,- /// which let a source-restricted turn widen itself back out: passing an- /// explicit scope naming a collection the ambient allowlist did not contain- /// made that explicit scope the sole query predicate, and the restriction- /// the turn was running under vanished.- ///- /// So the two are intersected. Membership is decided by the ambient scope's- /// own [`SourceScope::allows_source_id`] rule (equality or the engine's- /// `mem_src:{allowed}:` prefix), so the guard and the driver's SQL agree on- /// what "in scope" means rather than the guard inventing a second rule.- ///- /// An empty intersection is returned as an empty `Some`, not `None`: an- /// empty allow list denies all source-attributed content, which is the- /// fail-closed reading [`SourceScope`] documents. Returning `None` there- /// would turn "you asked for nothing you are allowed to see" into- /// "unrestricted", the exact leak this method exists to close.- pub fn narrow_scope(&self, requested: Option<&SourceScope>) -> Option<SourceScope> {- match (requested, self.ambient_scope()) {- (None, ambient) => ambient,- (Some(requested), None) => Some(requested.clone()),- (Some(requested), Some(ambient)) => {- let allow: Vec<String> = requested- .allow- .iter()- .filter(|id| ambient.allows_source_id(id))- .cloned()- .collect();- if allow.len() != requested.allow.len() {- log::debug!(- "[memory:guard] explicit source scope narrowed by the ambient \- allowlist requested={} admitted={}",- requested.allow.len(),- allow.len()- );- }- Some(SourceScope { allow })- }- }- }-- // ── Step 3: taint stamping ───────────────────────────────────────────────-- /// The provenance the guard stamps on a write.- ///- /// The contract is explicit that the driver never assigns provenance, and- /// that the single failure mode the guard exists to prevent is *laundering*- /// externally-sourced content into internal-trust content.- ///- /// So this is a monotone raise, not a plain override: the result is- /// [`MemoryTaint::ExternalSync`] when the caller asked for it **or** when- /// the turn is running under a source scope (a source-restricted turn is- /// by definition handling source-attributed content), and- /// [`MemoryTaint::Internal`] only when neither holds. A pure override would- /// happily rewrite a caller's `ExternalSync` down to `Internal` outside a- /// scope, which is precisely the laundering step.- pub fn stamp_taint(&self, requested: MemoryTaint) -> MemoryTaint {- if requested == MemoryTaint::ExternalSync || current_source_scope().is_some() {- MemoryTaint::ExternalSync- } else {- MemoryTaint::Internal- }- }-// ── Step 4: redaction ────────────────────────────────────────────────────/// Content on its way to the driver, redacted when the driver is external.///- /// **No-op for [`DriverClass::Embedded`] and [`DriverClass::Null`]**:- /// nothing leaves the device, and scrubbing in-process memory writes would- /// silently destroy the user's own data. The borrowed arm is what makes- /// that a byte-identical pass-through rather than a re-allocation that- /// merely happens to compare equal.+ /// **No-op for [`DriverClass::Embedded`], [`DriverClass::Module`] and+ /// [`DriverClass::Null`]**: nothing leaves the device, and scrubbing+ /// in-process memory writes would silently destroy the user's own data. The+ /// borrowed arm is what makes that a byte-identical pass-through rather+ /// than a re-allocation that merely happens to compare equal.////// For [`DriverClass::External`] the content goes through the same/// conservative secret/PII scrubber every other host write path uses@@ -334,14 +198,8 @@ impl GuardPolicy {/// **Do not substitute `memory::util::redact::redact` here.** That function/// is a *log* redactor: it returns an 8-hex-character SHA-256 prefix, so/// using it on egress content would not redact the write, it would delete- /// it. `redact` belongs in log lines only, and that is where- /// [`super::audit`] uses it.- ///- /// The external arm is unreachable today — `binding::admit` refuses every- /// external driver, so none can be bound — and is exercised for real in M6- /// when the http adapter lands. It ships now so the branch exists at the- /// same time as the class check that selects it.- pub fn redact_outbound<'a>(&self, content: &'a str) -> Cow<'a, str> {+ /// it. `redact` belongs in log lines only.+ fn redact_outbound<'a>(&self, content: &'a str) -> Cow<'a, str> {match self.class {DriverClass::Embedded | DriverClass::Module | DriverClass::Null => {Cow::Borrowed(content)@@ -355,7 +213,7 @@ impl GuardPolicy {/// [`Self::redact_outbound`] for structured payloads (KV values, document/// metadata), via `memory::safety::sanitize_json`. Same class rule: an/// unmodified pass-through for embedded and null drivers.- pub fn redact_outbound_json(&self, value: serde_json::Value) -> serde_json::Value {+ fn redact_outbound_json(&self, value: serde_json::Value) -> serde_json::Value {match self.class {DriverClass::Embedded | DriverClass::Module | DriverClass::Null => value,DriverClass::External => crate::memory::safety::sanitize_json(&value).value,@@ -368,26 +226,20 @@ impl GuardPolicy {////// Bind-time refusal already covers the trust rule (`binding::admit` sends/// every `trust_state != "trusted"` external driver to the fallback), so- /// this is the *per-call* seam and nothing more: it re-checks trust so a- /// guard constructed some other way cannot skip it, and it discloses the- /// transfer through the existing privacy-egress machinery.- ///- /// Deliberately minimal. There is no external driver in the tree yet, so- /// building byte counters and a rolling budget here would be accounting for- /// traffic that cannot exist; the real budget lands in M6 alongside the- /// transport that can spend it.+ /// this is the *per-call* seam: it re-checks trust so a guard constructed+ /// some other way cannot skip it, and it discloses the transfer through the+ /// existing privacy-egress machinery.////// `carries_content` selects the disclosed [`DataKind`]:/// [`DataKind::FileContent`] for calls that hand raw memory bodies across/// the boundary, [`DataKind::Metadata`] for the rest. Neither is a perfect- /// fit — there is no `MemoryContent` kind today — and adding one is an M6- /// decision to take with the adapter, not a guess to bake in now.+ /// fit — there is no `MemoryContent` kind today.////// # Errors////// [`MemoryError::Invalid`] when the driver is external and its/// `trust_state` has not been explicitly raised.- pub fn check_egress(&self, method: &str, carries_content: bool) -> Result<(), MemoryError> {+ fn check_egress(&self, method: &str, carries_content: bool) -> Result<(), MemoryError> {if self.class != DriverClass::External {return Ok(());}@@ -423,27 +275,35 @@ impl GuardPolicy {/// `0` reads as "no budget" rather than "return nothing": a zero-length/// budget that silently emptied every recall would be indistinguishable/// from a broken driver, and the config's own default is 1000.- pub fn recall_budget(&self) -> Option<usize> {+ fn recall_budget(&self) -> Option<usize> {(self.hooks.recall_max_chars > 0).then_some(self.hooks.recall_max_chars)}/// The capture char budget, or `None` when it is disabled. Same zero rule/// as [`Self::recall_budget`].- pub fn capture_budget(&self) -> Option<usize> {+ fn capture_budget(&self) -> Option<usize> {(self.hooks.capture_max_chars > 0).then_some(self.hooks.capture_max_chars)}// `max_context_tokens` is deliberately NOT enforced here. It is a// context-*assembly* budget — how much recalled text an agent turn may// inject into a prompt — and no method on the driver contract assembles a- // prompt. Enforcing it in the guard would mean inventing a tokenizer and- // applying it to a `Vec<MemoryEntry>` that has not been rendered yet. It- // belongs to the auto-recall hook (M5), which is the thing that actually- // builds the context block.+ // prompt. It belongs to the auto-recall hook, which is the thing that+ // actually builds the context block.++ // ── Step 7: audit ────────────────────────────────────────────────────────++ fn on_denied(&self, method: &str, reason: &str) {+ super::audit::publish_guard_denied(self, method, reason);+ }++ fn on_allowed(&self, method: &str, namespace: &str, chars: usize) {+ super::audit::log_allowed(self, method, namespace, chars);+ }}/// Wrap `policy` for sharing with the family decorators.-pub fn shared(policy: GuardPolicy) -> Arc<GuardPolicy> {+pub fn shared(policy: HostGuardPolicy) -> Arc<HostGuardPolicy> {Arc::new(policy)}