Skip to main content

agentmux_srv_core/identity/aws_broker/
sessions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sessions srv has minted for container agents, and how often it may mint (spec ยง8).
5//!
6//! The AWS CLI calls `credential_process` on every command, and botocore treats credentials with under ten minutes
7//! left as expired, so a session is handed out again only while at least [`REUSE_MARGIN`] remains, and a request that
8//! finds none mints. One mint at a time per (agent, grant, reason): concurrent requests wait for the same result.
9
10use std::collections::{HashMap, VecDeque};
11use std::future::Future;
12use std::sync::{Arc, Mutex};
13
14use chrono::{DateTime, Duration, Utc};
15
16use super::mint::{Minted, MintError};
17
18/// Credentials with less than this left are not handed out again.
19pub const REUSE_MARGIN: Duration = Duration::minutes(10);
20const WINDOW: Duration = Duration::hours(1);
21/// Past this many slots, the ones with nothing live in them are dropped when a new one is made.
22const PRUNE_ABOVE: usize = 32;
23
24#[derive(Clone, PartialEq, Eq, Hash)]
25struct Key {
26    agent: String,
27    grant: String,
28    reason: String,
29}
30
31struct Slot {
32    session: Option<Minted>,
33}
34
35#[derive(Debug, PartialEq, Eq)]
36pub enum SessionError {
37    /// More mints than the grant allows in the last hour.
38    TooMany { cap: u32 },
39    Mint(MintError),
40}
41
42/// Whether the answer is a session that was already there.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Source {
45    Fresh,
46    /// Minted before, still more than the margin from expiring.
47    Reused,
48}
49
50#[derive(Default)]
51pub struct Sessions {
52    slots: Mutex<HashMap<Key, Arc<tokio::sync::Mutex<Slot>>>>,
53    attempts: Mutex<HashMap<(String, String), VecDeque<DateTime<Utc>>>>,
54}
55
56impl Sessions {
57    /// The slot for `key`, made if need be. Slots that hold nothing usable (expired, or never filled) are dropped first,
58    /// so the map holds at most the sessions that are live: an agent that varies its reason cannot grow it.
59    fn slot(&self, key: &Key, now: DateTime<Utc>) -> Arc<tokio::sync::Mutex<Slot>> {
60        let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
61        if slots.len() >= PRUNE_ABOVE {
62            // A slot being minted into is locked: it stays.
63            slots.retain(|_, s| s.try_lock().map_or(true, |g| g.session.as_ref().is_some_and(|m| m.expiration > now)));
64        }
65        slots.entry(key.clone()).or_insert_with(|| Arc::new(tokio::sync::Mutex::new(Slot { session: None }))).clone()
66    }
67
68    /// Drop the slot for `key` if it holds no session: a request that could not mint leaves nothing behind.
69    fn forget_if_empty(&self, key: &Key) {
70        let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
71        if slots.get(key).is_some_and(|s| s.try_lock().is_ok_and(|g| g.session.is_none())) {
72            slots.remove(key);
73        }
74    }
75
76    /// Count an attempt at minting for (agent, grant) unless the last hour already has `cap`.
77    fn allow_attempt(&self, agent: &str, grant: &str, cap: u32, now: DateTime<Utc>) -> bool {
78        let mut all = self.attempts.lock().unwrap_or_else(|e| e.into_inner());
79        let times = all.entry((agent.to_string(), grant.to_string())).or_default();
80        while times.front().is_some_and(|t| now - *t >= WINDOW) {
81            times.pop_front();
82        }
83        if times.len() >= cap as usize {
84            return false;
85        }
86        times.push_back(now);
87        true
88    }
89
90    /// The session for (agent, grant, reason): the one minted before while it has more than the margin left, else the
91    /// result of `mint`. Attempts count against `cap` per hour whether or not they succeed, so a failing loop is
92    /// bounded too.
93    pub async fn get_or_mint<F, Fut>(
94        &self,
95        agent: &str,
96        grant: &str,
97        reason: &str,
98        cap: u32,
99        now: DateTime<Utc>,
100        mint: F,
101    ) -> Result<(Minted, Source), SessionError>
102    where
103        F: FnOnce() -> Fut,
104        Fut: Future<Output = Result<Minted, MintError>>,
105    {
106        let key = Key { agent: agent.to_string(), grant: grant.to_string(), reason: reason.to_string() };
107        let slot = self.slot(&key, now);
108        let outcome = {
109            let mut held = slot.lock().await;
110            if let Some(session) = held.session.as_ref().filter(|s| s.expiration - now >= REUSE_MARGIN) {
111                return Ok((session.clone(), Source::Reused));
112            }
113            held.session = None;
114            if !self.allow_attempt(agent, grant, cap, now) {
115                Err(SessionError::TooMany { cap })
116            } else {
117                match mint().await {
118                    Ok(minted) => {
119                        held.session = Some(minted.clone());
120                        Ok((minted, Source::Fresh))
121                    }
122                    Err(e) => Err(SessionError::Mint(e)),
123                }
124            }
125        };
126        if outcome.is_err() {
127            drop(slot);
128            self.forget_if_empty(&key);
129        }
130        outcome
131    }
132
133    /// Forget everything held for an agent (its container stopped).
134    pub fn revoke_agent(&self, agent: &str) {
135        self.slots.lock().unwrap_or_else(|e| e.into_inner()).retain(|k, _| k.agent != agent);
136        // The attempts stay: a loop that restarts its container must not reset the hourly cap.
137    }
138
139    #[cfg(test)]
140    pub fn held(&self, agent: &str) -> usize {
141        self.slots.lock().unwrap().keys().filter(|k| k.agent == agent).count()
142    }
143}
144
145/// srv's sessions: one cache for the process.
146pub fn global() -> &'static Sessions {
147    static SESSIONS: std::sync::OnceLock<Sessions> = std::sync::OnceLock::new();
148    SESSIONS.get_or_init(Sessions::default)
149}
150
151#[cfg(test)]
152#[path = "sessions_tests.rs"]
153mod tests;