1use std::sync::Arc;
19
20use serde_json::{json, Value};
21
22use crate::backend::storage::store::{IdentityAccount, Store};
23use crate::identity::oauth_tokens::{RefreshError, TokenBlob, TokenSecrets};
24use crate::muxbus::github_broker::{self, BrokerError, TokenGrant};
25
26pub const PROVIDER: &str = "github";
28
29pub fn client_id_override() -> Option<String> {
32 std::env::var("AGENTMUX_GITHUB_APP_CLIENT_ID").ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
33}
34
35pub fn is_brokered(account: &IdentityAccount) -> bool {
37 account.provider == PROVIDER && account.context.get("broker").and_then(Value::as_bool) == Some(true)
38}
39
40pub fn owner_of(account: &IdentityAccount) -> Option<(u64, String)> {
42 owner_in(&account.context)
43}
44
45fn owner_in(context: &Value) -> Option<(u64, String)> {
46 Some((context.get("github_user_id")?.as_u64()?, context.get("github_login")?.as_str()?.to_string()))
47}
48
49pub fn workflows_allowed(account: &IdentityAccount, agent: &str) -> bool {
52 workflows_allowed_in(&account.context, agent)
53}
54
55fn workflows_allowed_in(context: &Value, agent: &str) -> bool {
56 context
57 .get("workflows_agents")
58 .and_then(Value::as_array)
59 .is_some_and(|list| list.iter().any(|a| a.as_str().is_some_and(|a| a.eq_ignore_ascii_case(agent))))
60}
61
62pub fn grant_json(grant: &TokenGrant, now_ms: i64) -> Value {
67 json!({
68 "access_token": grant.access_token,
69 "refresh_token": grant.refresh_token,
70 "expires_in": ((grant.expires_at_ms - now_ms) / 1000).max(1),
71 "github_user_id": grant.github_user_id,
72 "login": grant.login,
73 "broker": true,
74 })
75}
76
77pub fn identity_in(json: &Value) -> Option<(u64, String)> {
79 let id = json.get("github_user_id").and_then(Value::as_u64)?;
80 let login = json.get("login").and_then(Value::as_str).filter(|l| !l.is_empty())?;
81 Some((id, login.to_string()))
82}
83
84pub fn stamp_context(context: &mut Value, json: &Value) {
86 if let Some((id, login)) = identity_in(json) {
87 context["github_user_id"] = json!(id);
88 context["github_login"] = json!(login);
89 } else if let Some(c) = context.as_object_mut() {
90 c.remove("github_user_id");
93 c.remove("github_login");
94 }
95 if json.get("broker").and_then(Value::as_bool) == Some(true) {
96 context["broker"] = json!(true);
97 } else if let Some(c) = context.as_object_mut() {
98 c.remove("broker");
100 }
101}
102
103pub fn display_name_for(json: &Value) -> Option<String> {
105 identity_in(json).map(|(_, login)| format!("@{login}"))
106}
107
108pub async fn user_of_token(token: &str) -> Result<(u64, String), String> {
110 let reply = crate::identity::oauth_client::http()
111 .get("https://api.github.com/user")
112 .header("Authorization", format!("Bearer {token}"))
113 .header("Accept", "application/vnd.github+json")
114 .header("X-GitHub-Api-Version", "2022-11-28")
115 .send()
116 .await
117 .map_err(|e| format!("couldn't ask GitHub who this is: {}", e.without_url()))?;
118 if !reply.status().is_success() {
119 return Err(format!("GitHub answered {} when asked who this is", reply.status().as_u16()));
120 }
121 let body: Value = reply.json().await.map_err(|_| "GitHub's answer about who this is wasn't readable".to_string())?;
122 let id = body.get("id").and_then(Value::as_u64).ok_or("GitHub's answer had no user id")?;
123 let login = body.get("login").and_then(Value::as_str).ok_or("GitHub's answer had no login")?;
124 Ok((id, login.to_string()))
125}
126
127pub fn refresh_error_for(e: BrokerError) -> RefreshError {
130 match e {
131 BrokerError::Reauthorize | BrokerError::Blocked | BrokerError::NotConnected | BrokerError::NotLive(_) => {
132 RefreshError::Reauth(e.to_string())
133 }
134 other => RefreshError::Failed(other.to_string()),
135 }
136}
137
138pub async fn refresh_blob(mstore: &Arc<Store>, blob: &TokenBlob, now: i64) -> Result<TokenBlob, RefreshError> {
141 let Some(refresh) = blob.refresh_token.as_deref().filter(|r| !r.is_empty()) else {
142 return Err(RefreshError::Reauth("the access token expired and there is no refresh token".to_string()));
143 };
144 let who = github_broker::caller(mstore).await.map_err(refresh_error_for)?;
145 let grant = github_broker::refresh(crate::identity::oauth_client::http(), &who, refresh).await.map_err(refresh_error_for)?;
146 if !grant.identity_checked {
147 tracing::info!(target: "identity", "identity.github: refreshed; GitHub couldn't be asked who this is, so the recorded user stands");
148 }
149 TokenBlob::from_token_response(&grant_json(&grant, now * 1000), now, Some(refresh), None).map_err(RefreshError::Failed)
150}
151
152pub async fn revoke_before_delete<S: TokenSecrets>(mstore: &Arc<Store>, secrets: &S, account: &IdentityAccount) -> Option<Value> {
156 if !is_brokered(account) {
157 return None;
158 }
159 let raw = match secrets.get(&account.id).await {
160 Ok(Some(raw)) => raw,
161 Ok(None) => return None,
162 Err(e) => return Some(json!({ "outcome": "failed", "detail": format!("couldn't read the stored token: {e}") })),
163 };
164 let blob = TokenBlob::parse(&raw)?;
165 let who = match github_broker::caller(mstore).await {
166 Ok(who) => who,
167 Err(e) => return Some(json!({ "outcome": "failed", "detail": e.to_string() })),
168 };
169 match github_broker::revoke(crate::identity::oauth_client::http(), &who, Some(&blob.access_token), blob.refresh_token.as_deref()).await {
170 Ok(done) => {
171 tracing::info!(target: "identity", account_id = %account.id, revoked = done.revoked, disconnected = done.disconnected, "identity.delete: GitHub grant ended through the broker");
172 Some(json!({ "outcome": "revoked" }))
173 }
174 Err(BrokerError::NotConnected) => Some(json!({ "outcome": "revoked" })),
176 Err(e) => Some(json!({ "outcome": "failed", "detail": e.to_string() })),
177 }
178}
179
180#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
182#[ts(export, export_to = "../../../frontend/types/rpc/")]
183#[serde(rename_all = "camelCase")]
184pub struct GithubConnection {
185 pub signed_in: bool,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub reason: Option<String>,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub error: Option<String>,
193 #[serde(default)]
194 pub connected: bool,
195 #[serde(default, skip_serializing_if = "Option::is_none")]
197 pub status: Option<String>,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub github_user_id: Option<String>,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub login: Option<String>,
203 #[serde(default)]
206 pub gh_agent_on_this_computer: bool,
207}
208
209pub async fn connection_of(mstore: &Arc<Store>) -> GithubConnection {
211 let gh_agent = tokio::task::spawn_blocking(crate::backend::gh_guard::gh_agent_on_this_computer).await.unwrap_or(false);
212 GithubConnection { gh_agent_on_this_computer: gh_agent, ..broker_connection_of(mstore).await }
213}
214
215async fn broker_connection_of(mstore: &Arc<Store>) -> GithubConnection {
217 let who = match github_broker::caller(mstore).await {
218 Ok(who) => who,
219 Err(e) => return GithubConnection { signed_in: false, reason: Some(e.to_string()), ..Default::default() },
220 };
221 match github_broker::connection(crate::identity::oauth_client::http(), &who).await {
222 Ok(c) => GithubConnection {
223 signed_in: true,
224 connected: c.connected,
225 status: Some(c.status),
226 github_user_id: c.github_user_id.map(|id| id.to_string()),
227 login: c.login,
228 ..Default::default()
229 },
230 Err(e) => GithubConnection { signed_in: true, error: Some(e.to_string()), ..Default::default() },
231 }
232}
233
234pub fn grant_is_gone(c: &GithubConnection) -> bool {
237 c.signed_in && c.error.is_none() && matches!(c.status.as_deref(), Some("revoked" | "blocked" | "none"))
238}
239
240pub async fn sync_connection(mstore: &Arc<Store>, identity_store: &Arc<Store>) -> GithubConnection {
245 let answer = connection_of(mstore).await;
246 if grant_is_gone(&answer) {
247 for account in mstore.identity_list(Some(PROVIDER)).unwrap_or_default().into_iter().filter(is_brokered) {
248 if account.status != crate::identity::oauth_tokens::STATUS_NEEDS_REAUTH {
249 tracing::info!(target: "identity", account_id = %account.id, status = ?answer.status, "identity.github: the grant is gone, the account asks to be connected again");
250 crate::identity::oauth_tokens::set_status(mstore, identity_store, &account.id, crate::identity::oauth_tokens::STATUS_NEEDS_REAUTH);
251 }
252 }
253 }
254 answer
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260
261 fn grant() -> TokenGrant {
262 serde_json::from_value(json!({
263 "access_token": "ghu_A", "refresh_token": "ghr_B",
264 "expires_at_ms": 1_000_000 + 8 * 3600 * 1000, "refresh_expires_at_ms": 1_000_000 + 180 * 86400 * 1000_i64,
265 "github_user_id": 42, "login": "octo",
266 }))
267 .unwrap()
268 }
269
270 #[test]
271 fn a_grant_becomes_a_token_response_the_flow_can_store() {
272 let j = grant_json(&grant(), 1_000_000);
273 assert_eq!(j["expires_in"], 8 * 3600);
274 let blob = TokenBlob::from_token_response(&j, 1_000, None, None).unwrap();
275 assert_eq!((blob.access_token.as_str(), blob.refresh_token.as_deref()), ("ghu_A", Some("ghr_B")));
276 assert_eq!(blob.expires_at, 1_000 + 8 * 3600);
277 assert_eq!(identity_in(&j), Some((42, "octo".to_string())));
278 assert_eq!(display_name_for(&j).as_deref(), Some("@octo"));
279 }
280
281 #[test]
282 fn a_grant_already_expired_asks_for_a_refresh_at_once() {
283 let j = grant_json(&grant(), 1_000_000 + 9 * 3600 * 1000);
284 let blob = TokenBlob::from_token_response(&j, 5_000, None, None).unwrap();
286 assert!(blob.expires_at > 0 && blob.needs_refresh(5_000), "{blob:?}");
287 }
288
289 #[test]
290 fn a_grant_that_cannot_say_who_it_is_does_not_keep_the_previous_user() {
291 let mut c = json!({ "oauth": true, "github_user_id": 7, "github_login": "old" });
292 stamp_context(&mut c, &json!({ "access_token": "x" }));
293 assert!(c.get("github_user_id").is_none() && c.get("github_login").is_none(), "{c}");
294 assert_eq!(c["oauth"], true);
295 }
296
297 #[test]
298 fn the_context_records_who_is_connected_and_whether_through_the_broker() {
299 let mut c = json!({ "oauth": true });
300 stamp_context(&mut c, &grant_json(&grant(), 0));
301 assert_eq!((c["github_user_id"].clone(), c["github_login"].clone(), c["broker"].clone()), (json!(42), json!("octo"), json!(true)));
302 let device = json!({ "access_token": "x", "github_user_id": 42, "login": "octo" });
304 stamp_context(&mut c, &device);
305 assert!(c.get("broker").is_none());
306 assert_eq!(c["github_login"], "octo");
307 }
308
309 #[test]
310 fn the_answer_says_whether_this_computer_has_gh_agent_signed_in_or_not() {
311 let signed_out = GithubConnection { gh_agent_on_this_computer: true, ..Default::default() };
312 let v = serde_json::to_value(&signed_out).unwrap();
313 assert_eq!((v["signedIn"].clone(), v["ghAgentOnThisComputer"].clone()), (json!(false), json!(true)));
314 let old_answer: GithubConnection = serde_json::from_value(json!({ "signedIn": true, "connected": true })).unwrap();
315 assert!(!old_answer.gh_agent_on_this_computer, "absent means no");
316 assert!(!grant_is_gone(&signed_out), "it says nothing about the grant");
317 }
318
319 #[test]
320 fn only_a_clear_answer_says_the_grant_is_gone() {
321 let c = |signed_in, error: Option<&str>, status: Option<&str>| GithubConnection {
322 signed_in,
323 error: error.map(String::from),
324 status: status.map(String::from),
325 ..Default::default()
326 };
327 for gone in ["revoked", "blocked", "none"] {
328 assert!(grant_is_gone(&c(true, None, Some(gone))), "{gone}");
329 }
330 assert!(!grant_is_gone(&c(true, None, Some("active"))));
331 assert!(!grant_is_gone(&c(true, Some("unavailable"), None)), "a failure to ask says nothing");
332 assert!(!grant_is_gone(&c(false, None, Some("revoked"))), "signed out: nothing was asked");
333 }
334
335 #[test]
336 fn the_owner_is_the_recorded_github_user_and_workflows_are_off_unless_the_agent_is_listed() {
337 let ctx = json!({ "github_user_id": 42, "github_login": "octo", "broker": true, "workflows_agents": ["Korp", "agenty"] });
338 assert_eq!(owner_in(&ctx), Some((42, "octo".to_string())));
339 assert_eq!(owner_in(&json!({ "github_login": "octo" })), None);
340 assert!(workflows_allowed_in(&ctx, "korp"), "slugs compare without case");
341 assert!(!workflows_allowed_in(&ctx, "agentx"));
342 assert!(!workflows_allowed_in(&json!({ "broker": true }), "korp"));
343 assert!(!workflows_allowed_in(&json!({ "workflows_agents": "korp" }), "korp"), "a list, not a string");
344 }
345
346 #[test]
347 fn only_a_brokered_github_account_is_brokered() {
348 let mut a = crate::identity::oauth_tokens::tests::oauth_account("a", "github", "cid");
349 assert!(!is_brokered(&a));
350 a.context["broker"] = json!(true);
351 assert!(is_brokered(&a));
352 a.provider = "google".to_string();
353 assert!(!is_brokered(&a));
354 }
355
356 #[test]
357 fn a_dropped_grant_asks_to_connect_again_and_a_bad_moment_does_not() {
358 for e in [BrokerError::Reauthorize, BrokerError::Blocked, BrokerError::NotConnected, BrokerError::NotLive("revoked".into())] {
359 assert!(matches!(refresh_error_for(e), RefreshError::Reauth(_)));
360 }
361 for e in [BrokerError::Unavailable("503".into()), BrokerError::NotSignedIn("no".into()), BrokerError::Other { status: 500, error: "x".into() }] {
362 assert!(matches!(refresh_error_for(e), RefreshError::Failed(_)));
363 }
364 }
365}