Skip to content

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

Rust

fix(hooks): stop putting the server bearer on hook command lines (#552) (#561)

Fabio Akitad2e5c9877333
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 06f158cf..70137419 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -251,6 +251,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Reported by @alvadorn alongside #546 and split out at their suggestion.
+- The server bearer is no longer written onto hook command lines (#552).
+ `install-hooks --apply` stored it in the agent's config as
+ `--auth-token <token>` for native hooks and as an `AI_MEMORY_AUTH_TOKEN=`
+ shell prefix for the script hooks, so it sat in `/proc/<pid>/cmdline` —
+ readable by any local user — for the lifetime of every hook, and of every
+ `curl` those hooks ran, on every tool call.
+
+ It now lives in two `0600` files inside the `0700` data dir:
+ `auth-token` for the native `ai-memory hook` path, and `auth-header` for the
+ shell hooks, which pass it to `curl -H @<file>`. The second file is the point
+ rather than duplication — building the header inline would put the credential
+ straight back on a command line.
+
+ Backward compatible: an explicit `--auth-token`, or `AI_MEMORY_AUTH_TOKEN` in
+ the environment, still wins, so configs written before this keep working.
+ Re-run `install-hooks --apply` to move an existing install onto the stored
+ form. Only `--apply` persists; printing a snippet writes no credential.
+
### Docs
- `docs/windows.md` gains **Scenario E**, a persistent-server story for native
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index e9473d18..2bc01eb8 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -615,7 +615,14 @@ where
// mode is decided without a round-trip: an explicit `--auth-token` is
// stored inline; otherwise a present OIDC token marks the event `oidc`
// (resolved + refreshed at drain time); otherwise anonymous.
- let oidc_present = args.auth_token.is_none()
+ // #552: the bearer is no longer rendered onto the hook's command line, so
+ // fall back to the copy `install-hooks --apply` persisted under the data
+ // dir. An explicit `--auth-token` still wins, which keeps every config
+ // written before this change working exactly as it did.
+ let persisted_token = crate::config::read_hook_auth_token(&dd);
+ let effective_token = args.auth_token.as_deref().or(persisted_token.as_deref());
+
+ let oidc_present = effective_token.is_none()
&& OidcToken::load(&dd.join("auth.json"))
.ok()
.flatten()
@@ -638,12 +645,7 @@ where
"{base}/hook?event={}&agent={}{}{}&ingest_key={ingest_key}",
args.event, args.agent, hook_qs, capture_qs
);
- let entry = hook_spool::entry_for(
- event_url,
- payload.clone(),
- args.auth_token.as_deref(),
- oidc_present,
- );
+ let entry = hook_spool::entry_for(event_url, payload.clone(), effective_token, oidc_present);
if hook_spool::enqueue(&spool, &entry).is_err() {
eprintln!(
"ai-memory hook warning: failed to spool lifecycle event; capture for this event was skipped"
@@ -690,7 +692,7 @@ where
// handoff on demand via the MCP `memory_handoff_accept` tool.
if agent_kind.session_start_injects_handoff() {
let client = build_client();
- let bearer = hook_spool::resolve_bearer(&client, &dd, args.auth_token.as_deref()).await;
+ let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;
let native_session_qs = canonical_session_id.as_deref().map_or_else(
|| session_qs.clone(),
|session_id| format!("&session_id={}", url_encode(session_id)),
@@ -728,7 +730,7 @@ where
&& AgentKind::from_wire(&args.agent).user_prompt_injects_handoff()
{
let client = build_client();
- let bearer = hook_spool::resolve_bearer(&client, &dd, args.auth_token.as_deref()).await;
+ let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;
let native_session_qs = canonical_session_id
.as_deref()
.map_or_else(String::new, |session_id| {
@@ -797,11 +799,13 @@ where
if should_spawn_background_drainer(&args.event)
&& let Err(err) = after_background_drain_event_enqueue(
&dd,
- // The hook's own token: current by definition, since the agent
- // config it came from was rendered by the last `install-hooks`.
- // The drain uses it only to retry an entry the server has already
- // rejected with 401 (#542).
- args.auth_token.as_deref(),
+ // The hook's own token, resolved the same way it authenticates
+ // its own request: `--auth-token`, else the environment, else the
+ // copy `install-hooks --apply` persisted under the data dir
+ // (#552). Current by construction either way. The drain uses it
+ // only to retry an entry the server has already rejected with 401
+ // (#542).
+ effective_token,
spawn_background_drainer,
)
{
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index ca67d7dc..63b57e10 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -334,7 +334,35 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
.clone()
.or_else(|| config.auth.bearer_token.clone())
.or_else(|| inferred.as_ref().and_then(|mcp| mcp.auth_token.clone()));
- let auth = auth_token_owned.as_deref();
+ // #552: persist the bearer under the data dir (0600) and keep it OUT of
+ // the rendered config. Before this it went onto every hook's command line —
+ // as `--auth-token <token>` for native hooks, as an `AI_MEMORY_AUTH_TOKEN=`
+ // shell prefix for the script hooks — so it was readable through
+ // `/proc/<pid>/cmdline` by any local user for as long as each hook ran, on
+ // every tool call.
+ //
+ // Only `--apply` persists: a printed snippet is the operator's to place, and
+ // writing a credential as a side effect of a dry run would be a surprise.
+ let persisted = if args.apply
+ && let Some(token) = auth_token_owned.as_deref()
+ {
+ crate::config::store_hook_auth_token(&config.data_dir, token).with_context(|| {
+ format!(
+ "storing the hook auth token under {}",
+ config.data_dir.display()
+ )
+ })?;
+ true
+ } else {
+ false
+ };
+ // Renderers take `Option<&str>` and omit the credential entirely when it is
+ // `None`, so one decision here covers every agent instead of twenty edits.
+ let auth = if persisted {
+ None
+ } else {
+ auth_token_owned.as_deref()
+ };
// P1.8 multi-user attribution: `--as-user` is metadata only — the
// token stamped into the hook env block is whatever the operator
// passed via `--auth-token` (typically a native key from
@@ -6688,7 +6716,10 @@ model = "gpt-5"
let tmp = TempDir::new().unwrap();
let data_dir = tmp.path().join("data");
let agent_label = "stage-empty-in-place";
- let in_place = data_dir.join("ai-memory/hooks").join(agent_label);
+ // Must equal what `stage_hook_scripts_in` computes, or this stops
+ // being the source==dest case it exists to cover and duplicates the
+ // different-paths test below (#554 moved the destination shape).
+ let in_place = data_dir.join("hooks").join(agent_label);
fs::create_dir_all(&in_place).unwrap();
// Intentionally no scripts in `in_place`.
@@ -6776,6 +6807,63 @@ model = "gpt-5"
);
}
+ /// #552, the regression guard: `--apply` must persist the bearer under the
+ /// data dir and leave it out of the agent config entirely.
+ ///
+ /// Before this, the token was written into the rendered command — as
+ /// `--auth-token <token>` for native hooks — so it sat in the agent's
+ /// config file *and* in `/proc/<pid>/cmdline` for the lifetime of every
+ /// hook, on every tool call.
+ #[test]
+ fn apply_persists_the_bearer_and_keeps_it_out_of_the_agent_config() {
+ let home = TempDir::new().unwrap();
+ let cfg_dir = TempDir::new().unwrap();
+ let settings = cfg_dir.path().join("settings.json");
+ std::fs::write(&settings, "{}").unwrap();
+
+ let config = crate::config::Config::load(None, Some(home.path().to_path_buf())).unwrap();
+ let args = InstallHooksArgs {
+ agent: AgentChoice::ClaudeCode,
+ apply: true,
+ server_url: Some("http://127.0.0.1:49374".to_string()),
+ auth_token: Some("SEKRIT-BEARER-552".to_string()),
+ config_file: Some(settings.clone()),
+ // Point at the repo's bundle explicitly. Without this the test
+ // leans on hook-dir discovery, which from `target/debug/deps`
+ // walks to `<repo>/target` and then falls through to whatever the
+ // machine happens to have staged — passing for a reason that has
+ // nothing to do with what is under test.
+ hooks_dir: Some(
+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks"),
+ ),
+ ..default_hook_args()
+ };
+
+ run(&config, args).expect("apply should succeed");
+
+ let rendered = std::fs::read_to_string(&settings).unwrap();
+ assert!(
+ !rendered.contains("SEKRIT-BEARER-552"),
+ "the bearer must not be written into the agent config: {rendered}"
+ );
+ assert!(
+ !rendered.contains("--auth-token"),
+ "no --auth-token flag may reach a hook command line: {rendered}"
+ );
+
+ assert_eq!(
+ crate::config::read_hook_auth_token(&config.data_dir).as_deref(),
+ Some("SEKRIT-BEARER-552"),
+ "the bearer must be persisted where the hook can read it"
+ );
+ assert!(
+ std::fs::read_to_string(crate::config::hook_auth_header_path_in(&config.data_dir))
+ .unwrap()
+ .contains("SEKRIT-BEARER-552"),
+ "the curl header file must carry it too"
+ );
+ }
+
#[test]
fn hook_source_candidates_include_native_package_dir() {
let candidates = hook_source_candidates(
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index ed81382e..366eaf08 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -634,6 +634,16 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {
apply_change(change, name.as_deref(), &url)?;
}
+ // Removing the hooks removes the only readers of the stored bearer, so
+ // leaving it on disk would strand a live credential (#552). Best-effort:
+ // an unremovable file must not fail a teardown that otherwise succeeded.
+ if let Err(error) = crate::config::clear_hook_auth_token(&config.data_dir) {
+ eprintln!(
+ "ai-memory uninstall warning: could not remove the stored auth token under {}: {error}",
+ config.data_dir.display()
+ );
+ }
+
if args.purge_data {
for path in data_purge::purge_data_dirs(&config.data_dir)? {
println!("✓ purged {}", path.display());
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 96bd8704..c99afd66 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -1384,6 +1384,93 @@ fn non_empty(s: Option<&str>) -> Option<&str> {
s.map(str::trim).filter(|s| !s.is_empty())
}
+/// `<data_dir>/auth-token` — the raw bearer, `0600`.
+#[must_use]
+pub fn hook_auth_token_path_in(data_dir: &Path) -> PathBuf {
+ data_dir.join("auth-token")
+}
+
+/// `<data_dir>/auth-header` — the same bearer as a complete
+/// `Authorization:` line, `0600`.
+///
+/// A second file rather than a second parse: the shell hooks pass this to
+/// `curl -H @<file>`, which is what keeps the credential out of *curl's*
+/// argv. Building the header inline would put it straight back on a command
+/// line, which is the whole problem (#552).
+#[must_use]
+pub fn hook_auth_header_path_in(data_dir: &Path) -> PathBuf {
+ data_dir.join("auth-header")
+}
+
+/// Persist the bearer for hooks to read, replacing any previous pair.
+///
+/// Both files are written `0600` inside the data dir, which is itself `0700`.
+/// That is strictly less exposure than the status quo, where the token sat in
+/// the agent's own config file *and* on the command line of every hook and
+/// every `curl` — readable through `/proc/<pid>/cmdline` by any local user for
+/// as long as each ran.
+///
+/// # Errors
+/// Propagates IO failures from creating the data dir or writing either file.
+pub fn store_hook_auth_token(data_dir: &Path, token: &str) -> std::io::Result<()> {
+ std::fs::create_dir_all(data_dir)?;
+ write_secret(&hook_auth_token_path_in(data_dir), token)?;
+ write_secret(
+ &hook_auth_header_path_in(data_dir),
+ &format!("Authorization: Bearer {token}\n"),
+ )
+}
+
+/// Remove a persisted bearer pair. Absent files are not an error.
+///
+/// # Errors
+/// Propagates IO failures other than "not found".
+pub fn clear_hook_auth_token(data_dir: &Path) -> std::io::Result<()> {
+ for path in [
+ hook_auth_token_path_in(data_dir),
+ hook_auth_header_path_in(data_dir),
+ ] {
+ match std::fs::remove_file(&path) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => return Err(e),
+ }
+ }
+ Ok(())
+}
+
+/// Read the persisted bearer, if one was stored. Trailing newline trimmed.
+#[must_use]
+pub fn read_hook_auth_token(data_dir: &Path) -> Option<String> {
+ let raw = std::fs::read_to_string(hook_auth_token_path_in(data_dir)).ok()?;
+ let trimmed = raw.trim();
+ (!trimmed.is_empty()).then(|| trimmed.to_owned())
+}
+
+/// Write `contents` to `path` with owner-only permissions.
+///
+/// The mode is set on the handle before any bytes are written on Unix, so the
+/// secret is never briefly world-readable between `create` and `set_permissions`.
+fn write_secret(path: &Path, contents: &str) -> std::io::Result<()> {
+ #[cfg(unix)]
+ {
+ use std::io::Write as _;
+ use std::os::unix::fs::OpenOptionsExt as _;
+ let mut file = std::fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .mode(0o600)
+ .open(path)?;
+ file.write_all(contents.as_bytes())
+ }
+ #[cfg(not(unix))]
+ {
+ // Windows has no mode bits here; the data dir's own ACL is the boundary.
+ std::fs::write(path, contents)
+ }
+}
+
fn default_data_dir() -> PathBuf {
dirs::data_local_dir()
.unwrap_or_else(|| PathBuf::from("."))
@@ -1417,6 +1504,82 @@ fn normalize_home_dir(home: &str) -> Option<String> {
#[cfg(test)]
mod tests {
+
+ /// #552: the bearer used to travel on every hook's command line, readable
+ /// through `/proc/<pid>/cmdline` by any local user. It now lives in the
+ /// data dir instead — which is only an improvement if the files are not
+ /// world-readable, so the mode is asserted rather than assumed.
+ #[test]
+ fn a_persisted_hook_token_is_owner_only_and_round_trips() {
+ let tmp = TempDir::new().unwrap();
+ let dd = tmp.path().join("data");
+
+ store_hook_auth_token(&dd, "s3cret-bearer").unwrap();
+
+ assert_eq!(read_hook_auth_token(&dd).as_deref(), Some("s3cret-bearer"));
+ assert_eq!(
+ std::fs::read_to_string(hook_auth_header_path_in(&dd)).unwrap(),
+ "Authorization: Bearer s3cret-bearer\n",
+ "the header file is what curl reads with -H @file"
+ );
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ for path in [hook_auth_token_path_in(&dd), hook_auth_header_path_in(&dd)] {
+ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(
+ mode,
+ 0o600,
+ "{} must be owner-only, got {mode:o}",
+ path.display()
+ );
+ }
+ }
+ }
+
+ /// Re-running `install-hooks --apply` after `user rotate-token` must leave
+ /// the new bearer, not both.
+ #[test]
+ fn storing_a_second_token_replaces_the_first() {
+ let tmp = TempDir::new().unwrap();
+ let dd = tmp.path().join("data");
+ store_hook_auth_token(&dd, "old-token").unwrap();
+ store_hook_auth_token(&dd, "new-token").unwrap();
+
+ assert_eq!(read_hook_auth_token(&dd).as_deref(), Some("new-token"));
+ assert!(
+ !std::fs::read_to_string(hook_auth_header_path_in(&dd))
+ .unwrap()
+ .contains("old-token"),
+ "a rotated token must not leave the previous one behind"
+ );
+ }
+
+ /// Absent, empty, and whitespace-only files all read as "no token" rather
+ /// than as an empty bearer, which would send `Authorization: Bearer `.
+ #[test]
+ fn an_absent_or_blank_token_file_reads_as_none() {
+ let tmp = TempDir::new().unwrap();
+ let dd = tmp.path().join("data");
+ assert!(read_hook_auth_token(&dd).is_none(), "absent");
+
+ std::fs::create_dir_all(&dd).unwrap();
+ std::fs::write(hook_auth_token_path_in(&dd), "").unwrap();
+ assert!(read_hook_auth_token(&dd).is_none(), "empty");
+ std::fs::write(hook_auth_token_path_in(&dd), " \n ").unwrap();
+ assert!(read_hook_auth_token(&dd).is_none(), "whitespace only");
+ }
+
+ #[test]
+ fn clearing_a_token_is_idempotent() {
+ let tmp = TempDir::new().unwrap();
+ let dd = tmp.path().join("data");
+ store_hook_auth_token(&dd, "tok").unwrap();
+ clear_hook_auth_token(&dd).unwrap();
+ assert!(read_hook_auth_token(&dd).is_none());
+ clear_hook_auth_token(&dd).expect("clearing twice must not error");
+ }
use super::*;
use secrecy::{ExposeSecret, SecretString};
use tempfile::TempDir;
diff --git a/docs/users.md b/docs/users.md
index 795a77b8..663582aa 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -479,6 +479,29 @@ not come back; issue a new key instead. Native keys authenticate as
root automation still uses `[auth].bearer_token`. External `amk_` keys
stay in `mcp-auth`; they are not listed here.
+#### Where the token is stored
+
+`install-hooks --apply --auth-token …` writes the bearer to two files inside
+the data dir, both `0600` (the data dir itself is `0700`):
+
+| file | read by |
+|---|---|
+| `<data_dir>/auth-token` | the native `ai-memory hook` command |
+| `<data_dir>/auth-header` | the shell hooks, via `curl -H @<file>` |
+
+It is deliberately **not** written into the agent's own config any more. Before
+#552 it went onto the hook's command line — `--auth-token <token>` for native
+hooks, an `AI_MEMORY_AUTH_TOKEN=` shell prefix for the script hooks — which put
+it in the agent's config file *and* in `/proc/<pid>/cmdline` for the lifetime of
+every hook and every `curl`, readable by any local user, on every tool call.
+The second file exists for exactly that reason: building the header inline
+would put the credential straight back on a command line.
+
+An explicit `--auth-token` on a hook command, or `AI_MEMORY_AUTH_TOKEN` in the
+environment, still takes precedence — so configs written before this keep
+working unchanged. Re-run `install-hooks --apply` to move an existing install
+onto the stored form.
+
#### What rotation does to already-spooled hook events
A lifecycle hook that cannot reach the server writes the event to the local
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index 198f4d79..6cc6b287 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -367,12 +367,27 @@ ai_memory_clear_session_id() {
# The 0.5s timeout matches the project-wide hook latency budget
# (never block the agent), and the trailing `|| true` makes the
# function safe to call from `set -e` scripts.
+# Path of the `Authorization:` header file `install-hooks --apply` writes
+# (0600, inside the 0700 data dir). Printed only when readable.
+ai_memory_auth_header_file() {
+ _amhf="${AI_MEMORY_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/ai-memory}/auth-header"
+ [ -r "$_amhf" ] && printf '%s' "$_amhf"
+}
+
ai_memory_post_hook() {
+ _amhdr=$(ai_memory_auth_header_file)
if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
curl -s --max-time 0.5 -X POST "$1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \
--data-binary @-
+ elif [ -n "$_amhdr" ]; then
+ # `-H @file`: curl reads the header from disk, so the bearer never
+ # appears in curl's argv the way an inline `-H` would (#552).
+ curl -s --max-time 0.5 -X POST "$1" \
+ -H "Content-Type: application/json" \
+ -H @"$_amhdr" \
+ --data-binary @-
else
curl -s --max-time 0.5 -X POST "$1" \
-H "Content-Type: application/json" \
@@ -387,9 +402,12 @@ ai_memory_post_hook() {
# stdout (and prepended to the agent's context), so we want to avoid
# truncating a handoff that was almost ready.
ai_memory_get_handoff() {
+ _amhdr=$(ai_memory_auth_header_file)
if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
curl -s --max-time 1.0 "$1" \
-H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"
+ elif [ -n "$_amhdr" ]; then
+ curl -s --max-time 1.0 "$1" -H @"$_amhdr"
else
curl -s --max-time 1.0 "$1"
fi