1use 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#[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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub installation_id: Option<String>,
51}
52
53#[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 pub installation_id: String,
60 pub account_login: String,
62 pub repository_selection: String,
64 pub status: String,
66 pub visible_count: u32,
68 #[ts(type = "number")]
69 pub verified_at_ms: i64,
70}
71
72#[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 pub signed_in: bool,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub error: Option<String>,
82 pub installations: Vec<GithubInstallation>,
83 #[serde(default)]
85 pub linked: Vec<String>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub install_url: Option<String>,
89}
90
91const MAX_LINKS_PER_CALL: usize = 10;
93const PAGE_SIZE: usize = 100;
95const MAX_PAGES: usize = 5;
96const TRIP_TTL_MS: i64 = 30 * 60 * 1000;
98
99struct 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
111pub 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
124pub 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
129pub fn new_since(before: &HashSet<u64>, on_github: &[u64]) -> Vec<u64> {
131 on_github.iter().copied().filter(|id| !before.contains(id)).collect()
132}
133
134pub 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
141pub 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
146async 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
176async 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
200async 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
209async 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 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
237pub 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 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 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}