Skip to content

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

Rust

fix(auth): validate OIDC endpoints at request sinks

AkitaOnRailsd7cb6a97bda5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f375933..9ab90c2f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,11 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
### Fixed
+- Hardened OIDC credential transport after CodeQL alert #176: the shared
+ refresh-grant sink now requires a typed TLS-or-loopback endpoint, and device
+ authorization and token polling revalidate their endpoints immediately
+ before each request. A caller-mutated discovery object can no longer bypass
+ the login-time HTTPS check.
- On Windows, `setup` now starts the logon host with a plain executable path,
and the host passes plain drive/UNC data-directory and config arguments to the
supervisor and server it launches, instead of the `\\?\` verbatim prefix a
diff --git a/crates/ai-memory-llm/src/oidc.rs b/crates/ai-memory-llm/src/oidc.rs
index 1675c350..6a7da319 100644
--- a/crates/ai-memory-llm/src/oidc.rs
+++ b/crates/ai-memory-llm/src/oidc.rs
@@ -20,7 +20,9 @@ use serde::{Deserialize, Serialize};
use crate::auth_file::now_ms;
use crate::error::{LlmError, LlmResult};
use crate::response::{provider_error_body, response_json_limited};
-use crate::stored_token::{StoredOAuthToken, refresh_grant};
+use crate::stored_token::{
+ CredentialEndpoint, StoredOAuthToken, credential_endpoint, refresh_grant,
+};
/// Default device-flow scopes: `openid` (ID token), `profile` (so the access
/// token carries `preferred_username` → `X-Memory-Actor-User` on the server),
@@ -174,27 +176,8 @@ pub enum PollOutcome {
/// Refuse an OIDC URL that would carry the device code or tokens in clear
/// text. OIDC requires an `https` issuer and OAuth requires TLS at the token
/// endpoint; plain `http` stays usable on loopback for local test issuers.
-fn require_tls(what: &str, url: &str) -> LlmResult<()> {
- let parsed = reqwest::Url::parse(url)
- .map_err(|e| LlmError::Auth(format!("OIDC {what} {url:?} is not a valid URL: {e}")))?;
- let loopback = parsed.host_str().is_some_and(|host| {
- let host = host
- .strip_prefix('[')
- .and_then(|host| host.strip_suffix(']'))
- .unwrap_or(host);
- host.eq_ignore_ascii_case("localhost")
- || host
- .parse::<std::net::IpAddr>()
- .is_ok_and(|ip| ip.is_loopback())
- });
- match parsed.scheme() {
- "https" => Ok(()),
- "http" if loopback => Ok(()),
- _ => Err(LlmError::Auth(format!(
- "OIDC {what} {url:?} must use https (plain http is accepted only on \
- localhost, 127.0.0.1 or ::1)"
- ))),
- }
+fn require_tls(what: &str, url: &str) -> LlmResult<CredentialEndpoint> {
+ credential_endpoint(&format!("OIDC {what}"), url)
}
/// Resolve the device + token endpoints from the issuer's discovery document.
@@ -209,7 +192,12 @@ pub async fn discover(client: &reqwest::Client, issuer: &str) -> LlmResult<OidcD
"{}/.well-known/openid-configuration",
issuer.trim_end_matches('/')
);
- let resp = client.get(&url).send().await.map_err(LlmError::from)?;
+ let endpoint = require_tls("discovery endpoint", &url)?;
+ let resp = client
+ .get(endpoint.as_url().clone())
+ .send()
+ .await
+ .map_err(LlmError::from)?;
let status = resp.status();
if !status.is_success() {
let body = provider_error_body(resp).await;
@@ -236,8 +224,12 @@ pub async fn request_device_code(
client_id: &str,
scope: &str,
) -> LlmResult<DeviceAuthorizationResponse> {
+ let endpoint = require_tls(
+ "device_authorization_endpoint",
+ &discovery.device_authorization_endpoint,
+ )?;
let resp = client
- .post(&discovery.device_authorization_endpoint)
+ .post(endpoint.as_url().clone())
.form(&[("client_id", client_id), ("scope", scope)])
.send()
.await
@@ -263,8 +255,9 @@ pub async fn poll_token_once(
client_id: &str,
device_code: &str,
) -> LlmResult<PollOutcome> {
+ let endpoint = require_tls("token_endpoint", &discovery.token_endpoint)?;
let resp = client
- .post(&discovery.token_endpoint)
+ .post(endpoint.as_url().clone())
.form(&[
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
("device_code", device_code),
@@ -297,13 +290,13 @@ pub async fn poll_token_once(
/// Returns [`LlmError::Auth`] when the refresh grant is rejected (the caller
/// should fall back to the stale token or prompt a re-login).
pub async fn refresh_access_token(token: &OidcToken) -> LlmResult<OidcToken> {
- require_tls("token_endpoint", &token.extra.token_endpoint)?;
+ let token_endpoint = require_tls("token_endpoint", &token.extra.token_endpoint)?;
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.build()?;
let token_response = refresh_grant::<OidcTokenResponse>(
&client,
- &token.extra.token_endpoint,
+ &token_endpoint,
token.refresh.expose_secret(),
&token.extra.client_id,
"OIDC refresh failed",
@@ -516,6 +509,80 @@ mod tests {
assert_eq!(found.device_authorization_endpoint, device);
}
+ #[tokio::test]
+ async fn credential_sinks_revalidate_mutated_discovery_endpoints() {
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ // OidcDiscovery has public fields, so login-time validation is not a
+ // sufficient boundary: another caller can construct or mutate one.
+ // Route remote names through a local proxy to prove the guards reject
+ // before either credential-bearing request reaches the wire.
+ let proxy = MockServer::start().await;
+ let client = reqwest::Client::builder()
+ .proxy(reqwest::Proxy::http(proxy.uri()).unwrap())
+ .build()
+ .unwrap();
+ let remote = OidcDiscovery {
+ device_authorization_endpoint: "http://idp.example.com/device".into(),
+ token_endpoint: "http://idp.example.com/token".into(),
+ };
+ let device_error = request_device_code(&client, &remote, "client", OIDC_DEFAULT_SCOPE)
+ .await
+ .expect_err("a mutated remote HTTP device endpoint must be refused");
+ let token_error = poll_token_once(&client, &remote, "client", "device-code")
+ .await
+ .expect_err("a mutated remote HTTP token endpoint must be refused");
+ for error in [device_error, token_error] {
+ assert!(matches!(error, LlmError::Auth(message) if message.contains("must use https")));
+ }
+ assert!(
+ proxy
+ .received_requests()
+ .await
+ .unwrap_or_default()
+ .is_empty(),
+ "a rejected endpoint reached the proxy"
+ );
+
+ // Plain HTTP remains supported for an explicitly loopback test IdP.
+ let local = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/device"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "device_code": "device-code",
+ "user_code": "ABCD",
+ "verification_uri": "https://idp.example.com/verify"
+ })))
+ .mount(&local)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/token"))
+ .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
+ "error": "authorization_pending"
+ })))
+ .mount(&local)
+ .await;
+ let loopback = OidcDiscovery {
+ device_authorization_endpoint: format!("{}/device", local.uri()),
+ token_endpoint: format!("{}/token", local.uri()),
+ };
+ request_device_code(
+ &reqwest::Client::new(),
+ &loopback,
+ "client",
+ OIDC_DEFAULT_SCOPE,
+ )
+ .await
+ .expect("loopback device endpoint remains supported");
+ assert!(matches!(
+ poll_token_once(&reqwest::Client::new(), &loopback, "client", "device-code")
+ .await
+ .unwrap(),
+ PollOutcome::Pending
+ ));
+ }
+
#[tokio::test]
async fn refresh_refuses_a_persisted_plain_http_remote_endpoint() {
let mut token = sample();
diff --git a/crates/ai-memory-llm/src/openai_oauth.rs b/crates/ai-memory-llm/src/openai_oauth.rs
index a26e7670..416c516c 100644
--- a/crates/ai-memory-llm/src/openai_oauth.rs
+++ b/crates/ai-memory-llm/src/openai_oauth.rs
@@ -20,7 +20,7 @@ use crate::codex_responses::{CodexResponsesAuth, post_codex_responses};
use crate::error::{LlmError, LlmResult};
use crate::openai::{STRUCTURED_OUTPUT_SCHEMA_NAME, enforce_strict_object_schemas};
use crate::provider::LlmProvider;
-use crate::stored_token::{StoredOAuthToken, refresh_grant};
+use crate::stored_token::{StoredOAuthToken, credential_endpoint, refresh_grant};
use crate::text::truncate_with_ellipsis;
use crate::types::{ChatRequest, ChatResponse, ExtraHeaders, ReasoningEffort, Usage};
@@ -270,9 +270,11 @@ async fn refresh_access_token(
client: &reqwest::Client,
current: &OpenAiOAuthToken,
) -> LlmResult<OpenAiOAuthToken> {
+ let token_endpoint =
+ credential_endpoint("OpenAI OAuth token endpoint", OPENAI_OAUTH_TOKEN_URL)?;
let token_response = refresh_grant::<OpenAiOAuthTokenResponse>(
client,
- OPENAI_OAUTH_TOKEN_URL,
+ &token_endpoint,
current.refresh.expose_secret(),
CODEX_CLIENT_ID,
"openai-oauth refresh failed",
diff --git a/crates/ai-memory-llm/src/stored_token.rs b/crates/ai-memory-llm/src/stored_token.rs
index 41f95853..8b097702 100644
--- a/crates/ai-memory-llm/src/stored_token.rs
+++ b/crates/ai-memory-llm/src/stored_token.rs
@@ -16,6 +16,41 @@ use crate::auth_file::{load_entry, now_ms, save_entry};
use crate::error::{LlmError, LlmResult};
use crate::response::{provider_error_body, response_json_limited};
+/// A credential-bearing HTTP endpoint validated as TLS-protected, except for
+/// explicit loopback development servers. Keeping the parsed URL behind this
+/// type prevents a new grant caller from reaching the request sink with an
+/// unchecked string.
+pub(crate) struct CredentialEndpoint(reqwest::Url);
+
+impl CredentialEndpoint {
+ pub(crate) fn as_url(&self) -> &reqwest::Url {
+ &self.0
+ }
+}
+
+pub(crate) fn credential_endpoint(context: &str, url: &str) -> LlmResult<CredentialEndpoint> {
+ let parsed = reqwest::Url::parse(url)
+ .map_err(|e| LlmError::Auth(format!("{context} {url:?} is not a valid URL: {e}")))?;
+ let loopback = parsed.host_str().is_some_and(|host| {
+ let host = host
+ .strip_prefix('[')
+ .and_then(|host| host.strip_suffix(']'))
+ .unwrap_or(host);
+ host.eq_ignore_ascii_case("localhost")
+ || host
+ .parse::<std::net::IpAddr>()
+ .is_ok_and(|ip| ip.is_loopback())
+ });
+ match parsed.scheme() {
+ "https" => Ok(CredentialEndpoint(parsed)),
+ "http" if loopback => Ok(CredentialEndpoint(parsed)),
+ _ => Err(LlmError::Auth(format!(
+ "{context} {url:?} must use https (plain http is accepted only on \
+ localhost, 127.0.0.1 or ::1)"
+ ))),
+ }
+}
+
/// Refresh once the access token is within this margin of expiry.
const REFRESH_MARGIN_MS: u64 = 60_000;
@@ -116,7 +151,7 @@ impl<E> StoredOAuthToken<E> {
/// failed" and the matching re-login hint).
pub(crate) async fn refresh_grant<T>(
client: &reqwest::Client,
- token_endpoint: &str,
+ token_endpoint: &CredentialEndpoint,
refresh_token: &str,
client_id: &str,
failure_label: &str,
@@ -126,7 +161,7 @@ where
T: DeserializeOwned,
{
let resp = client
- .post(token_endpoint)
+ .post(token_endpoint.as_url().clone())
// Bounded here because callers hand us their shared client, whose
// global timeout was removed in favour of per-request timeouts —
// a token exchange is quick, so the default ceiling is plenty.
@@ -185,6 +220,7 @@ mod tests {
#[tokio::test]
async fn refresh_grant_parses_success_body() {
let endpoint = serve_once("200 OK", r#"{"access_token":"fresh-access"}"#).await;
+ let endpoint = credential_endpoint("test token endpoint", &endpoint).unwrap();
let client = reqwest::Client::new();
let parsed = refresh_grant::<TestResponse>(
@@ -204,6 +240,7 @@ mod tests {
#[tokio::test]
async fn refresh_grant_surfaces_status_body_and_relogin_hint() {
let endpoint = serve_once("401 Unauthorized", r#"{"error":"invalid_grant"}"#).await;
+ let endpoint = credential_endpoint("test token endpoint", &endpoint).unwrap();
let client = reqwest::Client::new();
let err = refresh_grant::<TestResponse>(
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index e8b7008d..407ed55a 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -98,7 +98,7 @@ means the boundary is not built yet.
| 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |
| 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install, except that a request carrying any proxy forwarding header (`Forwarded`, `X-Forwarded-For`/`-Host`/`-Proto`/`-Server`/`-Port`, `X-Original-Forwarded-For`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`; `PROXY_HEADERS`) counts as non-loopback, since a plain-HTTP proxy can rewrite `Host` to loopback while the browser behind it sent no fetch metadata. No first-party client sends those headers. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment Every `/web` surface (built-in pages including `/web/pending`, the login page, a custom SPA and `/api/v1`) answers `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` (`ai-memory-web/src/mount.rs` `deny_framing`), because a framed page's own Approve/Reject `fetch()` is same-origin and the guard rightly lets it through | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one; then a `127.0.0.1` fetch carrying each proxy forwarding header and no marker → 403 with the baton still open, and the same fetch with the marker claims it. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` (incl. a loopback `Host` with each proxy header, refused without the marker and admitted with it, and a named row per header so none can drop out of the list) and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg); `ai-memory-web/src/mount.rs` `web_surfaces_refuse_to_be_framed` (`/web`, `/web/pending`, `/web/login`, `/api/v1/projects` all carry both headers; bites with `deny_framing` neutralized) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; with the proxy-header rule disabled, the proxied loopback e2e fetch claims the baton and the unit decision test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. A plain-HTTP proxy that rewrites `Host` to its loopback upstream and adds no forwarding header (nginx's default `proxy_pass`) looks exactly like a local client, so in front of an unauthenticated server it must add `X-Forwarded-For` or keep `proxy_set_header Host $host`, or the server must sit behind TLS or use a bearer token (`security.md`, `https-via-proxy.md`). Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op |
| 12d | The web UI and `/api/v1` cannot write, and render stored text inert | `crates/ai-memory-web/clippy.toml` `disallowed-methods`: every `Wiki` write and destructive method (`write_page`, `write_page_if`, `apply_batch`, the delete/evict/purge/restore/move/reindex/remove-dir helpers, `commit_all`, `approve_auto_improve_proposal`) and the `writer()` / `git()` accessors are lint errors in the crate, so the `Wiki` held by `WebState` stays read-only under `cargo clippy -D warnings`; only the integration-test module carries the `allow`, for fixtures. Templates are askama with HTML auto-escaping; the history diff (`templates/history.html`) and the session timeline (`templates/session.html`) print page lines, observation titles and bodies escaped, with no `|safe`, and no captured value is interpolated into a script | `ai-memory-web` `history_replay.rs` `session_timeline_renders_captured_markup_inert` (a `<script>` title and body plus `"><img onerror>` and `' onmouseover='` payloads, checked to survive ingest first, render escaped) and `history_diff_renders_page_markup_inert` (the same payloads in a page version's diff lines); `mount.rs` `web_surfaces_refuse_to_be_framed` covers the history, timeline and history-API routes (200 with both anti-framing headers) | STRONG. Bite checks: a `Wiki::write_page` and a `Wiki::delete_page` call added to `routes/history.rs` fail `cargo clippy -p ai-memory-web --all-targets -- -D warnings` with `use of a disallowed method`; `|safe` on the observation body or a diff line fails the matching inert-render test. The lint is per crate: a write reached through another crate's helper is outside it, which review and the `/api/v1` "zero writer calls" rule still cover |
-| 12e | OIDC device login and refresh never send credential-bearing requests in clear text off loopback or through redirects | `ai-memory-llm/src/oidc.rs` `discover` checks the issuer with `require_tls` before fetching discovery, then the advertised `device_authorization_endpoint` and `token_endpoint`; `refresh_access_token` revalidates the persisted token endpoint and builds a no-redirect client; `ai-memory-cli/src/commands/auth.rs` builds every authentication-flow client with redirects disabled. `https` passes, plain `http` passes only for `localhost`, `127.0.0.1`/`127.0.0.0/8` and `::1`, anything else is an `LlmError::Auth` | `oidc.rs` `discover_refuses_plain_http_issuer_before_any_request` (remote `http` issuer refused with no request reaching the mock), `discover_refuses_plain_http_endpoints_from_the_document` (an `http` token or device endpoint in the document refused), `refresh_refuses_a_persisted_plain_http_remote_endpoint`, `refresh_does_not_forward_the_refresh_token_through_redirects`, `require_tls_accepts_https_and_loopback_http_only` (table incl. `localhost.example.com`); CLI `auth_client_never_forwards_credentials_through_redirects`; legitimate control `discover_accepts_a_loopback_issuer_and_endpoints` | STRONG |
+| 12e | OIDC device login and refresh never send credential-bearing requests in clear text off loopback or through redirects | `ai-memory-llm/src/stored_token.rs` `CredentialEndpoint` / `credential_endpoint` make TLS-or-loopback validation a typed prerequisite of the shared refresh-grant POST; `oidc.rs` `discover`, `request_device_code`, `poll_token_once` and `refresh_access_token` validate again at every request sink so a caller-mutated discovery or persisted endpoint cannot bypass login-time checks; refresh builds a no-redirect client; `ai-memory-cli/src/commands/auth.rs` builds every authentication-flow client with redirects disabled. `https` passes, plain `http` passes only for `localhost`, `127.0.0.1`/`127.0.0.0/8` and `::1`, anything else is an `LlmError::Auth` | `oidc.rs` `discover_refuses_plain_http_issuer_before_any_request` (remote `http` issuer refused with no request reaching the mock), `discover_refuses_plain_http_endpoints_from_the_document` (an `http` token or device endpoint in the document refused), `credential_sinks_revalidate_mutated_discovery_endpoints` (both device and poll sinks refuse caller-mutated remote HTTP, with loopback controls), `refresh_refuses_a_persisted_plain_http_remote_endpoint`, `refresh_does_not_forward_the_refresh_token_through_redirects`, `require_tls_accepts_https_and_loopback_http_only` (table incl. `localhost.example.com`); CLI `auth_client_never_forwards_credentials_through_redirects`; legitimate control `discover_accepts_a_loopback_issuer_and_endpoints` | STRONG |
| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_continued_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050), and to a `/clear`ed session only when that session's own transcript records the `/clear` command and names the run's session as its launch `session_id` from this checkout or below it; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_continued_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `transcript.rs` `claude_continued_session_follows_only_this_launchs_clear` (an uncleared transcript, a quoted `/clear`, another checkout's clear, a concurrent launch's clear, a subagent file, and a pre-run clear refused; own clear and the newest of two as controls); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`, `a_claude_run_that_was_cleared_follows_the_new_session`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet |
| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |