1use 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 #[serde(default)]
36 purpose: Option<String>,
37}
38
39fn 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
47fn 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
55const NEEDS_SIGN_IN_FOR_AGENT: &str = "GitHub needs the person to sign in to AgentMux Cloud (Connectors → Accounts)";
57
58fn 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
68pub(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 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 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 "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 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 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 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 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
169fn 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
179fn 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
186fn refusal_for(host_error: Option<String>, e: &TokenError) -> (StatusCode, String) {
189 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 let said = match e {
200 TokenError::Broker(BrokerError::NotSignedIn(why)) => format!("{NEEDS_SIGN_IN_FOR_AGENT} ({why})"),
201 other => other.to_string(),
202 };
203 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 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}