Skip to main content

agentmux_srv_core/backend/storage/
agent_credentials.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Per-agent M2M Cognito credential for muxbus Tier-4 credential binding.
5//! See db_agent_credentials in migrations.rs (SHARED_STORE_SCHEMA_VERSION v4).
6//! The relay side is designed in the private cloud repo.
7//!
8//! One row per locally-registered agent_id — distinct from the single
9//! account-level db_muxbus_credentials singleton (muxbus.rs), which stores
10//! the human's PKCE login used only to provision these.
11
12use rusqlite::params;
13
14use super::error::StoreError;
15use super::store::Store;
16
17#[derive(Debug, Clone, Default)]
18pub struct AgentCredential {
19    pub client_id: String,
20    pub client_secret: String,
21    pub token_endpoint: String,
22    /// Cached client_credentials access token — separate from client_secret
23    /// so a fresh token fetch doesn't require re-provisioning.
24    pub access_token: String,
25    pub expires_at: i64,
26}
27
28impl AgentCredential {
29    /// client_credentials tokens carry no refresh token (per the cloud-side
30    /// design) — "valid" just means "not expired yet," with the
31    /// same 300s early-refresh margin used by MuxBusCredentials.
32    pub fn is_valid(&self) -> bool {
33        !self.access_token.is_empty() && self.expires_at - agentmux_common::time::now_secs() > 300
34    }
35}
36
37/// The row key for `agent_id` in this channel's sign-in: the lowercased agent
38/// id, behind the channel's prefix when channels share the store. These cached
39/// credentials belong to the account a channel is signed in as, and two
40/// channels may be signed in as different accounts.
41fn scoped_key(agent_id: &str) -> String {
42    format!("{}{}", super::muxbus::current_agent_credential_prefix(), agent_id.to_lowercase())
43}
44
45impl Store {
46    pub fn agent_credential_load(&self, agent_id: &str) -> Result<Option<AgentCredential>, StoreError> {
47        let key = scoped_key(agent_id);
48        let conn = self.conn.lock().unwrap();
49        let mut stmt = conn.prepare(
50            "SELECT client_id, client_secret, token_endpoint, access_token, expires_at
51             FROM db_agent_credentials WHERE agent_id = ?1",
52        )?;
53        match stmt.query_row(params![key], |row| {
54            Ok(AgentCredential {
55                client_id: row.get(0)?,
56                client_secret: row.get(1)?,
57                token_endpoint: row.get(2)?,
58                access_token: row.get(3)?,
59                expires_at: row.get(4)?,
60            })
61        }) {
62            Ok(c) => {
63                crate::backend::transcript::withhold_sources::agent_relay_credential(agent_id, &c.client_secret, &c.access_token, c.expires_at);
64                Ok(Some(c))
65            }
66            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
67            Err(e) => Err(e.into()),
68        }
69    }
70
71    /// Save a newly-provisioned client_id/client_secret (access_token/expires_at
72    /// left at their defaults — the caller fetches a token separately via
73    /// agent_credential_save_token).
74    pub fn agent_credential_save(
75        &self,
76        agent_id: &str,
77        client_id: &str,
78        client_secret: &str,
79        token_endpoint: &str,
80    ) -> Result<(), StoreError> {
81        crate::backend::transcript::withhold_sources::agent_relay_credential(agent_id, client_secret, "", 0);
82        let key = scoped_key(agent_id);
83        let conn = self.conn.lock().unwrap();
84        conn.execute(
85            "INSERT INTO db_agent_credentials
86                 (agent_id, client_id, client_secret, token_endpoint, created_at)
87             VALUES (?1, ?2, ?3, ?4, ?5)
88             ON CONFLICT(agent_id) DO UPDATE SET
89                 client_id = excluded.client_id,
90                 client_secret = excluded.client_secret,
91                 token_endpoint = excluded.token_endpoint",
92            params![key, client_id, client_secret, token_endpoint, agentmux_common::time::now_secs()],
93        )?;
94        Ok(())
95    }
96
97    /// Cache a freshly-fetched client_credentials access token against an
98    /// already-provisioned agent. No-op if the agent has no row yet (the
99    /// caller should provision first).
100    pub fn agent_credential_save_token(
101        &self,
102        agent_id: &str,
103        access_token: &str,
104        expires_at: i64,
105    ) -> Result<(), StoreError> {
106        crate::backend::transcript::withhold_sources::agent_relay_credential(agent_id, "", access_token, expires_at);
107        let key = scoped_key(agent_id);
108        let conn = self.conn.lock().unwrap();
109        conn.execute(
110            "UPDATE db_agent_credentials SET access_token = ?2, expires_at = ?3 WHERE agent_id = ?1",
111            params![key, access_token, expires_at],
112        )?;
113        Ok(())
114    }
115
116    /// Clear a per-agent credential's cached access token (client_id/secret
117    /// are left intact — only the token is suspect). Used when the server
118    /// rejects a request with 401 despite our cached expires_at still
119    /// looking valid (revoked/rotated out-of-band): forces the next
120    /// ensure_agent_credential call to re-fetch via fetch_m2m_token instead
121    /// of retrying the exact same rejected token. No-op if the agent has no
122    /// row. reagentx P1 on PR #2342.
123    pub fn agent_credential_invalidate_token(&self, agent_id: &str) -> Result<(), StoreError> {
124        let key = scoped_key(agent_id);
125        let conn = self.conn.lock().unwrap();
126        conn.execute(
127            "UPDATE db_agent_credentials SET access_token = '', expires_at = 0 WHERE agent_id = ?1",
128            params![key],
129        )?;
130        Ok(())
131    }
132
133    /// Delete one agent's credential row outright — for a client the cloud
134    /// no longer recognizes (`invalid_client`), where keeping the
135    /// client_id/secret would only fail again. The next
136    /// `ensure_agent_credential` re-provisions it. No-op if there is no row.
137    /// docs/specs/SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.4.
138    pub fn agent_credential_delete(&self, agent_id: &str) -> Result<(), StoreError> {
139        let key = scoped_key(agent_id);
140        let conn = self.conn.lock().unwrap();
141        conn.execute("DELETE FROM db_agent_credentials WHERE agent_id = ?1", params![key])?;
142        Ok(())
143    }
144
145    /// Wipe every cached per-agent M2M credential. `db_agent_credentials`
146    /// carries no account/user_sub column of its own — each row is only
147    /// ever meaningful under the muxbus account that provisioned it — so a
148    /// genuine account switch (muxbus_save with a different user_sub) or a
149    /// logout (muxbus_clear) must wipe this cache wholesale; otherwise a
150    /// stale row keeps authenticating this agent_id's requests as the
151    /// PREVIOUS account after the human has switched to a different one.
152    /// Re-provisioning is cheap and idempotent on the cloud side, so clearing on every account transition —
153    /// not just the ones that turn out to matter — is the safe default.
154    /// reagentx P0 on PR #2342.
155    pub fn agent_credentials_clear_all(&self) -> Result<(), StoreError> {
156        self.agent_credentials_clear_prefix(&super::muxbus::current_agent_credential_prefix())
157    }
158
159    /// Every channel's row for one agent: what deleting the agent removes.
160    pub fn agent_credentials_purge_agent(&self, agent_id: &str) -> Result<usize, StoreError> {
161        let conn = self.conn.lock().unwrap();
162        Ok(conn.execute(
163            "DELETE FROM db_agent_credentials
164             WHERE agent_id = ?1 OR (instr(agent_id, '/') > 0 AND substr(agent_id, instr(agent_id, '/') + 1) = ?1)",
165            params![agent_id.to_lowercase()],
166        )?)
167    }
168
169    /// The rows behind `prefix` (a channel's `<channel>/`), or, with an empty
170    /// prefix, the unprefixed ones.
171    fn agent_credentials_clear_prefix(&self, prefix: &str) -> Result<(), StoreError> {
172        let conn = self.conn.lock().unwrap();
173        if prefix.is_empty() {
174            // The host-wide set (and a channel's own store): rows with no
175            // channel prefix. Other channels' rows are theirs.
176            conn.execute("DELETE FROM db_agent_credentials WHERE instr(agent_id, '/') = 0", [])?;
177        } else {
178            conn.execute(
179                "DELETE FROM db_agent_credentials WHERE substr(agent_id, 1, length(?1)) = ?1",
180                params![prefix],
181            )?;
182        }
183        Ok(())
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    // A shared-schema store built on a temp file (open_shared needs a real
192    // path; :memory: would be re-created per connection) — db_agent_credentials
193    // lives in the shared schema (SHARED_STORE_SCHEMA_VERSION v3), not objects.db.
194    fn shared_store() -> Store {
195        Store::open_shared(std::path::Path::new(":memory:")).unwrap()
196    }
197
198    /// Channels sharing the store keep their cached credentials apart; the
199    /// host-wide set (`stable`) and each channel clear only their own.
200    #[test]
201    fn a_channels_credentials_are_its_own_rows_and_clear_all_clears_only_those() {
202        let store = shared_store();
203        let conn = store.conn.lock().unwrap();
204        for key in ["agentx", "local-main-x/agentx", "local-main-y/agentx"] {
205            conn.execute(
206                "INSERT INTO db_agent_credentials (agent_id, client_id) VALUES (?1, 'c')",
207                params![key],
208            )
209            .unwrap();
210        }
211        let count = |conn: &rusqlite::Connection| -> i64 {
212            conn.query_row("SELECT COUNT(*) FROM db_agent_credentials", [], |r| r.get(0)).unwrap()
213        };
214        assert_eq!(count(&conn), 3);
215        drop(conn);
216        let left = |store: &Store| -> Vec<String> {
217            let conn = store.conn.lock().unwrap();
218            let mut stmt = conn.prepare("SELECT agent_id FROM db_agent_credentials ORDER BY agent_id").unwrap();
219            stmt.query_map([], |r| r.get(0)).unwrap().collect::<Result<_, _>>().unwrap()
220        };
221        // The host-wide set clears only the unprefixed row.
222        store.agent_credentials_clear_prefix("").unwrap();
223        assert_eq!(left(&store), vec!["local-main-x/agentx".to_string(), "local-main-y/agentx".to_string()]);
224        // A channel clears only its own.
225        store.agent_credentials_clear_prefix("local-main-x/").unwrap();
226        assert_eq!(left(&store), vec!["local-main-y/agentx".to_string()]);
227    }
228
229    /// Deleting an agent removes its row in every channel and no one else's.
230    #[test]
231    fn purging_an_agent_removes_its_rows_in_every_channel() {
232        let store = shared_store();
233        {
234            let conn = store.conn.lock().unwrap();
235            for key in ["agentx", "local-main-x/agentx", "dev-main-y/agentx", "agentxy", "local-main-x/agenty"] {
236                conn.execute("INSERT INTO db_agent_credentials (agent_id, client_id) VALUES (?1, 'c')", params![key])
237                    .unwrap();
238            }
239        }
240        assert_eq!(store.agent_credentials_purge_agent("AgentX").unwrap(), 3);
241        let conn = store.conn.lock().unwrap();
242        let left: Vec<String> = conn
243            .prepare("SELECT agent_id FROM db_agent_credentials ORDER BY agent_id")
244            .unwrap()
245            .query_map([], |r| r.get(0))
246            .unwrap()
247            .collect::<Result<_, _>>()
248            .unwrap();
249        assert_eq!(left, vec!["agentxy".to_string(), "local-main-x/agenty".to_string()]);
250    }
251
252    #[test]
253    fn load_returns_none_when_unprovisioned() {
254        let store = shared_store();
255        assert!(store.agent_credential_load("agentx").unwrap().is_none());
256    }
257
258    #[test]
259    fn save_then_load_round_trips() {
260        let store = shared_store();
261        store
262            .agent_credential_save("AgentX", "client-1", "secret-1", "https://auth.example.com/oauth2/token")
263            .unwrap();
264
265        // Lookup is case-insensitive — normalized the same way agent_id is
266        // normalized everywhere else in this codebase.
267        let loaded = store.agent_credential_load("agentx").unwrap().unwrap();
268        assert_eq!(loaded.client_id, "client-1");
269        assert_eq!(loaded.client_secret, "secret-1");
270        assert_eq!(loaded.token_endpoint, "https://auth.example.com/oauth2/token");
271        assert_eq!(loaded.access_token, "");
272        assert!(!loaded.is_valid()); // no access_token yet
273    }
274
275    #[test]
276    fn save_is_idempotent_and_updates_in_place() {
277        let store = shared_store();
278        store.agent_credential_save("agentx", "client-1", "secret-1", "endpoint-1").unwrap();
279        store.agent_credential_save("agentx", "client-2", "secret-2", "endpoint-2").unwrap();
280
281        let loaded = store.agent_credential_load("agentx").unwrap().unwrap();
282        assert_eq!(loaded.client_id, "client-2");
283        assert_eq!(loaded.client_secret, "secret-2");
284    }
285
286    #[test]
287    fn save_token_caches_access_token_and_expiry() {
288        let store = shared_store();
289        store.agent_credential_save("agentx", "client-1", "secret-1", "endpoint-1").unwrap();
290
291        let future = agentmux_common::time::now_secs() + 3600;
292        store.agent_credential_save_token("agentx", "tok-abc", future).unwrap();
293
294        let loaded = store.agent_credential_load("agentx").unwrap().unwrap();
295        assert_eq!(loaded.access_token, "tok-abc");
296        assert_eq!(loaded.expires_at, future);
297        assert!(loaded.is_valid());
298    }
299
300    #[test]
301    fn save_token_is_a_noop_when_not_provisioned() {
302        let store = shared_store();
303        // No agent_credential_save call first -- row doesn't exist.
304        store.agent_credential_save_token("agentx", "tok-abc", agentmux_common::time::now_secs() + 3600).unwrap();
305        assert!(store.agent_credential_load("agentx").unwrap().is_none());
306    }
307
308    #[test]
309    fn invalidate_token_clears_token_and_expiry_but_keeps_client() {
310        let store = shared_store();
311        store.agent_credential_save("agentx", "client-1", "secret-1", "endpoint-1").unwrap();
312        store
313            .agent_credential_save_token("agentx", "tok-abc", agentmux_common::time::now_secs() + 3600)
314            .unwrap();
315
316        store.agent_credential_invalidate_token("agentx").unwrap();
317
318        let loaded = store.agent_credential_load("agentx").unwrap().unwrap();
319        assert_eq!(loaded.access_token, "");
320        assert_eq!(loaded.expires_at, 0);
321        assert!(!loaded.is_valid());
322        // Provisioned client identity survives — only the token was suspect.
323        assert_eq!(loaded.client_id, "client-1");
324        assert_eq!(loaded.client_secret, "secret-1");
325    }
326
327    #[test]
328    fn invalidate_token_is_a_noop_when_not_provisioned() {
329        let store = shared_store();
330        store.agent_credential_invalidate_token("agentx").unwrap();
331        assert!(store.agent_credential_load("agentx").unwrap().is_none());
332    }
333
334    #[test]
335    fn delete_removes_only_that_agents_row() {
336        let store = shared_store();
337        store.agent_credential_save("agentx", "client-1", "secret-1", "endpoint-1").unwrap();
338        store.agent_credential_save("agenty", "client-2", "secret-2", "endpoint-2").unwrap();
339
340        store.agent_credential_delete("AgentX").unwrap();
341
342        assert!(store.agent_credential_load("agentx").unwrap().is_none());
343        assert!(store.agent_credential_load("agenty").unwrap().is_some());
344        // Deleting a missing row is fine.
345        store.agent_credential_delete("agentx").unwrap();
346    }
347
348    #[test]
349    fn clear_all_wipes_every_agent_credential() {
350        let store = shared_store();
351        store.agent_credential_save("agentx", "client-1", "secret-1", "endpoint-1").unwrap();
352        store.agent_credential_save("agenty", "client-2", "secret-2", "endpoint-2").unwrap();
353
354        store.agent_credentials_clear_all().unwrap();
355
356        assert!(store.agent_credential_load("agentx").unwrap().is_none());
357        assert!(store.agent_credential_load("agenty").unwrap().is_none());
358    }
359
360    #[test]
361    fn clear_all_is_a_noop_on_an_empty_table() {
362        let store = shared_store();
363        store.agent_credentials_clear_all().unwrap();
364        assert!(store.agent_credential_load("agentx").unwrap().is_none());
365    }
366
367    #[test]
368    fn is_valid_respects_the_300s_early_refresh_margin() {
369        let mut cred = AgentCredential {
370            client_id: "c".to_string(),
371            client_secret: "s".to_string(),
372            token_endpoint: "e".to_string(),
373            access_token: "tok".to_string(),
374            expires_at: agentmux_common::time::now_secs() + 301,
375        };
376        assert!(cred.is_valid());
377
378        cred.expires_at = agentmux_common::time::now_secs() + 299;
379        assert!(!cred.is_valid());
380    }
381
382    #[test]
383    fn is_valid_false_with_no_access_token() {
384        let cred = AgentCredential {
385            expires_at: agentmux_common::time::now_secs() + 3600,
386            ..Default::default()
387        };
388        assert!(!cred.is_valid());
389    }
390}