Skip to main content

agentmux_srv_core/identity/
github_connect.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Connect with GitHub, desktop side.
5//!
6//! The person's grant to the AgentMux App is made, refreshed and ended through the
7//! broker (`muxbus::github_broker`), which holds the App's client secret. This module
8//! is what the service-OAuth flow (`oauth_client`) and the token path (`oauth_tokens`)
9//! lean on for a GitHub account:
10//!
11//! - a **brokered** account is one made through the broker; its context says so
12//!   (`broker: true`) and carries the GitHub user's numeric id and login;
13//! - signed out of AgentMux Cloud there is no broker, so a connect falls back to the
14//!   device flow with the App's client id, and the account is not brokered: GitHub
15//!   won't refresh its token without the secret, so it asks to be connected again
16//!   when the 8 hours are up.
17
18use 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
26/// The provider whose grant is brokered.
27pub const PROVIDER: &str = "github";
28
29/// The AgentMux App's public client id, for a build that doesn't ship one yet (and
30/// for a developer's own App). A shipped id replaces this when the App is registered.
31pub 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
35/// Whether `account` was connected through the broker.
36pub fn is_brokered(account: &IdentityAccount) -> bool {
37    account.provider == PROVIDER && account.context.get("broker").and_then(Value::as_bool) == Some(true)
38}
39
40/// Who a brokered account is: the GitHub user's numeric id and login, as recorded at connect.
41pub 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
49/// Whether the person let `agent` change CI workflows: the account's per-agent opt-in
50/// (`workflows_agents`, a list of agent slugs). Off for every agent until it is set.
51pub 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
62/// A grant as a GitHub-shaped token response, so the flow's last step stores it
63/// like any other: the expiry in seconds from now, the numeric id and login, and the
64/// marker that the account is brokered. A grant already expired (or about to) is one second
65/// from now, never 0: the blob reads 0 as "doesn't expire", so it would never be refreshed.
66pub 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
77/// The id and login in a token response made by [`grant_json`].
78pub 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
84/// What the account's context records about who is connected, and how.
85pub 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        // A grant that couldn't say who it is: the previous user's id and login would be wrong
91        // for it, so the account shows nobody rather than someone it isn't.
92        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        // Connected again without the broker: no longer refreshed through it.
99        c.remove("broker");
100    }
101}
102
103/// The label an account shows for who is connected.
104pub fn display_name_for(json: &Value) -> Option<String> {
105    identity_in(json).map(|(_, login)| format!("@{login}"))
106}
107
108/// Who a GitHub token belongs to (`GET /user`), for a grant the device flow made.
109pub 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
127/// What the desktop does about a broker failure during a refresh: the grant is gone
128/// (connect again) or it was only a bad moment (try later).
129pub 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
138/// A new blob for a brokered account's refresh token. GitHub's refresh tokens are
139/// single use, so the caller must store what this returns before anything else.
140pub 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
152/// Before a brokered account is deleted: end its grant through the broker, so it
153/// doesn't live on at GitHub. `{ outcome: "revoked" | "failed", detail? }`
154/// for the delete's result, or `None` when this isn't a brokered account.
155pub 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        // The broker has no grant for this account: nothing is left to end.
175        Err(BrokerError::NotConnected) => Some(json!({ "outcome": "revoked" })),
176        Err(e) => Some(json!({ "outcome": "failed", "detail": e.to_string() })),
177    }
178}
179
180/// What the broker says about this AgentMux account's GitHub connection (`github.connection`).
181#[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    /// Signed in to AgentMux Cloud. Without it there is nothing to ask.
186    pub signed_in: bool,
187    /// Why the broker couldn't be asked, when it couldn't.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub reason: Option<String>,
190    /// The broker was asked and answered with a failure.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub error: Option<String>,
193    #[serde(default)]
194    pub connected: bool,
195    /// `none`, `active`, `revoked` or `blocked`.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub status: Option<String>,
198    /// GitHub's numeric user id, as text.
199    #[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    /// This computer has gh-agent, which gives agents their GitHub identity instead of the App
204    /// (crate::backend::gh_guard). True whether or not the person is signed in to AgentMux Cloud.
205    #[serde(default)]
206    pub gh_agent_on_this_computer: bool,
207}
208
209/// The broker's word on this account's GitHub connection, for Connectors.
210pub 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
215/// What the broker says, without what this computer has.
216async 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
234/// Whether a connection answer says the grant is gone: revoked on GitHub, blocked, or never made
235/// (or ended from another install). Only a clear answer counts; a failure to ask says nothing.
236pub 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
240/// [`connection_of`], and the brokered accounts whose grant is gone ask to be connected again
241/// (the account's card shows "Reconnect needed"): a grant revoked on GitHub shows as revoked.
242/// Nothing is cleared here: an account that works again is made valid by the
243/// refresh that proves it.
244pub 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        // Not 0: the blob reads that as "never expires" and would never refresh it.
285        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        // The same account connected again by the device flow: still who it is, no longer brokered.
303        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}