Skip to content

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

Rust

fix(auth): harden OIDC bearer fallback

AkitaOnRails54b17224b2b9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33e9193c..b2ba29d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -37,10 +37,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Thin-client HTTP CLI commands (`status`, `search`, `read-page`, `write-page`,
- `delete-page`, `backup`, `embed`, `reindex`, and related admin commands) now
- fall back to a stored OIDC device-flow token from `auth.json` when
- `AI_MEMORY_AUTH_TOKEN` / `[auth].bearer_token` is absent. Static bearer tokens
- still take precedence.
+ `delete-page`, `backup`, `embed`, and related admin commands) now fall back to
+ a stored OIDC device-flow token from `auth.json` when `AI_MEMORY_AUTH_TOKEN` /
+ `[auth].bearer_token` is absent. This sends a bearer for external OIDC-aware
+ gateways/bridges; native ai-memory server auth still uses the static root
+ bearer or DB-user tokens, and `/admin/*` remains root-only unless a gateway
+ translates accepted OIDC auth into upstream auth that ai-memory accepts.
+ Static bearer tokens still take precedence.
## [1.3.0] - 2026-06-24
diff --git a/README.md b/README.md
index 7ed06437..4cdf81ef 100644
--- a/README.md
+++ b/README.md
@@ -376,7 +376,10 @@ wrapper keeps shell-script hooks by default; set up OIDC from a native release
binary or source install. Thin-client HTTP commands such as `ai-memory status`
and `ai-memory search` also use the stored OIDC access token when no static
`AI_MEMORY_AUTH_TOKEN` / `[auth].bearer_token` is configured; the static bearer
-still wins when present.
+still wins when present. This is for OIDC-aware gateways/bridges; native
+ai-memory server auth still accepts static root bearer / DB-user tokens, and
+`/admin/*` remains root-only unless a gateway translates accepted OIDC auth into
+upstream auth that ai-memory accepts.
OIDC/Keycloak session ids are login-provider sessions, not ai-memory agent
sessions. Shared servers that rely on `[auto_scope]` session isolation still
diff --git a/crates/ai-memory-cli/src/auth_bearer.rs b/crates/ai-memory-cli/src/auth_bearer.rs
index 78b4b2a3..7b7370f9 100644
--- a/crates/ai-memory-cli/src/auth_bearer.rs
+++ b/crates/ai-memory-cli/src/auth_bearer.rs
@@ -24,16 +24,20 @@ pub async fn resolve_bearer(
/// Load the stored OIDC token, refreshing and persisting it when stale.
///
-/// Returns the access token, or `None` when there is no token or refresh
-/// failed. Failing open to "no bearer" preserves the old unauthenticated CLI
-/// behavior and lets the server return the authoritative auth error.
+/// Returns the access token, or `None` when there is no token. Refresh failures
+/// fall back to the existing token because it may still be inside the provider's
+/// accepted clock-skew window.
pub async fn resolve_oidc(client: &reqwest::Client, auth_path: &Path) -> Option<String> {
let mut token = OidcToken::load(auth_path).ok().flatten()?;
if token.needs_refresh() {
let Ok(refreshed) = refresh_access_token(client, &token).await else {
- return None;
+ return Some(token.access.expose_secret().to_string());
};
- let _ = refreshed.save(auth_path);
+ if refreshed.save(auth_path).is_err() {
+ // Avoid using a rotated token that was not persisted; keep this
+ // request aligned with the still-current auth.json state.
+ return Some(token.access.expose_secret().to_string());
+ }
token = refreshed;
}
Some(token.access.expose_secret().to_string())
@@ -45,18 +49,47 @@ mod tests {
use secrecy::SecretString;
- fn save_oidc_token(path: &Path, access: &str) {
- let token = OidcToken {
+ fn oidc_token(endpoint: &str, access: &str, expires_at_ms: u64) -> OidcToken {
+ OidcToken {
access: SecretString::from(access.to_string()),
refresh: SecretString::from("refresh-token".to_string()),
- expires_at_ms: u64::MAX,
+ expires_at_ms,
issuer: "https://issuer.example.com/realms/team".to_string(),
client_id: "ai-memory-cli".to_string(),
- token_endpoint: "https://issuer.example.com/token".to_string(),
- };
+ token_endpoint: endpoint.to_string(),
+ }
+ }
+
+ fn save_oidc_token(path: &Path, access: &str) {
+ let token = oidc_token("https://issuer.example.com/token", access, u64::MAX);
token.save(path).expect("save test OIDC token");
}
+ fn save_refreshing_oidc_token(path: &Path, endpoint: &str, access: &str) {
+ let token = oidc_token(endpoint, access, 0);
+ token.save(path).expect("save test OIDC token");
+ }
+
+ async fn serve_refresh(status: &'static str, body: &'static str) -> String {
+ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let Ok((mut stream, _)) = listener.accept().await else {
+ return;
+ };
+ let mut buf = [0_u8; 4096];
+ let _ = stream.read(&mut buf).await;
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ });
+ format!("http://{addr}/token")
+ }
+
#[tokio::test]
async fn static_token_wins_over_stored_oidc() {
let tmp = tempfile::tempdir().unwrap();
@@ -91,4 +124,57 @@ mod tests {
assert!(bearer.is_none());
}
+
+ #[tokio::test]
+ async fn refresh_failure_falls_back_to_existing_token() {
+ let endpoint = serve_refresh("401 Unauthorized", r#"{"error":"invalid_grant"}"#).await;
+ let tmp = tempfile::tempdir().unwrap();
+ let auth_path = tmp.path().join("auth.json");
+ save_refreshing_oidc_token(&auth_path, &endpoint, "old-access");
+ let client = reqwest::Client::new();
+
+ let bearer = resolve_bearer(&client, &auth_path, None).await;
+
+ assert_eq!(bearer.as_deref(), Some("old-access"));
+ }
+
+ #[tokio::test]
+ async fn refresh_success_persists_and_uses_refreshed_token() {
+ let endpoint = serve_refresh(
+ "200 OK",
+ r#"{"access_token":"new-access","refresh_token":"new-refresh","expires_in":300}"#,
+ )
+ .await;
+ let tmp = tempfile::tempdir().unwrap();
+ let auth_path = tmp.path().join("auth.json");
+ save_refreshing_oidc_token(&auth_path, &endpoint, "old-access");
+ let client = reqwest::Client::new();
+
+ let bearer = resolve_bearer(&client, &auth_path, None).await;
+ let saved = OidcToken::load(&auth_path).unwrap().unwrap();
+
+ assert_eq!(bearer.as_deref(), Some("new-access"));
+ assert_eq!(saved.access.expose_secret(), "new-access");
+ assert_eq!(saved.refresh.expose_secret(), "new-refresh");
+ }
+
+ #[tokio::test]
+ async fn refresh_save_failure_falls_back_to_existing_token() {
+ let endpoint = serve_refresh(
+ "200 OK",
+ r#"{"access_token":"new-access","refresh_token":"new-refresh","expires_in":300}"#,
+ )
+ .await;
+ let tmp = tempfile::tempdir().unwrap();
+ let auth_path = tmp.path().join("auth.json");
+ save_refreshing_oidc_token(&auth_path, &endpoint, "old-access");
+ std::fs::create_dir(auth_path.with_extension("json.tmp")).unwrap();
+ let client = reqwest::Client::new();
+
+ let bearer = resolve_bearer(&client, &auth_path, None).await;
+ let saved = OidcToken::load(&auth_path).unwrap().unwrap();
+
+ assert_eq!(bearer.as_deref(), Some("old-access"));
+ assert_eq!(saved.access.expose_secret(), "old-access");
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rs
index 08093694..bd2ff63d 100644
--- a/crates/ai-memory-cli/src/commands/hook_spool.rs
+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs
@@ -583,6 +583,18 @@ mod tests {
assert_eq!(a.auth_mode, AuthMode::Anonymous);
}
+ #[tokio::test]
+ async fn resolve_bearer_delegates_static_and_absent_oidc_semantics() {
+ let tmp = tempfile::tempdir().unwrap();
+ let client = reqwest::Client::new();
+
+ let static_bearer = resolve_bearer(&client, tmp.path(), Some("static-token")).await;
+ let absent_bearer = resolve_bearer(&client, tmp.path(), None).await;
+
+ assert_eq!(static_bearer.as_deref(), Some("static-token"));
+ assert!(absent_bearer.is_none());
+ }
+
#[test]
fn enqueue_then_list_round_trips() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/docs/install.md b/docs/install.md
index 94e7d17a..80f1095c 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -325,7 +325,10 @@ ai-memory auth login oidc-device \
The stored OIDC access token is also used by thin-client HTTP commands
(`status`, `search`, `read-page`, `write-page`, `backup`, `embed`, and
similar) when no static `AI_MEMORY_AUTH_TOKEN` / `[auth].bearer_token` is
-configured. Static bearer auth still has precedence.
+configured. Static bearer auth still has precedence. This is for external
+OIDC-aware gateways/bridges; native ai-memory server auth still uses static root
+bearer / DB-user tokens, and `/admin/*` remains root-only unless a gateway
+translates accepted OIDC auth into upstream auth that ai-memory accepts.
OIDC/Keycloak `sid` claims describe the login provider's session, not the
coding-agent session ai-memory uses for `[auto_scope]` isolation. Gateways may
diff --git a/docs/users.md b/docs/users.md
index 4767444c..26c4087c 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -302,9 +302,11 @@ the bearer authenticates, attribution flows from the token's owner
for every `/admin/*` endpoint. DB users created with `user add` are
normal users, not additional admins.
- **OIDC is request authentication, not page authorization.** Native hooks and
- thin-client CLI commands can use a per-developer OIDC device token, but
- ai-memory still has one shared wiki per server and no per-page RBAC. The
- Keycloak/OIDC `sid` claim is also not an ai-memory agent session id; session
- auto-scope needs the lifecycle-hook session id or explicit `workspace` +
- `project` / `scopes`. If you need data isolation, run separate ai-memory
- servers or isolate at a reverse proxy.
+ thin-client CLI commands can send a per-developer OIDC bearer for an external
+ OIDC-aware gateway/bridge. Native ai-memory server auth still uses static root
+ bearer / DB-user tokens, and `/admin/*` stays root-only unless a gateway
+ translates accepted OIDC auth into upstream auth that ai-memory accepts.
+ ai-memory still has one shared wiki per server and no
+ per-page RBAC. The Keycloak/OIDC `sid` claim is also not an ai-memory agent
+ session id; session auto-scope needs the lifecycle-hook session id or explicit
+ `workspace` + `project` / `scopes`.