Skip to main content

agentmux_srv/server/app_api/
github_token.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/github/token`: the GitHub token an agent's `git` and `gh` use.
5//!
6//! `agentmux-bashwrap` asks here, from the agent's own shell, as git's credential helper and
7//! before each wrapped command. Who is asking is the agent its `X-Agent-Token` was minted for,
8//! never a name in the request; the request says only which repository. The token is the AgentMux
9//! GitHub App's installation token, narrowed to that repository by AgentMux Cloud's broker
10//! (`identity::github_tokens`). The answer also says who the agent works for (the GitHub account's id
11//! and login) and who the App's bot is, for the PR tag and the commit's author. When there is no
12//! token, the answer says why, in words an agent can show; nothing here falls back to another credential.
13
14use axum::extract::{Extension, State};
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::Json;
18use serde::Deserialize;
19use serde_json::json;
20
21use super::AppState;
22use crate::identity::github_connect;
23use crate::identity::github_tokens::{self, TokenError, Want};
24use crate::muxbus::github_broker::BrokerError;
25use crate::sagas::credential_notice::{self, Cause};
26use crate::server::caller::Caller;
27
28#[derive(Debug, Deserialize)]
29pub(crate) struct GithubTokenRequest {
30    owner: String,
31    repo: String,
32    /// What the token is for, as the caller says: `git` from git's credential helper, anything else (or nothing) is a
33    /// `gh` call. It only ever narrows: a container that says `git` gets a token that writes contents and nothing
34    /// else, one that says anything else gets a token that cannot write contents. It is never the way to a wider token.
35    #[serde(default)]
36    purpose: Option<String>,
37}
38
39/// The scope of the token a container on a gh-agent host is given for `purpose`: only git's own asks for a push token.
40fn scope_for(purpose: Option<&str>) -> crate::identity::gh_agent_token::Scope {
41    match purpose {
42        Some("git") => crate::identity::gh_agent_token::Scope::Push,
43        _ => crate::identity::gh_agent_token::Scope::Api,
44    }
45}
46
47/// Whether a push token that failed is asked for again without workflows write: an App without it cannot give that, and the push
48/// token without it still pushes everything else. Not after a gh-agent that is too old (it would be again), and not after one
49/// that was slow: a second wait would run past the container's own, and its answer would never arrive.
50fn retry_without_workflows(workflows: bool, scope: crate::identity::gh_agent_token::Scope, failure: Option<&String>) -> bool {
51    use crate::identity::gh_agent_token::{is_too_old, is_took_too_long, Scope};
52    workflows && scope == Scope::Push && failure.is_some_and(|e| !is_too_old(e) && !is_took_too_long(e))
53}
54
55/// What an agent is told when the person isn't signed in to AgentMux Cloud (the Connect with GitHub design).
56const NEEDS_SIGN_IN_FOR_AGENT: &str = "GitHub needs the person to sign in to AgentMux Cloud (Connectors → Accounts)";
57
58/// The status a refusal is answered with: the request's fault (4xx) or a bad moment (503).
59fn status_for(e: &TokenError) -> StatusCode {
60    match e {
61        TokenError::BadTarget(_) => StatusCode::BAD_REQUEST,
62        TokenError::NoInstallation { .. } | TokenError::NoGithubAccount => StatusCode::FORBIDDEN,
63        TokenError::Broker(BrokerError::Unavailable(_)) => StatusCode::SERVICE_UNAVAILABLE,
64        TokenError::Broker(_) => StatusCode::FORBIDDEN,
65    }
66}
67
68/// `POST /api/v1/github/token`
69pub(crate) async fn handle_github_token(
70    State(state): State<AppState>,
71    caller: Option<Extension<Caller>>,
72    Json(req): Json<GithubTokenRequest>,
73) -> Response {
74    let refuse = |status: StatusCode, message: String| (status, Json(json!({ "error": message }))).into_response();
75    let Some(uid) = caller.as_ref().and_then(|Extension(c)| c.uid()).map(str::to_string) else {
76        return refuse(StatusCode::UNAUTHORIZED, "no agent token: GitHub tokens are for an agent's own commands".to_string());
77    };
78    let mstore = state.mstore.clone();
79    let lookup = uid.clone();
80    let (slug, in_container) = match tokio::task::spawn_blocking(move || mstore.agent_def_get(&lookup)).await {
81        Ok(Ok(Some(def))) => { let in_container = def.runtime().is_container(); (def.slug, in_container) }
82        Ok(Ok(None)) => return refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine".to_string()),
83        _ => return refuse(StatusCode::INTERNAL_SERVER_ERROR, "couldn't read the agent".to_string()),
84    };
85    // The person's GitHub account: who the agent works for, and whether this agent may change CI workflows.
86    let accounts = state.id_store.clone();
87    let account = tokio::task::spawn_blocking(move || {
88        accounts.identity_list(Some(github_connect::PROVIDER)).unwrap_or_default().into_iter().find(github_connect::is_brokered)
89    })
90    .await
91    .ok()
92    .flatten();
93    let owner = account.as_ref().and_then(github_connect::owner_of);
94    let workflows = account.as_ref().is_some_and(|a| github_connect::workflows_allowed(a, &slug));
95    // A container agent is given a token only where its git setup was switched on (the hooks mounted,
96    // `github_tokens::container_git_hooks`), and from the host's `gh-agent` first.
97    let mut host_error = None;
98    if in_container {
99        if crate::identity::github_tokens::container_git_hooks().is_none() {
100            tracing::warn!(target: "identity", agent = %slug, "identity.github: a container agent asked for a token where its git setup is off");
101            return refuse(StatusCode::FORBIDDEN, "no GitHub token for a container agent on this machine".to_string());
102        }
103        let scope = scope_for(req.purpose.as_deref());
104        let mut asked = crate::identity::gh_agent_token::token_for(&slug, &req.owner, &req.repo, scope, workflows).await;
105        if retry_without_workflows(workflows, scope, asked.as_ref().err()) {
106            asked = crate::identity::gh_agent_token::token_for(&slug, &req.owner, &req.repo, scope, false).await;
107        }
108        match asked {
109            Ok(host) => {
110                let now = chrono::Utc::now().timestamp();
111                tracing::info!(target: "identity", agent = %slug, owner = %req.owner, repo = %req.repo, "identity.github: a container agent's token from the host's gh-agent");
112                credential_notice::worked(&state, &uid, &slug, Cause::Github);
113                return Json(json!({
114                    "token": host.token.as_str(),
115                    "expiresAt": if host.expires_at > now { host.expires_at } else { now + 300 },
116                    "botSlug": host.bot_slug,
117                    // gh-agent doesn't say the bot's user id: it is looked up (once), so a commit is the
118                    // bot's like a native agent's; the owner is the connected account's, when there is one.
119                    "botUserId": match host.bot_slug.as_deref() {
120                        Some(bot) => crate::identity::gh_agent_token::bot_user_id(bot).await,
121                        None => None,
122                    },
123                    "ownerGithubId": owner.as_ref().map(|(id, _)| *id),
124                    "ownerLogin": owner.as_ref().map(|(_, login)| login.as_str()),
125                }))
126                .into_response();
127            }
128            // A gh-agent that cannot give a narrowed token is not a reason to give a container another one.
129            Err(e) if crate::identity::gh_agent_token::is_too_old(&e) => {
130                tracing::warn!(target: "identity", agent = %slug, owner = %req.owner, repo = %req.repo, error = %e, "identity.github: a container agent's token was refused");
131                return refuse(StatusCode::FORBIDDEN, e);
132            }
133            // Nor is a gh-agent that was only slow: a container that loads the machine must not be able to turn a slow answer
134            // into the connection's token (below), which is per repository but can write contents.
135            Err(e) if crate::identity::gh_agent_token::is_took_too_long(&e) => {
136                tracing::warn!(target: "identity", agent = %slug, owner = %req.owner, repo = %req.repo, error = %e, "identity.github: a container agent's token was refused");
137                return refuse(StatusCode::SERVICE_UNAVAILABLE, e);
138            }
139            // Any other failure of gh-agent (a repository its App does not cover, no identity for the agent) falls through to
140            // the person's own GitHub connection, as it always did. That token is not narrowed by this change; it is the
141            // Cloud-connected path, which a machine without gh-agent uses throughout.
142            Err(e) => host_error = Some(e),
143        }
144    }
145    let backend = github_tokens::Live { mstore: state.id_store.clone(), identity_store: state.identity_store.clone() };
146    let want = Want { agent: slug, owner: req.owner, repo: req.repo, workflows };
147    match github_tokens::global().token_for(&backend, &want, chrono::Utc::now().timestamp()).await {
148        Ok(minted) => {
149            // (A native agent never has a line up, so this is a lookup that finds nothing.)
150            credential_notice::worked(&state, &uid, &want.agent, Cause::Github);
151            Json(json!({
152                "token": minted.token.as_str(),
153                "expiresAt": minted.expires_at,
154                "botSlug": minted.bot.slug,
155                "botUserId": minted.bot.bot_user_id,
156                "ownerGithubId": owner.as_ref().map(|(id, _)| *id),
157                "ownerLogin": owner.as_ref().map(|(_, login)| login.as_str()),
158            }))
159            .into_response()
160        }
161        Err(e) => {
162            tracing::info!(target: "identity", agent = %want.agent, owner = %want.owner, repo = %want.repo, error = %e, "identity.github: no agent token");
163            let (status, message) = refusal_shown(&state, &uid, &want.agent, in_container, host_error, &e);
164            refuse(status, message)
165        }
166    }
167}
168
169/// [`refusal_for`], and for a container agent the sentence it was given is also put in its pane, when the person can fix it.
170fn refusal_shown(state: &AppState, uid: &str, slug: &str, in_container: bool, host_error: Option<String>, e: &TokenError) -> (StatusCode, String) {
171    let shows = in_container && the_persons_to_fix(e, host_error.as_deref());
172    let (status, message) = refusal_for(host_error, e);
173    if shows {
174        credential_notice::refused(state, uid, slug, Cause::Github, &message);
175    }
176    (status, message)
177}
178
179/// Whether a refusal is one the person can fix, so a container agent's pane says so: GitHub isn't connected, the
180/// App isn't installed where the repository is, or the Cloud sign-in lapsed. A slow `gh-agent` is only a bad moment.
181fn the_persons_to_fix(e: &TokenError, host_error: Option<&str>) -> bool {
182    let slow = host_error.is_some_and(crate::identity::gh_agent_token::is_took_too_long);
183    !slow && matches!(e, TokenError::NoGithubAccount | TokenError::NoInstallation { .. } | TokenError::Broker(BrokerError::NotSignedIn(_) | BrokerError::NotConnected))
184}
185
186/// What a refusal says, and its status, once the broker path has failed too (`host_error`: what `gh-agent` said
187/// first, for a container agent).
188fn refusal_for(host_error: Option<String>, e: &TokenError) -> (StatusCode, String) {
189    // `gh-agent` is there but ran out of time (a busy machine, a slow network): the broker has no account because
190    // none was ever needed, so "isn't connected" would send the person to fix what isn't broken. Ask again.
191    let nothing_to_connect = matches!(e, TokenError::NoGithubAccount | TokenError::Broker(BrokerError::NotSignedIn(_) | BrokerError::NotConnected));
192    if let Some(host) = host_error.as_deref().filter(|h| crate::identity::gh_agent_token::is_took_too_long(h)) {
193        if nothing_to_connect {
194            return (StatusCode::SERVICE_UNAVAILABLE, host.to_string());
195        }
196    }
197    // A lapsed or missing Cloud sign-in is the person's to fix, in words an agent can show.
198    // The reason rides along: "not running yet" or "key can't be read" are not fixed by signing in.
199    let said = match e {
200        TokenError::Broker(BrokerError::NotSignedIn(why)) => format!("{NEEDS_SIGN_IN_FOR_AGENT} ({why})"),
201        other => other.to_string(),
202    };
203    // A container agent was tried against gh-agent first: say both, in words it can show.
204    match host_error {
205        Some(host) => (status_for(e), format!("{host}; {said}")),
206        None => (status_for(e), said),
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn only_git_asks_for_a_push_token_and_nothing_else_is_wider_than_api() {
216        use crate::identity::gh_agent_token::Scope;
217        assert_eq!(scope_for(Some("git")), Scope::Push);
218        for other in [None, Some("api"), Some(""), Some("push"), Some("GIT"), Some("admin"), Some("installation")] {
219            assert_eq!(scope_for(other), Scope::Api, "{other:?}");
220        }
221    }
222
223    #[test]
224    fn a_slow_push_mint_is_not_asked_again_without_workflows() {
225        use crate::identity::gh_agent_token::{took_too_long, Scope, GH_AGENT_TOO_OLD};
226        let other = "gh-agent gave no token for that repository".to_string();
227        assert!(retry_without_workflows(true, Scope::Push, Some(&other)));
228        assert!(!retry_without_workflows(true, Scope::Push, Some(&took_too_long())), "a second wait would outlast the container's");
229        assert!(!retry_without_workflows(true, Scope::Push, Some(&GH_AGENT_TOO_OLD.to_string())));
230        assert!(!retry_without_workflows(false, Scope::Push, Some(&other)));
231        assert!(!retry_without_workflows(true, Scope::Api, Some(&other)));
232        assert!(!retry_without_workflows(true, Scope::Push, None));
233    }
234
235    #[test]
236    fn a_request_without_a_purpose_is_still_a_request() {
237        let r: GithubTokenRequest = serde_json::from_str(r#"{"owner":"o","repo":"r"}"#).unwrap();
238        assert_eq!(r.purpose, None);
239        let r: GithubTokenRequest = serde_json::from_str(r#"{"owner":"o","repo":"r","purpose":"git"}"#).unwrap();
240        assert_eq!(scope_for(r.purpose.as_deref()), crate::identity::gh_agent_token::Scope::Push);
241    }
242
243    #[test]
244    fn a_refusal_is_the_requests_fault_unless_it_was_only_a_bad_moment() {
245        assert_eq!(status_for(&TokenError::BadTarget("x".into())), StatusCode::BAD_REQUEST);
246        assert_eq!(status_for(&TokenError::NoInstallation { owner: "o".into() }), StatusCode::FORBIDDEN);
247        assert_eq!(status_for(&TokenError::NoGithubAccount), StatusCode::FORBIDDEN);
248        assert_eq!(status_for(&TokenError::Broker(BrokerError::NotConnected)), StatusCode::FORBIDDEN);
249        assert_eq!(status_for(&TokenError::Broker(BrokerError::Unavailable("x".into()))), StatusCode::SERVICE_UNAVAILABLE);
250    }
251
252    #[test]
253    fn a_gh_agent_that_ran_out_of_time_is_not_reported_as_a_missing_connection() {
254        let slow = Some(crate::identity::gh_agent_token::took_too_long());
255        for e in [TokenError::NoGithubAccount, TokenError::Broker(BrokerError::NotConnected), TokenError::Broker(BrokerError::NotSignedIn("not running yet".into()))] {
256            let (status, message) = refusal_for(slow.clone(), &e);
257            assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
258            assert!(message.starts_with("GitHub token took too long") && !message.contains("isn't connected") && !message.contains("sign in"), "{message}");
259        }
260        // Anything else the broker said is still said, after the timeout.
261        let (status, message) = refusal_for(slow, &TokenError::NoInstallation { owner: "o".into() });
262        assert_eq!(status, StatusCode::FORBIDDEN);
263        assert!(message.starts_with("GitHub token took too long") && message.contains("Try again in a minute; ") && message.contains("isn't installed"), "{message}");
264    }
265
266    #[test]
267    fn only_a_refusal_the_person_can_fix_is_shown_in_the_agents_pane() {
268        let slow = crate::identity::gh_agent_token::took_too_long();
269        for e in [TokenError::NoGithubAccount, TokenError::NoInstallation { owner: "o".into() }, TokenError::Broker(BrokerError::NotConnected), TokenError::Broker(BrokerError::NotSignedIn("lapsed".into()))] {
270            assert!(the_persons_to_fix(&e, None), "{e:?}");
271            assert!(the_persons_to_fix(&e, Some("gh-agent gave no token for that repository")), "{e:?}");
272            assert!(!the_persons_to_fix(&e, Some(&slow)), "a slow gh-agent is a bad moment, not a connection to fix: {e:?}");
273        }
274        assert!(!the_persons_to_fix(&TokenError::BadTarget("x".into()), None));
275        assert!(!the_persons_to_fix(&TokenError::Broker(BrokerError::Unavailable("x".into())), None));
276    }
277
278    #[test]
279    fn without_a_timeout_the_refusals_read_as_before() {
280        let (status, message) = refusal_for(None, &TokenError::NoGithubAccount);
281        assert_eq!((status, message.as_str()), (StatusCode::FORBIDDEN, "GitHub isn't connected on this AgentMux account: connect it in Connectors → Accounts"));
282        let (_, signed_out) = refusal_for(Some("gh-agent gave no token for that repository".into()), &TokenError::Broker(BrokerError::NotSignedIn("lapsed".into())));
283        assert!(signed_out.starts_with("gh-agent gave no token for that repository; ") && signed_out.contains(NEEDS_SIGN_IN_FOR_AGENT) && signed_out.ends_with("(lapsed)"), "{signed_out}");
284    }
285}