Skip to content

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

Rust

fix(cli,llm): redact auth.json values, warn on unusable proxy vars

lhzapatae49989ca0952
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6609cfa4..0cc6bd92 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,32 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
+### Security
+- A malformed OAuth entry in `auth.json` no longer prints the stored value in
+ its error. When a field held a value of the wrong type, such as a token
+ written into `expires` by a hand edit or a provisioning script, the parse
+ error quoted the token, and from there it reached terminals, CI logs and
+ captured hook output. The error now names the type it found with the value
+ replaced by `<redacted>`.
+ ([#1565](https://github.com/akitaonrails/ai-memory/pull/1565))
+
+### Fixed
+- Every command except `hook` and `mcp-bridge` now warns, naming the variable
+ but not its value, when `HTTPS_PROXY`, `HTTP_PROXY` or `ALL_PROXY` (or a
+ lower-case spelling) is set to something the HTTP client cannot use: bytes
+ that are not UTF-8, such as a Latin-1 password, a URI with an unencoded
+ space or non-ASCII character, or an unsupported scheme. The client skips
+ such a value and connects directly, so provider and login requests used to
+ time out on a network that blocks direct egress, or bypass a required proxy
+ where it does not, with nothing pointing at the proxy setting.
+ ([#1565](https://github.com/akitaonrails/ai-memory/pull/1565))
+- `init`, `auth` and `auth enable` print paths on Windows without the `\\?\`
+ verbatim prefix of the canonical data dir, in their output and their errors,
+ as the hook and service commands already did, and so does the
+ `ai-memory starting` line every command logs. A path copied from those
+ messages now works in `cmd` and in scripts that look for it.
+ ([#1565](https://github.com/akitaonrails/ai-memory/pull/1565))
+
## [3.2.0] - 2026-10-21
### Added
diff --git a/Cargo.lock b/Cargo.lock
index 41885307..b8272aac 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -55,6 +55,7 @@ dependencies = [
"figment",
"flate2",
"fs2",
+ "http",
"jiff",
"jsonc-parser",
"libc",
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index 41a4c964..d4899e4a 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -53,6 +53,7 @@ dirs.workspace = true
figment.workspace = true
flate2.workspace = true
fs2.workspace = true
+http.workspace = true
libc.workspace = true
# `transport-streamable-http-client-reqwest` pulls reqwest in with no TLS backend
# (`__reqwest = ["dep:reqwest"]` and nothing more), so the bridge could not reach an
diff --git a/crates/ai-memory-cli/src/commands/auth.rs b/crates/ai-memory-cli/src/commands/auth.rs
index 5febfaf1..2367b1b1 100644
--- a/crates/ai-memory-cli/src/commands/auth.rs
+++ b/crates/ai-memory-cli/src/commands/auth.rs
@@ -16,6 +16,7 @@ use serde::{Deserialize, Serialize};
use tokio::time::sleep;
use crate::cli::{AuthArgs, AuthCommand, AuthProviderChoice};
+use crate::commands::path_util::display_path;
use crate::config::Config;
const DEVICE_USER_CODE_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/usercode";
@@ -108,7 +109,7 @@ async fn login_oidc_device(
println!("oidc-device: logged in");
println!("issuer: {issuer}");
- println!("token file: {}", path.display());
+ println!("token file: {}", display_path(&path));
Ok(())
}
@@ -149,7 +150,7 @@ fn logout_oidc_device(config: &Config) -> Result<()> {
let path = config.oidc_device_token_path();
OidcToken::remove(&path).map_err(anyhow::Error::from)?;
println!("oidc-device: logged out");
- println!("token file: {}", path.display());
+ println!("token file: {}", display_path(&path));
Ok(())
}
@@ -180,7 +181,7 @@ async fn login_openai_oauth(config: &Config, timeout_secs: u64) -> Result<()> {
if let Some(account_id) = token.extra.account_id.as_deref() {
println!("account: {account_id}");
}
- println!("token file: {}", path.display());
+ println!("token file: {}", display_path(&path));
Ok(())
}
@@ -188,7 +189,7 @@ fn logout_openai_oauth(config: &Config) -> Result<()> {
let path = config.openai_oauth_token_path();
OpenAiOAuthToken::remove(&path).map_err(anyhow::Error::from)?;
println!("openai-oauth: logged out");
- println!("token file: {}", path.display());
+ println!("token file: {}", display_path(&path));
Ok(())
}
@@ -216,7 +217,7 @@ async fn login_copilot(
let path = config.copilot_token_path();
token.save(&path).map_err(anyhow::Error::from)?;
println!("copilot: logged in");
- println!("token file: {}", path.display());
+ println!("token file: {}", display_path(&path));
Ok(())
}
@@ -224,7 +225,7 @@ fn logout_copilot(config: &Config) -> Result<()> {
let path = config.copilot_token_path();
CopilotToken::remove(&path).map_err(anyhow::Error::from)?;
println!("copilot: logged out");
- println!("token file: {}", path.display());
+ println!("token file: {}", display_path(&path));
Ok(())
}
@@ -237,11 +238,11 @@ fn status(config: &Config) -> Result<()> {
println!("account: {account_id}");
}
println!("expires in: {}", format_duration_until(token.expires_at_ms));
- println!("token file: {}", openai_path.display());
+ println!("token file: {}", display_path(&openai_path));
}
None => {
println!("openai-oauth: not logged in");
- println!("token file: {}", openai_path.display());
+ println!("token file: {}", display_path(&openai_path));
}
}
@@ -274,11 +275,11 @@ fn status(config: &Config) -> Result<()> {
if let Some(api_base_url) = token.api_base_url.as_deref() {
println!("api base: {api_base_url}");
}
- println!("token file: {}", copilot_path.display());
+ println!("token file: {}", display_path(&copilot_path));
}
None => {
println!("copilot: not logged in");
- println!("token file: {}", copilot_path.display());
+ println!("token file: {}", display_path(&copilot_path));
}
}
@@ -288,11 +289,11 @@ fn status(config: &Config) -> Result<()> {
println!("oidc-device: logged in");
println!("issuer: {}", token.extra.issuer);
println!("expires in: {}", format_duration_until(token.expires_at_ms));
- println!("token file: {}", oidc_path.display());
+ println!("token file: {}", display_path(&oidc_path));
}
None => {
println!("oidc-device: not logged in");
- println!("token file: {}", oidc_path.display());
+ println!("token file: {}", display_path(&oidc_path));
}
}
Ok(())
diff --git a/crates/ai-memory-cli/src/commands/auth_enable.rs b/crates/ai-memory-cli/src/commands/auth_enable.rs
index 30c48097..c478551b 100644
--- a/crates/ai-memory-cli/src/commands/auth_enable.rs
+++ b/crates/ai-memory-cli/src/commands/auth_enable.rs
@@ -24,6 +24,7 @@ use anyhow::{Context as _, Result, bail};
use crate::cli::{AuthEnableArgs, InstallMcpArgs, McpClient, SchemaFlavor};
use crate::commands::install_mcp::{self, mcp_server_url_from_base};
+use crate::commands::path_util::display_path;
use crate::config::Config;
use crate::local_auth::{self, HookCredential};
use crate::server_profiles::{self, ProfileName};
@@ -164,19 +165,19 @@ fn record_token_file(config_path: &Path) -> Result<bool> {
Ok(text) => Some(text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => {
- return Err(e).with_context(|| format!("reading {}", config_path.display()));
+ return Err(e).with_context(|| format!("reading {}", display_path(config_path)));
}
};
let mut doc: toml_edit::DocumentMut = existing
.as_deref()
.unwrap_or_default()
.parse()
- .with_context(|| format!("parsing {}", config_path.display()))?;
+ .with_context(|| format!("parsing {}", display_path(config_path)))?;
let auth = doc
.entry("auth")
.or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()))
.as_table_like_mut()
- .with_context(|| format!("`auth` in {} is not a table", config_path.display()))?;
+ .with_context(|| format!("`auth` in {} is not a table", display_path(config_path)))?;
if auth.get("bearer_token_file").is_some() {
return Ok(false);
}
@@ -194,17 +195,17 @@ fn record_token_file(config_path: &Path) -> Result<bool> {
};
if let Some(parent) = config_path.parent() {
crate::commands::path_util::create_private_dir(parent)
- .with_context(|| format!("creating {}", parent.display()))?;
+ .with_context(|| format!("creating {}", display_path(parent)))?;
}
// The atomic write's temp file is owner-only; an existing config keeps
// the mode it had (a packaged one may be group-readable on purpose).
ai_memory_wiki::write_atomic(config_path, doc.to_string().as_bytes())
- .with_context(|| format!("writing {}", config_path.display()))?;
+ .with_context(|| format!("writing {}", display_path(config_path)))?;
#[cfg(unix)]
if let Some(mode) = mode {
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(config_path, std::fs::Permissions::from_mode(mode))
- .with_context(|| format!("restoring the mode of {}", config_path.display()))?;
+ .with_context(|| format!("restoring the mode of {}", display_path(config_path)))?;
}
Ok(true)
}
@@ -311,7 +312,7 @@ fn print_outcome(outcome: &EnableOutcome) {
} else {
"kept"
},
- outcome.token_path.display()
+ display_path(&outcome.token_path)
);
println!(
"config: {} {}",
@@ -320,7 +321,7 @@ fn print_outcome(outcome: &EnableOutcome) {
} else {
"already names the token file:"
},
- outcome.config_path.display()
+ display_path(&outcome.config_path)
);
match outcome.hooks {
Some(HookCredential::Seeded) => {
@@ -338,7 +339,7 @@ fn print_outcome(outcome: &EnableOutcome) {
match &line.wiring {
Wiring::Rewired => println!(
"mcp {client}: re-registered in {} so it reads the token without holding it",
- line.path.display()
+ display_path(&line.path)
),
Wiring::OtherServer(url) => {
println!("mcp {client}: targets {url}, another server; left unchanged");
diff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rs
index e0067347..9fc4cb00 100644
--- a/crates/ai-memory-cli/src/commands/init.rs
+++ b/crates/ai-memory-cli/src/commands/init.rs
@@ -9,6 +9,7 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use crate::cli::InitArgs;
+use crate::commands::path_util::display_path;
use crate::config::Config;
use ai_memory_mcp::auth::generate_token_hex;
@@ -107,7 +108,7 @@ fn root_bearer_for_new_config(config: &Config, fresh: bool) -> Result<Option<Rec
println!(
"Generated a root bearer token in {} (owner-only). The server requires it on every \
route but /healthz; hooks, the CLI and `ai-memory mcp-bridge` read it from there.",
- minted.path.display()
+ display_path(&minted.path)
);
Ok(Some(RecordedBearer {
raw: crate::server_profiles::ROOT_TOKEN_RELATIVE.to_owned(),
@@ -169,12 +170,13 @@ pub(crate) fn initialize(
// way it did.
let fresh = !cfg_path.exists() && !root.join("db").join(ai_memory_store::DB_FILENAME).exists();
create_private_dir_all(root)
- .with_context(|| format!("creating data root {}", root.display()))?;
+ .with_context(|| format!("creating data root {}", display_path(root)))?;
for sub in SUBDIRS {
let path = root.join(sub);
- create_private_dir_all(&path).with_context(|| format!("creating {}", path.display()))?;
- tracing::info!(path = %path.display(), "ensured directory");
+ create_private_dir_all(&path)
+ .with_context(|| format!("creating {}", display_path(&path)))?;
+ tracing::info!(path = %display_path(&path), "ensured directory");
}
let mut outcome = InitOutcome {
@@ -184,13 +186,13 @@ pub(crate) fn initialize(
};
if cfg_path.exists() && !args.force {
tracing::info!(
- path = %cfg_path.display(),
+ path = %display_path(&cfg_path),
"config already exists; leaving untouched (pass --force to overwrite)",
);
} else {
if let Some(parent) = cfg_path.parent() {
create_private_dir_all(parent)
- .with_context(|| format!("creating config dir {}", parent.display()))?;
+ .with_context(|| format!("creating config dir {}", display_path(parent)))?;
}
// Pepper is generated NOW (not at first server start) so it's
// stable from install onwards: see comment in render_default_
@@ -211,10 +213,10 @@ pub(crate) fn initialize(
bearer_line
);
let mut f = private_config_file(&cfg_path, args.force)
- .with_context(|| format!("creating {}", cfg_path.display()))?;
+ .with_context(|| format!("creating {}", display_path(&cfg_path)))?;
f.write_all(body.as_bytes())
- .with_context(|| format!("writing {}", cfg_path.display()))?;
- tracing::info!(path = %cfg_path.display(), "wrote default config");
+ .with_context(|| format!("writing {}", display_path(&cfg_path)))?;
+ tracing::info!(path = %display_path(&cfg_path), "wrote default config");
outcome.config_written = true;
}
diff --git a/crates/ai-memory-cli/src/commands/path_util.rs b/crates/ai-memory-cli/src/commands/path_util.rs
index 85537049..647b291b 100644
--- a/crates/ai-memory-cli/src/commands/path_util.rs
+++ b/crates/ai-memory-cli/src/commands/path_util.rs
@@ -88,6 +88,13 @@ pub(crate) fn claude_config_paths(
paths
}
+/// `path` as shown to the operator: without a safe `\\?\` verbatim prefix,
+/// which the canonical data dir carries on Windows and which `cmd` and most
+/// scripts cannot use when the path is copied out of a message.
+pub(crate) fn display_path(path: &Path) -> String {
+ strip_windows_verbatim_prefix(&path.to_string_lossy()).into_owned()
+}
+
/// Strip only Windows verbatim path prefixes that are safe to render as plain
/// paths. Unknown verbatim forms are left unchanged.
pub(crate) fn strip_windows_verbatim_prefix(path: &str) -> Cow<'_, str> {
@@ -161,6 +168,24 @@ mod tests {
);
}
+ #[test]
+ fn display_path_drops_the_verbatim_prefix() {
+ assert_eq!(
+ display_path(Path::new(
+ r"\\?\C:\Users\me\AppData\Local\ai-memory\auth.json"
+ )),
+ r"C:\Users\me\AppData\Local\ai-memory\auth.json"
+ );
+ assert_eq!(
+ display_path(Path::new(r"\\?\UNC\server\share\ai-memory")),
+ r"\\server\share\ai-memory"
+ );
+ assert_eq!(
+ display_path(Path::new("/home/alice/.local/share/ai-memory")),
+ "/home/alice/.local/share/ai-memory"
+ );
+ }
+
#[test]
fn strip_windows_verbatim_prefix_handles_drive_paths() {
assert_eq!(
diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rs
index 1af674c3..ba09fe26 100644
--- a/crates/ai-memory-cli/src/lib.rs
+++ b/crates/ai-memory-cli/src/lib.rs
@@ -28,6 +28,7 @@ mod local_auth;
mod logging;
mod marker;
mod process_guard;
+mod proxy_env;
mod server_profiles;
mod terminal;
@@ -81,10 +82,15 @@ pub async fn run() -> Result<()> {
info!(
version = env!("CARGO_PKG_VERSION"),
server_url = %config.server_url,
- data_dir = %config.data_dir.display(),
+ data_dir = %commands::path_util::display_path(&config.data_dir),
bind = %config.bind,
"ai-memory starting",
);
+ // The bridge only talks to the local server with proxies disabled, and an
+ // MCP client would surface the warning on every session start.
+ if !matches!(command, Command::McpBridge(_)) {
+ proxy_env::warn_unusable(&config.runtime_env);
+ }
match command {
Command::Init(args) => commands::init::run(&config, args, config_path.as_deref()),
diff --git a/crates/ai-memory-cli/src/proxy_env.rs b/crates/ai-memory-cli/src/proxy_env.rs
new file mode 100644
index 00000000..8f80462e
--- /dev/null
+++ b/crates/ai-memory-cli/src/proxy_env.rs
@@ -0,0 +1,128 @@
+//! Startup warning for proxy variables the HTTP client cannot use.
+//!
+//! reqwest reads `HTTPS_PROXY` and its siblings through hyper-util, which
+//! skips a value that is not UTF-8 or does not parse as a URI and carries on
+//! without a proxy. Provider, OIDC and upgrade requests then go out directly:
+//! a timeout on a network that blocks direct egress, or traffic that bypasses
+//! a required proxy on one that does not. The checks below mirror
+//! hyper-util 0.1's acceptance rules (`parse_env_uri`) so the operator hears
+//! about it; the value itself is never logged, since it often carries a
+//! password.
+
+use std::ffi::OsStr;
+
+use crate::config::RuntimeEnv;
+
+/// Variables hyper-util consults, in its lookup order.
+const PROXY_VARS: [&str; 6] = [
+ "ALL_PROXY",
+ "all_proxy",
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+];
+
+/// Log one warning per proxy variable that is set but unusable.
+pub(crate) fn warn_unusable(env: &RuntimeEnv) {
+ for (name, reason) in unusable(|name| env.var_os(name)) {
+ tracing::warn!(
+ variable = name,
+ "{name} {reason}, so the HTTP client ignores it and connects without that proxy"
+ );
+ }
+}
+
+fn unusable(
+ lookup: impl Fn(&str) -> Option<std::ffi::OsString>,
+) -> Vec<(&'static str, &'static str)> {
+ PROXY_VARS
+ .iter()
+ // Windows matches variable names case-insensitively, so the lower-case
+ // spelling is the same variable there.
+ .filter(|name| !(cfg!(windows) && name.bytes().any(|b| b.is_ascii_lowercase())))
+ .filter_map(|&name| Some((name, problem(&lookup(name)?)?)))
+ .collect()
+}
+
+fn problem(value: &OsStr) -> Option<&'static str> {
+ let Some(text) = value.to_str() else {
+ return Some("is not valid UTF-8");
+ };
+ // hyper-util treats an empty value as unset, and so does every shell user.
+ if text.is_empty() {
+ return None;
+ }
+ let Ok(uri) = text.parse::<http::Uri>() else {
+ return Some(
+ "is not a valid URI (percent-encode spaces and non-ASCII characters in \
+ the user name and password)",
+ );
+ };
+ match uri.scheme_str() {
+ None | Some("http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h") => {}
+ Some(_) => return Some("uses an unsupported proxy scheme"),
+ }
+ if uri.authority().is_none() {
+ return Some("names no proxy host");
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use std::ffi::OsString;
+
+ use super::*;
+
+ fn only(name: &'static str, value: OsString) -> impl Fn(&str) -> Option<OsString> {
+ move |asked| (asked == name).then(|| value.clone())
+ }
+
+ #[test]
+ fn usable_values_raise_no_warning() {
+ for value in [
+ "http://proxy.example:3128",
+ "http://user:p%C3%[email protected]:3128",
+ "https://proxy.example",
+ "proxy.example:3128",
+ "socks5h://127.0.0.1:1080",
+ "",
+ ] {
+ assert!(
+ unusable(only("HTTPS_PROXY", value.into())).is_empty(),
+ "{value:?} was reported as unusable"
+ );
+ }
+ }
+
+ #[test]
+ fn values_the_client_skips_are_reported_by_name() {
+ for value in [
+ "http://user:p\u{e7}[email protected]:3128",
+ "http://user:p [email protected]:3128",
+ " http://proxy.example:3128",
+ "ftp://proxy.example:21",
+ ] {
+ let found = unusable(only("HTTPS_PROXY", value.into()));
+ assert_eq!(found.len(), 1, "{value:?} was not reported");
+ assert_eq!(found[0].0, "HTTPS_PROXY");
+ }
+ }
+
+ /// A Latin-1 password byte (`ç` is 0xE7) makes the whole value non-UTF-8.
+ #[cfg(unix)]
+ #[test]
+ fn a_non_utf8_value_is_reported_without_its_bytes() {
+ use std::os::unix::ffi::OsStringExt as _;
+ let value = OsString::from_vec(b"http://user:a\xe7\[email protected]:3128".to_vec());
+ let found = unusable(only("http_proxy", value));
+ assert_eq!(found, vec![("http_proxy", "is not valid UTF-8")]);
+ assert!(!found[0].1.contains("proxy.example"));
+ }
+
+ #[test]
+ fn unset_variables_raise_no_warning() {
+ assert!(unusable(|_| None).is_empty());
+ }
+}
diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rs
index 6a7b98df..98329219 100644
--- a/crates/ai-memory-cli/tests/suite/main.rs
+++ b/crates/ai-memory-cli/tests/suite/main.rs
@@ -43,6 +43,7 @@ mod service_host_windows;
mod setup_e2e;
mod shutdown_signals;
mod upgrade_e2e;
+mod windows_plain_paths;
mod workstream_provenance;
mod yolo_ai_jail;
diff --git a/crates/ai-memory-cli/tests/suite/windows_plain_paths.rs b/crates/ai-memory-cli/tests/suite/windows_plain_paths.rs
new file mode 100644
index 00000000..cbb87652
--- /dev/null
+++ b/crates/ai-memory-cli/tests/suite/windows_plain_paths.rs
@@ -0,0 +1,63 @@
+//! On Windows the canonical data dir carries a `\\?\` verbatim prefix. `init`
+//! and `auth` print paths under it in their output and errors, and an operator
+//! copies them from there into `cmd` or a script, which cannot use that form.
+
+#![cfg(windows)]
+
+use std::process::Output;
+
+use crate::e2e_support::hermetic;
+
+const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");
+
+fn run(data_dir: &std::path::Path, args: &[&str]) -> (Output, String) {
+ let out = hermetic(BIN)
+ .arg("--data-dir")
+ .arg(data_dir)
+ .args(args)
+ .output()
+ .unwrap();
+ let text = format!(
+ "{}{}",
+ String::from_utf8_lossy(&out.stdout),
+ String::from_utf8_lossy(&out.stderr)
+ );
+ (out, text)
+}
+
+#[test]
+fn init_and_auth_status_print_plain_paths() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("data");
+ for args in [&["init"][..], &["auth", "status"]] {
+ let (out, text) = run(&data_dir, args);
+ assert!(out.status.success(), "{args:?} failed:\n{text}");
+ assert!(text.contains(r":\"), "{args:?} printed no path:\n{text}");
+ assert!(
+ !text.contains(r"\\?\"),
+ "{args:?} printed a verbatim path:\n{text}"
+ );
+ }
+}
+
+#[test]
+fn init_error_names_a_plain_path() {
+ let tmp = tempfile::tempdir().unwrap();
+ // A file where the data dir's parent should be: the parent canonicalises,
+ // so the data dir keeps the prefix, and creating it fails.
+ let blocker = tmp.path().join("not-a-dir");
+ std::fs::write(&blocker, b"").unwrap();
+ let (out, text) = run(&blocker.join("data"), &["init"]);
+ assert!(
+ !out.status.success(),
+ "init succeeded under a file:\n{text}"
+ );
+ assert!(
+ text.contains("creating data root"),
+ "unexpected error:\n{text}"
+ );
+ assert!(
+ !text.contains(r"\\?\"),
+ "init error printed a verbatim path:\n{text}"
+ );
+}
diff --git a/crates/ai-memory-llm/src/auth_file.rs b/crates/ai-memory-llm/src/auth_file.rs
index ff3fc850..40d46677 100644
--- a/crates/ai-memory-llm/src/auth_file.rs
+++ b/crates/ai-memory-llm/src/auth_file.rs
@@ -24,9 +24,32 @@ where
if entry.get("type").and_then(serde_json::Value::as_str) != Some("oauth") {
return Ok(None);
}
- serde_json::from_value::<T>(entry)
+ serde_json::from_value::<T>(entry.clone())
.map(Some)
- .map_err(|e| LlmError::Auth(format!("parse {key} auth entry: {e}")))
+ .map_err(|_| {
+ // serde quotes the offending value, and a value in the wrong field
+ // of this file is usually a token. Describe the error from a copy
+ // with every string blanked so the message never carries one.
+ let detail = serde_json::from_value::<T>(redact_strings(entry)).map_or_else(
+ |e| e.to_string(),
+ |_| "entry does not match the expected shape".to_owned(),
+ );
+ LlmError::Auth(format!("parse {key} auth entry: {detail}"))
+ })
+}
+
+fn redact_strings(value: serde_json::Value) -> serde_json::Value {
+ use serde_json::Value;
+ match value {
+ Value::String(_) => Value::String("<redacted>".to_owned()),
+ Value::Array(items) => Value::Array(items.into_iter().map(redact_strings).collect()),
+ Value::Object(map) => Value::Object(
+ map.into_iter()
+ .map(|(field, value)| (field, redact_strings(value)))
+ .collect(),
+ ),
+ other => other,
+ }
}
pub(crate) fn save_entry<T>(path: &Path, key: &str, entry: Option<T>) -> LlmResult<()>
@@ -218,6 +241,55 @@ mod tests {
);
}
+ /// A token written into a field of the wrong type (here `expires`, by a
+ /// hand edit or a provisioning script) must not come back in the error,
+ /// which reaches terminals, CI logs and captured hook output.
+ #[test]
+ fn wrong_type_error_does_not_echo_the_stored_value() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("auth.json");
+ let secret = "sk-leak-0123456789abcdef";
+ std::fs::write(
+ &path,
+ serde_json::to_vec_pretty(&serde_json::json!({
+ "test": { "type": "oauth", "access": "a", "refresh": "r", "expires": secret }
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ let err = load_entry::<TestEntry>(&path, "test").unwrap_err();
+ let LlmError::Auth(msg) = err else {
+ panic!("unexpected error: {err}");
+ };
+ assert!(
+ !msg.contains(secret),
+ "auth entry error leaked the value: {msg}"
+ );
+ assert!(
+ msg.contains("parse test auth entry") && msg.contains("invalid type: string"),
+ "the error must still say what is wrong: {msg}"
+ );
+ }
+
+ #[test]
+ fn missing_field_error_still_names_the_field() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("auth.json");
+ std::fs::write(
+ &path,
+ serde_json::to_vec_pretty(&serde_json::json!({
+ "test": { "type": "oauth", "access": "a", "expires": 1 }
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ let err = load_entry::<TestEntry>(&path, "test").unwrap_err();
+ assert!(
+ matches!(err, LlmError::Auth(ref msg) if msg.contains("missing field `refresh`")),
+ "unexpected error: {err}"
+ );
+ }
+
#[test]
fn save_preserves_sibling_keys() {
let dir = tempfile::tempdir().unwrap();
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 2d435ee8..a35369ef 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -75,6 +75,7 @@ means the boundary is not built yet.
| 7d | The Cursor Agent CLI child, which reads captured session text, never sees the server's own credentials | `ai-memory-llm/src/cursor_agent.rs` `complete_text` spawns `agent` with `env_clear()` plus `CursorAuth::child_env`, which `CursorAuth::new` filters through `cursor_child_env` (an allowlist of `PATH`/`HOME`/user, locale, temp/XDG, session bus, proxy/CA and Windows basics, plus `LC_*`/`CURSOR_*`); the environment and the workspace root are captured once by `ai-memory-cli/src/config.rs` `Config::cursor_auth`, so the provider reads no environment itself; a relative workspace root is refused | `cursor_provider.rs` `the_child_gets_only_the_allowlisted_environment` (`AI_MEMORY_AUTH_TOKEN` and `OPENAI_API_KEY` canaries and the test process's own `CARGO_*` variables never reach the child; control: `PATH`, `HOME` and `CURSOR_API_KEY` do, and the workspace sits under the injected root; bite-checked by dropping `env_clear()`), `a_relative_workspace_root_is_refused`; `config.rs` `cursor_provider_hands_the_child_only_allowlisted_env` | STRONG |
| 7e | Executable auto-improvement eval policy is server-owned | `ai-memory-mcp/src/admin.rs` retains the legacy request `eval` key only as a rejected compatibility field and builds `AutoImproveReviewConfig.eval` exclusively from `AdminState`; `ai-memory-cli/src/commands/auto_improve.rs` sends no executable policy over HTTP | MCP `auto_improve_admin_refuses_request_eval_and_inherits_server_defaults` sends a request-controlled program path and receives 422, then omits the field and proves the configured server gate still runs | STRONG |
| 7f | Remote authentication and provider error bodies cannot inject terminal controls or expose recognizable secrets at the display cap | `ai-memory-llm/src/response.rs` `provider_error_body` bounds the network read to 1 MiB, applies the built-in sanitizer to the complete bounded body, then caps terminal output to 1 KiB; every LLM provider and every failure branch in `ai-memory-cli/src/commands/auth.rs` uses that helper | `response.rs` `provider_error_body_redacts_a_secret_straddling_the_display_cut`, `provider_error_body_strips_terminal_control_sequences`, and `provider_error_body_caps_what_it_reads_and_what_it_shows` (legitimate prefix/control preserved while secrets and controls are removed) | STRONG |
+| 7g | A malformed `auth.json` OAuth entry never echoes a stored value in its parse error | `ai-memory-llm/src/auth_file.rs` `load_entry` builds the error for a failed entry from a copy whose string values `redact_strings` has replaced with `<redacted>`, so serde's quoted offending value is never a stored one; the OpenAI OAuth, OIDC device and Copilot token loaders all read through it | `auth_file.rs` `wrong_type_error_does_not_echo_the_stored_value` (a token in `expires` is absent from the message, which still says `invalid type: string`) with the control `missing_field_error_still_names_the_field` | STRONG |
| 8a | Messaging: recipient-only visibility | `ai-memory-store/src/ops.rs` pop target-select + `reader.rs` `list_messages` (`to_*` predicate) | `agent_messages.rs` `a_message_is_only_visible_to_its_recipient`; `agent_messages_tools.rs` non-recipient cannot pop | STRONG |
| 8b | Messaging: cancel-own-only | `ai-memory-store/src/ops.rs` `cancel_messages` (AND-gated on `from_*` sender coordinate) | `agent_messages.rs` — whole-outbox **and** a foreign **specific-id** cancel refused | STRONG |
| 8c | Messaging: pop-exactly-once | `ai-memory-store/src/ops.rs` `pop_message_in_transaction` atomic CAS `WHERE state='pending'` | `agent_messages.rs` — sequential **and** `tokio::join!` concurrent double-pop yields exactly one `Some` | STRONG |