Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(auth): harden trusted proxy identity

AkitaOnRails37c3abed097d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f13b8ff..155aa8b6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,24 +8,18 @@ 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 (#333).
-- 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
- (#333).
+- Trusted-proxy identity now has a dedicated
+ `[auth].actor_proxy_bearer_token`, distinct from the root bearer. Proxy
+ requests must assert either a username or the complete OIDC issuer/subject
+ pair; missing, partial, duplicated, or comma-folded identity headers fail
+ closed. Proxied root access requires the configured OIDC issuer/subject pair;
+ a display username never grants root. Ordinary root and DB-user requests
+ continue to ignore raw actor headers, and leaving the proxy token unset
+ preserves existing behavior (#333).
+- Qualified identity keys now keep usernames separate from OIDC
+ `(issuer, subject)` pairs and drive active-project routing consistently for
+ hook and MCP requests. The stable OIDC pair outranks display usernames, so
+ same-subject users from different issuers cannot alias each other (#333).
- 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 —
diff --git a/README.md b/README.md
index d115a3d4..12cd595b 100644
--- a/README.md
+++ b/README.md
@@ -610,7 +610,10 @@ page view UI. Data stays single-tenant — there is no per-page RBAC. A
first user row is what immediately switches every `/admin/*` endpoint to
root-only, including status/search/read-page and user-management routes.
`ai-memory init` generates a pepper for new installs without changing
-single-user behavior until a user is added. See
+single-user behavior until a user is added. An SSO gateway can instead use a
+dedicated `[auth].actor_proxy_bearer_token` and trusted `X-Memory-Actor-*`
+headers; its credential is deliberately separate from the root bearer so a
+missing identity cannot become root. See
[`docs/users.md`](docs/users.md) for the full walkthrough and the
four-rung auth ladder.
diff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rs
index 6c7d926c..2f21fef3 100644
--- a/crates/ai-memory-cli/src/commands/init.rs
+++ b/crates/ai-memory-cli/src/commands/init.rs
@@ -46,6 +46,13 @@ token_pepper = \"{pepper}\"
# root_username = \"boss\"
# root_email = \"[email protected]\"
# root_name = \"Boss\"
+#
+# Trusted authenticating proxy (optional). Give the proxy a bearer token that
+# differs from bearer_token. It must replace client-supplied X-Memory-Actor-*
+# headers and assert either User or the Issuer+Sub pair on every request.
+# actor_proxy_bearer_token = \"<distinct-random-token>\"
+# root_issuer = \"https://idp.example\"
+# root_subject = \"<stable-root-subject>\"
"
)
}
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index a26cec0e..c7da0ac1 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -91,24 +91,28 @@ 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.
+/// Validate the trusted proxy's least-privilege credential and optional stable
+/// root identity before binding the server.
fn validate_trusted_proxy_auth(auth: &AuthSettings) -> Result<()> {
- if configured(auth.actor_proxy_secret.as_ref()) && !configured(auth.root_username.as_ref()) {
+ let proxy_enabled = configured(auth.actor_proxy_bearer_token.as_ref());
+ if proxy_enabled && !configured(auth.bearer_token.as_ref()) {
+ anyhow::bail!(
+ "[auth].actor_proxy_bearer_token requires [auth].bearer_token so administration keeps a distinct root credential"
+ );
+ }
+ if proxy_enabled
+ && auth.actor_proxy_bearer_token.as_deref().map(str::trim)
+ == auth.bearer_token.as_deref().map(str::trim)
+ {
+ anyhow::bail!(
+ "[auth].actor_proxy_bearer_token must differ from [auth].bearer_token; sharing the root credential would let a missing proxy identity fall through as root"
+ );
+ }
+ let root_issuer = configured(auth.root_issuer.as_ref());
+ let root_subject = configured(auth.root_subject.as_ref());
+ if root_issuer != root_subject {
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"
+ "[auth].root_issuer and [auth].root_subject must be configured together because an OIDC subject is unique only within its issuer"
);
}
Ok(())
@@ -116,13 +120,10 @@ fn validate_trusted_proxy_auth(auth: &AuthSettings) -> Result<()> {
/// 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.
+/// The MCP admin gates read this to know that distinct operators are in play
+/// even when 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())
+ configured(auth.actor_proxy_bearer_token.as_ref())
}
struct ConsolidatorSetup {
@@ -637,38 +638,38 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
// created. Admin mode separately switches on a fresh
// store-backed users-exist read.
let mut auth_state = AuthState::new(config.auth.bearer_token.clone());
- let root_user = config.auth.root_username.clone();
- if root_user.as_deref().is_some_and(|s| !s.trim().is_empty()) {
+ let root_user = config
+ .auth
+ .root_username
+ .clone()
+ .filter(|value| !value.trim().is_empty());
+ let root_issuer = config
+ .auth
+ .root_issuer
+ .clone()
+ .filter(|value| !value.trim().is_empty());
+ let root_subject = config
+ .auth
+ .root_subject
+ .clone()
+ .filter(|value| !value.trim().is_empty());
+ if root_user.is_some() || root_issuer.is_some() {
auth_state = auth_state.with_root_actor(ai_memory_core::ActorContext {
user: root_user,
+ issuer: root_issuer,
+ sub: root_subject,
name: config.auth.root_name.clone(),
email: config.auth.root_email.clone(),
..ai_memory_core::ActorContext::default()
});
}
- if let Some(secret) = config
+ if let Some(proxy_token) = config
.auth
- .actor_proxy_secret
+ .actor_proxy_bearer_token
.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());
+ auth_state = auth_state.with_trusted_proxy_bearer(proxy_token.clone());
}
if let Some(pepper) = config
.auth
@@ -1587,6 +1588,51 @@ mod tests {
}
}
+ #[test]
+ fn trusted_proxy_configuration_requires_distinct_credentials() {
+ let missing_root = AuthSettings {
+ actor_proxy_bearer_token: Some("proxy-token".into()),
+ ..AuthSettings::default()
+ };
+ assert!(validate_trusted_proxy_auth(&missing_root).is_err());
+
+ let shared = AuthSettings {
+ bearer_token: Some("same-token".into()),
+ actor_proxy_bearer_token: Some(" same-token ".into()),
+ ..AuthSettings::default()
+ };
+ assert!(validate_trusted_proxy_auth(&shared).is_err());
+
+ let valid = AuthSettings {
+ bearer_token: Some("root-token".into()),
+ actor_proxy_bearer_token: Some("proxy-token".into()),
+ ..AuthSettings::default()
+ };
+ assert!(validate_trusted_proxy_auth(&valid).is_ok());
+ assert!(trusted_proxy_identity_enabled(&valid));
+ }
+
+ #[test]
+ fn root_oidc_identity_requires_issuer_and_subject_together() {
+ for (issuer, subject, valid) in [
+ (None, None, true),
+ (Some("https://idp.example"), None, false),
+ (None, Some("root-subject"), false),
+ (Some("https://idp.example"), Some("root-subject"), true),
+ ] {
+ let auth = AuthSettings {
+ root_issuer: issuer.map(str::to_string),
+ root_subject: subject.map(str::to_string),
+ ..AuthSettings::default()
+ };
+ assert_eq!(
+ validate_trusted_proxy_auth(&auth).is_ok(),
+ valid,
+ "issuer={issuer:?}, subject={subject:?}"
+ );
+ }
+ }
+
#[test]
fn maintenance_start_delay_handles_never_overdue_and_remaining_cadence() {
let interval = Duration::from_secs(120);
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 83ab78bc..76c781c2 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -357,6 +357,13 @@ pub struct AuthSettings {
/// pre-multi-user behaviour — bearer authenticates but
/// attributes anonymously.
pub root_username: Option<String>,
+ /// OIDC issuer for the root operator when a trusted proxy asserts stable
+ /// identities. Configure together with [`Self::root_subject`].
+ pub root_issuer: Option<String>,
+ /// OIDC subject for the root operator. Configure together with
+ /// [`Self::root_issuer`]; only this pair can grant a proxy-authenticated
+ /// request root capability. A display username is not a stable root key.
+ pub root_subject: Option<String>,
/// Optional email for the root user, surfaced alongside
/// `root_username` in the web UI + `/api/v1` responses.
pub root_email: Option<String>,
@@ -372,20 +379,16 @@ 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.
+ /// Dedicated bearer token for 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.
+ /// credential upstream. This token must differ from [`Self::bearer_token`]
+ /// so an omitted or malformed identity cannot fall through as root.
+ /// Actor headers on ordinary root and DB-user requests are ignored.
///
/// Only set this when the server is reachable *only* through that proxy.
- pub actor_proxy_secret: Option<String>,
+ pub actor_proxy_bearer_token: Option<String>,
}
/// `[auto_scope]` — controls how the hook-published "currently active
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
index 61f6f2c9..71352569 100644
--- a/crates/ai-memory-core/src/active_project.rs
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -94,17 +94,17 @@ pub enum ActiveProjectMode {
/// Composite identity used to key per-actor entries.
///
/// - `PerSession` mode populates only `session_id`.
-/// - `PerActor` mode populates both (`user` is the username row from
-/// `users`, or the configured `root_username` for rung 1 callers).
+/// - `PerActor` mode populates both (`user` holds the qualified identity key:
+/// `user:<name>` or an issuer-qualified OIDC subject).
///
/// An [`ActorKey`] with both fields `None` is treated the same as "no actor"
/// — the request falls back to the single slot. That keeps anonymous /
/// pre-identity callers working without a special branch at every call site.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct ActorKey {
- /// Stable username when the request was authenticated as a known user
- /// (rung 1 root with `root_username`, or rung 2 DB user). `None` for
- /// anonymous calls.
+ /// Qualified stable identity when the request was authenticated as a known
+ /// user. The field name is retained for API compatibility; values are
+ /// produced by `ActorContext::identity_key`, not copied from raw headers.
pub user: Option<String>,
/// Per-agent-run session identifier published by the lifecycle hooks
/// (Claude Code, Codex, OpenCode, …). `None` when the call site has no
diff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rs
index 516127c9..09abb74e 100644
--- a/crates/ai-memory-core/src/actor.rs
+++ b/crates/ai-memory-core/src/actor.rs
@@ -72,10 +72,12 @@ pub struct ActorContext {
/// in this session" against `audit_log` + `observations`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
- /// Reserved for the external-auth-proxy rung: the JWT `sub` claim
- /// (stable user UUID). Kept `Option<String>` so payloads to the
- /// future admission webhook chain stay forward-compatible with the
- /// shape PR #55 documents — we don't fill it from rungs 0-3.
+ /// Issuer for the external-auth-proxy rung's OIDC subject. A subject is
+ /// unique only within its issuer, so proxy authentication accepts these
+ /// two fields only as a pair.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub issuer: Option<String>,
+ /// OIDC `sub` claim asserted by an external authenticating proxy.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sub: Option<String>,
/// Reserved for the external-auth-proxy rung: the DCR client UUID
@@ -255,6 +257,7 @@ impl ActorContext {
|| self.name.is_some()
|| self.email.is_some()
|| self.session_id.is_some()
+ || self.issuer.is_some()
|| self.sub.is_some()
|| self.client.is_some()
}
@@ -273,7 +276,7 @@ impl ActorContext {
/// 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
+ /// forwards only the issuer and subject claims asserts 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
@@ -287,19 +290,18 @@ impl ActorContext {
/// 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
+ /// An `(issuer, sub)` pair wins whenever both fields are present. OIDC pins
+ /// this ordering: the spec defines that pair as the stable 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
+ /// adding the OIDC pair) 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.
+ /// Blank and whitespace-only values name nobody. A partial OIDC pair is
+ /// deliberately not an identity; trusted-proxy ingress rejects it.
#[must_use]
pub fn identity_key(&self) -> Option<IdentityKey> {
let trimmed = |v: &Option<String>| {
@@ -308,8 +310,8 @@ impl ActorContext {
.filter(|s| !s.is_empty())
.map(str::to_owned)
};
- if let Some(sub) = trimmed(&self.sub) {
- return Some(IdentityKey::Subject(sub));
+ if let (Some(issuer), Some(subject)) = (trimmed(&self.issuer), trimmed(&self.sub)) {
+ return Some(IdentityKey::Subject { issuer, subject });
}
trimmed(&self.user).map(IdentityKey::User)
}
@@ -317,17 +319,20 @@ impl ActorContext {
/// 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.
+/// The variant is part of the identity: a username and an OIDC subject with
+/// equal text are different operators. Everything that persists or compares
+/// an identity goes through [`Self::storage_key`], so call sites cannot flatten
+/// the namespaces or discard an OIDC issuer.
#[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 the OIDC issuer and subject pair. `sub` alone is not globally
+ /// unique when a proxy accepts tokens from more than one issuer.
+ Subject {
+ /// Exact OIDC `iss` value validated by the proxy.
+ issuer: String,
+ /// Exact OIDC `sub` value validated by the proxy.
+ 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
@@ -336,141 +341,20 @@ pub enum IdentityKey {
}
impl IdentityKey {
- /// The TEXT form stored in owner columns and compared by
- /// [`OwnerFilter::admits`]: `sub:<subject>` or `user:<name>`.
+ /// The TEXT form used for in-memory routing and future owner columns:
+ /// `oidc:<issuer-byte-length>:<issuer><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).
+ /// Length-prefixing the issuer makes the OIDC form unambiguous without
+ /// constraining either value or adding an encoding dependency.
#[must_use]
pub fn storage_key(&self) -> String {
match self {
- Self::Subject(sub) => format!("sub:{sub}"),
+ Self::Subject { issuer, subject } => {
+ format!("oidc:{}:{issuer}{subject}", issuer.len())
+ }
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)]
@@ -594,6 +478,10 @@ mod tests {
assert!(a.has_any());
a = ActorContext::default();
+ a.issuer = Some("https://idp.example".into());
+ assert!(a.has_any());
+ a = ActorContext::default();
+
a.sub = Some("8f3a".into());
assert!(a.has_any());
a = ActorContext::default();
@@ -602,111 +490,54 @@ 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.
+ /// OIDC identity is the issuer and subject pair, never the subject alone.
#[test]
- fn identity_key_accepts_sub_when_no_username_was_asserted() {
- let sub_only = ActorContext {
+ fn identity_key_accepts_oidc_pair_without_username() {
+ let oidc = ActorContext {
+ issuer: Some("https://idp.example".into()),
sub: Some("oidc-subject-123".into()),
..ActorContext::default()
};
assert_eq!(
- sub_only.identity_key(),
- Some(IdentityKey::Subject("oidc-subject-123".into()))
+ oidc.identity_key(),
+ Some(IdentityKey::Subject {
+ issuer: "https://idp.example".into(),
+ 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.
+ /// The stable OIDC pair outranks the display username.
#[test]
- fn identity_key_prefers_sub_over_user() {
+ fn identity_key_prefers_oidc_pair_over_user() {
let both = ActorContext {
user: Some("alice".into()),
+ issuer: Some("https://idp.example".into()),
sub: Some("oidc-subject-123".into()),
..ActorContext::default()
};
assert_eq!(
both.identity_key(),
- Some(IdentityKey::Subject("oidc-subject-123".into()))
+ Some(IdentityKey::Subject {
+ issuer: "https://idp.example".into(),
+ 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() {
+ fn identity_storage_keys_keep_namespaces_and_issuers_distinct() {
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)));
+ let issuer_a = IdentityKey::Subject {
+ issuer: "https://idp-a.example".into(),
+ subject: "alice".into(),
+ };
+ let issuer_b = IdentityKey::Subject {
+ issuer: "https://idp-b.example".into(),
+ subject: "alice".into(),
+ };
+ assert_ne!(by_name.storage_key(), issuer_a.storage_key());
+ assert_ne!(issuer_a.storage_key(), issuer_b.storage_key());
}
/// Naming nobody stays naming nobody: an agent/session-only actor carries
@@ -723,25 +554,29 @@ mod tests {
assert_eq!(transport_only.identity_key(), None);
let blank = ActorContext {
user: Some(" ".into()),
+ issuer: Some("\n".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() {
+ fn partial_oidc_pair_does_not_override_username() {
let actor = ActorContext {
- user: Some(" ".into()),
+ user: Some("alice".into()),
sub: Some("oidc-subject-123".into()),
..ActorContext::default()
};
assert_eq!(
actor.identity_key(),
- Some(IdentityKey::Subject("oidc-subject-123".into()))
+ Some(IdentityKey::User("alice".into()))
);
+ let sub_only = ActorContext {
+ sub: Some("oidc-subject-123".into()),
+ ..ActorContext::default()
+ };
+ assert_eq!(sub_only.identity_key(), None);
}
#[test]
@@ -773,6 +608,7 @@ mod tests {
name: Some("Alice Smith".into()),
email: Some("alice@home".into()),
session_id: Some("019e6d".into()),
+ issuer: Some("https://idp.example".into()),
sub: Some("8f3a-uuid".into()),
client: Some("72836f52-uuid".into()),
};
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 346c74cd..d49946fc 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -38,8 +38,8 @@ pub use active_project::{
ActiveProject, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES, DEFAULT_PER_KEY_TTL,
};
pub use actor::{
- ActorContext, AuthLevel, AuthzError, Capability, IdentityKey, OwnerFilter,
- SKIP_ADMISSION_CHAIN_HEADER, owner_stamp, parse_skip_admission_chain, skip_admission_chain_for,
+ ActorContext, AuthLevel, AuthzError, Capability, IdentityKey, SKIP_ADMISSION_CHAIN_HEADER,
+ parse_skip_admission_chain, skip_admission_chain_for,
};
pub use error::{MemoryError, MemoryResult};
pub use handoff::{Handoff, HandoffState, NewHandoff};
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index ee29d966..d4f38828 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -510,14 +510,13 @@ async fn handle_hook(
// it. Runs before the semaphore so a dropped event consumes no capacity.
// The auth middleware in front of `/hook` injects the request's
// [`ActorContext`] (rung 1 root, rung 2 DB user, or anonymous). We
- // capture its `user` field NOW — before the spawn drops the request
- // extensions — so `process()` can key the `ActiveProject` map by the
- // authenticated identity when `[auto_scope] mode = per_actor` is on.
- let actor_user = actor_ext
- .map(|axum::Extension(ctx)| ctx.user)
- .unwrap_or_default();
+ // derive its qualified identity NOW, before the spawn drops the request
+ // extensions, so `process()` can key `ActiveProject` consistently with MCP.
+ let actor_identity = actor_ext
+ .and_then(|axum::Extension(ctx)| ctx.identity_key())
+ .map(|identity| identity.storage_key());
let actor_key = ActorKey {
- user: actor_user.clone(),
+ user: actor_identity.clone(),
session_id: env.session_id.clone(),
};
if should_drop_subagent(&state, &env, &actor_key).await {
@@ -527,7 +526,7 @@ async fn handle_hook(
warn!("hook ingest saturated; dropping event with 429");
return (StatusCode::TOO_MANY_REQUESTS, "hook queue full");
};
- let rate_key = ingest_rate_key(&env, actor_user.as_deref());
+ let rate_key = ingest_rate_key(&env, actor_identity.as_deref());
if !state
.ingest_rate
.lock()
@@ -539,7 +538,7 @@ async fn handle_hook(
}
tokio::spawn(async move {
let _permit = permit;
- process_envelope(state, env, actor_user).await;
+ process_envelope(state, env, actor_identity).await;
});
(StatusCode::ACCEPTED, "queued")
}
@@ -653,9 +652,9 @@ async fn handle_hook_batch(
}
// All items in a batch share the drain's single identity, so the actor is
// captured once from the batch request (mirrors `handle_hook`).
- let actor_user = actor_ext
- .map(|axum::Extension(ctx)| ctx.user)
- .unwrap_or_default();
+ let actor_identity = actor_ext
+ .and_then(|axum::Extension(ctx)| ctx.identity_key())
+ .map(|identity| identity.storage_key());
let mut accepted_indices = Vec::new();
for (idx, mut item) in items.into_iter().enumerate() {
// Same unconditional assistant-message backstop as `handle_hook`, applied
@@ -675,7 +674,7 @@ async fn handle_hook_batch(
continue;
};
let actor_key = ActorKey {
- user: actor_user.clone(),
+ user: actor_identity.clone(),
session_id: env.session_id.clone(),
};
// Accept-but-drop subagent captures (see `handle_hook`): count the item
@@ -695,7 +694,7 @@ async fn handle_hook_batch(
Json(HookBatchAck::indexed(accepted_indices)),
);
};
- let rate_key = ingest_rate_key(&env, actor_user.as_deref());
+ let rate_key = ingest_rate_key(&env, actor_identity.as_deref());
if !state
.ingest_rate
.lock()
@@ -707,7 +706,7 @@ async fn handle_hook_batch(
continue;
}
let _permit = permit;
- if let Err(e) = process(&state, env, actor_user.clone()).await {
+ if let Err(e) = process(&state, env, actor_identity.clone()).await {
warn!(error = %e, accepted = accepted_indices.len(), "hook batch item failed; stopping (fail-fast)");
return (
StatusCode::OK,
@@ -1069,10 +1068,10 @@ async fn handle_handoff(
Query(query): Query<HandoffQuery>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
) -> impl IntoResponse {
- let actor_user = actor_ext
- .map(|axum::Extension(ctx)| ctx.user)
- .unwrap_or_default();
- match fetch_and_accept_handoff(&state, query, actor_user).await {
+ let actor_identity = actor_ext
+ .and_then(|axum::Extension(ctx)| ctx.identity_key())
+ .map(|identity| identity.storage_key());
+ match fetch_and_accept_handoff(&state, query, actor_identity).await {
Ok(Some(markdown)) => (StatusCode::OK, markdown),
Ok(None) => (StatusCode::OK, String::new()),
Err(e) => {
@@ -1085,7 +1084,7 @@ async fn handle_handoff(
async fn fetch_and_accept_handoff(
state: &HookState,
query: HandoffQuery,
- actor_user: Option<String>,
+ actor_identity: Option<String>,
) -> anyhow::Result<Option<String>> {
let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);
// A managed run's ledger is additive, not a replacement. Returning it here
@@ -1100,7 +1099,7 @@ async fn fetch_and_accept_handoff(
// therefore falls back to the single slot (graceful degradation),
// while `per_actor` keys by `user` alone.
let actor_key = ai_memory_core::ActorKey {
- user: actor_user,
+ user: actor_identity,
session_id: None,
};
let (ws, proj) = resolve_project_ids_inner(
@@ -1892,8 +1891,12 @@ fn sticky_within_session_tree(
std::path::Path::new(&event_norm).starts_with(std::path::Path::new(&session_norm))
}
-async fn process_envelope(state: Arc<HookState>, env: HookEnvelope, actor_user: Option<String>) {
- if let Err(e) = process(&state, env, actor_user).await {
+async fn process_envelope(
+ state: Arc<HookState>,
+ env: HookEnvelope,
+ actor_identity: Option<String>,
+) {
+ if let Err(e) = process(&state, env, actor_identity).await {
warn!(error = %e, "hook processing failed");
}
}
@@ -1930,12 +1933,12 @@ async fn enqueue_session_end_consolidation(
async fn process(
state: &HookState,
env: HookEnvelope,
- actor_user: Option<String>,
+ actor_identity: Option<String>,
) -> anyhow::Result<()> {
let session_id = resolve_session_id(&env)?;
// Build the actor key used to scope the in-process `ActiveProject`
- // pointer. `user` is whatever the auth middleware extracted from this
- // request; `session_id` is the RAW string from the payload (NOT the
+ // pointer. `user` is the qualified key derived from auth middleware;
+ // `session_id` is the RAW string from the payload (NOT the
// resolved UUID) — agents that forward an opaque session id over
// `X-Memory-Actor-Session-Id` on /mcp pass the same raw string, so set
// and get land on the same map slot. The MCP server's
@@ -1943,7 +1946,7 @@ async fn process(
// (anonymous + no session) is allowed — `set_for` falls back to the
// single slot.
let actor_key = ai_memory_core::ActorKey {
- user: actor_user.clone(),
+ user: actor_identity,
session_id: env.session_id.clone(),
};
// Session-sticky attribution: for an event whose session already
diff --git a/crates/ai-memory-mcp/src/actor.rs b/crates/ai-memory-mcp/src/actor.rs
index 159783b8..d332063e 100644
--- a/crates/ai-memory-mcp/src/actor.rs
+++ b/crates/ai-memory-mcp/src/actor.rs
@@ -44,6 +44,7 @@ pub fn actor_from_headers(headers: &HeaderMap) -> ActorContext {
ActorContext {
agent: header_str(headers, "x-memory-actor-agent"),
user: header_str(headers, "x-memory-actor-user"),
+ issuer: header_str(headers, "x-memory-actor-issuer"),
sub: header_str(headers, "x-memory-actor-sub"),
client: header_str(headers, "x-memory-actor-client"),
session_id: header_str(headers, "x-memory-actor-session-id"),
@@ -115,6 +116,10 @@ mod tests {
HeaderValue::from_static("claude-code"),
);
h.insert("x-memory-actor-user", HeaderValue::from_static("djalmajr"));
+ h.insert(
+ "x-memory-actor-issuer",
+ HeaderValue::from_static("https://idp.example"),
+ );
h.insert("x-memory-actor-sub", HeaderValue::from_static("8f3a-uuid"));
h.insert(
"x-memory-actor-client",
@@ -127,6 +132,7 @@ mod tests {
let ctx = actor_from_headers(&h);
assert_eq!(ctx.agent.as_deref(), Some("claude-code"));
assert_eq!(ctx.user.as_deref(), Some("djalmajr"));
+ assert_eq!(ctx.issuer.as_deref(), Some("https://idp.example"));
assert_eq!(ctx.sub.as_deref(), Some("8f3a-uuid"));
assert_eq!(ctx.client.as_deref(), Some("72836f52-uuid"));
assert_eq!(ctx.session_id.as_deref(), Some("019e6d-session"));
@@ -139,6 +145,7 @@ mod tests {
let ctx = actor_from_headers(&h);
assert!(ctx.agent.is_none());
assert!(ctx.user.is_none());
+ assert!(ctx.issuer.is_none());
assert!(ctx.sub.is_none());
assert!(ctx.client.is_none());
assert!(ctx.session_id.is_none());
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 281240a5..8daacbea 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -141,7 +141,7 @@ pub struct AdminState {
/// 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`).
+ /// end-user identities (`[auth].actor_proxy_bearer_token`).
///
/// Proxy-asserted operators never get a `users` row, so `users_exist()`
/// alone answers "does this deployment distinguish operators" with a
@@ -7619,6 +7619,68 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
}
+ #[tokio::test]
+ async fn trusted_proxy_topology_gates_admin_without_db_users() {
+ use ai_memory_core::ActorContext;
+
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let router = admin_router(AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None,
+ auto_improve_require_approval: false,
+ auto_improve_review_config: Default::default(),
+ embedder: None,
+ provider_health: ProviderHealth::default(),
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path: store.db_path().to_path_buf(),
+ bind: "127.0.0.1:49374".to_string(),
+ home_dir: None,
+ bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
+ token_pepper: Some(ai_memory_store::TokenPepper::new("test-pepper-admin")),
+ active_project: ai_memory_core::ActiveProject::new(),
+ scope_invalidator: None,
+ trusted_proxy_identity: true,
+ })
+ .layer(axum::middleware::from_fn(
+ |mut req: Request<Body>, next: axum::middleware::Next| async move {
+ let level = match req
+ .headers()
+ .get("x-test-auth-level")
+ .and_then(|value| value.to_str().ok())
+ {
+ Some("root") => ai_memory_core::AuthLevel::Root,
+ Some("user") => ai_memory_core::AuthLevel::User,
+ _ => ai_memory_core::AuthLevel::Anonymous,
+ };
+ req.extensions_mut().insert(level);
+ req.extensions_mut().insert(ActorContext::anonymous());
+ next.run(req).await
+ },
+ ));
+
+ for (level, expected) in [
+ (None, StatusCode::UNAUTHORIZED),
+ (Some("user"), StatusCode::FORBIDDEN),
+ (Some("root"), StatusCode::OK),
+ ] {
+ let mut request = Request::builder().uri("/admin/status");
+ if let Some(level) = level {
+ request = request.header("x-test-auth-level", level);
+ }
+ let response = router
+ .clone()
+ .oneshot(request.body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(response.status(), expected, "level={level:?}");
+ }
+ }
+
#[tokio::test]
async fn admin_mode_switches_after_first_user_without_restart() {
let (_tmp, router) = user_admin_test_router("root-token");
diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rs
index 21f1048b..79cb4762 100644
--- a/crates/ai-memory-mcp/src/auth.rs
+++ b/crates/ai-memory-mcp/src/auth.rs
@@ -44,7 +44,7 @@
use std::sync::Arc;
-use ai_memory_core::{ActorContext, AuthLevel};
+use ai_memory_core::{ActorContext, AuthLevel, IdentityKey};
use ai_memory_store::{ReaderPool, TokenPepper, WriterHandle, hash_token};
use axum::extract::State;
use axum::http::{HeaderMap, Method, Request, StatusCode, header};
@@ -97,12 +97,10 @@ 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>,
+ /// Dedicated bearer credential for a trusted authenticating proxy. It is
+ /// separate from the root bearer so a missing identity assertion cannot
+ /// accidentally turn proxy traffic into root traffic.
+ actor_proxy_bearer: Option<String>,
}
impl AuthState {
@@ -132,34 +130,33 @@ impl AuthState {
/// 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.
+ /// Only the stable OIDC pair can match; usernames are display data and
+ /// never grant 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,
- }
+ let Some(root @ IdentityKey::Subject { .. }) = self.root_actor.identity_key() else {
+ return false;
+ };
+ actor
+ .identity_key()
+ .is_some_and(|asserted| root == asserted)
}
/// 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
+ /// this server with a dedicated proxy bearer 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.
+ /// default.
///
- /// 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.
+ /// Presenting this bearer authenticates only the proxy rung. A blank value
+ /// 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());
+ pub fn with_trusted_proxy_bearer(mut self, token: impl Into<String>) -> Self {
+ let token = token.into();
+ self.actor_proxy_bearer = Some(token).filter(|s| !s.trim().is_empty());
self
}
@@ -214,44 +211,31 @@ impl AuthState {
/// `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.
+/// Every header the trusted-proxy assertion reads.
/// A repeated occurrence of any of them makes the assertion ambiguous — see
-/// [`overlay_trusted_proxy_actor`].
+/// [`trusted_proxy_actor`].
const PROXY_ASSERTION_HEADERS: [&str; 6] = [
- ACTOR_PROXY_SECRET_HEADER,
"x-memory-actor-user",
+ "x-memory-actor-issuer",
"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,
+/// Why a trusted-proxy identity assertion was rejected.
+#[derive(Debug)]
+enum ProxyAssertionError {
/// 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,
+ /// A proxy credential must always name a human.
+ MissingIdentity,
+ /// OIDC issuer and subject are accepted only together.
+ PartialOidcIdentity,
}
-/// 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.
+/// Parse the identity asserted by an already-authenticated proxy.
///
/// # The proxy MUST strip client-supplied `X-Memory-Actor-*` headers
///
@@ -260,58 +244,25 @@ enum ProxyAssertion {
/// 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;
+/// ([`ProxyAssertionError::Ambiguous`]) instead of one of the two being picked.
+fn trusted_proxy_actor(headers: &HeaderMap) -> Result<ActorContext, ProxyAssertionError> {
+ if PROXY_ASSERTION_HEADERS.iter().any(|name| {
+ headers.get_all(*name).iter().count() > 1
+ || headers
+ .get(*name)
+ .and_then(|value| value.to_str().ok())
+ .is_some_and(|value| value.contains(','))
+ }) {
+ return Err(ProxyAssertionError::Ambiguous);
}
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.issuer.is_some() != asserted.sub.is_some() {
+ return Err(ProxyAssertionError::PartialOidcIdentity);
}
- if asserted.session_id.is_some() {
- actor.session_id = asserted.session_id;
+ if asserted.identity_key().is_none() {
+ return Err(ProxyAssertionError::MissingIdentity);
}
- ProxyAssertion::Applied
+ Ok(asserted)
}
/// axum middleware closure. Wire with
@@ -365,51 +316,11 @@ pub async fn require_bearer(
.or(from_cookie.as_deref())
.unwrap_or("");
- // Rung 1: bearer matches the root token → attribute as root.
+ // Rung 1: root credential. Actor assertion headers are intentionally
+ // ignored here; only the distinct proxy credential may assert them.
if bool::from(provided.as_bytes().ct_eq(expected.as_bytes())) {
- let mut actor = state.root_actor.clone();
- // The agent field comes from the request layer (MCP client
- // 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(level);
+ req.extensions_mut().insert(state.root_actor.clone());
+ req.extensions_mut().insert(AuthLevel::Root);
// First successful Basic-auth hit (no cookie yet) → also stamp
// the cookie so the user doesn't get the dialog again next
@@ -424,7 +335,35 @@ pub async fn require_bearer(
return next.run(req).await;
}
- // Rung 2: bearer doesn't match root. If multi-user is enabled,
+ // Rung 1b: only an explicit Bearer token can enter the trusted-proxy
+ // branch. Basic auth and cookies are browser conveniences for the root
+ // credential, not a way to impersonate the proxy.
+ if let (Some(proxy_expected), Some(proxy_provided)) =
+ (state.actor_proxy_bearer.as_deref(), from_bearer.as_deref())
+ && bool::from(proxy_provided.as_bytes().ct_eq(proxy_expected.as_bytes()))
+ {
+ let actor = match trusted_proxy_actor(req.headers()) {
+ Ok(actor) => actor,
+ Err(error) => {
+ debug!(
+ ?error,
+ "auth rejected: invalid trusted-proxy identity assertion"
+ );
+ return invalid_proxy_identity(error);
+ }
+ };
+ let level = if state.asserts_root_identity(&actor) {
+ AuthLevel::Root
+ } else {
+ AuthLevel::User
+ };
+ debug!(actor.user = ?actor.user, actor.issuer = ?actor.issuer, actor.sub = ?actor.sub, ?level, "identity asserted by trusted proxy");
+ req.extensions_mut().insert(actor);
+ req.extensions_mut().insert(level);
+ return next.run(req).await;
+ }
+
+ // Rung 2: bearer matches neither root nor proxy. If multi-user is enabled,
// hash + look up the token against the `users` table.
if let Some(mu) = state.multiuser.as_ref()
&& !provided.is_empty()
@@ -538,13 +477,19 @@ fn build_session_cookie(token: &str) -> String {
/// 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 invalid_proxy_identity(error: ProxyAssertionError) -> Response {
+ let message = match error {
+ ProxyAssertionError::Ambiguous => {
+ "ambiguous X-Memory-Actor-* header: the proxy must replace client-supplied actor headers, not append to them\n"
+ }
+ ProxyAssertionError::MissingIdentity => {
+ "trusted proxy must assert X-Memory-Actor-User or both X-Memory-Actor-Issuer and X-Memory-Actor-Sub\n"
+ }
+ ProxyAssertionError::PartialOidcIdentity => {
+ "trusted proxy must assert X-Memory-Actor-Issuer and X-Memory-Actor-Sub together\n"
+ }
+ };
+ (StatusCode::BAD_REQUEST, message).into_response()
}
fn unauthorized(include_basic_challenge: bool) -> Response {
@@ -963,7 +908,7 @@ mod tests {
let state = Arc::new(
AuthState::new(Some("the-root-token".into()))
.with_root_actor(root)
- .with_trusted_proxy("proxy-shared-secret"),
+ .with_trusted_proxy_bearer("proxy-bearer-token"),
);
let router = Router::new()
.route("/level", get(echo_auth_level))
@@ -976,8 +921,7 @@ mod tests {
.oneshot(
Request::builder()
.uri("/level")
- .header("Authorization", "Bearer the-root-token")
- .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")
+ .header("Authorization", "Bearer proxy-bearer-token")
.header("X-Memory-Actor-User", user)
.body(Body::empty())
.unwrap(),
@@ -991,28 +935,25 @@ mod tests {
}
};
- 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");
+ for user in ["alice", "root-operator"] {
+ assert_eq!(
+ level_for(user).await,
+ "user",
+ "a proxy username alone must never grant root capability"
+ );
+ }
}
- /// 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.
+ /// A proxy credential without a human assertion must fail closed.
#[tokio::test]
- async fn proxy_secret_without_an_asserted_user_keeps_root_level() {
+ async fn proxy_bearer_without_an_asserted_identity_is_refused() {
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"),
+ .with_trusted_proxy_bearer("proxy-bearer-token"),
);
let resp = Router::new()
.route("/level", get(echo_auth_level))
@@ -1020,34 +961,27 @@ mod tests {
.oneshot(
Request::builder()
.uri("/level")
- .header("Authorization", "Bearer the-root-token")
- .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")
+ .header("Authorization", "Bearer proxy-bearer-token")
.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");
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
- /// 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.
+ /// An ingress that terminates OIDC can name a human with the stable pair
+ /// even when it does not forward `preferred_username`.
#[tokio::test]
- async fn proxy_asserting_only_sub_is_downgraded_to_user_level() {
+ async fn proxy_asserting_oidc_identity_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"),
+ .with_trusted_proxy_bearer("proxy-bearer-token"),
);
let resp = Router::new()
.route("/level", get(echo_auth_level))
@@ -1055,8 +989,8 @@ mod tests {
.oneshot(
Request::builder()
.uri("/level")
- .header("Authorization", "Bearer the-root-token")
- .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")
+ .header("Authorization", "Bearer proxy-bearer-token")
+ .header("X-Memory-Actor-Issuer", "https://idp.example")
.header("X-Memory-Actor-Sub", "oidc-subject-123")
.body(Body::empty())
.unwrap(),
@@ -1069,10 +1003,85 @@ mod tests {
assert_eq!(
String::from_utf8(bytes.to_vec()).unwrap(),
"user",
- "a sub-only assertion names somebody who is not the root operator"
+ "an OIDC assertion names somebody who is not the root operator"
+ );
+ }
+
+ #[tokio::test]
+ async fn oidc_root_requires_the_exact_issuer_and_subject_pair() {
+ let state = Arc::new(
+ AuthState::new(Some("the-root-token".into()))
+ .with_root_actor(ActorContext {
+ user: Some("root-operator".into()),
+ issuer: Some("https://idp.example".into()),
+ sub: Some("root-subject".into()),
+ ..ActorContext::default()
+ })
+ .with_trusted_proxy_bearer("proxy-bearer-token"),
+ );
+ let router = Router::new()
+ .route("/level", get(echo_auth_level))
+ .layer(axum::middleware::from_fn_with_state(state, require_bearer));
+ let level_for = |issuer: &'static str, subject: &'static str| {
+ let router = router.clone();
+ async move {
+ let response = router
+ .oneshot(
+ Request::builder()
+ .uri("/level")
+ .header("Authorization", "Bearer proxy-bearer-token")
+ .header("X-Memory-Actor-User", "root-operator")
+ .header("X-Memory-Actor-Issuer", issuer)
+ .header("X-Memory-Actor-Sub", subject)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)
+ .await
+ .unwrap();
+ String::from_utf8(bytes.to_vec()).unwrap()
+ }
+ };
+
+ assert_eq!(
+ level_for("https://idp.example", "root-subject").await,
+ "root"
+ );
+ assert_eq!(
+ level_for("https://other-idp.example", "root-subject").await,
+ "user"
+ );
+ assert_eq!(
+ level_for("https://idp.example", "someone-else").await,
+ "user"
);
}
+ #[tokio::test]
+ async fn partial_oidc_identity_is_refused() {
+ let state = AuthState::new(Some("the-root-token".into()))
+ .with_trusted_proxy_bearer("proxy-bearer-token");
+ for (name, value) in [
+ ("X-Memory-Actor-Issuer", "https://idp.example"),
+ ("X-Memory-Actor-Sub", "subject-only"),
+ ] {
+ let response = router_with_state(state.clone())
+ .oneshot(
+ Request::builder()
+ .uri("/probe")
+ .header("Authorization", "Bearer proxy-bearer-token")
+ .header(name, value)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST, "header {name}");
+ }
+ }
+
/// 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
@@ -1084,13 +1093,12 @@ mod tests {
user: Some("root-operator".into()),
..ActorContext::default()
})
- .with_trusted_proxy("proxy-shared-secret");
+ .with_trusted_proxy_bearer("proxy-bearer-token");
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("Authorization", "Bearer proxy-bearer-token")
// Bob's own header, then the proxy's appended one.
.header("X-Memory-Actor-User", "alice")
.header("X-Memory-Actor-User", "bob")
@@ -1106,25 +1114,22 @@ mod tests {
);
}
- /// 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.
+ /// Some proxies fold repeated headers into a comma-separated value. Reject
+ /// that representation too rather than choosing one asserted identity.
#[tokio::test]
- async fn duplicated_proxy_secret_header_is_refused() {
+ async fn folded_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");
+ .with_trusted_proxy_bearer("proxy-bearer-token");
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")
+ .header("Authorization", "Bearer proxy-bearer-token")
+ .header("X-Memory-Actor-User", "alice,bob")
.body(Body::empty())
.unwrap(),
)
@@ -1142,7 +1147,7 @@ mod tests {
user: Some("root-operator".into()),
..ActorContext::default()
})
- .with_trusted_proxy("proxy-shared-secret"),
+ .with_trusted_proxy_bearer("proxy-bearer-token"),
);
let resp = Router::new()
.route("/level", get(echo_auth_level))
@@ -1162,24 +1167,22 @@ mod tests {
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`.
+ /// A proxy's OIDC identity replaces the root actor template completely.
#[tokio::test]
- async fn proxy_asserting_only_sub_drops_root_and_carries_the_subject() {
+ async fn proxy_oidc_identity_drops_root_template_and_carries_the_pair() {
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");
+ .with_trusted_proxy_bearer("proxy-bearer-token");
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("Authorization", "Bearer proxy-bearer-token")
+ .header("X-Memory-Actor-Issuer", "https://idp.example")
.header("X-Memory-Actor-Sub", "oidc-subject-123")
.body(Body::empty())
.unwrap(),
@@ -1188,6 +1191,7 @@ mod tests {
.unwrap();
let actor = body_as_actor(resp).await;
assert_eq!(actor.user, None, "the root username must not survive");
+ assert_eq!(actor.issuer.as_deref(), Some("https://idp.example"));
assert_eq!(actor.sub.as_deref(), Some("oidc-subject-123"));
assert_eq!(actor.email, None);
}
@@ -1197,7 +1201,7 @@ mod tests {
/// 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() {
+ async fn actor_headers_are_ignored_without_a_configured_proxy_bearer() {
let root = ActorContext {
user: Some("boss".into()),
..ActorContext::default()
@@ -1223,16 +1227,17 @@ mod tests {
);
}
- /// Same headers, secret configured but NOT presented: still ignored.
+ /// Root credentials never consume proxy assertion headers, even when the
+ /// proxy rung is configured.
#[tokio::test]
- async fn actor_headers_are_ignored_without_the_proxy_secret_header() {
+ async fn actor_headers_are_ignored_on_the_root_rung() {
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");
+ .with_trusted_proxy_bearer("proxy-bearer-token");
let resp = router_with_state(state)
.oneshot(
Request::builder()
@@ -1248,36 +1253,34 @@ mod tests {
assert_eq!(actor.user.as_deref(), Some("boss"));
}
- /// A wrong secret is as good as none.
+ /// An unknown proxy bearer cannot fall through into the root rung.
#[tokio::test]
- async fn actor_headers_are_ignored_when_the_proxy_secret_mismatches() {
+ async fn wrong_proxy_bearer_is_unauthorized() {
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");
+ .with_trusted_proxy_bearer("proxy-bearer-token");
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("Authorization", "Bearer wrong-proxy-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"));
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
- /// The point of the feature: with the secret proven, two different humans
- /// behind the same root credential become two different actors.
+ /// The point of the feature: two people behind one proxy credential become
+ /// different actors.
#[tokio::test]
- async fn trusted_proxy_identity_overlays_the_root_actor() {
+ async fn trusted_proxy_identity_builds_an_independent_actor() {
let root = ActorContext {
user: Some("boss".into()),
email: Some("[email protected]".into()),
@@ -1287,7 +1290,7 @@ mod tests {
let state = Arc::new(
AuthState::new(Some("the-root-token".into()))
.with_root_actor(root)
- .with_trusted_proxy("proxy-shared-secret"),
+ .with_trusted_proxy_bearer("proxy-bearer-token"),
);
let router = Router::new()
.route("/probe", get(echo_actor))
@@ -1299,8 +1302,7 @@ mod tests {
.oneshot(
Request::builder()
.uri("/probe")
- .header("Authorization", "Bearer the-root-token")
- .header("X-Memory-Actor-Proxy-Secret", "proxy-shared-secret")
+ .header("Authorization", "Bearer proxy-bearer-token")
.header("X-Memory-Actor-User", user)
.header("X-Memory-Actor-Session-Id", format!("sess-{user}"))
.body(Body::empty())
@@ -1319,17 +1321,16 @@ mod tests {
}
}
- /// A blank secret must not enable the overlay — otherwise an empty config
- /// value would make a missing header compare equal and trust everyone.
+ /// A blank proxy bearer must not enable the trusted rung.
#[tokio::test]
- async fn blank_proxy_secret_does_not_enable_the_overlay() {
+ async fn blank_proxy_bearer_does_not_enable_the_proxy_rung() {
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(" ");
+ .with_trusted_proxy_bearer(" ");
let resp = router_with_state(state)
.oneshot(
Request::builder()
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 0213d99e..84f4ccc0 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -391,7 +391,7 @@ pub struct AiMemoryServer {
/// 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`).
+ /// identities (`[auth].actor_proxy_bearer_token`).
///
/// Distinct operators reach this server by two independent routes: rows in
/// `users` (rung 2) and proxy-asserted usernames (rung 1b). Only the first
@@ -976,7 +976,7 @@ impl AiMemoryServer {
}
/// Declare that a trusted proxy may assert end-user identities — mirror of
- /// `AuthState::with_trusted_proxy`, which is where the secret itself lives.
+ /// `AuthState::with_trusted_proxy_bearer`, which owns the credential.
///
/// Without this the admin gates cannot tell a proxied deployment apart from
/// a single-operator one; see [`Self::trusted_proxy_identity`].
@@ -1029,10 +1029,9 @@ impl AiMemoryServer {
/// Build the [`ActorKey`] for a tool call from the request's stored
/// extensions and headers.
///
- /// - `user` is taken from the middleware-injected
- /// [`ai_memory_core::ActorContext`] (rung 1 root, rung 2 DB user) —
- /// never from raw client-supplied headers, since user identity is
- /// security-critical.
+ /// - `user` is the qualified key derived from the middleware-injected
+ /// [`ai_memory_core::ActorContext`] (root, proxy, or DB user), never from
+ /// raw client-supplied headers.
/// - `session_id` comes from the same `ActorContext` when the auth
/// middleware filled it; if not, falls back to the rung-4
/// `X-Memory-Actor-Session-Id` request header, then to the standard
@@ -1051,7 +1050,9 @@ impl AiMemoryServer {
return ai_memory_core::ActorKey::default();
};
let ctx = parts.extensions.get::<ai_memory_core::ActorContext>();
- let user = ctx.and_then(|c| c.user.clone());
+ let user = ctx
+ .and_then(ai_memory_core::ActorContext::identity_key)
+ .map(|identity| identity.storage_key());
let header_session = |name: &str| {
parts
.headers
@@ -3459,7 +3460,7 @@ mod tests {
assert_eq!(
AiMemoryServer::actor_key_from_parts(Some(&parts)),
ai_memory_core::ActorKey {
- user: Some("alice".into()),
+ user: Some("user:alice".into()),
session_id: Some("session-from-header".into()),
},
"real HTTP request parts must preserve auth identity and routing session"
@@ -3992,10 +3993,28 @@ mod tests {
let actor = AiMemoryServer::actor_key_from_parts(Some(&parts));
- assert_eq!(actor.user.as_deref(), Some("alice"));
+ assert_eq!(actor.user.as_deref(), Some("user:alice"));
assert_eq!(actor.session_id.as_deref(), Some("context-session"));
}
+ #[test]
+ fn actor_key_uses_issuer_qualified_subject() {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(ai_memory_core::ActorContext {
+ user: Some("display-name".into()),
+ issuer: Some("https://idp.example".into()),
+ sub: Some("subject-123".into()),
+ ..ai_memory_core::ActorContext::default()
+ });
+
+ let actor = AiMemoryServer::actor_key_from_parts(Some(&parts));
+
+ assert_eq!(
+ actor.user.as_deref(),
+ Some("oidc:19:https://idp.examplesubject-123")
+ );
+ }
+
#[tokio::test]
async fn server_constructs_with_tool_router() {
let (_tmp, _store, _server, _ws, _pj) = setup_server().await;
@@ -8183,6 +8202,34 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn mcp_admin_capability_honors_trusted_proxy_topology() {
+ let (_tmp, _store, server, _ws, _project) = setup_server().await;
+ let proxied = server.with_trusted_proxy_identity(true);
+
+ for (level, allowed) in [
+ (AuthLevel::Anonymous, false),
+ (AuthLevel::User, false),
+ (AuthLevel::Root, true),
+ ] {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(level);
+ assert_eq!(
+ proxied.require_admin_capability(&parts).await.is_ok(),
+ allowed,
+ "level={level:?}"
+ );
+ }
+
+ assert!(
+ proxied
+ .require_admin_capability(&test_parts_default())
+ .await
+ .is_ok(),
+ "stdio/in-process calls have no HTTP auth extension and retain local admin access"
+ );
+ }
+
/// `memory_handoff_accept` with no pending handoff returns a
/// happy-path `{"handoff": null}` payload (NOT an error). This
/// is the documented contract — the agent can call accept on
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index 63ab183a..74fa5a69 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -23,7 +23,7 @@ separated.
|---------------|------------------------|----------------------------------------------------------------------------------------------------------|
| `single` | (none — global slot) | **Default.** Single operator, one project at a time. Backward-compatible with every existing install. |
| `per_session` | `session_id` | Session-aware clients/bridges that forward the hook session id on every MCP request. |
-| `per_actor` | `(user, session_id)`, with a user-only no-session slot | Shared engine fielding multiple authenticated users (multi-user mode, rung 2). Isolates across operators and fails closed when a forwarded session id does not match hook activity. |
+| `per_actor` | `(qualified identity, session_id)`, with an identity-only no-session slot | Shared engine fielding multiple authenticated users or trusted-proxy identities. Isolates across operators and fails closed when a forwarded session id does not match hook activity. |
Both opt-in modes still publish to the single slot in parallel, so a
caller with no actor identity (anonymous probe, legacy code path) sees
@@ -82,6 +82,7 @@ AI_MEMORY_AUTO_SCOPE__MAX_ENTRIES=8192
|----------------------------------------------------|----------------------------|
| Hook payload (`/hook?event=…&agent=…`) | `session_id`, `agent` |
| Auth middleware (rung 1 root with `root_username`) | `user` ← root_username |
+| Auth middleware (rung 1b trusted proxy) | username or OIDC `(issuer, subject)` pair |
| Auth middleware (rung 2 DB user) | `user` ← `users.username` |
| MCP request header `X-Memory-Actor-Session-Id` | `session_id` for tool calls |
| MCP request header `Mcp-Session-Id` | fallback `session_id` for tool calls |
@@ -92,8 +93,8 @@ lifecycle-hook payload. It is not an OIDC/Keycloak login session: the
provider's JWT `sid` claim identifies an IdP browser/device session and
must not be used as ai-memory's actor session key.
-`per_session` reads from `session_id`; `per_actor` reads from both
-`user` and `session_id`. In `per_actor`, a request that has `user` but
+`per_session` reads from `session_id`; `per_actor` reads from both the
+qualified identity and `session_id`. In `per_actor`, a request that has identity but
no session id can use that user's latest no-session slot instead of the
process-wide single slot. A request that does carry a session id must
match a hook-published keyed entry; if it does not, ai-memory falls back
@@ -138,7 +139,8 @@ the legacy single slot.
OIDC/Keycloak authentication can identify the human user, client, and
agent, but it does not automatically identify the current coding-agent
session. If a gateway validates a Keycloak JWT, it should propagate
-`X-Memory-Actor-User` / `Sub` / `Client` / `Agent`; it should only emit
+`X-Memory-Actor-User` or the `Issuer` + `Sub` pair, plus optional `Client` /
+`Agent`; it should only emit
`X-Memory-Actor-Session-Id` when a real agent session id has been
forwarded by a session-aware bridge.
diff --git a/docs/users.md b/docs/users.md
index f49f89bd..0946f25f 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -9,8 +9,9 @@ there is no per-page RBAC, no per-user data scoping, no group
permissions. What multi-user mode adds is *who-did-this*: every write
attributes to a named user, audit-log rows carry that identity, and the
web UI can show "Last edited by Alice Smith" instead of the anonymous
-default. Every `/admin/*` endpoint stays root-only once at least one user
-row exists, including read-only status/search/read-page helpers.
+default. Every `/admin/*` endpoint stays root-only once the deployment has a
+DB user or trusted-proxy identities, including read-only
+status/search/read-page helpers.
If you run ai-memory alone, you can skip this page — your install
keeps working unchanged.
@@ -45,81 +46,69 @@ 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. |
+| **1b — Proxy-asserted user** | Bearer matches the distinct `[auth].actor_proxy_bearer_token`. | Identity is taken from trusted `X-Memory-Actor-*` headers. The request is a **user** unless its OIDC issuer/subject pair exactly matches the configured root pair. Missing or malformed identity is rejected. |
| **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. |
-The rungs are sticky: a request is matched at the lowest tier that
-applies, never escalates. Root token always wins over any users-row
-collision; the two namespaces are intentionally distinct.
+The rungs are sticky: a request is matched at the first credential that
+applies, never escalates. Startup rejects equal root and proxy credentials;
+root and proxy credentials take precedence over any accidental DB-token
+collision.
## 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.
+A deployment that terminates SSO validates the end user's credential, then
+authenticates upstream with a proxy-only bearer and describes the human in
+`X-Memory-Actor-*` headers. Those headers are **ignored by default** on root
+and DB-user requests because anything that can reach the port could otherwise
+claim any identity.
-Set `[auth].actor_proxy_secret` and have the proxy echo it in
-`X-Memory-Actor-Proxy-Secret` to change that:
+Configure a distinct proxy credential:
```toml
[auth]
-bearer_token = "…" # required: the overlay only applies to root-bearer requests
-actor_proxy_secret = "…" # shared with the proxy; compared in constant time
+bearer_token = "<root-token>" # direct administration
+actor_proxy_bearer_token = "<different-token>" # SSO proxy only
+
+# Optional stable identity for the root human behind an OIDC proxy.
+root_issuer = "https://idp.example"
+root_subject = "<root-subject>"
```
-- 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.
+- The proxy token **is** the switch. A blank value counts as unset. It must
+ differ from `bearer_token`, and `serve` refuses startup otherwise or when the
+ root bearer is absent.
- 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.
+ one read. Repeated headers and comma-folded values are rejected with `400`
+ rather than resolved to one identity.
+- Every proxy request must assert `X-Memory-Actor-User`, or both
+ `X-Memory-Actor-Issuer` and `X-Memory-Actor-Sub`. The OIDC fields are a pair:
+ the standard guarantees subject uniqueness only within an issuer. A partial
+ pair or a request that names nobody is rejected with `400`.
+- Proxy callers are users by default. A username-only assertion can never
+ become root, including one equal to `root_username`, because an OIDC display
+ username is not a stable unique identifier. Proxied root access requires an
+ exact match with `root_issuer` plus `root_subject`.
+- Origin health checks or maintenance calls that need root should use the root
+ bearer, not the proxy bearer. Raw actor headers on the root rung are ignored.
## 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.
+Identity-sensitive routing uses a *qualified* identity, never a bare string.
+`ActorContext::identity_key()` resolves a request to the OIDC
+`(issuer, subject)` pair when both are present, or to `user:<name>` for a
+username-only identity. The namespaces are disjoint, and identical subjects
+from different issuers stay different.
+
+The OIDC pair outranks `user` because OIDC defines `(iss, sub)` as the stable
+identifier and explicitly forbids relying on `preferred_username` for
+uniqueness. Configure the proxy to forward both values from day one. Adding a
+display username later then preserves the same identity; moving from a
+username-only assertion to the OIDC pair deliberately changes it once.
## Implementation contract