Skip to main content

agentmux_srv_core/identity/
github_installs.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Connect with GitHub, desktop side: the installations of the AgentMux GitHub App.
5//!
6//! An account's agents get tokens for an installation only once the account is *linked* to it
7//! (the broker's record, `muxbus::github_broker`). This is what Connectors → Accounts drives
8//! (`github.installations`):
9//!
10//! - **list**: the account's links, as rows;
11//! - **start**: open GitHub's install page for the App, and remember which installations the
12//!   person's GitHub sign-in could already see, so that a new one is theirs;
13//! - **sync**: link an installation that appeared since `start` (called while the person is on
14//!   GitHub; the broker checks the installation against their own token);
15//! - **refresh**: present a fresh user token to the broker, which re-reads what the account can see
16//!   (`links/revalidate`), and link every installation the sign-in sees that isn't linked yet;
17//! - **unlink**: end the account's link; the installation stays on GitHub.
18//!
19//! The GitHub user token is read here and goes to the broker and to GitHub only; nothing of it is
20//! stored or shown.
21
22use crate::backend::storage::store::Store;
23use crate::muxbus::github_broker::{self, BrokerError, LinkedInstallation};
24use serde::{Deserialize, Serialize};
25use std::collections::HashSet;
26use std::sync::{Arc, Mutex};
27
28/// What `github.installations` is asked to do.
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, ts_rs::TS)]
30#[ts(export, export_to = "../../../frontend/types/rpc/")]
31#[serde(rename_all = "lowercase")]
32pub enum GithubInstallationsAction {
33    #[default]
34    List,
35    Start,
36    Sync,
37    Refresh,
38    Unlink,
39}
40
41/// Request for `github.installations`.
42#[derive(Debug, Clone, Default, Deserialize, Serialize, ts_rs::TS)]
43#[ts(export, export_to = "../../../frontend/types/rpc/")]
44#[serde(rename_all = "camelCase")]
45pub struct GithubInstallationsReq {
46    #[serde(default)]
47    pub action: GithubInstallationsAction,
48    /// `unlink`: the installation's id, as text.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub installation_id: Option<String>,
51}
52
53/// One of the account's links to an installation, for the list.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
55#[ts(export, export_to = "../../../frontend/types/rpc/")]
56#[serde(rename_all = "camelCase")]
57pub struct GithubInstallation {
58    /// GitHub's installation id, as text.
59    pub installation_id: String,
60    /// The GitHub account (a person or an organization) the App is installed on.
61    pub account_login: String,
62    /// `all` or `selected`: every repository of the account, or the ones chosen.
63    pub repository_selection: String,
64    /// `active`, `suspended`, `deleted` or `revoked` (the account's link was cut: access lost on GitHub).
65    pub status: String,
66    /// How many of its repositories this account can see.
67    pub visible_count: u32,
68    #[ts(type = "number")]
69    pub verified_at_ms: i64,
70}
71
72/// What `github.installations` answers.
73#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
74#[ts(export, export_to = "../../../frontend/types/rpc/")]
75#[serde(rename_all = "camelCase")]
76pub struct GithubInstallations {
77    /// Signed in to AgentMux Cloud. Without it there is nothing to ask.
78    pub signed_in: bool,
79    /// Why the call failed, in words for the person.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub error: Option<String>,
82    pub installations: Vec<GithubInstallation>,
83    /// Installations this call linked (ids as text).
84    #[serde(default)]
85    pub linked: Vec<String>,
86    /// `start`: the page that was opened.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub install_url: Option<String>,
89}
90
91/// At most this many installations are linked by one call.
92const MAX_LINKS_PER_CALL: usize = 10;
93/// GitHub's pages of `GET /user/installations`, and the most read.
94const PAGE_SIZE: usize = 100;
95const MAX_PAGES: usize = 5;
96/// An install trip that nobody finishes is forgotten after this long.
97const TRIP_TTL_MS: i64 = 30 * 60 * 1000;
98
99/// An install trip in progress: what the person could see when it began, and the state the broker issued.
100struct Trip {
101    before: HashSet<u64>,
102    state: Option<String>,
103    started_ms: i64,
104}
105
106fn trip() -> &'static Mutex<Option<Trip>> {
107    static TRIP: Mutex<Option<Trip>> = Mutex::new(None);
108    &TRIP
109}
110
111/// The row for one link.
112pub fn row_of(link: &LinkedInstallation) -> GithubInstallation {
113    let status = if link.link_status != "active" { "revoked" } else { link.installation_status.as_str() };
114    GithubInstallation {
115        installation_id: link.installation_id.to_string(),
116        account_login: link.github_account.login.clone(),
117        repository_selection: link.repository_selection.clone(),
118        status: status.to_string(),
119        visible_count: link.visible_count.min(u64::from(u32::MAX)) as u32,
120        verified_at_ms: link.verified_at_ms,
121    }
122}
123
124/// The installations on GitHub that the account has no live link to.
125pub fn unlinked(on_github: &[u64], linked: &[LinkedInstallation]) -> Vec<u64> {
126    on_github.iter().copied().filter(|id| !linked.iter().any(|l| l.installation_id == *id && l.link_status == "active")).collect()
127}
128
129/// The installations that were not there when the trip began.
130pub fn new_since(before: &HashSet<u64>, on_github: &[u64]) -> Vec<u64> {
131    on_github.iter().copied().filter(|id| !before.contains(id)).collect()
132}
133
134/// The install page is only opened if it is the App's page on GitHub: a short list of characters a
135/// page address needs after the prefix, so nothing in it means anything to the shell that opens it.
136pub fn is_install_page(url: &str) -> bool {
137    url.strip_prefix("https://github.com/apps/")
138        .is_some_and(|rest| !rest.is_empty() && rest.chars().all(|c| c.is_ascii_alphanumeric() || "-._~/?=&".contains(c)))
139}
140
141/// The installation ids in a page of `GET /user/installations`.
142pub fn installation_ids(page: &serde_json::Value) -> Vec<u64> {
143    page.get("installations").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|i| i.get("id").and_then(|id| id.as_u64())).collect()).unwrap_or_default()
144}
145
146/// Every installation of the App that this GitHub sign-in can see.
147async fn user_installations(token: &str) -> Result<Vec<u64>, String> {
148    let mut all = Vec::new();
149    for page in 1..=MAX_PAGES {
150        let reply = crate::identity::oauth_client::http()
151            .get(format!("https://api.github.com/user/installations?per_page={PAGE_SIZE}&page={page}"))
152            .header("Authorization", format!("Bearer {token}"))
153            .header("Accept", "application/vnd.github+json")
154            .header("X-GitHub-Api-Version", "2022-11-28")
155            .send()
156            .await
157            .map_err(|e| format!("couldn't ask GitHub for your installations: {}", e.without_url()))?;
158        let status = reply.status().as_u16();
159        if status == 401 {
160            return Err("GitHub no longer accepts this connection: connect GitHub again".to_string());
161        }
162        if !(200..300).contains(&status) {
163            return Err(format!("GitHub answered {status} when asked for your installations"));
164        }
165        let body: serde_json::Value = reply.json().await.map_err(|_| "GitHub's list of your installations wasn't readable".to_string())?;
166        let ids = installation_ids(&body);
167        let full = ids.len() >= PAGE_SIZE;
168        all.extend(ids);
169        if !full {
170            break;
171        }
172    }
173    Ok(all)
174}
175
176/// The person's own GitHub token, from the brokered account (refreshed if it is near its end).
177async fn user_token(mstore: &Arc<Store>, identity_store: &Arc<Store>) -> Result<zeroize::Zeroizing<String>, String> {
178    let account = mstore
179        .identity_list(Some(crate::identity::github_connect::PROVIDER))
180        .unwrap_or_default()
181        .into_iter()
182        .find(crate::identity::github_connect::is_brokered)
183        .ok_or("GitHub isn't connected: connect GitHub first")?;
184    crate::identity::oauth_tokens::access_token_for(
185        &crate::identity::oauth_tokens::LiveHttp,
186        &crate::identity::oauth_tokens::KeychainSecrets,
187        mstore,
188        identity_store,
189        &account,
190        Some(mstore),
191    )
192    .await
193    .map_err(|e| format!("GitHub needs to be connected again ({e})"))
194}
195
196fn text(e: BrokerError) -> String {
197    e.to_string()
198}
199
200/// A state for the next link: the one the trip holds, else a new one.
201async fn state_for_link(http: &reqwest::Client, who: &github_broker::Caller) -> Result<String, BrokerError> {
202    let held = trip().lock().ok().and_then(|mut t| t.as_mut().and_then(|t| t.state.take()));
203    match held {
204        Some(state) => Ok(state),
205        None => Ok(github_broker::installation_state(http, who).await?.state),
206    }
207}
208
209/// Link each of `ids` that the person's token proves they can see; the ones it doesn't are skipped.
210async fn link_all(http: &reqwest::Client, who: &github_broker::Caller, token: &str, ids: Vec<u64>) -> Result<Vec<u64>, String> {
211    let mut done = Vec::new();
212    for id in ids.into_iter().take(MAX_LINKS_PER_CALL) {
213        let state = state_for_link(http, who).await.map_err(text)?;
214        match github_broker::link_installation(http, who, id, &state, token).await {
215            Ok(_) => done.push(id),
216            // Not theirs to link (or it just went), too big for the record, or the state is spent: next time.
217            Err(BrokerError::InstallationNotVisible | BrokerError::StateInvalid | BrokerError::InstallationTooLarge) => {}
218            Err(e) => return Err(text(e)),
219        }
220    }
221    Ok(done)
222}
223
224async fn start(http: &reqwest::Client, who: &github_broker::Caller, token: &str) -> Result<String, String> {
225    let before: HashSet<u64> = user_installations(token).await?.into_iter().collect();
226    let issued = github_broker::installation_state(http, who).await.map_err(text)?;
227    if !is_install_page(&issued.install_url) {
228        return Err("AgentMux Cloud gave an install page that isn't GitHub's: not opening it".to_string());
229    }
230    if let Ok(mut t) = trip().lock() {
231        *t = Some(Trip { before, state: Some(issued.state), started_ms: agentmux_common::time::now_ms() });
232    }
233    crate::util::open_browser(&issued.install_url);
234    Ok(issued.install_url)
235}
236
237/// What the call did, and the account's links after it.
238pub async fn run(mstore: &Arc<Store>, identity_store: &Arc<Store>, req: GithubInstallationsReq) -> GithubInstallations {
239    let who = match github_broker::caller(mstore).await {
240        Ok(who) => who,
241        Err(e) => return GithubInstallations { signed_in: false, error: Some(text(e)), ..Default::default() },
242    };
243    let http = crate::identity::oauth_client::http();
244    let mut out = GithubInstallations { signed_in: true, ..Default::default() };
245    let done: Result<(), String> = async {
246        match req.action {
247            GithubInstallationsAction::List => {}
248            GithubInstallationsAction::Start => {
249                let token = user_token(mstore, identity_store).await?;
250                out.install_url = Some(start(http, &who, &token).await?);
251            }
252            GithubInstallationsAction::Sync => {
253                let before = trip().lock().ok().and_then(|t| {
254                    t.as_ref().filter(|t| agentmux_common::time::now_ms() - t.started_ms < TRIP_TTL_MS).map(|t| t.before.clone())
255                });
256                // Nothing was started here (or it was long ago): there is nothing that is new.
257                if let Some(before) = before {
258                    let token = user_token(mstore, identity_store).await?;
259                    let ids = new_since(&before, &user_installations(&token).await?);
260                    out.linked = link_all(http, &who, &token, ids).await?.iter().map(u64::to_string).collect();
261                }
262            }
263            GithubInstallationsAction::Refresh => {
264                let token = user_token(mstore, identity_store).await?;
265                github_broker::revalidate(http, &who, &token).await.map_err(text)?;
266                let linked = github_broker::installations(http, &who).await.map_err(text)?;
267                let ids = unlinked(&user_installations(&token).await?, &linked);
268                out.linked = link_all(http, &who, &token, ids).await?.iter().map(u64::to_string).collect();
269            }
270            GithubInstallationsAction::Unlink => {
271                let id: u64 = req.installation_id.as_deref().and_then(|s| s.parse().ok()).ok_or("unlink needs the installation's id")?;
272                github_broker::unlink_installation(http, &who, id).await.map_err(text)?;
273            }
274        }
275        Ok(())
276    }
277    .await;
278    if let Err(e) = done {
279        out.error = Some(e);
280    }
281    match github_broker::installations(http, &who).await {
282        Ok(list) => out.installations = list.iter().map(row_of).collect(),
283        Err(e) if out.error.is_none() => out.error = Some(text(e)),
284        Err(_) => {}
285    }
286    out
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use crate::muxbus::github_broker::InstallationAccount;
293
294    fn link(id: u64, installation: &str, link: &str) -> LinkedInstallation {
295        LinkedInstallation {
296            installation_id: id,
297            github_account: InstallationAccount { id: id * 10, login: format!("org{id}") },
298            repository_selection: "selected".to_string(),
299            installation_status: installation.to_string(),
300            link_status: link.to_string(),
301            verified_at_ms: 5,
302            visible_count: 3,
303            linked_at_ms: 1,
304        }
305    }
306
307    #[test]
308    fn a_row_says_what_the_person_can_use() {
309        let r = row_of(&link(7, "active", "active"));
310        assert_eq!((r.installation_id.as_str(), r.account_login.as_str(), r.status.as_str(), r.visible_count), ("7", "org7", "active", 3));
311        // A cut link shows as revoked whatever the installation says; a suspended installation says so.
312        assert_eq!(row_of(&link(7, "active", "revoked")).status, "revoked");
313        assert_eq!(row_of(&link(7, "suspended", "active")).status, "suspended");
314        assert_eq!(row_of(&link(7, "deleted", "active")).status, "deleted");
315    }
316
317    #[test]
318    fn a_new_installation_is_one_that_was_not_there_when_the_trip_began() {
319        let before: HashSet<u64> = [1, 2].into_iter().collect();
320        assert_eq!(new_since(&before, &[1, 2, 3, 4]), vec![3, 4]);
321        assert!(new_since(&before, &[2, 1]).is_empty());
322    }
323
324    #[test]
325    fn a_refresh_links_what_the_sign_in_sees_and_has_no_live_link() {
326        let linked = vec![link(1, "active", "active"), link(2, "active", "revoked")];
327        assert_eq!(unlinked(&[1, 2, 3], &linked), vec![2, 3]);
328        assert!(unlinked(&[1], &linked).is_empty());
329    }
330
331    #[test]
332    fn only_githubs_page_for_the_app_is_opened() {
333        assert!(is_install_page("https://github.com/apps/muxagent/installations/new?state=abc"));
334        for bad in ["http://github.com/apps/muxagent", "https://evil.example/apps/x", "https://github.com/apps/", "https://github.com.evil.example/apps/x", "https://github.com/apps/a@b", "https://github.com/apps/x\" & calc", "https://github.com/apps/x%20y", "https://github.com/apps/x^y", "https://github.com/apps/x\ny", "https://github.com/apps/x'y", "https://github.com/apps/x;y", "https://github.com/apps/x|y"] {
335            assert!(!is_install_page(bad), "{bad}");
336        }
337    }
338
339    #[test]
340    fn the_ids_come_out_of_githubs_page() {
341        let page = serde_json::json!({ "total_count": 2, "installations": [{ "id": 11, "account": { "login": "a" } }, { "id": 22 }, { "name": "no id" }] });
342        assert_eq!(installation_ids(&page), vec![11, 22]);
343        assert!(installation_ids(&serde_json::json!({})).is_empty());
344    }
345
346    #[test]
347    fn the_broker_s_refusals_read_as_sentences() {
348        use crate::muxbus::github_broker::error_for;
349        let body = |code: &str| serde_json::json!({ "error": code });
350        assert_eq!(error_for(403, &body("installation_not_visible")), BrokerError::InstallationNotVisible);
351        assert_eq!(error_for(400, &body("state_invalid")), BrokerError::StateInvalid);
352        assert_eq!(error_for(422, &body("installation_too_large")), BrokerError::InstallationTooLarge);
353        assert!(BrokerError::StateInvalid.to_string().contains("start it again"));
354    }
355}