Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(auth): qualified identity keys and trusted-proxy identity assertion
Djalma Júnior79fb16667cee
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4d01a0d4..b56675ac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Trusted-proxy identity: a proxy that terminates SSO can name the real end+ user by echoing `[auth].actor_proxy_secret` in+ `X-Memory-Actor-Proxy-Secret` beside the root bearer. Asserted callers drop+ to the user tier (only the configured `root_username` keeps root), a+ duplicated actor header is refused with 400 rather than resolved to either+ value, and headers without the secret are ignored as before. The server+ refuses to start with a proxy secret but no `root_username`, because no+ proxied request could ever reach a root-only capability again. Unset — the+ default — nothing changes (#310).+- Qualified identity keys: every ownership decision resolves a request to+ `sub:<subject>` or `user:<name>` via one accessor+ (`ActorContext::identity_key`), never a bare string, so a username equal to+ somebody else's OIDC subject can no longer alias their identity. `sub`+ outranks `user` because OIDC defines it as the stable identifier; the+ filesystem-safe `path_segment` derivation ships alongside for per-operator+ wiki paths. `OwnerFilter` / `owner_stamp` carry the read and write sides of+ the same contract, with "absent = shared" as the compatibility rule+ (#310).+- The `/admin/*` route layer and the MCP `memory_forget_sweep` tool now ask+ "does this deployment distinguish operators" instead of "do `users` rows+ exist", so a trusted-proxy deployment — which never writes a `users` row —+ gets root-only admin gating instead of waving every proxied caller through+ the single-operator escape hatch (#310).+## [1.21.0] - 2026-07-31### Addeddiff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 8e286d06..a26cec0e 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -87,6 +87,44 @@ fn validate_existing_users_auth(users_exist: bool, auth: &AuthSettings) -> Resul}}+fn configured(value: Option<&String>) -> bool {+ value.is_some_and(|v| !v.trim().is_empty())+}++/// A trusted proxy that asserts end-user identities needs an operator to be+/// root.+///+/// `require_bearer` downgrades every proxy-named caller to `AuthLevel::User`+/// unless the asserted username matches `[auth].root_username`. With no root+/// username configured that comparison can never succeed, so no request through+/// the proxy — the only ingress such a deployment has — could ever reach a+/// root-only capability: `/admin/users` would 403, the first DB user could+/// never be created, and the server would come up permanently locked out of its+/// own administration. Refuse to start instead of failing later, per request.+fn validate_trusted_proxy_auth(auth: &AuthSettings) -> Result<()> {+ if configured(auth.actor_proxy_secret.as_ref()) && !configured(auth.root_username.as_ref()) {+ anyhow::bail!(+ "[auth].actor_proxy_secret is set but [auth].root_username is not: every identity the \+ proxy asserts is downgraded to a non-root user except the configured root operator, \+ so with no root_username nothing could ever perform a root-only operation (user \+ management, admin routes). Set [auth].root_username to the operator who administers \+ this server, or unset [auth].actor_proxy_secret"+ );+ }+ Ok(())+}++/// Can a trusted proxy actually assert identities on this server?+///+/// Both halves are required: the overlay only runs on requests that+/// authenticated with the root bearer, so a proxy secret without+/// `[auth].bearer_token` asserts nothing (and only warns, below). The MCP admin+/// gates read this to know that distinct operators are in play even though a+/// proxied deployment never writes a `users` row.+fn trusted_proxy_identity_enabled(auth: &AuthSettings) -> bool {+ configured(auth.actor_proxy_secret.as_ref()) && configured(auth.bearer_token.as_ref())+}+struct ConsolidatorSetup {server: AiMemoryServer,consolidator: Option<Arc<Consolidator>>,@@ -318,6 +356,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {}validate_existing_users_auth(store.reader.users_exist().await?, &config.auth)?;+ validate_trusted_proxy_auth(&config.auth)?;// Run any outstanding wiki-structure migrations before the watcher starts// so file moves and renames are never raced by the reconciler.@@ -417,7 +456,8 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {&config.auto_improve,)).with_active_project(active_project.clone())- .with_sanitizer(sanitizer.clone());+ .with_sanitizer(sanitizer.clone())+ .with_trusted_proxy_identity(trusted_proxy_identity_enabled(&config.auth));if let Some(e) = embedder.clone() {server = server.with_embedder(e);}@@ -585,6 +625,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {.map(|p| ai_memory_store::TokenPepper::new(p.clone())),active_project: active_project.clone(),scope_invalidator: Some(scope_invalidator),+ trusted_proxy_identity: trusted_proxy_identity_enabled(&config.auth),});// Multi-rung auth assembly:// - rung 0 (no bearer_token configured) → AuthState::new@@ -605,6 +646,30 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {..ai_memory_core::ActorContext::default()});}+ if let Some(secret) = config+ .auth+ .actor_proxy_secret+ .as_ref()+ .filter(|s| !s.trim().is_empty())+ {+ // The overlay is only reachable from the root-bearer rung, so+ // a proxy secret without a bearer token silently does nothing.+ // Say so rather than leaving the operator believing per-user+ // attribution is on.+ if config+ .auth+ .bearer_token+ .as_deref()+ .is_none_or(|token| token.trim().is_empty())+ {+ tracing::warn!(+ "[auth].actor_proxy_secret is set but [auth].bearer_token is not; \+ trusted-proxy identity is inactive because it only applies to \+ requests authenticated with the root bearer token"+ );+ }+ auth_state = auth_state.with_trusted_proxy(secret.clone());+ }if let Some(pepper) = config.auth.token_pepperdiff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 8c6eb060..83ab78bc 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -372,6 +372,20 @@ pub struct AuthSettings {/// token resolution even during first-user bootstrap; operational admin/// access becomes root-only once a user row exists.pub token_pepper: Option<String>,+ /// Shared secret proving a request came from a trusted authenticating+ /// proxy, allowing it to name the real end user in `X-Memory-Actor-*`+ /// headers.+ ///+ /// A proxy that terminates SSO usually cannot forward the user's own+ /// credential upstream — it authenticates with [`Self::bearer_token`] and+ /// describes the human in headers. Those headers are ignored unless this+ /// secret is set AND the proxy echoes it in `X-Memory-Actor-Proxy-Secret`,+ /// because anything able to reach the port could otherwise claim any+ /// identity. Leave unset (the default) and every proxied caller is+ /// attributed to [`Self::root_username`], as before.+ ///+ /// Only set this when the server is reachable *only* through that proxy.+ pub actor_proxy_secret: Option<String>,}/// `[auto_scope]` — controls how the hook-published "currently activediff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rsindex 5455605a..516127c9 100644--- a/crates/ai-memory-core/src/actor.rs+++ b/crates/ai-memory-core/src/actor.rs@@ -202,6 +202,45 @@ impl AuthLevel {}}+/// Canonical name of the admission-chain loop-prevention header.+pub const SKIP_ADMISSION_CHAIN_HEADER: &str = "x-memory-skip-admission-chain";++/// Parse the admission-chain skip list from the raw+/// `X-Memory-Skip-Admission-Chain` header value (comma-separated webhook+/// names). Entries are trimmed and empty tokens dropped, so `"a, ,b,"` →+/// `["a", "b"]`; `None` yields an empty list.+#[must_use]+pub fn parse_skip_admission_chain(raw: Option<&str>) -> Vec<String> {+ raw.map(|value| {+ value+ .split(',')+ .map(str::trim)+ .filter(|token| !token.is_empty())+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default()+}++/// The same list, but honoured only for a caller that holds+/// [`Capability::SkipAdmissionChain`].+///+/// The header is client-controlled, so a regular DB user must not be able to+/// set it and walk past a `reject`-policy admission webhook. Every transport+/// that forwards the skip list (MCP tools, admin routes, hook ingress) goes+/// through this one predicate rather than re-deriving the tier rule.+#[must_use]+pub fn skip_admission_chain_for(level: AuthLevel, raw: Option<&str>) -> Vec<String> {+ if level+ .authorize(Capability::SkipAdmissionChain, true)+ .is_ok()+ {+ parse_skip_admission_chain(raw)+ } else {+ Vec::new()+ }+}+impl ActorContext {/// `true` if at least one identity field is set.///@@ -227,6 +266,211 @@ impl ActorContext {pub fn anonymous() -> Self {Self::default()}++ /// Does this actor name a specific human, and under what key?+ ///+ /// Every ownership decision in the engine — which rows a caller may read,+ /// which name a new row is stamped with — goes through here rather than+ /// reaching for [`Self::user`] directly, because "identified" is not the+ /// same question as "has a username". An ingress that terminates OIDC and+ /// forwards only the subject claim asserts `sub` with no+ /// `preferred_username`; the auth middleware already resolves that request+ /// to `AuthLevel::User`, so a per-site `.user` check would call the same+ /// request identified for authorization and anonymous for ownership — and+ /// the operator would stop seeing rows they had just written.+ ///+ /// The key is *qualified* — [`IdentityKey::Subject`] or+ /// [`IdentityKey::User`], never a bare string — because the two name+ /// spaces are populated by different parties. A username is chosen by a+ /// person; an OIDC subject is issued by an IdP. Stored raw in one TEXT+ /// column, a username equal to somebody else's subject would silently+ /// share that person's rows. Qualification makes the collision+ /// unrepresentable rather than unlikely.+ ///+ /// `sub` wins whenever it is present. OIDC pins this ordering:+ /// the spec defines `sub` as the stable, non-reassignable identifier and+ /// explicitly forbids relying on `preferred_username` for identity. It is+ /// also the direction that stays stable through the common upgrade — an+ /// ingress that forwarded only `sub` and later starts forwarding a+ /// username keeps the same key. The reverse upgrade (username-only, later+ /// adding `sub`) re-buckets once, at the moment the deployment starts+ /// asserting the stronger identifier; `docs/users.md` tells operators to+ /// forward `sub` from day one exactly so that moment never comes.+ ///+ /// Blank and whitespace-only values name nobody — they would otherwise+ /// mint an owner literally called `""` that the next blank-actor caller+ /// would match. Same rule [`OwnerFilter::for_actor_context`] applies.+ #[must_use]+ pub fn identity_key(&self) -> Option<IdentityKey> {+ let trimmed = |v: &Option<String>| {+ v.as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_owned)+ };+ if let Some(sub) = trimmed(&self.sub) {+ return Some(IdentityKey::Subject(sub));+ }+ trimmed(&self.user).map(IdentityKey::User)+ }+}++/// A qualified operator identity — the one value ownership is keyed on.+///+/// The variant is part of the identity: `User("alice")` and+/// `Subject("alice")` are different operators, always. Everything that+/// persists or compares an identity goes through [`Self::storage_key`] (DB+/// TEXT columns) or [`Self::path_segment`] (wiki paths); nothing stores the+/// raw value, so no call site can accidentally flatten the two name spaces+/// back into one.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub enum IdentityKey {+ /// Named by an IdP-issued OIDC subject claim. Checked first: `sub` is the+ /// identifier the OIDC spec defines as stable and non-reassignable.+ Subject(String),+ /// Named by an asserted or configured username. Usernames are display+ /// names in OIDC terms — present, human-readable, and explicitly not+ /// guaranteed stable — so this variant keys a caller only when no+ /// subject was asserted.+ User(String),+}++impl IdentityKey {+ /// The TEXT form stored in owner columns and compared by+ /// [`OwnerFilter::admits`]: `sub:<subject>` or `user:<name>`.+ ///+ /// The prefix runs to the first `:`; only these two prefixes exist, so+ /// the encoding needs no escaping — whatever follows the first `:` is the+ /// raw value, even if it contains further colons (subjects are often+ /// URLs).+ #[must_use]+ pub fn storage_key(&self) -> String {+ match self {+ Self::Subject(sub) => format!("sub:{sub}"),+ Self::User(user) => format!("user:{user}"),+ }+ }++ /// A filesystem-safe, injective encoding for per-operator wiki paths+ /// (`_slots/<segment>/…`).+ ///+ /// Subjects and usernames may hold anything the IdP or operator chose —+ /// URLs are common subjects — and wiki pages are real files on every+ /// platform the server runs on, so the raw value cannot be a path+ /// component. Values made only of `[A-Za-z0-9._-]` (≤ 64 chars, no+ /// leading dot) pass through readably as `s-<value>` / `u-<value>`;+ /// anything else becomes lowercase hex of its UTF-8 bytes under the+ /// distinct `sx-` / `ux-` prefixes. The prefixes are what keep the+ /// encoding injective: a passthrough value that *looks* like hex+ /// (`s-c3a9`) can never collide with the value that *hexes* to the same+ /// digits (`sx-c3a9`).+ #[must_use]+ pub fn path_segment(&self) -> String {+ fn passthrough(value: &str) -> bool {+ value.len() <= 64+ && !value.starts_with('.')+ && value+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))+ }+ fn hex(value: &str) -> String {+ value.bytes().fold(String::new(), |mut acc, b| {+ use std::fmt::Write;+ let _ = write!(acc, "{b:02x}");+ acc+ })+ }+ match self {+ Self::Subject(v) if passthrough(v) => format!("s-{v}"),+ Self::Subject(v) => format!("sx-{}", hex(v)),+ Self::User(v) if passthrough(v) => format!("u-{v}"),+ Self::User(v) => format!("ux-{}", hex(v)),+ }+ }+}++/// Which owned rows a caller is allowed to see or act on.+///+/// Used for handoffs and for sessions. A row whose owner is `None` is+/// *shared*: it predates ownership, was written by a caller with no actor, or+/// was deliberately published to the whole project. Shared rows stay visible+/// to everyone, which is what keeps single-operator servers behaving exactly+/// as before.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum OwnerFilter {+ /// An identified caller: their own rows plus the shared ones. Holds the+ /// [`IdentityKey::storage_key`] form — the same TEXT that+ /// [`owner_stamp`] writes — so admit checks are exact string equality+ /// with no re-derivation.+ User(String),+ /// A caller with no actor: shared rows only. Prevents an unattributed+ /// reader (or a browser hitting a read-only API) from draining or+ /// reading something that belongs to a specific operator.+ Unattributed,+ /// Explicit opt-in to every owner, for operator recovery ("give me+ /// whatever is pending here, even if it is not mine").+ Any,+}++impl OwnerFilter {+ /// Build the filter for a caller, applying the one identity rule in+ /// [`ActorContext::identity_key`] instead of re-deriving it at the call+ /// site.+ #[must_use]+ pub fn for_actor_context(actor: &ActorContext) -> Self {+ match actor.identity_key() {+ Some(key) => Self::User(key.storage_key()),+ None => Self::Unattributed,+ }+ }++ /// Does a row owned by `owner` pass this filter?+ #[must_use]+ pub fn admits(&self, owner: Option<&str>) -> bool {+ match (self, owner) {+ // Shared rows are visible to everyone (legacy + single-user).+ (_, None) => true,+ (Self::Any, _) => true,+ (Self::User(me), Some(owner)) => me == owner,+ (Self::Unattributed, Some(_)) => false,+ }+ }+}++/// The owner to stamp on a row a request creates — the write-side mirror of+/// [`OwnerFilter::for_actor_context`], which decides what that same request+/// may read.+///+/// `distinguishes_operators` is the deployment-level question the admin gates+/// already ask (`users` rows exist, or a trusted proxy asserts identities),+/// and it is what makes this more than `identity.map(storage_key)`.+///+/// # Why a deployment that names one operator must still stamp nothing+///+/// On a server with `[auth].bearer_token` + `[auth].root_username` and no+/// users and no proxy, every HTTP request resolves to that single name.+/// Stamping it does not separate anybody from anybody — there is only one+/// operator — but it does split that operator in two, because the transports+/// disagree about whether a request carries an actor at all: the HTTP write+/// would land owned, while the SAME person's stdio / in-process MCP transport+/// carries no actor, filters as [`OwnerFilter::Unattributed`], and could no+/// longer see what they just wrote. Producing the pre-ownership `NULL` there+/// is what keeps the transports agreeing.+///+/// The read side deliberately does **not** take this gate: a caller still+/// filters as `OwnerFilter::User(key)`, which admits both the shared rows and+/// any row already stamped with that key, so rows written while a deployment+/// did distinguish operators stay reachable after it stops (the last `users`+/// row is deleted).+#[must_use]+pub fn owner_stamp(+ identity: Option<&IdentityKey>,+ distinguishes_operators: bool,+) -> Option<String> {+ if !distinguishes_operators {+ return None;+ }+ identity.map(IdentityKey::storage_key)}#[cfg(test)]@@ -302,6 +546,26 @@ mod tests {));}+ #[test]+ fn skip_admission_chain_parses_csv_and_honours_the_tier_rule() {+ assert_eq!(+ parse_skip_admission_chain(Some("a, ,b,")),+ vec!["a".to_string(), "b".to_string()]+ );+ assert!(parse_skip_admission_chain(None).is_empty());+ for level in [AuthLevel::Root, AuthLevel::Anonymous] {+ assert_eq!(+ skip_admission_chain_for(level, Some("mirror")),+ vec!["mirror".to_string()],+ "{level:?} may skip a webhook it re-entered from",+ );+ }+ assert!(+ skip_admission_chain_for(AuthLevel::User, Some("mirror")).is_empty(),+ "a DB user must not bypass a reject-policy webhook via a header",+ );+ }+#[test]fn has_any_truth_table() {// Each field individually flips has_any() to true. Catches an@@ -338,6 +602,148 @@ mod tests {assert!(a.has_any());}+ /// An actor the auth middleware resolved to `AuthLevel::User` must be+ /// identified for ownership too, whichever field the proxy filled in. The+ /// sub-only rung is the one a per-site `.user` check silently drops.+ #[test]+ fn identity_key_accepts_sub_when_no_username_was_asserted() {+ let sub_only = ActorContext {+ sub: Some("oidc-subject-123".into()),+ ..ActorContext::default()+ };+ assert_eq!(+ sub_only.identity_key(),+ Some(IdentityKey::Subject("oidc-subject-123".into()))+ );+ }++ /// `sub` outranks `user`: OIDC defines `sub` as the stable identifier and+ /// forbids relying on `preferred_username`. The concrete upgrade this+ /// protects: an ingress that forwarded only `sub` and later starts+ /// forwarding a username must keep the same key, or the operator's rows+ /// re-bucket the day the proxy config improves.+ #[test]+ fn identity_key_prefers_sub_over_user() {+ let both = ActorContext {+ user: Some("alice".into()),+ sub: Some("oidc-subject-123".into()),+ ..ActorContext::default()+ };+ assert_eq!(+ both.identity_key(),+ Some(IdentityKey::Subject("oidc-subject-123".into()))+ );+ }++ /// The aliasing the qualified form exists to kill: a username equal to+ /// somebody else's subject is a DIFFERENT identity, in storage and in+ /// admit checks. Raw TEXT keys would have merged these two people.+ #[test]+ fn a_username_never_aliases_an_equal_subject() {+ let by_name = IdentityKey::User("alice".into());+ let by_subject = IdentityKey::Subject("alice".into());+ assert_ne!(by_name.storage_key(), by_subject.storage_key());+ assert_ne!(by_name.path_segment(), by_subject.path_segment());++ let names_filter = OwnerFilter::User(by_name.storage_key());+ assert!(!names_filter.admits(Some(&by_subject.storage_key())));+ }++ /// Subjects are IdP-issued and often URLs; wiki paths are real files on+ /// every platform. Path-hostile values hex-encode under a DISTINCT prefix+ /// so a passthrough value that merely looks like hex cannot collide with+ /// the value that hexes to the same digits.+ #[test]+ fn path_segment_is_filesystem_safe_and_injective() {+ assert_eq!(IdentityKey::User("alice".into()).path_segment(), "u-alice");+ assert_eq!(+ IdentityKey::Subject("103459784".into()).path_segment(),+ "s-103459784"+ );+ let url_sub = IdentityKey::Subject("https://idp.example/id/42".into());+ let seg = url_sub.path_segment();+ assert!(seg.starts_with("sx-"), "url subject must hex-encode: {seg}");+ assert!(+ seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'),+ "segment must be path-safe: {seg}"+ );+ // The ambiguity the split prefixes prevent: "c3a9" passes through,+ // "é" hexes to c3a9 — different prefixes, no collision.+ assert_eq!(IdentityKey::Subject("c3a9".into()).path_segment(), "s-c3a9");+ assert_eq!(IdentityKey::Subject("é".into()).path_segment(), "sx-c3a9");+ }++ /// The write-side gate: identity alone is not enough to stamp — the+ /// deployment must actually distinguish operators, or a single-operator+ /// server would split its own transports (HTTP names the operator, stdio+ /// carries no actor).+ #[test]+ fn owner_stamp_requires_both_identity_and_a_distinguishing_deployment() {+ let key = IdentityKey::Subject("oidc-subject-123".into());+ assert_eq!(owner_stamp(Some(&key), false), None);+ assert_eq!(owner_stamp(None, true), None);+ assert_eq!(+ owner_stamp(Some(&key), true),+ Some("sub:oidc-subject-123".into())+ );+ }++ /// The admit matrix in one place: shared rows reach everyone, owned rows+ /// reach their owner and `Any`, and an unattributed caller sees only the+ /// shared ones.+ #[test]+ fn owner_filter_admit_matrix() {+ let alice = OwnerFilter::for_actor_context(&ActorContext {+ user: Some("alice".into()),+ ..ActorContext::default()+ });+ let owned = IdentityKey::User("alice".into()).storage_key();+ let other = IdentityKey::User("bob".into()).storage_key();++ for filter in [&alice, &OwnerFilter::Unattributed, &OwnerFilter::Any] {+ assert!(filter.admits(None), "shared rows reach everyone");+ }+ assert!(alice.admits(Some(&owned)));+ assert!(!alice.admits(Some(&other)));+ assert!(!OwnerFilter::Unattributed.admits(Some(&owned)));+ assert!(OwnerFilter::Any.admits(Some(&other)));+ }++ /// Naming nobody stays naming nobody: an agent/session-only actor carries+ /// transport detail, not identity, and blanks are not names.+ #[test]+ fn identity_key_is_none_without_a_named_human() {+ assert_eq!(ActorContext::anonymous().identity_key(), None);+ let transport_only = ActorContext {+ agent: Some("claude-code".into()),+ session_id: Some("s-1".into()),+ client: Some("72836f52".into()),+ ..ActorContext::default()+ };+ assert_eq!(transport_only.identity_key(), None);+ let blank = ActorContext {+ user: Some(" ".into()),+ sub: Some("\t".into()),+ ..ActorContext::default()+ };+ assert_eq!(blank.identity_key(), None);+ }++ /// A blank `user` beside a real `sub` must fall through rather than+ /// resolving the whole actor to "nobody".+ #[test]+ fn identity_key_skips_a_blank_user_and_uses_sub() {+ let actor = ActorContext {+ user: Some(" ".into()),+ sub: Some("oidc-subject-123".into()),+ ..ActorContext::default()+ };+ assert_eq!(+ actor.identity_key(),+ Some(IdentityKey::Subject("oidc-subject-123".into()))+ );+ }+#[test]fn anonymous_serialises_to_empty_object() {// Every absent field is omitted (not `null`) — keeps thediff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 9c6ba30e..346c74cd 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -37,7 +37,10 @@ pub const GLOBAL_SCOPE_PROJECT: &str = "_global";pub use active_project::{ActiveProject, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES, DEFAULT_PER_KEY_TTL,};-pub use actor::{ActorContext, AuthLevel, AuthzError, Capability};+pub use actor::{+ ActorContext, AuthLevel, AuthzError, Capability, IdentityKey, OwnerFilter,+ SKIP_ADMISSION_CHAIN_HEADER, owner_stamp, parse_skip_admission_chain, skip_admission_chain_for,+};pub use error::{MemoryError, MemoryResult};pub use handoff::{Handoff, HandoffState, NewHandoff};pub use ids::{diff --git a/crates/ai-memory-mcp/src/actor.rs b/crates/ai-memory-mcp/src/actor.rsindex a7c426ad..159783b8 100644--- a/crates/ai-memory-mcp/src/actor.rs+++ b/crates/ai-memory-mcp/src/actor.rs@@ -24,7 +24,7 @@//! bypass a reject-policy admission webhook by setting a client-controlled//! header.-use ai_memory_core::{ActorContext, AuthLevel, Capability, UserId};+use ai_memory_core::{ActorContext, AuthLevel, UserId};use axum::http::HeaderMap;use axum::http::request::Parts;@@ -72,6 +72,12 @@ pub fn author_id_from_parts(parts: &Parts) -> Option<UserId> {parts.extensions.get::<UserId>().copied()}+fn header_value(headers: &HeaderMap) -> Option<&str> {+ headers+ .get(ai_memory_core::SKIP_ADMISSION_CHAIN_HEADER)+ .and_then(|v| v.to_str().ok())+}+/// Parse the admission-chain loop-prevention skip list from the/// `X-Memory-Skip-Admission-Chain` request header (comma-separated/// webhook names). A webhook that writes back into the engine (e.g. via@@ -82,17 +88,7 @@ pub fn author_id_from_parts(parts: &Parts) -> Option<UserId> {/// and empty tokens dropped, so `"a, ,b,"` → `["a", "b"]`.#[must_use]pub fn skip_webhooks_from_headers(headers: &HeaderMap) -> Vec<String> {- headers- .get("x-memory-skip-admission-chain")- .and_then(|v| v.to_str().ok())- .map(|s| {- s.split(',')- .map(str::trim)- .filter(|t| !t.is_empty())- .map(str::to_string)- .collect()- })- .unwrap_or_default()+ ai_memory_core::parse_skip_admission_chain(header_value(headers))}/// Parse the skip-list header only for trusted re-entry contexts.@@ -103,14 +99,7 @@ pub fn skip_webhooks_from_parts(parts: &Parts) -> Vec<String> {.get::<AuthLevel>().copied().unwrap_or(AuthLevel::Anonymous);- if level- .authorize(Capability::SkipAdmissionChain, true)- .is_ok()- {- skip_webhooks_from_headers(&parts.headers)- } else {- Vec::new()- }+ ai_memory_core::skip_admission_chain_for(level, header_value(&parts.headers))}#[cfg(test)]diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 4b5dbcce..281240a5 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -140,6 +140,17 @@ pub struct AdminState {/// stale cached pair. `None` when no hook router is attached (stdio //// admin-only tests).pub scope_invalidator: Option<ScopeInvalidator>,+ /// True when a trusted authenticating proxy is configured to assert+ /// end-user identities (`[auth].actor_proxy_secret`).+ ///+ /// Proxy-asserted operators never get a `users` row, so `users_exist()`+ /// alone answers "does this deployment distinguish operators" with a+ /// permanent no — and every proxied caller walks through the+ /// single-operator escape hatch on the `/admin/*` gate. Static config, set+ /// once at startup; `false` for every deployment that never configures a+ /// proxy secret, which is what keeps single-operator servers on their+ /// historical behaviour.+ pub trusted_proxy_identity: bool,}/// Async hook-router project-cache invalidator installed by the serve command.@@ -584,7 +595,17 @@ async fn require_root_for_multiuser_admin(// Read this for every request rather than caching a post-creation flag: a// committed first user immediately closes bootstrap admin access, including// across concurrent requests and without a server restart.- let multi_user_enabled = match state.reader.users_exist().await {+ //+ // Same notion of "this deployment distinguishes operators" the MCP admin+ // gate uses. Keyed on `users_exist()` alone, a trusted-proxy deployment+ // with no `users` rows would wave a proxy-asserted `AuthLevel::User` caller+ // through every operational route below — purge, delete-page, backup — and+ // only `/admin/users*` would survive on its own inner root check.+ let multi_user_enabled = match state+ .reader+ .distinguishes_operators(state.trusted_proxy_identity)+ .await+ {Ok(exists) => exists,Err(error) => {tracing::error!(%error, "admin authorization could not determine whether users exist");@@ -5158,6 +5179,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});let resp = router@@ -5243,6 +5265,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});// Default: only the newest open session for the scope + agent.@@ -5347,6 +5370,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});(tmp, router)}@@ -5379,6 +5403,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,}}@@ -6437,6 +6462,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});post_write_page(&router, "default", "doomed", "notes/x.md", "bye").await;@@ -6545,6 +6571,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});post_write_page(&router, "default", "doomed", "notes/x.md", "bye").await;@@ -6646,6 +6673,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});post_write_page(&router, "default", "doomed", "notes/x.md", "bye").await;@@ -6753,6 +6781,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});post_write_page_with_actor(@@ -7299,6 +7328,7 @@ mod tests {token_pepper: Some(pepper),active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});// Wrap in a middleware that stamps the AuthLevel ourselves —// the real auth middleware lives in ai-memory-cli, and this@@ -7683,6 +7713,7 @@ mod tests {token_pepper: Some(ai_memory_store::TokenPepper::new("test-pepper-admin")),active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,}).layer(axum::middleware::from_fn(|mut req: Request<Body>, next: axum::middleware::Next| async move {@@ -7988,6 +8019,7 @@ mod tests {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,});// Inject a Root level so we're past the require_root gate;// the 503 must come from require_pepper.diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rsindex b5136e10..21f1048b 100644--- a/crates/ai-memory-mcp/src/auth.rs+++ b/crates/ai-memory-mcp/src/auth.rs@@ -47,7 +47,7 @@ use std::sync::Arc;use ai_memory_core::{ActorContext, AuthLevel};use ai_memory_store::{ReaderPool, TokenPepper, WriterHandle, hash_token};use axum::extract::State;-use axum::http::{Method, Request, StatusCode, header};+use axum::http::{HeaderMap, Method, Request, StatusCode, header};use axum::middleware::Next;use axum::response::{IntoResponse, Response};use subtle::ConstantTimeEq;@@ -97,6 +97,12 @@ pub struct AuthState {/// Multi-user lookup tier. `None` until both pepper and reader/// are available — see [`Self::with_multiuser`].multiuser: Option<MultiUserResolver>,+ /// Shared secret that a trusted authenticating proxy presents to assert an+ /// end-user identity via `X-Memory-Actor-*` headers — see+ /// [`Self::with_trusted_proxy`]. `None` (the default) means those headers+ /// are ignored entirely, which is the only safe default for a server whose+ /// port anything on the network can reach.+ actor_proxy_secret: Option<String>,}impl AuthState {@@ -123,6 +129,40 @@ impl AuthState {self}+ /// Does `actor` name the operator configured as root?+ ///+ /// Used to decide whether a proxy-asserted identity keeps root capability.+ /// With no `root_username` configured there is no one to match, so nobody+ /// the proxy names is root.+ fn asserts_root_identity(&self, actor: &ActorContext) -> bool {+ match (self.root_actor.user.as_deref(), actor.user.as_deref()) {+ (Some(root), Some(asserted)) => root == asserted,+ _ => false,+ }+ }++ /// Trust an authenticating proxy to assert WHO the caller is.+ ///+ /// A proxy that terminates SSO (validating an OIDC token, say) usually+ /// cannot forward the end user's credential upstream: it authenticates to+ /// this server with the single root token and describes the human in+ /// `X-Memory-Actor-*` headers. Without a way to tell that proxy apart from+ /// any other client, those headers cannot be believed — anyone able to+ /// reach the port could claim to be anyone — so they are ignored by+ /// default and every caller collapses into the one root identity.+ ///+ /// Presenting `secret` in `X-Memory-Actor-Proxy-Secret` on a request that+ /// already authenticated as root lets the headers overlay the root actor.+ /// The secret IS the switch: there is no separate "trust headers" flag to+ /// turn on without one, so this cannot be enabled insecurely by accident.+ /// A blank secret is treated as absent.+ #[must_use]+ pub fn with_trusted_proxy(mut self, secret: impl Into<String>) -> Self {+ let secret = secret.into();+ self.actor_proxy_secret = Some(secret).filter(|s| !s.trim().is_empty());+ self+ }+/// Enable multi-user lookups: a bearer that doesn't match the root/// token is hashed with `pepper` and checked against the `users`/// table; a hit attributes the request to that user's identity.@@ -152,6 +192,128 @@ impl AuthState {}}+/// axum middleware closure. Wire with+/// `axum::middleware::from_fn_with_state(state, require_bearer)`.+///+/// Token sources, in priority order:+/// 1. `Authorization: Bearer <token>` header. Works for any method.+/// This is what MCP + hook clients send.+/// 2. **GET only:** `Authorization: Basic <base64(user:token)>`.+/// Username is ignored; the password portion is the token.+/// Browsers send this automatically after the native credential+/// prompt fires on a 401 + `WWW-Authenticate: Basic`. On success+/// we also set the `ai_memory_auth` cookie so subsequent visits+/// (including from a fresh browser session) skip the prompt.+/// 3. **GET only:** `ai_memory_auth` cookie set by the Basic handshake.+///+/// POST / PUT / DELETE / etc. require the Bearer header. Cookie and+/// Basic auth are GET-only, which confines cookie-CSRF to read-only+/// pages — `/mcp` + `/hook` are POST-only and stay header-gated.+///+/// On 401 for GET requests the response includes both `Basic` and+/// `Bearer` challenges in `WWW-Authenticate`. Browsers honour the+/// `Basic` challenge (native dialog); MCP clients honour the `Bearer`+/// challenge.+/// Header a trusted proxy uses to prove it is the proxy.+const ACTOR_PROXY_SECRET_HEADER: &str = "x-memory-actor-proxy-secret";++/// Every header the trusted-proxy overlay reads, including the secret itself.+/// A repeated occurrence of any of them makes the assertion ambiguous — see+/// [`overlay_trusted_proxy_actor`].+const PROXY_ASSERTION_HEADERS: [&str; 6] = [+ ACTOR_PROXY_SECRET_HEADER,+ "x-memory-actor-user",+ "x-memory-actor-sub",+ "x-memory-actor-agent",+ "x-memory-actor-client",+ "x-memory-actor-session-id",+];++/// What the trusted-proxy overlay concluded about a request.+enum ProxyAssertion {+ /// No overlay: no configured secret, no secret header, or a mismatch. The+ /// root actor is untouched and the caller stays plain root.+ Absent,+ /// The proxy proved itself; the actor now carries whatever it asserted,+ /// which may be nobody.+ Applied,+ /// The proxy's headers arrived more than once, so WHO the caller is cannot+ /// be decided. The request must fail rather than pick a value.+ Ambiguous,+}++/// Let a trusted proxy say WHO the caller is, overlaying the asserted identity+/// onto the root actor.+///+/// Everything is fail-closed: no configured secret, a missing header, or a+/// mismatch all leave `actor` untouched, so the pre-existing behaviour (every+/// proxied caller collapses into the single root identity) is what you get+/// until an operator deliberately configures the shared secret.+///+/// Only fields the proxy actually asserts are overlaid; the root actor's own+/// values survive for anything the proxy left out.+///+/// # The proxy MUST strip client-supplied `X-Memory-Actor-*` headers+///+/// This whole overlay assumes the `X-Memory-Actor-*` values on the wire are the+/// proxy's, not the caller's. An ingress configured to *append* its headers+/// rather than replace them leaves the client's value in place beside the+/// proxy's, and there is no way to tell which is which — so a duplicate is+/// treated as a spoofing attempt and the request is refused+/// ([`ProxyAssertion::Ambiguous`]) instead of one of the two being picked.+fn overlay_trusted_proxy_actor(+ state: &AuthState,+ headers: &HeaderMap,+ actor: &mut ActorContext,+) -> ProxyAssertion {+ let Some(expected) = state.actor_proxy_secret.as_deref() else {+ return ProxyAssertion::Absent;+ };+ // Checked before the comparison below because `HeaderMap::get` returns the+ // FIRST value: a client that prepends its own secret header would otherwise+ // force a mismatch, suppress the proxy's assertion, and be handed the+ // undowngraded root identity — an escalation, not just a lost overlay.+ if PROXY_ASSERTION_HEADERS+ .iter()+ .any(|name| headers.get_all(*name).iter().count() > 1)+ {+ return ProxyAssertion::Ambiguous;+ }+ let presented = headers+ .get(ACTOR_PROXY_SECRET_HEADER)+ .and_then(|value| value.to_str().ok())+ .unwrap_or("");+ // Constant-time: this is a credential comparison like the bearer above.+ // Differing lengths already compare unequal, so an absent header is safe.+ if !bool::from(presented.as_bytes().ct_eq(expected.as_bytes())) {+ return ProxyAssertion::Absent;+ }+ let asserted = crate::actor::actor_from_headers(headers);+ // The proxy owns the IDENTITY fields wholesale: user, name, email and sub+ // are taken from what it asserts, never merged with the root template.+ // Merging per-field looks harmless but is not — a proxy that forwards only+ // `sub` would leave the root template's `user` in place, so every human+ // would share one owner while carrying someone else's subject. Taking the+ // block as a unit means a proxy that names nobody yields an unattributed+ // actor (shared-only access), which is the fail-safe direction.+ actor.user = asserted.user;+ actor.sub = asserted.sub;+ actor.name = None;+ actor.email = None;+ // Transport/agent detail is not identity: keep whatever the request layer+ // already knew when the proxy does not describe it.+ if asserted.client.is_some() {+ actor.client = asserted.client;+ }+ if asserted.agent.is_some() {+ actor.agent = asserted.agent;+ }+ if asserted.session_id.is_some() {+ actor.session_id = asserted.session_id;+ }+ ProxyAssertion::Applied+}+/// axum middleware closure. Wire with/// `axum::middleware::from_fn_with_state(state, require_bearer)`.///@@ -210,8 +372,44 @@ pub async fn require_bearer(// info, hook payload) — not from config. Leave it for the// hook router / MCP server to overlay onto the actor.actor.agent = actor.agent.or(None);+ // Rung 1b: a trusted proxy may name the real human behind this root+ // credential. No-op unless the shared secret is configured AND+ // presented, so an untrusted client cannot assert an identity by+ // setting headers.+ let assertion = overlay_trusted_proxy_actor(&state, req.headers(), &mut actor);+ if matches!(assertion, ProxyAssertion::Ambiguous) {+ debug!("auth rejected: duplicated trusted-proxy identity header");+ return ambiguous_proxy_identity();+ }+ // The credential is root's, but the human it stands for usually is not.+ // Keeping AuthLevel::Root here would hand root capability to every+ // person the proxy authenticates, which would silently void the+ // admin-gated operations (sweep, purge, delete) for exactly the+ // multi-operator deployment this overlay exists to serve. Only a+ // caller the proxy names AS the configured root operator stays root.+ //+ // The downgrade needs an asserted IDENTITY, not merely a valid secret:+ // a proxy that echoes the secret on its own health checks or on+ // machine-to-machine traffic asserts nobody, and demoting those would+ // strip root from the deployment's own maintenance calls.+ //+ // "Somebody" cannot mean `user` alone. An ingress that terminates OIDC+ // and forwards only the subject claim names a human just as much — one+ // that can never match `root_username` — so keying on `user` would hand+ // root to every person behind exactly the proxy this overlay serves.+ // Any identity field the overlay adopts counts.+ let named_someone = matches!(assertion, ProxyAssertion::Applied)+ && (actor.user.is_some() || actor.sub.is_some());+ let level = if named_someone && !state.asserts_root_identity(&actor) {+ AuthLevel::User+ } else {+ AuthLevel::Root+ };+ if matches!(assertion, ProxyAssertion::Applied) {+ debug!(actor.user = ?actor.user, ?level, "identity asserted by trusted proxy");+ }req.extensions_mut().insert(actor);- req.extensions_mut().insert(AuthLevel::Root);+ req.extensions_mut().insert(level);// First successful Basic-auth hit (no cookie yet) → also stamp// the cookie so the user doesn't get the dialog again next@@ -336,6 +534,19 @@ fn build_session_cookie(token: &str) -> String {format!("{AUTH_COOKIE}={token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=2592000")}+/// The proxy's identity headers contradict themselves. Not a 401 — the+/// credential was fine; the request itself is malformed, and retrying it with+/// the same headers will keep failing until the ingress is fixed to REPLACE+/// `X-Memory-Actor-*` rather than append to whatever the client sent.+fn ambiguous_proxy_identity() -> Response {+ (+ StatusCode::BAD_REQUEST,+ "duplicate X-Memory-Actor-* header: the proxy must replace \+ client-supplied actor headers, not append to them\n",+ )+ .into_response()+}+fn unauthorized(include_basic_challenge: bool) -> Response {let mut resp = (StatusCode::UNAUTHORIZED, "auth required\n").into_response();// Order of challenges matters: browsers parse the first challenge@@ -740,6 +951,400 @@ mod tests {assert!(!actor.has_any(), "rung 0 must inject anonymous actor");}+ /// A proxy-asserted human must NOT inherit root capability: the credential+ /// belongs to the proxy, the identity belongs to an ordinary person, and+ /// admin-gated operations (sweep, purge, delete) key off the level.+ #[tokio::test]+ async fn proxy_asserted_identity_is_downgraded_to_user_level() {+ let root = ActorContext {+ user: Some("root-operator".into()),+ ..ActorContext::default()+ };+ let state = Arc::new(+ AuthState::new(Some("the-root-token".into()))+ .with_root_actor(root)+ .with_trusted_proxy("proxy-shared-secret"),+ );+ let router = Router::new()+ .route("/level", get(echo_auth_level))+ .layer(axum::middleware::from_fn_with_state(state, require_bearer));++ let level_for = |user: &'static str| {+ let router = router.clone();+ async move {+ let resp = router+ .oneshot(+ Request::builder()+ .uri("/level")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")+ .header("X-Memory-Actor-User", user)+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)+ .await+ .unwrap();+ String::from_utf8(bytes.to_vec()).unwrap()+ }+ };++ assert_eq!(+ level_for("alice").await,+ "user",+ "an ordinary human behind the proxy must not hold root capability"+ );+ // The operator the server is configured to treat as root keeps it.+ assert_eq!(level_for("root-operator").await, "root");+ }++ /// The proxy's own traffic — health checks, machine-to-machine calls —+ /// carries the secret but names nobody. Downgrading on the secret alone+ /// would strip root from those for no reason: there is no other human whose+ /// authority the request could be standing in for.+ #[tokio::test]+ async fn proxy_secret_without_an_asserted_user_keeps_root_level() {+ let state = Arc::new(+ AuthState::new(Some("the-root-token".into()))+ .with_root_actor(ActorContext {+ user: Some("root-operator".into()),+ ..ActorContext::default()+ })+ .with_trusted_proxy("proxy-shared-secret"),+ );+ let resp = Router::new()+ .route("/level", get(echo_auth_level))+ .layer(axum::middleware::from_fn_with_state(state, require_bearer))+ .oneshot(+ Request::builder()+ .uri("/level")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")+ .header("X-Memory-Actor-Agent", "healthcheck")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)+ .await+ .unwrap();+ assert_eq!(String::from_utf8(bytes.to_vec()).unwrap(), "root");+ }++ /// An ingress that terminates OIDC and forwards only the subject claim+ /// (no `preferred_username`, so no `X-Memory-Actor-User`) still names a+ /// human. That human can never match `root_username`, so keeping root here+ /// would hand purge, delete and the forget sweep to everyone behind the+ /// proxy — worse than the collapse-into-root this overlay replaces.+ #[tokio::test]+ async fn proxy_asserting_only_sub_is_downgraded_to_user_level() {+ let state = Arc::new(+ AuthState::new(Some("the-root-token".into()))+ .with_root_actor(ActorContext {+ user: Some("root-operator".into()),+ ..ActorContext::default()+ })+ .with_trusted_proxy("proxy-shared-secret"),+ );+ let resp = Router::new()+ .route("/level", get(echo_auth_level))+ .layer(axum::middleware::from_fn_with_state(state, require_bearer))+ .oneshot(+ Request::builder()+ .uri("/level")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")+ .header("X-Memory-Actor-Sub", "oidc-subject-123")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)+ .await+ .unwrap();+ assert_eq!(+ String::from_utf8(bytes.to_vec()).unwrap(),+ "user",+ "a sub-only assertion names somebody who is not the root operator"+ );+ }++ /// An ingress that APPENDS `X-Memory-Actor-User` instead of replacing it+ /// leaves the caller's own value first in the list, and `HeaderMap::get`+ /// returns the first — so Bob sending `X-Memory-Actor-User: alice` would be+ /// Alice everywhere. Neither value may be adopted: refuse the request.+ #[tokio::test]+ async fn duplicated_actor_user_header_is_refused() {+ let state = AuthState::new(Some("the-root-token".into()))+ .with_root_actor(ActorContext {+ user: Some("root-operator".into()),+ ..ActorContext::default()+ })+ .with_trusted_proxy("proxy-shared-secret");+ let resp = router_with_state(state)+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")+ // Bob's own header, then the proxy's appended one.+ .header("X-Memory-Actor-User", "alice")+ .header("X-Memory-Actor-User", "bob")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(+ resp.status(),+ StatusCode::BAD_REQUEST,+ "an ambiguous asserted identity must fail closed, not resolve to one of the two"+ );+ }++ /// The secret header has the same first-wins hazard, and worse consequences:+ /// a client that prepends garbage forces a mismatch, suppresses the proxy's+ /// assertion, and would be handed the undowngraded ROOT identity.+ #[tokio::test]+ async fn duplicated_proxy_secret_header_is_refused() {+ let state = AuthState::new(Some("the-root-token".into()))+ .with_root_actor(ActorContext {+ user: Some("root-operator".into()),+ ..ActorContext::default()+ })+ .with_trusted_proxy("proxy-shared-secret");+ let resp = router_with_state(state)+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-Proxy-Secret", "not-the-secret")+ .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")+ .header("X-Memory-Actor-User", "bob")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ }++ /// Without a proxy assertion the root bearer keeps root, unchanged.+ #[tokio::test]+ async fn plain_root_bearer_keeps_root_level() {+ let state = Arc::new(+ AuthState::new(Some("the-root-token".into()))+ .with_root_actor(ActorContext {+ user: Some("root-operator".into()),+ ..ActorContext::default()+ })+ .with_trusted_proxy("proxy-shared-secret"),+ );+ let resp = Router::new()+ .route("/level", get(echo_auth_level))+ .layer(axum::middleware::from_fn_with_state(state, require_bearer))+ .oneshot(+ Request::builder()+ .uri("/level")+ .header("Authorization", "Bearer the-root-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)+ .await+ .unwrap();+ assert_eq!(String::from_utf8(bytes.to_vec()).unwrap(), "root");+ }++ /// A proxy that forwards only the subject names nobody, so the actor must+ /// come out unattributed rather than silently keeping the root username —+ /// otherwise every human collapses onto one owner carrying a foreign `sub`.+ #[tokio::test]+ async fn proxy_asserting_only_sub_drops_root_and_carries_the_subject() {+ let state = AuthState::new(Some("the-root-token".into()))+ .with_root_actor(ActorContext {+ user: Some("root-operator".into()),+ email: Some("[email protected]".into()),+ ..ActorContext::default()+ })+ .with_trusted_proxy("proxy-shared-secret");+ let resp = router_with_state(state)+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")+ .header("X-Memory-Actor-Sub", "oidc-subject-123")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let actor = body_as_actor(resp).await;+ assert_eq!(actor.user, None, "the root username must not survive");+ assert_eq!(actor.sub.as_deref(), Some("oidc-subject-123"));+ assert_eq!(actor.email, None);+ }++ /// Security boundary: the `X-Memory-Actor-*` headers are pure client input.+ /// With no proxy secret configured they must be ignored completely, or+ /// anyone who can reach the port authenticates as root and then names+ /// themselves whoever they like.+ #[tokio::test]+ async fn actor_headers_are_ignored_without_a_configured_proxy_secret() {+ let root = ActorContext {+ user: Some("boss".into()),+ ..ActorContext::default()+ };+ let state = AuthState::new(Some("the-root-token".into())).with_root_actor(root);+ let resp = router_with_state(state)+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-User", "impostor")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let actor = body_as_actor(resp).await;+ assert_eq!(+ actor.user.as_deref(),+ Some("boss"),+ "unproven actor headers must not override the root identity"+ );+ }++ /// Same headers, secret configured but NOT presented: still ignored.+ #[tokio::test]+ async fn actor_headers_are_ignored_without_the_proxy_secret_header() {+ let root = ActorContext {+ user: Some("boss".into()),+ ..ActorContext::default()+ };+ let state = AuthState::new(Some("the-root-token".into()))+ .with_root_actor(root)+ .with_trusted_proxy("proxy-shared-secret");+ let resp = router_with_state(state)+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-User", "impostor")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let actor = body_as_actor(resp).await;+ assert_eq!(actor.user.as_deref(), Some("boss"));+ }++ /// A wrong secret is as good as none.+ #[tokio::test]+ async fn actor_headers_are_ignored_when_the_proxy_secret_mismatches() {+ let root = ActorContext {+ user: Some("boss".into()),+ ..ActorContext::default()+ };+ let state = AuthState::new(Some("the-root-token".into()))+ .with_root_actor(root)+ .with_trusted_proxy("proxy-shared-secret");+ let resp = router_with_state(state)+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-Proxy-Secret", "wrong")+ .header("X-Memory-Actor-User", "impostor")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let actor = body_as_actor(resp).await;+ assert_eq!(actor.user.as_deref(), Some("boss"));+ }++ /// The point of the feature: with the secret proven, two different humans+ /// behind the same root credential become two different actors.+ #[tokio::test]+ async fn trusted_proxy_identity_overlays_the_root_actor() {+ let root = ActorContext {+ user: Some("boss".into()),+ email: Some("[email protected]".into()),+ name: Some("Boss".into()),+ ..ActorContext::default()+ };+ let state = Arc::new(+ AuthState::new(Some("the-root-token".into()))+ .with_root_actor(root)+ .with_trusted_proxy("proxy-shared-secret"),+ );+ let router = Router::new()+ .route("/probe", get(echo_actor))+ .layer(axum::middleware::from_fn_with_state(state, require_bearer));++ for user in ["alice", "bob"] {+ let resp = router+ .clone()+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")+ .header("X-Memory-Actor-User", user)+ .header("X-Memory-Actor-Session-Id", format!("sess-{user}"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let actor = body_as_actor(resp).await;+ assert_eq!(actor.user.as_deref(), Some(user));+ assert_eq!(actor.session_id.as_deref(), Some(&*format!("sess-{user}")));+ // The root template's contact details describe the root operator,+ // not the human just named, so they must not be carried over.+ assert_eq!(actor.email, None);+ assert_eq!(actor.name, None);+ }+ }++ /// A blank secret must not enable the overlay — otherwise an empty config+ /// value would make a missing header compare equal and trust everyone.+ #[tokio::test]+ async fn blank_proxy_secret_does_not_enable_the_overlay() {+ let root = ActorContext {+ user: Some("boss".into()),+ ..ActorContext::default()+ };+ let state = AuthState::new(Some("the-root-token".into()))+ .with_root_actor(root)+ .with_trusted_proxy(" ");+ let resp = router_with_state(state)+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .header("X-Memory-Actor-User", "impostor")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let actor = body_as_actor(resp).await;+ assert_eq!(actor.user.as_deref(), Some("boss"));+ }+#[tokio::test]async fn rung1_root_token_attributes_via_root_actor_template() {// Bearer matches config token → middleware stamps thediff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 618e0a83..0213d99e 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -390,6 +390,17 @@ pub struct AiMemoryServer {/// actor with redundant reinforcement writes. Shared across `Clone`s/// so every request handler consults the same clock.access_bump_seen: Arc<Mutex<HashMap<PageId, Instant>>>,+ /// True when a trusted authenticating proxy is configured to assert end-user+ /// identities (`[auth].actor_proxy_secret`).+ ///+ /// Distinct operators reach this server by two independent routes: rows in+ /// `users` (rung 2) and proxy-asserted usernames (rung 1b). Only the first+ /// is visible to `users_exist()`, so the admin gates need this flag too —+ /// see [`AiMemoryServer::require_admin_capability`]. Static config, set+ /// once at startup; `false` for stdio and for every deployment that never+ /// configures a proxy secret, which is what keeps single-operator servers+ /// on their historical behaviour.+ trusted_proxy_identity: bool,// Read by the `#[tool_handler]` macro expansion; rustc's dead-code// analysis can't see that, so the lint must be allowed explicitly.#[allow(dead_code)]@@ -959,10 +970,22 @@ impl AiMemoryServer {auto_improve_require_approval: false,auto_improve_review_config: default_auto_improve_review_config(),access_bump_seen: Arc::new(Mutex::new(HashMap::new())),+ trusted_proxy_identity: false,tool_router: Self::tool_router(),}}+ /// Declare that a trusted proxy may assert end-user identities — mirror of+ /// `AuthState::with_trusted_proxy`, which is where the secret itself lives.+ ///+ /// Without this the admin gates cannot tell a proxied deployment apart from+ /// a single-operator one; see [`Self::trusted_proxy_identity`].+ #[must_use]+ pub fn with_trusted_proxy_identity(mut self, enabled: bool) -> Self {+ self.trusted_proxy_identity = enabled;+ self+ }+/// Configure whether auto-improvement requires manual pending-writes approval.#[must_use]pub fn with_auto_improve_require_approval(mut self, require_approval: bool) -> Self {@@ -1827,6 +1850,50 @@ impl AiMemoryServer {}}+ /// Does this deployment tell its operators apart?+ ///+ /// "Several operators" is not the same question as "are there `users` rows".+ /// A trusted proxy asserts usernames that never get a row, so a deployment+ /// on that rung would report `users_exist() == false` forever.+ ///+ /// One notion, several call sites: the admin gates ask it, so a+ /// single-operator server behaves exactly as it did before either route+ /// existed.+ async fn deployment_distinguishes_operators(&self) -> ai_memory_store::StoreResult<bool> {+ self.reader+ .distinguishes_operators(self.trusted_proxy_identity)+ .await+ }++ /// Gate an operation behind [`ai_memory_core::Capability::Admin`].+ ///+ /// Mirrors the `/admin/*` middleware: operator topology is resolved per+ /// call rather than cached, so committing a first user immediately tightens+ /// access without a restart, and a deployment that distinguishes nobody+ /// keeps its historical single-operator behaviour — see+ /// [`Self::deployment_distinguishes_operators`].+ async fn require_admin_capability(+ &self,+ parts: &axum::http::request::Parts,+ ) -> Result<(), McpError> {+ // An absent AuthLevel means no auth middleware ran at all — the stdio /+ // in-process transport, where the caller already has the data directory.+ // Over HTTP `require_bearer` always inserts a level (rung 0 inserts+ // Anonymous), so this cannot mask a real unauthenticated request.+ // Treating "absent" as Anonymous instead would make this tool+ // permanently unusable over stdio the moment any user row exists.+ let Some(level) = parts.extensions.get::<ai_memory_core::AuthLevel>().copied() else {+ return Ok(());+ };+ let multi_user_enabled = self+ .deployment_distinguishes_operators()+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ level+ .authorize(ai_memory_core::Capability::Admin, multi_user_enabled)+ .map_err(|e| McpError::invalid_request(e.message().to_string(), None))+ }+/// Run the M8 forget sweep over episodic pages.#[tool(description = "Run the retention sweep: walk is_latest=1 \episodic pages, score them with the agentmemory-style retention \@@ -1839,6 +1906,10 @@ impl AiMemoryServer {Parameters(args): Parameters<SweepArgs>,OptionalParts(parts): OptionalParts,) -> Result<CallToolResult, McpError> {+ // The sweep permanently removes page versions. On a server with real+ // operators that makes it an admin operation; with nobody to tell+ // apart this is a no-op, preserving single-user behaviour.+ self.require_admin_capability(&parts).await?;let aps_actor = Self::actor_key_from_parts(Some(&parts));let (ws, proj) = self.effective_ids_for_read_args_with_actor(diff --git a/crates/ai-memory-mcp/tests/admin_backup.rs b/crates/ai-memory-mcp/tests/admin_backup.rsindex 4735dcb4..bd10e54e 100644--- a/crates/ai-memory-mcp/tests/admin_backup.rs+++ b/crates/ai-memory-mcp/tests/admin_backup.rs@@ -41,6 +41,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/admin_bootstrap.rsindex e596d42e..6f8d03ec 100644--- a/crates/ai-memory-mcp/tests/admin_bootstrap.rs+++ b/crates/ai-memory-mcp/tests/admin_bootstrap.rs@@ -38,6 +38,7 @@ async fn make_admin_state(tmp: &TempDir) -> AdminState {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,}}diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rsindex dcd070aa..022b71a0 100644--- a/crates/ai-memory-mcp/tests/admin_move.rs+++ b/crates/ai-memory-mcp/tests/admin_move.rs@@ -57,6 +57,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};(state, store)}@@ -86,6 +87,7 @@ async fn make_state_with_chain(tmp: &TempDir, chain: AdmissionChain) -> (AdminSttoken_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};(state, store)}@@ -467,6 +469,7 @@ async fn move_project_carries_source_embedding() {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};// Seed source page (gets a synthetic embedding on write).@@ -754,6 +757,7 @@ async fn true_move_notifies_admission_with_destination_names() {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body a").await;@@ -808,6 +812,7 @@ async fn make_state_with_embedder(tmp: &TempDir) -> (AdminState, Store) {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};(state, store)}@@ -1035,6 +1040,7 @@ fn build_state(store: &Store, tmp: &TempDir) -> AdminState {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,}}@@ -1531,6 +1537,7 @@ async fn true_move_aborts_when_admission_rejects() {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body a").await;@@ -1626,6 +1633,7 @@ async fn copy_purge_purge_admission_runs_before_db_destruction() {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};// Pre-seed BOTH sides so move-project takes the copy-purge path (merge// into existing dst/proj), not the lossless true-move path.@@ -1738,6 +1746,7 @@ async fn move_copy_skips_contributors_webhook_but_runs_others() {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};// Pre-seed BOTH sides so the move takes the copy-purge (merge) path.seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body a").await;diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rsindex 6c654e0e..55577880 100644--- a/crates/ai-memory-mcp/tests/admin_phase3.rs+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs@@ -55,6 +55,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rsindex ed39ef4d..a279c9f0 100644--- a/crates/ai-memory-mcp/tests/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/admin_purge.rs@@ -47,6 +47,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,db_path,};(state, store)@@ -426,6 +427,7 @@ async fn purge_project_rejecting_admission_leaves_source_intact() {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};let (ws, _keep, doomed) = seed_two_projects(&store, &state.wiki).await;@@ -527,6 +529,7 @@ async fn purge_project_idempotent_second_call_is_404() {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};seed_two_projects(&store, &state_a.wiki).await;diff --git a/crates/ai-memory-mcp/tests/admin_read_page.rs b/crates/ai-memory-mcp/tests/admin_read_page.rsindex b41dabd4..cff8a698 100644--- a/crates/ai-memory-mcp/tests/admin_read_page.rs+++ b/crates/ai-memory-mcp/tests/admin_read_page.rs@@ -34,6 +34,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_rename.rs b/crates/ai-memory-mcp/tests/admin_rename.rsindex fbd7342b..1c11c3d0 100644--- a/crates/ai-memory-mcp/tests/admin_rename.rs+++ b/crates/ai-memory-mcp/tests/admin_rename.rs@@ -40,6 +40,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};(state, store)}@@ -328,6 +329,7 @@ async fn rename_project_pages_still_searchable() {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};let rename_resp = post(@@ -400,6 +402,7 @@ async fn rename_project_after_purge_returns_404_not_silent_200() {token_pepper: None,active_project: state.active_project.clone(),scope_invalidator: None,+ trusted_proxy_identity: false,};let purge_resp = post(purge_state,diff --git a/crates/ai-memory-mcp/tests/admin_status_search.rs b/crates/ai-memory-mcp/tests/admin_status_search.rsindex bf3fbb32..c67e0d97 100644--- a/crates/ai-memory-mcp/tests/admin_status_search.rs+++ b/crates/ai-memory-mcp/tests/admin_status_search.rs@@ -35,6 +35,7 @@ async fn make_admin_state(tmp: &TempDir) -> (AdminState, Store) {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_write_page.rs b/crates/ai-memory-mcp/tests/admin_write_page.rsindex 0c2b0375..da07b80e 100644--- a/crates/ai-memory-mcp/tests/admin_write_page.rs+++ b/crates/ai-memory-mcp/tests/admin_write_page.rs@@ -35,6 +35,7 @@ async fn make_state(tmp: &TempDir) -> AdminState {token_pepper: None,active_project: ai_memory_core::ActiveProject::new(),scope_invalidator: None,+ trusted_proxy_identity: false,}}diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 62ba7c00..af1bb5ed 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -5348,6 +5348,30 @@ impl ReaderPool {self.with_conn(crate::users::users_exist).await}+ /// Does this deployment tell its operators apart?+ ///+ /// Two independent routes produce distinct operators: rows in `users`, and+ /// usernames asserted by a trusted authenticating proxy. Only the first is+ /// visible from the store, so the caller passes the second in — a+ /// proxy-only deployment reports `users_exist() == false` forever.+ ///+ /// One notion, several gates: the admin authorization boundaries all key+ /// on this, so a single-operator server keeps the exact behaviour it had+ /// before either route existed.+ ///+ /// # Errors+ /// Propagates any SQL or pool error so callers can fail closed.+ pub async fn distinguishes_operators(&self, trusted_proxy_identity: bool) -> StoreResult<bool> {+ // Short-circuits the DB round-trip when the static config bit already+ // settles it. The users table is otherwise consulted per call rather+ // than cached, so committing a first user tightens access without a+ // restart.+ if trusted_proxy_identity {+ return Ok(true);+ }+ self.users_exist().await+ }+/// Return the last successful global maintenance completion for `job`.pub async fn maintenance_job_last_success(&self,diff --git a/docs/users.md b/docs/users.mdindex 8798c286..f49f89bd 100644--- a/docs/users.md+++ b/docs/users.md@@ -45,6 +45,7 @@ Every HTTP request is resolved to one of four authentication tiers:|---|---|---|| **0 — Anonymous** | No `[auth].bearer_token` set. | Allowed, no identity. Same as pre-multi-user defaults. || **1 — Root** | Bearer matches `[auth].bearer_token`. | Allowed as **root**. When `[auth].root_username` is set, writes attribute to that name; otherwise attribution stays anonymous. |+| **1b — Proxy-asserted user** | Bearer matches root **and** the request carries `X-Memory-Actor-Proxy-Secret` matching `[auth].actor_proxy_secret`. | Identity is taken from the `X-Memory-Actor-*` headers. When the proxy names somebody, the tier drops to **user** unless that somebody is `[auth].root_username`; when it names nobody (health checks, machine-to-machine calls) the request stays **root**, as it would without the overlay. See "Trusted proxy identity" below. || **2 — DB user** | Bearer doesn't match root, matches a `users.token_hash` row (via SHA-256 of token + `[auth].token_pepper`). | Allowed as **that user** for normal read/write APIs. All `/admin/*` endpoints are root-only in multi-user mode. The audit log records the username/email/name. || **3 — 401** | Bearer present but matches nothing. | Rejected. Closes the bypass — unknown bearers can't slip through as anonymous. |@@ -52,6 +53,74 @@ The rungs are sticky: a request is matched at the lowest tier thatapplies, never escalates. Root token always wins over any users-rowcollision; the two namespaces are intentionally distinct.+## Trusted proxy identity++A deployment that terminates SSO in front of the server usually cannot forward+the end user's own credential upstream: the proxy validates the token and then+authenticates to ai-memory with the single root bearer, describing the human in+`X-Memory-Actor-*` headers. Those headers are **ignored by default** — anything+that can reach the port could otherwise claim any identity — so without extra+configuration every human behind such a proxy collapses into one root actor.++Set `[auth].actor_proxy_secret` and have the proxy echo it in+`X-Memory-Actor-Proxy-Secret` to change that:++```toml+[auth]+bearer_token = "…" # required: the overlay only applies to root-bearer requests+actor_proxy_secret = "…" # shared with the proxy; compared in constant time+```++- The secret **is** the switch. There is no separate "trust headers" flag, so+ the feature cannot be enabled without one; a blank value counts as unset.+- Only set it when the server is reachable *only* through that proxy.+- **The proxy MUST strip client-supplied `X-Memory-Actor-*` headers before+ setting its own.** Use a directive that *replaces* the header rather than+ appending to it (nginx `proxy_set_header`, Traefik `customRequestHeaders`) —+ with an appending ingress the client's value arrives first and would be the+ one read. A request that carries any `X-Memory-Actor-*` header twice is+ rejected with `400` rather than resolved to one of the two identities, so a+ misconfigured ingress fails loudly instead of letting callers impersonate+ each other.+- `[auth].root_username` is **required** alongside the secret; the server+ refuses to start without it. Every asserted identity except that one is+ downgraded to a non-root user, so with no root operator named, nothing could+ ever reach `/admin/*` or create the first DB user.+- The asserted identity **replaces** the root template's user/name/email/sub as+ a block. A proxy that names nobody yields an unattributed actor rather than+ silently reusing the root username.+- The tier drops to **user**, so proxied humans do not inherit root capability.+ Only a caller the proxy names as `[auth].root_username` stays root. "Names+ somebody" covers any asserted identity field: an ingress that forwards only+ the subject claim (no `preferred_username`, so no `X-Memory-Actor-User`) has+ named a human who can never match `root_username`, and resolves at the user+ tier. Only a request asserting no identity at all stays root.+- Setting the secret without `bearer_token` logs a warning and does nothing.++## Identity keys++Ownership everywhere in the engine is keyed on a *qualified* identity — never+a bare string. `ActorContext::identity_key()` resolves each request to+`sub:<subject>` (when the proxy asserts an OIDC subject) or `user:<name>`+(when only a username was asserted). The two name spaces are disjoint by+construction: a username equal to somebody else's subject is a different+identity, in storage and in every admit check.++`sub` outranks `user` because OIDC defines `sub` as the stable,+non-reassignable identifier and explicitly forbids relying on+`preferred_username`. Practical consequence: **configure the proxy to forward+`sub` from day one if the IdP provides it.** An ingress that asserted only+`sub` and later adds a username keeps the same key; an ingress that asserted+only a username and later adds `sub` re-buckets that operator once, at the+moment the stronger identifier appears.++Where an identity becomes a wiki path segment, the raw value is never used —+subjects are often URLs, and pages are real files on every platform. The+derivation is `IdentityKey::path_segment()`: values made only of+`[A-Za-z0-9._-]` pass through readably (`u-alice`, `s-103459784`); anything+else hex-encodes under a distinct prefix (`sx-…`, `ux-…`) that keeps the+encoding injective.+## Implementation contractRequest identity and authorization are separate: