Skip to main content

agentmux_srv_core/identity/
github_tokens.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! GitHub tokens for agents.
5//!
6//! An agent that pushes or opens a pull request does it as the AgentMux GitHub App's bot, with
7//! an installation token AgentMux Cloud's broker mints (`github_broker::installation_token`),
8//! never with the person's own token and never with a token pasted in. This module is srv's
9//! side of that:
10//!
11//! - which installation a repository's owner is (the installations the account has linked);
12//! - a token narrowed to the one repository and the permissions an agent needs;
13//! - a cache per (agent, owner, repository, workflows), so an agent that runs many `git`/`gh`
14//!   commands an hour asks the broker about once, refreshed when less than five minutes remain;
15//! - what the person is told when there is no token: the reason, in words, and never a fall-back
16//!   to another credential.
17//!
18//! The broker is behind [`Backend`], so the cache and the choices are tested without a network.
19
20use std::collections::{BTreeMap, HashMap};
21use std::future::Future;
22use std::sync::{Arc, OnceLock};
23
24use zeroize::Zeroizing;
25
26use crate::backend::storage::store::Store;
27use crate::muxbus::github_broker::{self, AppBot, BrokerError, InstallationRequest, LinkedInstallation};
28
29/// A cached token is renewed when it has less than this long to live.
30pub const REFRESH_MARGIN_SECS: i64 = 300;
31/// How long the list of linked installations is trusted. A fresh install shows up within this.
32const INSTALLATIONS_TTL_SECS: i64 = 60;
33/// A refusal is remembered this long, so a command that asks many times doesn't ask the broker
34/// each time (its mint limit is per hour).
35const REFUSAL_TTL_SECS: i64 = 20;
36/// If the broker's expiry can't be read, the token is trusted this long.
37const FALLBACK_LIFETIME_SECS: i64 = 600;
38
39/// What an agent's token may do: push and open pull requests and issues, read repository
40/// metadata. `workflows: write` only for an agent the person allowed to change CI.
41pub fn permissions_for(workflows: bool) -> BTreeMap<String, String> {
42    let mut p: BTreeMap<String, String> = [("contents", "write"), ("pull_requests", "write"), ("issues", "write"), ("metadata", "read")]
43        .into_iter()
44        .map(|(k, v)| (k.to_string(), v.to_string()))
45        .collect();
46    if workflows {
47        p.insert("workflows".to_string(), "write".to_string());
48    }
49    p
50}
51
52/// A token wanted: for `agent`, on `owner/repo` (names as GitHub spells them; compared without case).
53#[derive(Debug, Clone, PartialEq, Eq, Hash)]
54pub struct Want {
55    pub agent: String,
56    pub owner: String,
57    pub repo: String,
58    pub workflows: bool,
59}
60
61impl Want {
62    fn normalized(&self) -> Self {
63        Self { agent: self.agent.clone(), owner: self.owner.to_ascii_lowercase(), repo: self.repo.to_ascii_lowercase(), workflows: self.workflows }
64    }
65
66    /// Who holds this token in the transcript withhold registry: each token is held until its own expiry.
67    fn withhold_owner(&self) -> String {
68        format!("github-token:{}:{}/{}:{}", self.agent, self.owner, self.repo, self.workflows)
69    }
70}
71
72/// GitHub's own rule for an owner or a repository name, narrowed: letters, digits, `-`, `_`, `.`.
73fn valid_name(name: &str) -> bool {
74    !name.is_empty() && name.len() <= 100 && name != "." && name != ".." && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
75}
76
77/// A minted token and what to do with it.
78#[derive(Clone)]
79pub struct Minted {
80    pub token: Zeroizing<String>,
81    /// Epoch seconds.
82    pub expires_at: i64,
83    pub bot: AppBot,
84}
85
86impl std::fmt::Debug for Minted {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        f.debug_struct("Minted").field("expires_at", &self.expires_at).field("bot", &self.bot).finish_non_exhaustive()
89    }
90}
91
92/// Why there is no token. [`Display`](std::fmt::Display) is what the person (or the agent) reads.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum TokenError {
95    /// The repository's owner isn't an installation this account has linked.
96    NoInstallation { owner: String },
97    /// `owner` or `repo` isn't a GitHub name.
98    BadTarget(String),
99    /// The broker or GitHub said no, or couldn't be reached.
100    Broker(BrokerError),
101    /// This AgentMux account has no GitHub connection to check a stale link with.
102    NoGithubAccount,
103}
104
105impl std::fmt::Display for TokenError {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        match self {
108            Self::NoInstallation { owner } => write!(
109                f,
110                "AgentMux can't act on {owner}'s repositories: the AgentMux GitHub App isn't installed there, or isn't linked to this AgentMux account. Install it in Connectors → Accounts"
111            ),
112            Self::BadTarget(what) => write!(f, "{what} isn't a GitHub owner or repository name"),
113            Self::Broker(e) => write!(f, "{e}"),
114            Self::NoGithubAccount => write!(f, "GitHub isn't connected on this AgentMux account: connect it in Connectors → Accounts"),
115        }
116    }
117}
118
119impl From<BrokerError> for TokenError {
120    fn from(e: BrokerError) -> Self {
121        Self::Broker(e)
122    }
123}
124
125/// What a mint asks for, owned so it can be asked twice.
126#[derive(Debug, Clone)]
127pub struct MintRequest {
128    pub installation_id: u64,
129    pub repositories: Vec<String>,
130    pub permissions: BTreeMap<String, String>,
131    pub agent: String,
132}
133
134/// The broker, as this module needs it.
135pub trait Backend {
136    fn installations(&self) -> impl Future<Output = Result<Vec<LinkedInstallation>, BrokerError>> + Send;
137    fn mint(&self, request: MintRequest) -> impl Future<Output = Result<github_broker::InstallationToken, BrokerError>> + Send;
138    /// Present the person's own fresh GitHub token so the broker re-reads what they can see.
139    fn revalidate(&self) -> impl Future<Output = Result<(), TokenError>> + Send;
140    /// Who the tokens are minted for: the person's brokered GitHub account, while AgentMux Cloud is
141    /// signed in. Another answer than the last one (or none) means what was cached is not theirs.
142    fn connection(&self) -> impl Future<Output = Result<String, TokenError>> + Send;
143}
144
145#[derive(Default)]
146struct State {
147    /// The connection every entry below was obtained under.
148    connection: Option<String>,
149    cache: HashMap<Want, Minted>,
150    installations: Option<(i64, Vec<LinkedInstallation>)>,
151    refused: HashMap<Want, (i64, TokenError)>,
152    /// One lock per token wanted, so a slow broker call for one repository doesn't hold up another's.
153    locks: HashMap<Want, Arc<tokio::sync::Mutex<()>>>,
154}
155
156/// The tokens srv has minted for agents.
157#[derive(Default)]
158pub struct Tokens {
159    state: std::sync::Mutex<State>,
160}
161
162impl Tokens {
163    fn st(&self) -> std::sync::MutexGuard<'_, State> {
164        self.state.lock().unwrap_or_else(|e| e.into_inner())
165    }
166
167    /// A token for `want`: the cached one while it has time left, else a new one.
168    pub async fn token_for<B: Backend>(&self, backend: &B, want: &Want, now: i64) -> Result<Minted, TokenError> {
169        for (what, name) in [("the owner", &want.owner), ("the repository", &want.repo)] {
170            if !valid_name(name) {
171                return Err(TokenError::BadTarget(format!("{what} {:?}", name.chars().take(40).collect::<String>())));
172            }
173        }
174        let want = want.normalized();
175        // A disconnect, a sign-out or another account takes back what was minted before it.
176        let connection = backend.connection().await;
177        self.bind(connection.as_ref().ok());
178        let connection = connection?;
179        // One at a time for this token: an agent's many commands at once must not each mint.
180        let lock = self.st().locks.entry(want.clone()).or_default().clone();
181        let _one = lock.lock().await;
182        if let Some(found) = self.remembered(&want, now) {
183            return found;
184        }
185        let result = self.mint(backend, &want, now).await;
186        let mut st = self.st();
187        // Not kept if the connection changed while the broker was answering.
188        if st.connection.as_ref() != Some(&connection) {
189            return result;
190        }
191        match &result {
192            Ok(minted) => {
193                st.refused.remove(&want);
194                // A token an agent's git or `gh` holds is never written into a transcript, until it runs out: a renewed
195                // token does not end the one it replaced, which works for its last minutes, and a disconnect only
196                // makes srv forget it, so the token still works until its expiry.
197                crate::backend::transcript::withhold::hold_until(&want.withhold_owner(), &minted.token, minted.expires_at.saturating_mul(1000));
198                st.cache.insert(want.clone(), minted.clone());
199            }
200            // A bad moment at the broker doesn't take back a token that still works.
201            Err(TokenError::Broker(BrokerError::Unavailable(_))) if st.cache.get(&want).is_some_and(|m| m.expires_at > now) => {
202                let kept = st.cache[&want].clone();
203                return Ok(kept);
204            }
205            Err(error) => {
206                st.cache.remove(&want);
207                st.refused.insert(want.clone(), (now + REFUSAL_TTL_SECS, error.clone()));
208            }
209        }
210        // What has run out is dropped, so the maps hold only what is in use.
211        st.cache.retain(|_, m| m.expires_at > now);
212        st.refused.retain(|_, (until, _)| *until > now);
213        let keep: Vec<Want> = st.cache.keys().chain(st.refused.keys()).cloned().collect();
214        st.locks.retain(|k, l| Arc::strong_count(l) > 1 || keep.contains(k) || *k == want);
215        result
216    }
217
218    /// Forget everything held when `connection` is not the one it was obtained under.
219    fn bind(&self, connection: Option<&String>) {
220        let mut st = self.st();
221        if st.connection.as_ref() != connection {
222            st.cache.clear();
223            st.refused.clear();
224            st.installations = None;
225            st.connection = connection.cloned();
226        }
227    }
228
229    /// The answer already known for `want`: a token with time left, or a refusal not yet expired.
230    fn remembered(&self, want: &Want, now: i64) -> Option<Result<Minted, TokenError>> {
231        let st = self.st();
232        if let Some(minted) = st.cache.get(want) {
233            if minted.expires_at - now > REFRESH_MARGIN_SECS {
234                return Some(Ok(minted.clone()));
235            }
236        }
237        match st.refused.get(want) {
238            Some((until, error)) if now < *until => Some(Err(error.clone())),
239            _ => None,
240        }
241    }
242
243    async fn mint<B: Backend>(&self, backend: &B, want: &Want, now: i64) -> Result<Minted, TokenError> {
244        let installation = self.installation_for(backend, &want.owner, now).await?;
245        let request = MintRequest {
246            installation_id: installation.installation_id,
247            repositories: vec![want.repo.clone()],
248            permissions: permissions_for(want.workflows),
249            agent: want.agent.clone(),
250        };
251        let answer = match backend.mint(request.clone()).await {
252            // The link wasn't verified lately: the person's own token proves it again, once.
253            Err(BrokerError::LinkStale) => {
254                backend.revalidate().await?;
255                self.st().installations = None;
256                backend.mint(request).await
257            }
258            Err(BrokerError::NotLinked) => {
259                self.st().installations = None;
260                Err(BrokerError::NotLinked)
261            }
262            other => other,
263        }?;
264        let expires_at = answer.expires_at_epoch().unwrap_or(now + FALLBACK_LIFETIME_SECS);
265        tracing::info!(target: "identity", agent = %want.agent, owner = %want.owner, repo = %want.repo, installation = installation.installation_id, "identity.github: minted an agent token");
266        Ok(Minted { token: Zeroizing::new(answer.token), expires_at, bot: answer.app })
267    }
268
269    async fn installation_for<B: Backend>(&self, backend: &B, owner: &str, now: i64) -> Result<LinkedInstallation, TokenError> {
270        let known = self.st().installations.clone();
271        let fresh = matches!(&known, Some((at, _)) if now - *at < INSTALLATIONS_TTL_SECS);
272        let list = match known {
273            Some((_, list)) if fresh => list,
274            _ => {
275                let list = backend.installations().await?;
276                self.st().installations = Some((now, list.clone()));
277                list
278            }
279        };
280        let found = |list: &[LinkedInstallation]| list.iter().find(|i| i.is_usable() && i.github_account.login.eq_ignore_ascii_case(owner)).cloned();
281        if let Some(i) = found(&list) {
282            return Ok(i);
283        }
284        // Not in a list this old: an install made in the last minute is worth one look.
285        if fresh {
286            let list = backend.installations().await?;
287            self.st().installations = Some((now, list.clone()));
288            if let Some(i) = found(&list) {
289                return Ok(i);
290            }
291        }
292        Err(TokenError::NoInstallation { owner: owner.to_string() })
293    }
294
295    /// The tokens held, for tests.
296    #[cfg(any(test, feature = "test-support"))]
297    fn cached(&self) -> usize {
298        self.st().cache.len()
299    }
300
301    /// The per-token locks kept, for tests.
302    #[cfg(any(test, feature = "test-support"))]
303    fn locks(&self) -> usize {
304        self.st().locks.len()
305    }
306}
307
308/// Set in the environment of an agent whose `git` and `gh` use the broker's tokens; the `gh`
309/// function `agentmux-bashwrap` exports reads it.
310pub const BROKER_ENV: &str = "AGENTMUX_GITHUB_BROKER";
311use agentmux_common::github_broker_shim::{GH_FUNCTION_BODY, GH_FUNCTION_NAME, GIT_FUNCTION_BODY, GIT_FUNCTION_NAME};
312/// The machine's name for a commit trailer, set with the git setup (read by `agentmux-bashwrap`).
313const GIT_HOST_ENV: &str = "AGENTMUX_GIT_HOST";
314
315/// This machine's name as the fleet writes it (`narko`): lower case, without a domain.
316pub(crate) fn host_label() -> Option<String> {
317    let name = whoami::fallible::hostname().ok()?;
318    short_host(&name)
319}
320
321fn short_host(name: &str) -> Option<String> {
322    let short = name.trim().split('.').next().unwrap_or("").to_ascii_lowercase();
323    (!short.is_empty()).then_some(short)
324}
325
326const HELPER_KEY: &str = "credential.https://github.com.helper";
327const HELPER: &str = "!agentmux-bashwrap git-credential";
328const HTTP_PATH_KEY: &str = "credential.https://github.com.useHttpPath";
329const REWRITE_KEY: &str = "url.https://github.com/.insteadOf";
330
331/// Point an agent's `git` at the broker's tokens, or take that out again.
332///
333/// With `enabled`, GitHub over https asks `agentmux-bashwrap git-credential` and nothing else:
334/// an empty helper before it clears every other (the person's stored login, a token cache), and
335/// the repository's path goes with the request so the token can be narrowed to it. `ssh` remotes
336/// to GitHub are rewritten to https, because an ssh key is the person's own credential. Prompts
337/// are off, so a refusal ends the command with the reason instead of waiting at a prompt no one
338/// sees. Without `enabled`, any of this left in the environment from an earlier start is removed.
339pub fn apply_agent_git_in(
340    env: &mut HashMap<String, String>,
341    process: impl Fn(&str) -> Option<String> + Copy,
342    enabled: bool,
343    hooks_dir: Option<&std::path::Path>,
344) {
345    use crate::backend::publish_guard::{set_git_config_list, HOOKS_PATH_KEY};
346    if enabled {
347        // AgentMux's own hooks: the push scan and the commit trailers.
348        if let Some(dir) = hooks_dir {
349            let dir = dir.to_string_lossy().into_owned();
350            set_git_config_list(env, process, HOOKS_PATH_KEY, &[dir.as_str()]);
351        }
352        set_git_config_list(env, process, HELPER_KEY, &["", HELPER]);
353        set_git_config_list(env, process, HTTP_PATH_KEY, &["true"]);
354        set_git_config_list(env, process, REWRITE_KEY, &["git@github.com:", "ssh://git@github.com/"]);
355        env.insert("GIT_TERMINAL_PROMPT".to_string(), "0".to_string());
356        env.insert(BROKER_ENV.to_string(), "1".to_string());
357        // The commit trailer names the agent as `agent@host`, and the host is this machine's name.
358        if let Some(host) = host_label() {
359            env.insert(GIT_HOST_ENV.to_string(), host);
360        }
361        // `gh` goes through the broker too, in every bash the agent runs, whichever CLI started it.
362        env.insert(GH_FUNCTION_NAME.to_string(), GH_FUNCTION_BODY.to_string());
363        // `git` too: a push can't skip the hooks, and a commit is the bot's.
364        env.insert(GIT_FUNCTION_NAME.to_string(), GIT_FUNCTION_BODY.to_string());
365    } else if env.contains_key(BROKER_ENV) {
366        for key in [HELPER_KEY, HTTP_PATH_KEY, REWRITE_KEY, HOOKS_PATH_KEY] {
367            set_git_config_list(env, process, key, &[]);
368        }
369        env.remove(BROKER_ENV);
370        env.remove(GIT_HOST_ENV);
371        env.remove(GH_FUNCTION_NAME);
372        env.remove(GIT_FUNCTION_NAME);
373        // Set with the rest, and only ever set by it: prompts come back with the connection gone.
374        env.remove("GIT_TERMINAL_PROMPT");
375    }
376}
377
378/// `env` without what [`apply_agent_git_in`] sets: for a container, which gets its own setup
379/// ([`apply_container_git`]) or none.
380pub fn without_agent_git(env: &HashMap<String, String>) -> HashMap<String, String> {
381    use crate::backend::publish_guard::{without_git_config_key, HOOKS_PATH_KEY};
382    if !env.contains_key(BROKER_ENV) {
383        return env.clone();
384    }
385    let mut out = [HELPER_KEY, HTTP_PATH_KEY, REWRITE_KEY, HOOKS_PATH_KEY].iter().fold(env.clone(), |e, key| without_git_config_key(&e, key));
386    out.remove(BROKER_ENV);
387    out.remove(GIT_HOST_ENV);
388    out.remove(GH_FUNCTION_NAME);
389    out.remove(GIT_FUNCTION_NAME);
390    out.remove("GIT_TERMINAL_PROMPT");
391    out
392}
393
394static STORE: OnceLock<Arc<Store>> = OnceLock::new();
395
396/// The account store, whose GitHub accounts decide whether agents use the broker.
397pub fn attach_store(store: Arc<Store>) {
398    let _ = STORE.set(store);
399}
400
401/// Whether agents on this machine get the broker's GitHub tokens: the person connected GitHub
402/// through AgentMux Cloud (a brokered account that still works), and this isn't a fleet host,
403/// where `gh-agent` already gives agents their GitHub identity.
404pub(crate) fn agents_use_broker(env: &HashMap<String, String>) -> bool {
405    if crate::backend::publish_guard::hooks_dir_for(env, |k| std::env::var(k).ok()).is_some() {
406        return false;
407    }
408    broker_account_connected()
409}
410
411/// Whether the person connected GitHub through AgentMux Cloud and the account still works.
412fn broker_account_connected() -> bool {
413    use std::sync::Mutex;
414    use std::time::{Duration, Instant};
415    static CACHE: Mutex<Option<(Instant, bool)>> = Mutex::new(None);
416    let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
417    if let Some((at, answer)) = *cache {
418        if at.elapsed() < Duration::from_secs(5) {
419            return answer;
420        }
421    }
422    let answer = STORE.get().is_some_and(|store| {
423        store
424            .identity_list(Some(crate::identity::github_connect::PROVIDER))
425            .unwrap_or_default()
426            .iter()
427            .any(|a| crate::identity::github_connect::is_brokered(a) && a.status != crate::identity::oauth_tokens::STATUS_NEEDS_REAUTH)
428    });
429    *cache = Some((Instant::now(), answer));
430    answer
431}
432
433/// Where AgentMux's git hooks are mounted, read-only, in a container agent's image. Ends in the
434/// directory's own name, which `agentmux-bashwrap` knows its hooks by.
435pub const CONTAINER_HOOKS_DIR: &str = "/opt/agentmux/github-hooks";
436
437/// The host's hooks directory when container agents get git and `gh` through AgentMux: a token
438/// source exists (the host's `gh-agent`, or the person's connected GitHub account) and the hooks
439/// can be written. Without the hooks there is no setup at all, so a container never gets a token
440/// whose pushes aren't scanned.
441pub fn container_git_hooks() -> Option<std::path::PathBuf> {
442    // The machine running the tests has its own answer; the tests give theirs.
443    if cfg!(any(test, feature = "test-support")) {
444        return None;
445    }
446    if crate::identity::gh_agent_token::installed().is_none() && !broker_account_connected() {
447        return None;
448    }
449    crate::identity::github_hooks::hooks_dir()
450}
451
452/// A container agent's exec environment with its git and `gh` set up like a host agent's: the
453/// credential helper, the `git` and `gh` functions and the hooks, which `agentmux-bashwrap` in the
454/// image runs from [`CONTAINER_HOOKS_DIR`].
455pub fn apply_container_git(env: &mut HashMap<String, String>) {
456    apply_agent_git_in(env, |_| None, true, Some(std::path::Path::new(CONTAINER_HOOKS_DIR)));
457    // The workspace and the clones in it are bind mounts owned by the host's user: without this git
458    // stops at "dubious ownership" (`/workspace` alone doesn't cover `/workspace/<clone>`). Everything
459    // in the container is the agent's own, and the setting is read from here only, never from a repository.
460    crate::backend::publish_guard::set_git_config_list(env, |_| None, "safe.directory", &["*"]);
461}
462
463/// [`apply_agent_git_in`] for a spawn: every path that starts an agent process or runs a command for
464/// one comes through `gh_guard::apply_gh_guard`, which calls this.
465#[cfg_attr(test, allow(dead_code))]
466pub fn apply_agent_git(env: &mut HashMap<String, String>) {
467    let enabled = agents_use_broker(env);
468    let hooks = enabled.then(crate::identity::github_hooks::hooks_dir).flatten();
469    apply_agent_git_in(env, |k| std::env::var(k).ok(), enabled, hooks.as_deref());
470}
471
472/// srv's tokens: one cache for the process.
473pub fn global() -> &'static Tokens {
474    static TOKENS: OnceLock<Tokens> = OnceLock::new();
475    TOKENS.get_or_init(Tokens::default)
476}
477
478/// The broker as this install reaches it: the cloud sign-in and the instance key, and the person's
479/// brokered GitHub account for a revalidation.
480pub struct Live {
481    pub mstore: Arc<Store>,
482    pub identity_store: Arc<Store>,
483}
484
485impl Backend for Live {
486    async fn installations(&self) -> Result<Vec<LinkedInstallation>, BrokerError> {
487        let who = github_broker::caller(&self.mstore).await?;
488        github_broker::installations(crate::identity::oauth_client::http(), &who).await
489    }
490
491    async fn mint(&self, request: MintRequest) -> Result<github_broker::InstallationToken, BrokerError> {
492        let who = github_broker::caller(&self.mstore).await?;
493        github_broker::installation_token(
494            crate::identity::oauth_client::http(),
495            &who,
496            &InstallationRequest {
497                installation_id: request.installation_id,
498                repositories: &request.repositories,
499                permissions: &request.permissions,
500                agent_id: &request.agent,
501            },
502        )
503        .await
504    }
505
506    async fn connection(&self) -> Result<String, TokenError> {
507        let account = self
508            .mstore
509            .identity_list(Some(crate::identity::github_connect::PROVIDER))
510            .unwrap_or_default()
511            .into_iter()
512            .find(crate::identity::github_connect::is_brokered)
513            .ok_or(TokenError::NoGithubAccount)?;
514        github_broker::caller(&self.mstore).await?;
515        Ok(format!("{}/{}", account.id, account.context.get("id").map(|v| v.to_string()).unwrap_or_default()))
516    }
517
518    async fn revalidate(&self) -> Result<(), TokenError> {
519        let account = self
520            .mstore
521            .identity_list(Some(crate::identity::github_connect::PROVIDER))
522            .unwrap_or_default()
523            .into_iter()
524            .find(crate::identity::github_connect::is_brokered)
525            .ok_or(TokenError::NoGithubAccount)?;
526        let token = crate::identity::oauth_tokens::access_token_for(
527            &crate::identity::oauth_tokens::LiveHttp,
528            &crate::identity::oauth_tokens::KeychainSecrets,
529            &self.mstore,
530            &self.identity_store,
531            &account,
532            Some(&self.mstore),
533        )
534        .await
535        .map_err(|e| TokenError::Broker(BrokerError::NotSignedIn(e)))?;
536        let who = github_broker::caller(&self.mstore).await?;
537        github_broker::revalidate(crate::identity::oauth_client::http(), &who, &token).await?;
538        Ok(())
539    }
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545    use crate::muxbus::github_broker::{InstallationAccount, InstallationToken};
546    use std::sync::Mutex;
547
548    fn link(id: u64, login: &str, installation: &str, link: &str) -> LinkedInstallation {
549        LinkedInstallation {
550            installation_id: id,
551            github_account: InstallationAccount { id: id * 10, login: login.to_string() },
552            repository_selection: "selected".to_string(),
553            installation_status: installation.to_string(),
554            link_status: link.to_string(),
555            verified_at_ms: 0,
556            visible_count: 0,
557            linked_at_ms: 0,
558        }
559    }
560
561    fn token(expires_at: &str) -> InstallationToken {
562        InstallationToken {
563            token: "ghs_TOKEN".to_string(),
564            expires_at: expires_at.to_string(),
565            permissions: BTreeMap::new(),
566            repository_ids: vec![1],
567            app: AppBot { slug: "muxagent".to_string(), bot_user_id: 77 },
568        }
569    }
570
571    /// A broker that answers from lists, and counts what it was asked.
572    struct Fake {
573        installs: Mutex<Vec<Vec<LinkedInstallation>>>,
574        mints: Mutex<Vec<Result<InstallationToken, BrokerError>>>,
575        asked: Mutex<Vec<MintRequest>>,
576        listed: Mutex<u32>,
577        revalidated: Mutex<u32>,
578        revalidate_ok: bool,
579        connection: Mutex<Result<String, TokenError>>,
580    }
581
582    impl Fake {
583        fn new(installs: Vec<Vec<LinkedInstallation>>, mints: Vec<Result<InstallationToken, BrokerError>>) -> Self {
584            Self { installs: Mutex::new(installs), mints: Mutex::new(mints), asked: Mutex::default(), listed: Mutex::new(0), revalidated: Mutex::new(0), revalidate_ok: true, connection: Mutex::new(Ok("acct-1".to_string())) }
585        }
586    }
587
588    impl Backend for Fake {
589        async fn installations(&self) -> Result<Vec<LinkedInstallation>, BrokerError> {
590            *self.listed.lock().unwrap() += 1;
591            let mut l = self.installs.lock().unwrap();
592            Ok(if l.len() > 1 { l.remove(0) } else { l[0].clone() })
593        }
594        async fn mint(&self, request: MintRequest) -> Result<InstallationToken, BrokerError> {
595            self.asked.lock().unwrap().push(request);
596            let mut m = self.mints.lock().unwrap();
597            if m.len() > 1 { m.remove(0) } else { m[0].clone().map_err(|e| e) }
598        }
599        async fn connection(&self) -> Result<String, TokenError> {
600            self.connection.lock().unwrap().clone()
601        }
602        async fn revalidate(&self) -> Result<(), TokenError> {
603            *self.revalidated.lock().unwrap() += 1;
604            if self.revalidate_ok { Ok(()) } else { Err(TokenError::NoGithubAccount) }
605        }
606    }
607
608    fn want(owner: &str, repo: &str) -> Want {
609        Want { agent: "korp".to_string(), owner: owner.to_string(), repo: repo.to_string(), workflows: false }
610    }
611
612    const NOW: i64 = 1_793_178_000;
613
614    fn ok_for(secs: i64) -> InstallationToken {
615        let at = chrono::DateTime::from_timestamp(NOW + secs, 0).unwrap().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
616        token(&at)
617    }
618
619    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
620        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
621    }
622
623    fn entries(e: &HashMap<String, String>) -> Vec<(String, String)> {
624        let n: usize = e.get("GIT_CONFIG_COUNT").and_then(|c| c.parse().ok()).unwrap_or(0);
625        (0..n).map(|i| (e[&format!("GIT_CONFIG_KEY_{i}")].clone(), e[&format!("GIT_CONFIG_VALUE_{i}")].clone())).collect()
626    }
627
628    #[test]
629    fn an_agent_with_the_broker_gets_only_its_credential_helper_for_github() {
630        let mut e = env(&[("GIT_CONFIG_COUNT", "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x")]);
631        apply_agent_git_in(&mut e, |_| None, true, None);
632        let got = entries(&e);
633        // The reset comes right before ours: whatever helper was configured before is not asked.
634        let at = got.iter().position(|(k, v)| k == HELPER_KEY && v.is_empty()).expect("the reset");
635        assert_eq!(got[at + 1], (HELPER_KEY.to_string(), HELPER.to_string()));
636        assert!(got.contains(&(HTTP_PATH_KEY.to_string(), "true".to_string())));
637        assert!(got.contains(&(REWRITE_KEY.to_string(), "git@github.com:".to_string())), "ssh remotes use the token too");
638        assert!(got.contains(&("user.name".to_string(), "x".to_string())), "other settings stay");
639        assert_eq!((e["GIT_TERMINAL_PROMPT"].as_str(), e[BROKER_ENV].as_str()), ("0", "1"));
640        assert_eq!(e[GH_FUNCTION_NAME], GH_FUNCTION_BODY, "gh reaches the broker in every provider's shell");
641        // Applied again (a persisted cmd:env): the same, not twice.
642        let before = e.clone();
643        apply_agent_git_in(&mut e, |_| None, true, None);
644        assert_eq!(e, before);
645    }
646
647    #[test]
648    fn an_agent_with_the_broker_gets_the_agentmux_hooks_and_git_function_and_loses_them_when_disconnected() {
649        let hooks = std::path::Path::new("/agentmux/github-hooks");
650        let mut e = env(&[("GIT_CONFIG_COUNT", "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x")]);
651        apply_agent_git_in(&mut e, |_| None, true, Some(hooks));
652        assert!(entries(&e).contains(&("core.hooksPath".to_string(), hooks.to_string_lossy().into_owned())));
653        assert_eq!(e[GIT_FUNCTION_NAME], GIT_FUNCTION_BODY);
654        // Applied again: the same, not twice.
655        let before = e.clone();
656        apply_agent_git_in(&mut e, |_| None, true, Some(hooks));
657        assert_eq!(e, before);
658        // Disconnected since: the hooks, the function and the rest are taken out; other settings stay.
659        apply_agent_git_in(&mut e, |_| None, false, None);
660        assert_eq!(entries(&e), vec![("user.name".to_string(), "x".to_string())]);
661        assert!(!e.contains_key(GIT_FUNCTION_NAME));
662        // A container gets neither.
663        let mut c = env(&[]);
664        apply_agent_git_in(&mut c, |_| None, true, Some(hooks));
665        let out = without_agent_git(&c);
666        assert!(!out.contains_key(GIT_FUNCTION_NAME) && !out.contains_key(GH_FUNCTION_NAME));
667    }
668
669    #[test]
670    fn an_agent_without_the_broker_keeps_its_own_git_and_loses_a_stale_setup() {
671        let mut plain = env(&[("GIT_CONFIG_COUNT", "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x")]);
672        let before = plain.clone();
673        apply_agent_git_in(&mut plain, |_| None, false, None);
674        assert_eq!(plain, before, "nothing added when GitHub isn't connected");
675        // Disconnected since the last start: what was set is taken out, the rest stays.
676        let mut e = before.clone();
677        apply_agent_git_in(&mut e, |_| None, true, None);
678        apply_agent_git_in(&mut e, |_| None, false, None);
679        assert_eq!(entries(&e), vec![("user.name".to_string(), "x".to_string())]);
680        assert!(!e.contains_key(BROKER_ENV) && !e.contains_key("GIT_TERMINAL_PROMPT") && !e.contains_key(GH_FUNCTION_NAME), "prompts and plain gh are back too");
681    }
682
683    #[tokio::test]
684    async fn a_token_is_narrowed_to_the_repository_and_the_default_permissions() {
685        let fake = Fake::new(vec![vec![link(5, "Octo-Org", "active", "active")]], vec![Ok(ok_for(3600))]);
686        let tokens = Tokens::default();
687        let minted = tokens.token_for(&fake, &want("octo-org", "Hello"), NOW).await.unwrap();
688        assert_eq!((minted.token.as_str(), minted.bot.slug.as_str(), minted.expires_at), ("ghs_TOKEN", "muxagent", NOW + 3600));
689        let asked = fake.asked.lock().unwrap();
690        assert_eq!(asked.len(), 1);
691        assert_eq!((asked[0].installation_id, asked[0].repositories.clone(), asked[0].agent.as_str()), (5, vec!["hello".to_string()], "korp"));
692        assert_eq!(asked[0].permissions, permissions_for(false));
693        assert!(!asked[0].permissions.contains_key("workflows"), "no CI changes unless the person allowed them");
694        assert!(!format!("{minted:?}").contains("ghs_TOKEN"));
695    }
696
697    #[tokio::test]
698    async fn a_minted_token_is_withheld_from_transcripts_until_it_runs_out() {
699        use crate::backend::transcript::withhold;
700        let now = chrono::Utc::now().timestamp();
701        let answer = |value: &str, secs: i64| {
702            let at = chrono::DateTime::from_timestamp(now + secs, 0).unwrap().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
703            InstallationToken { token: value.to_string(), ..token(&at) }
704        };
705        let shown = |value: &str| withhold::text(&format!("GH_TOKEN={value}")).into_owned();
706        let w = Want { agent: "withhold-gh-agent".into(), ..want("o", "r") };
707        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(answer("ghs_canary_withhold_0001", 3600)), Ok(answer("ghs_canary_withhold_0002", 7200))]);
708        let tokens = Tokens::default();
709
710        tokens.token_for(&fake, &w, now).await.unwrap();
711        assert_eq!(shown("ghs_canary_withhold_0001"), format!("GH_TOKEN={}", withhold::MARK), "withheld from the moment it is minted");
712
713        // Within five minutes of running out it is renewed: both tokens work, so both are withheld.
714        tokens.token_for(&fake, &w, now + 3600 - 100).await.unwrap();
715        assert_eq!(shown("ghs_canary_withhold_0002"), format!("GH_TOKEN={}", withhold::MARK));
716        assert_eq!(shown("ghs_canary_withhold_0001"), format!("GH_TOKEN={}", withhold::MARK), "the token that was replaced still works");
717
718        // A disconnect makes srv forget its cached tokens; they still work until they expire, so they stay withheld.
719        *fake.connection.lock().unwrap() = Err(TokenError::NoGithubAccount);
720        tokens.token_for(&fake, &w, now + 3600).await.unwrap_err();
721        assert_eq!(shown("ghs_canary_withhold_0002"), format!("GH_TOKEN={}", withhold::MARK));
722        assert_eq!(shown("ghs_canary_withhold_0001"), format!("GH_TOKEN={}", withhold::MARK));
723    }
724
725    #[tokio::test]
726    async fn a_minted_token_stops_being_withheld_when_it_runs_out() {
727        use crate::backend::transcript::withhold;
728        let at = chrono::Utc::now().timestamp() - 1;
729        let stamp = chrono::DateTime::from_timestamp(at, 0).unwrap().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
730        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(InstallationToken { token: "ghs_canary_withhold_0003".to_string(), ..token(&stamp) })]);
731        let w = Want { agent: "withhold-gh-expired".into(), ..want("o", "r") };
732        Tokens::default().token_for(&fake, &w, at - 3600).await.unwrap();
733        let line = "GH_TOKEN=ghs_canary_withhold_0003";
734        assert_eq!(withhold::text(line), line, "a token whose expiry has passed is not kept");
735    }
736
737    #[test]
738    fn workflows_are_asked_for_only_when_allowed() {
739        assert_eq!(permissions_for(true).get("workflows").map(String::as_str), Some("write"));
740        assert!(!permissions_for(false).contains_key("workflows"));
741        assert_eq!(permissions_for(false).get("metadata").map(String::as_str), Some("read"));
742    }
743
744    #[tokio::test]
745    async fn the_cache_serves_a_token_until_five_minutes_remain() {
746        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600)), Ok(ok_for(7200))]);
747        let tokens = Tokens::default();
748        let w = want("o", "r");
749        tokens.token_for(&fake, &w, NOW).await.unwrap();
750        tokens.token_for(&fake, &w, NOW + 3000).await.unwrap();
751        assert_eq!(fake.asked.lock().unwrap().len(), 1, "an agent's many commands share one mint");
752        // 299 s left: renewed.
753        let renewed = tokens.token_for(&fake, &w, NOW + 3600 - 299).await.unwrap();
754        assert_eq!(fake.asked.lock().unwrap().len(), 2);
755        assert_eq!(renewed.expires_at, NOW + 7200);
756        // Another agent, or workflows on, is another token.
757        tokens.token_for(&fake, &Want { agent: "agenty".into(), ..w.clone() }, NOW).await.unwrap();
758        tokens.token_for(&fake, &Want { workflows: true, ..w.clone() }, NOW).await.unwrap();
759        assert_eq!(fake.asked.lock().unwrap().len(), 4);
760        assert_eq!(tokens.cached(), 3);
761    }
762
763    #[tokio::test]
764    async fn a_disconnect_or_another_account_takes_back_the_cached_tokens() {
765        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600))]);
766        let tokens = Tokens::default();
767        let w = want("o", "r");
768        tokens.token_for(&fake, &w, NOW).await.unwrap();
769        tokens.token_for(&fake, &w, NOW + 10).await.unwrap();
770        assert_eq!(fake.asked.lock().unwrap().len(), 1);
771        // Disconnected (or signed out): no token, though the cached one has most of its hour left.
772        *fake.connection.lock().unwrap() = Err(TokenError::NoGithubAccount);
773        assert_eq!(tokens.token_for(&fake, &w, NOW + 20).await.unwrap_err(), TokenError::NoGithubAccount);
774        assert_eq!(tokens.cached(), 0);
775        // Connected again as the same account: asked afresh, not served from before.
776        *fake.connection.lock().unwrap() = Ok("acct-1".to_string());
777        tokens.token_for(&fake, &w, NOW + 30).await.unwrap();
778        assert_eq!(fake.asked.lock().unwrap().len(), 2);
779        // Another account: asked afresh too.
780        *fake.connection.lock().unwrap() = Ok("acct-2".to_string());
781        tokens.token_for(&fake, &w, NOW + 40).await.unwrap();
782        assert_eq!(fake.asked.lock().unwrap().len(), 3);
783    }
784
785    #[tokio::test]
786    async fn what_has_run_out_is_dropped_and_one_slow_token_does_not_hold_up_another() {
787        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600)), Ok(ok_for(3600)), Ok(ok_for(3600)), Ok(ok_for(10_800))]);
788        let tokens = Tokens::default();
789        for repo in ["a", "b", "c"] {
790            tokens.token_for(&fake, &want("o", repo), NOW).await.unwrap();
791        }
792        assert_eq!((tokens.cached(), tokens.locks()), (3, 3));
793        // An hour later all three have run out: asking for a fourth drops them.
794        tokens.token_for(&fake, &want("o", "d"), NOW + 7200).await.unwrap();
795        assert_eq!((tokens.cached(), tokens.locks()), (1, 1));
796    }
797
798    #[test]
799    fn the_host_is_the_machines_short_lower_case_name() {
800        assert_eq!(short_host("NARKO").as_deref(), Some("narko"));
801        assert_eq!(short_host(" Area54.lan. ").as_deref(), Some("area54"));
802        assert_eq!(short_host("").as_deref(), None);
803        assert_eq!(short_host(".local").as_deref(), None);
804    }
805
806    #[test]
807    fn the_host_name_rides_with_the_setup_and_leaves_with_it() {
808        let mut e = env(&[]);
809        apply_agent_git_in(&mut e, |_| None, true, None);
810        assert_eq!(e.get(GIT_HOST_ENV).map(String::as_str), host_label().as_deref());
811        assert!(!without_agent_git(&e).contains_key(GIT_HOST_ENV));
812        apply_agent_git_in(&mut e, |_| None, false, None);
813        assert!(!e.contains_key(GIT_HOST_ENV));
814    }
815
816    #[tokio::test]
817    async fn a_container_gets_none_of_the_agent_git_setup() {
818        let mut e = env(&[("GIT_CONFIG_COUNT", "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x"), ("OTHER", "kept")]);
819        apply_agent_git_in(&mut e, |_| None, true, None);
820        let out = without_agent_git(&e);
821        assert_eq!(entries(&out), vec![("user.name".to_string(), "x".to_string())]);
822        assert!(!out.contains_key(BROKER_ENV) && !out.contains_key("GIT_TERMINAL_PROMPT") && !out.contains_key(GH_FUNCTION_NAME));
823        assert_eq!(out["OTHER"], "kept");
824        // An env that never had it is returned as it was.
825        let plain = env(&[("A", "b")]);
826        assert_eq!(without_agent_git(&plain), plain);
827    }
828
829    #[test]
830    fn a_container_gets_the_helper_the_functions_and_the_hooks_where_the_image_finds_them() {
831        let mut e = env(&[("OTHER", "kept")]);
832        apply_container_git(&mut e);
833        assert_eq!(e[BROKER_ENV], "1");
834        assert!(e.contains_key(GH_FUNCTION_NAME) && e.contains_key(GIT_FUNCTION_NAME));
835        let config = entries(&e);
836        assert!(config.contains(&("core.hooksPath".to_string(), CONTAINER_HOOKS_DIR.to_string())), "{config:?}");
837        assert!(config.iter().any(|(k, v)| k == HELPER_KEY && v == HELPER));
838        assert!(config.contains(&("safe.directory".to_string(), "*".to_string())), "{config:?}");
839        // The directory is named like the host's, which the hook forwarding knows it by.
840        assert!(CONTAINER_HOOKS_DIR.ends_with("/github-hooks"));
841        assert_eq!(e["OTHER"], "kept");
842        // And a host path never reaches a container's config.
843        assert!(!config.iter().any(|(_, v)| v.contains(":\\") || v.contains(".agentmux")));
844    }
845
846    #[tokio::test]
847    async fn an_owner_without_an_active_link_gets_a_plain_answer_and_no_mint() {
848        let fake = Fake::new(
849            vec![vec![link(5, "other", "active", "active"), link(6, "o", "suspended", "active"), link(7, "o", "active", "revoked")]],
850            vec![Ok(ok_for(3600))],
851        );
852        let tokens = Tokens::default();
853        let err = tokens.token_for(&fake, &want("o", "r"), NOW).await.unwrap_err();
854        assert_eq!(err, TokenError::NoInstallation { owner: "o".to_string() });
855        assert!(err.to_string().contains("Install it in Connectors"), "{err}");
856        assert!(fake.asked.lock().unwrap().is_empty());
857    }
858
859    #[tokio::test]
860    async fn a_refusal_is_remembered_briefly_so_a_command_does_not_ask_over_and_over() {
861        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Err(BrokerError::RepositoryNotVisible("r".into())), Ok(ok_for(3600))]);
862        let tokens = Tokens::default();
863        let w = want("o", "r");
864        let first = tokens.token_for(&fake, &w, NOW).await.unwrap_err();
865        let again = tokens.token_for(&fake, &w, NOW + 5).await.unwrap_err();
866        assert_eq!(first, again);
867        assert_eq!(fake.asked.lock().unwrap().len(), 1);
868        assert!(tokens.token_for(&fake, &w, NOW + 25).await.is_ok(), "asked again after the refusal expires");
869    }
870
871    #[tokio::test]
872    async fn a_brief_outage_keeps_serving_a_token_that_still_works() {
873        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600)), Err(BrokerError::Unavailable("503".into()))]);
874        let tokens = Tokens::default();
875        let w = want("o", "r");
876        tokens.token_for(&fake, &w, NOW).await.unwrap();
877        // 200 s left: due for renewal, the broker is down, the token still works.
878        let served = tokens.token_for(&fake, &w, NOW + 3400).await.unwrap();
879        assert_eq!(served.expires_at, NOW + 3600);
880        // Once it has run out, it is an error, and a remembered one.
881        assert!(tokens.token_for(&fake, &w, NOW + 3601).await.is_err());
882    }
883
884    #[tokio::test]
885    async fn a_stale_link_is_revalidated_once_and_the_mint_retried() {
886        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Err(BrokerError::LinkStale), Ok(ok_for(3600))]);
887        let tokens = Tokens::default();
888        let minted = tokens.token_for(&fake, &want("o", "r"), NOW).await.unwrap();
889        assert_eq!(minted.expires_at, NOW + 3600);
890        assert_eq!((*fake.revalidated.lock().unwrap(), fake.asked.lock().unwrap().len()), (1, 2));
891    }
892
893    #[tokio::test]
894    async fn a_stale_link_that_cannot_be_revalidated_gives_no_token() {
895        let mut fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Err(BrokerError::LinkStale)]);
896        fake.revalidate_ok = false;
897        let err = Tokens::default().token_for(&fake, &want("o", "r"), NOW).await.unwrap_err();
898        assert_eq!(err, TokenError::NoGithubAccount);
899        assert_eq!(fake.asked.lock().unwrap().len(), 1, "no second try without a fresh proof");
900    }
901
902    #[tokio::test]
903    async fn a_new_install_is_found_without_waiting_for_the_list_to_age() {
904        let fake = Fake::new(vec![vec![], vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600))]);
905        let tokens = Tokens::default();
906        // The first look is stale-proof: an empty list, then the owner is installed and asked about again.
907        assert!(tokens.token_for(&fake, &want("nobody", "r"), NOW).await.is_err());
908        assert!(tokens.token_for(&fake, &want("o", "r"), NOW + 1).await.is_ok());
909        assert_eq!(*fake.listed.lock().unwrap(), 2);
910    }
911
912    #[tokio::test]
913    async fn names_that_are_not_github_names_never_reach_the_broker() {
914        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600))]);
915        let tokens = Tokens::default();
916        for (owner, repo) in [("o", "../x"), ("o/p", "r"), ("", "r"), ("o", ""), ("o", "a b"), ("o", &"x".repeat(101))] {
917            let err = tokens.token_for(&fake, &want(owner, repo), NOW).await.unwrap_err();
918            assert!(matches!(err, TokenError::BadTarget(_)), "{owner:?}/{repo:?}: {err}");
919        }
920        assert_eq!((*fake.listed.lock().unwrap(), fake.asked.lock().unwrap().len()), (0, 0));
921    }
922
923    #[tokio::test]
924    async fn a_broker_that_cannot_mint_yet_says_so_and_gives_no_token() {
925        let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Err(BrokerError::NotConfigured)]);
926        let err = Tokens::default().token_for(&fake, &want("o", "r"), NOW).await.unwrap_err();
927        assert_eq!(err, TokenError::Broker(BrokerError::NotConfigured));
928        assert!(err.to_string().contains("can't mint GitHub tokens yet"), "{err}");
929    }
930}