agentmux_srv_core/identity/browser_credential_store.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! OS-keychain-backed storage for browser-pane HTTP Basic-Auth credentials,
5//! scoped per identity so one agent's saved site credential is never
6//! reachable through another identity's browsing session.
7//!
8//! **The old store.** Sign-ins now live in the Vault, per browser profile
9//! ([`crate::backend::vault::signins`]); nothing is saved here any more, and
10//! this module only reads and deletes what is left as it moves in.
11//!
12//! Reuses [`crate::identity::secret_store`]'s existing `keyring`-crate
13//! wrapper (already backing `SecretRef::Keychain` for account API keys) —
14//! this module only builds the right account-key string and JSON-encodes
15//! the `{username, password}` pair; no new keychain code, no filesystem
16//! path involved (so `agentmux_common::data_paths::sanitize_path_segment`
17//! genuinely doesn't apply here — nothing is written to disk).
18//!
19//! See docs/status/majestic-painting-minsky plan (credential-isolated
20//! browser-pane auto-fill) and
21//! docs/specs/SPEC_BROWSER_PANE_HTTP_BASIC_AUTH_2026_05_18.md (the v1 spec
22//! that named "Persisted credential store (OS keyring)" as deferred future
23//! work — this module is that follow-up).
24
25use serde::{Deserialize, Serialize};
26use sha2::{Digest, Sha256};
27use zeroize::Zeroize;
28
29use crate::identity::secret_store;
30
31/// A saved browser credential. `Zeroize`s on drop so a decoded value
32/// doesn't linger in memory longer than the caller actually needs it —
33/// mirrors `secret_store::get`'s own `Zeroizing<String>` discipline for
34/// the raw keychain read.
35#[derive(Serialize, Deserialize, Zeroize)]
36#[zeroize(drop)]
37pub struct BrowserCredential {
38 pub username: String,
39 pub password: String,
40}
41
42/// Build the keychain account string for one (identity, protection-space)
43/// pair. Deliberately NOT naive `:`-concatenation of the raw fields —
44/// `origin` itself contains `:` (`https://host:8443`) and `realm` is
45/// server-supplied, effectively attacker-influenced, free text, so two
46/// different (origin, realm) pairs could otherwise concatenate to the same
47/// string (e.g. `origin="https://a:1"` + `realm="b"` vs
48/// `origin="https://a"` + `realm="1:b"`). Hashing a NUL-separated tuple
49/// removes any field-boundary ambiguity — NUL can't appear in either field
50/// in practice, but even if it could, the hash input's own delimiter
51/// collision risk is the same NUL-in-a-field edge case for both operands,
52/// which cancels out (unlike `:`, which is valid content in `origin`).
53///
54/// `identity_id` is kept as a literal prefix (not folded into the hash)
55/// so a corrupted/missing hash can't accidentally resolve under a
56/// different identity, and so the account string stays legible in
57/// diagnostic contexts (e.g. `keyring`-crate error messages) without
58/// revealing the origin/realm themselves — only which identity owns the
59/// entry.
60fn account_key(identity_id: &str, origin: &str, realm: &str, is_proxy: bool) -> String {
61 let mut hasher = Sha256::new();
62 hasher.update(origin.as_bytes());
63 hasher.update([0u8]);
64 hasher.update(realm.as_bytes());
65 hasher.update([0u8]);
66 hasher.update(if is_proxy { b"1" } else { b"0" });
67 let digest_hex = hex::encode(hasher.finalize());
68 format!("browser-auth:{identity_id}:{digest_hex}")
69}
70
71/// Look up a stored credential. `Ok(None)` means "nothing saved for this
72/// identity + protection-space" (not an error) — same contract as
73/// `secret_store::get_optional`, which this wraps directly so a transient
74/// keychain failure (locked keychain, no Secret Service daemon, permission
75/// denied) is distinguishable from "genuinely never saved" at the call
76/// site, the same distinction `secret_store`'s own doc comment argues for.
77pub fn load(
78 identity_id: &str,
79 origin: &str,
80 realm: &str,
81 is_proxy: bool,
82) -> Result<Option<BrowserCredential>, String> {
83 let key = account_key(identity_id, origin, realm, is_proxy);
84 let Some(json) = secret_store::get_optional(&key)? else {
85 return Ok(None);
86 };
87 let cred: BrowserCredential =
88 serde_json::from_str(&json).map_err(|e| format!("decode credential: {e}"))?;
89 Ok(Some(cred))
90}
91
92/// Delete the stored credential for this identity + protection-space.
93/// Idempotent (a missing entry is success) — same contract as
94/// `secret_store::delete`. Called when a stored credential turns out to be
95/// wrong (a re-challenge shortly after an auto-fill — see the
96/// credential_broker orchestration in agentmux-cef).
97pub fn delete(identity_id: &str, origin: &str, realm: &str, is_proxy: bool) -> Result<(), String> {
98 let key = account_key(identity_id, origin, realm, is_proxy);
99 secret_store::delete(&key)
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
107 fn account_key_is_namespaced_by_identity() {
108 let a = account_key("identity-a", "https://example.com", "realm", false);
109 let b = account_key("identity-b", "https://example.com", "realm", false);
110 assert_ne!(a, b, "different identities must never share an account key");
111 assert!(a.starts_with("browser-auth:identity-a:"));
112 assert!(b.starts_with("browser-auth:identity-b:"));
113 }
114
115 #[test]
116 fn account_key_is_stable_for_identical_inputs() {
117 let a = account_key("id", "https://example.com", "realm", true);
118 let b = account_key("id", "https://example.com", "realm", true);
119 assert_eq!(a, b);
120 }
121
122 #[test]
123 fn account_key_distinguishes_is_proxy() {
124 let a = account_key("id", "https://example.com", "realm", true);
125 let b = account_key("id", "https://example.com", "realm", false);
126 assert_ne!(a, b, "proxy-auth and origin-server-auth caches must not collide");
127 }
128
129 /// The exact bug naive `format!("{origin}:{realm}")` concatenation
130 /// would have: `origin` itself contains `:` (`https://host:port`), so
131 /// two different (origin, realm) pairs can produce the same
132 /// concatenated string. The NUL-separated-then-hashed scheme must not
133 /// have this problem.
134 #[test]
135 fn account_key_does_not_collide_across_delimiter_boundaries() {
136 let a = account_key("id", "https://a:1", "b", false);
137 let b = account_key("id", "https://a", "1:b", false);
138 assert_ne!(
139 a, b,
140 "origin/realm field-boundary shift must not collide (naive ':' concat would fail this)"
141 );
142 }
143
144 #[test]
145 fn account_key_distinguishes_origin() {
146 let a = account_key("id", "https://example.com", "realm", false);
147 let b = account_key("id", "https://other.com", "realm", false);
148 assert_ne!(a, b);
149 }
150
151 #[test]
152 fn account_key_distinguishes_realm() {
153 let a = account_key("id", "https://example.com", "realm-a", false);
154 let b = account_key("id", "https://example.com", "realm-b", false);
155 assert_ne!(a, b);
156 }
157
158 #[test]
159 fn browser_credential_json_round_trips() {
160 let cred = BrowserCredential {
161 username: "user".to_string(),
162 password: "pass".to_string(),
163 };
164 let json = serde_json::to_string(&cred).unwrap();
165 let decoded: BrowserCredential = serde_json::from_str(&json).unwrap();
166 assert_eq!(decoded.username, "user");
167 assert_eq!(decoded.password, "pass");
168 }
169}