1use std::time::Duration;
23
24use base64::engine::general_purpose::STANDARD as BASE64;
25use base64::Engine;
26use ed25519_dalek::Signer;
27use serde::Deserialize;
28use serde_json::{json, Value};
29use sha2::{Digest, Sha256};
30
31pub const SIGNATURE_DOMAIN: &str = "amx-github-broker-v1";
33const SEP: char = '\u{1}';
34const CALL_TIMEOUT: Duration = Duration::from_secs(20);
35
36pub fn signature_material(method: &str, path_and_query: &str, ts_ms: &str, body: &[u8]) -> String {
38 let body_hash = hex::encode(Sha256::digest(body));
39 [SIGNATURE_DOMAIN, &method.to_ascii_uppercase(), path_and_query, ts_ms, &body_hash].join(&SEP.to_string())
40}
41
42pub fn sign(seed: &[u8; 32], material: &str) -> String {
44 let key = ed25519_dalek::SigningKey::from_bytes(seed);
45 BASE64.encode(key.sign(material.as_bytes()).to_bytes())
46}
47
48pub struct Caller {
50 pub base: String,
52 pub bearer: String,
54 pub instance_id: String,
56 pub seed: [u8; 32],
58}
59
60impl std::fmt::Debug for Caller {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 f.debug_struct("Caller").field("base", &self.base).field("instance_id", &self.instance_id).finish_non_exhaustive()
63 }
64}
65
66pub const NO_VALID_SIGN_IN: &str = "no valid sign-in";
69
70impl BrokerError {
71 pub fn needs_sign_in(&self) -> bool {
74 matches!(self, Self::NotSignedIn(why) if why == NO_VALID_SIGN_IN)
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum BrokerError {
82 NotSignedIn(String),
84 Reauthorize,
86 Blocked,
88 InstallNotApproved(String),
90 NotLive(String),
92 NotConnected,
94 UserMismatch { current: GithubUser, new: GithubUser },
96 Unavailable(String),
98 NotLinked,
100 LinkStale,
102 RepositoryNotVisible(String),
104 PermissionNotAllowed(String),
106 BadRequest(String),
108 NotConfigured,
110 InstallSuspended,
112 PermissionNotGranted(String),
114 GithubRejected,
116 InstallationNotVisible,
118 StateInvalid,
120 InstallationTooLarge,
122 Other { status: u16, error: String },
124}
125
126impl std::fmt::Display for BrokerError {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 match self {
129 Self::NotSignedIn(why) => write!(f, "sign in to AgentMux Cloud first ({why})"),
130 Self::Reauthorize => write!(f, "GitHub no longer accepts this connection: connect GitHub again"),
131 Self::Blocked => write!(f, "this account's GitHub connection was blocked by an operator"),
132 Self::InstallNotApproved(code) => {
133 write!(f, "AgentMux Cloud doesn't accept this install yet ({code}): sign in again and approve it in the Console")
134 }
135 Self::NotLive(status) => write!(f, "the GitHub connection is {status}: connect GitHub again"),
136 Self::NotConnected => write!(f, "GitHub isn't connected on this AgentMux account"),
137 Self::UserMismatch { current, new } => {
138 write!(f, "this AgentMux account is connected as @{}, not @{}", current.login, new.login)
139 }
140 Self::Unavailable(why) => write!(f, "GitHub or AgentMux Cloud is unavailable right now ({why}); try again shortly"),
141 Self::NotLinked => write!(f, "the AgentMux GitHub App isn't linked to this account for that owner: install it in Connectors"),
142 Self::LinkStale => write!(f, "the link to that installation needs to be checked again"),
143 Self::RepositoryNotVisible(repo) => {
144 write!(f, "{repo} isn't a repository this account can reach through the AgentMux GitHub App: add it to the installation, or check you can see it on GitHub")
145 }
146 Self::PermissionNotAllowed(permission) => write!(f, "the AgentMux GitHub App can't give the {permission} permission"),
147 Self::BadRequest(why) => write!(f, "AgentMux Cloud refused a malformed GitHub request ({why})"),
148 Self::NotConfigured => write!(f, "AgentMux Cloud can't mint GitHub tokens yet"),
149 Self::InstallSuspended => write!(f, "the AgentMux GitHub App is suspended on that account: unsuspend it on GitHub"),
150 Self::PermissionNotGranted(permission) => write!(
151 f,
152 "that installation hasn't accepted the {permission} permission yet: its owner accepts it in GitHub's settings for the AgentMux App"
153 ),
154 Self::GithubRejected => write!(f, "GitHub refused to give a token for that repository"),
155 Self::InstallationNotVisible => write!(f, "that installation isn't one your GitHub sign-in can see: check you have access to it on GitHub"),
156 Self::StateInvalid => write!(f, "that install was started too long ago or already used: start it again"),
157 Self::InstallationTooLarge => write!(f, "that installation shows more repositories than AgentMux can link: install the App on fewer repositories"),
158 Self::Other { status, error } => write!(f, "AgentMux Cloud refused the GitHub request ({status} {error})"),
159 }
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
164pub struct GithubUser {
165 pub github_user_id: u64,
166 pub login: String,
167}
168
169#[derive(Clone, Deserialize)]
171pub struct TokenGrant {
172 pub access_token: String,
173 pub refresh_token: String,
174 pub expires_at_ms: i64,
175 pub refresh_expires_at_ms: i64,
176 pub github_user_id: u64,
177 pub login: String,
178 #[serde(default = "yes")]
181 pub identity_checked: bool,
182}
183
184fn yes() -> bool {
185 true
186}
187
188impl std::fmt::Debug for TokenGrant {
189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190 f.debug_struct("TokenGrant")
191 .field("github_user_id", &self.github_user_id)
192 .field("login", &self.login)
193 .field("expires_at_ms", &self.expires_at_ms)
194 .field("identity_checked", &self.identity_checked)
195 .finish_non_exhaustive()
196 }
197}
198
199#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
201pub struct Connection {
202 pub connected: bool,
203 #[serde(default)]
204 pub github_user_id: Option<u64>,
205 #[serde(default)]
206 pub login: Option<String>,
207 pub status: String,
209}
210
211#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
213pub struct Revoked {
214 #[serde(default)]
215 pub revoked: bool,
216 #[serde(default)]
217 pub disconnected: bool,
218 #[serde(default)]
219 pub reason: Option<String>,
220}
221
222pub struct InstallationRequest<'a> {
225 pub installation_id: u64,
226 pub repositories: &'a [String],
227 pub permissions: &'a std::collections::BTreeMap<String, String>,
228 pub agent_id: &'a str,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
234pub struct AppBot {
235 pub slug: String,
236 pub bot_user_id: u64,
237}
238
239#[derive(Clone, Deserialize)]
241pub struct InstallationToken {
242 pub token: String,
243 pub expires_at: String,
245 #[serde(default)]
246 pub permissions: std::collections::BTreeMap<String, String>,
247 #[serde(default)]
248 pub repository_ids: Vec<u64>,
249 pub app: AppBot,
250}
251
252impl std::fmt::Debug for InstallationToken {
253 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
254 f.debug_struct("InstallationToken")
255 .field("expires_at", &self.expires_at)
256 .field("permissions", &self.permissions)
257 .field("repository_ids", &self.repository_ids)
258 .field("app", &self.app)
259 .finish_non_exhaustive()
260 }
261}
262
263impl InstallationToken {
264 pub fn expires_at_epoch(&self) -> Option<i64> {
266 chrono::DateTime::parse_from_rfc3339(&self.expires_at).ok().map(|t| t.timestamp())
267 }
268}
269
270#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
272pub struct InstallationAccount {
273 pub id: u64,
274 pub login: String,
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
279pub struct LinkedInstallation {
280 pub installation_id: u64,
281 pub github_account: InstallationAccount,
282 #[serde(default)]
284 pub repository_selection: String,
285 pub installation_status: String,
287 pub link_status: String,
289 #[serde(default)]
290 pub verified_at_ms: i64,
291 #[serde(default)]
293 pub visible_count: u64,
294 #[serde(default)]
295 pub linked_at_ms: i64,
296}
297
298impl LinkedInstallation {
299 pub fn is_usable(&self) -> bool {
301 self.installation_status == "active" && self.link_status == "active"
302 }
303}
304
305#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
308pub struct InstallState {
309 pub state: String,
310 pub install_url: String,
311 #[serde(default)]
312 pub expires_at_ms: i64,
313 #[serde(default)]
316 pub one_trip: bool,
317}
318
319#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
321pub struct Revalidated {
322 #[serde(default)]
323 pub revalidated: Vec<u64>,
324 #[serde(default)]
325 pub revoked: Vec<u64>,
326 #[serde(default)]
327 pub remaining: u64,
328}
329
330pub fn code_body(code: &str, code_verifier: &str, redirect_uri: &str, replace: bool) -> Value {
332 let mut body = json!({ "grant": "code", "code": code, "code_verifier": code_verifier, "redirect_uri": redirect_uri });
333 if replace {
334 body["replace"] = json!(true);
335 }
336 body
337}
338
339pub fn trip_code_body(code: &str, state: &str, redirect_uri: &str, replace: bool) -> Value {
342 let mut body = json!({ "grant": "code", "code": code, "state": state, "redirect_uri": redirect_uri });
343 if replace {
344 body["replace"] = json!(true);
345 }
346 body
347}
348
349pub fn error_for(status: u16, body: &Value) -> BrokerError {
351 let code = body.get("error").and_then(Value::as_str).unwrap_or("").to_string();
352 let user = |key: &str| -> Option<GithubUser> { serde_json::from_value(body.get(key)?.clone()).ok() };
353 let text = |key: &str| -> String {
355 body.get(key).and_then(Value::as_str).unwrap_or("").chars().filter(|c| !c.is_control()).take(100).collect()
356 };
357 match (status, code.as_str()) {
358 (401, "reauthorize") => BrokerError::Reauthorize,
359 (401, c) if c.starts_with("install_signature") => BrokerError::InstallNotApproved(code),
360 (403, "install_unknown") | (403, "install_revoked") | (403, "install_not_approved") => BrokerError::InstallNotApproved(code),
361 (403, "not_linked") | (404, "not_linked") => BrokerError::NotLinked,
362 (403, "link_stale") => BrokerError::LinkStale,
363 (403, "repository_not_visible") => BrokerError::RepositoryNotVisible(text("repository")),
364 (403, "permission_not_allowed") => BrokerError::PermissionNotAllowed(text("permission")),
365 (400, "bad_request") => BrokerError::BadRequest(text("message")),
366 (503, "github_not_configured") => BrokerError::NotConfigured,
367 (403, "install_suspended") => BrokerError::InstallSuspended,
368 (403, "permission_not_granted") => BrokerError::PermissionNotGranted(text("permission")),
369 (502, "github_rejected") => BrokerError::GithubRejected,
370 (403, "installation_not_visible") => BrokerError::InstallationNotVisible,
371 (400, "state_invalid") => BrokerError::StateInvalid,
372 (422, "installation_too_large") => BrokerError::InstallationTooLarge,
373 (403, "blocked") => BrokerError::Blocked,
374 (403, "not_connected") | (404, "not_connected") => BrokerError::NotConnected,
375 (403, "revoked") => BrokerError::NotLive("revoked".to_string()),
376 (409, "github_user_mismatch") => match (user("current"), user("new")) {
377 (Some(current), Some(new)) => BrokerError::UserMismatch { current, new },
378 _ => BrokerError::Reauthorize,
380 },
381 (429, _) | (503, _) | (502, "github_unavailable") => BrokerError::Unavailable(if code.is_empty() { status.to_string() } else { code }),
382 (_, _) => BrokerError::Other { status, error: code },
383 }
384}
385
386async fn call(http: &reqwest::Client, who: &Caller, method: reqwest::Method, path: &str, body: Option<&Value>) -> Result<Value, BrokerError> {
388 let bytes = match body {
389 Some(v) => serde_json::to_vec(v).map_err(|e| BrokerError::Other { status: 0, error: e.to_string() })?,
390 None => Vec::new(),
391 };
392 let ts = chrono::Utc::now().timestamp_millis().to_string();
393 let material = signature_material(method.as_str(), path, &ts, &bytes);
394 let mut request = http
395 .request(method, format!("{}{}", who.base, path))
396 .timeout(CALL_TIMEOUT)
397 .header("User-Agent", crate::muxbus::relay::USER_AGENT)
398 .header("Authorization", format!("Bearer {}", who.bearer))
399 .header("x-amx-instance", &who.instance_id)
400 .header("x-amx-ts", &ts)
401 .header("x-amx-sig", sign(&who.seed, &material));
402 if body.is_some() {
403 request = request.header("Content-Type", "application/json").body(bytes);
404 }
405 let reply = request.send().await.map_err(|e| BrokerError::Unavailable(format!("couldn't reach AgentMux Cloud: {}", e.without_url())))?;
406 let status = reply.status().as_u16();
407 let text = reply.text().await.unwrap_or_default();
409 let parsed: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
410 if (200..300).contains(&status) {
411 return Ok(parsed);
412 }
413 Err(error_for(status, &parsed))
414}
415
416fn grant_of(value: Value) -> Result<TokenGrant, BrokerError> {
417 serde_json::from_value(value).map_err(|_| BrokerError::Other { status: 200, error: "unreadable_answer".to_string() })
418}
419
420pub async fn exchange_code(
422 http: &reqwest::Client,
423 who: &Caller,
424 code: &str,
425 code_verifier: &str,
426 redirect_uri: &str,
427 replace: bool,
428) -> Result<TokenGrant, BrokerError> {
429 let body = code_body(code, code_verifier, redirect_uri, replace);
430 grant_of(call(http, who, reqwest::Method::POST, "/github/v1/token", Some(&body)).await?)
431}
432
433pub async fn exchange_trip_code(
435 http: &reqwest::Client,
436 who: &Caller,
437 code: &str,
438 state: &str,
439 redirect_uri: &str,
440 replace: bool,
441) -> Result<TokenGrant, BrokerError> {
442 let body = trip_code_body(code, state, redirect_uri, replace);
443 grant_of(call(http, who, reqwest::Method::POST, "/github/v1/token", Some(&body)).await?)
444}
445
446pub async fn refresh(http: &reqwest::Client, who: &Caller, refresh_token: &str) -> Result<TokenGrant, BrokerError> {
449 let body = json!({ "grant": "refresh", "refresh_token": refresh_token });
450 grant_of(call(http, who, reqwest::Method::POST, "/github/v1/token", Some(&body)).await?)
451}
452
453pub async fn revoke(http: &reqwest::Client, who: &Caller, access_token: Option<&str>, refresh_token: Option<&str>) -> Result<Revoked, BrokerError> {
456 let mut body = json!({ "grant": "revoke" });
457 if let Some(a) = access_token.filter(|a| !a.is_empty()) {
458 body["access_token"] = json!(a);
459 }
460 if let Some(r) = refresh_token.filter(|r| !r.is_empty()) {
461 body["refresh_token"] = json!(r);
462 }
463 let answer = call(http, who, reqwest::Method::POST, "/github/v1/token", Some(&body)).await?;
464 serde_json::from_value(answer).map_err(|_| BrokerError::Other { status: 200, error: "unreadable_answer".to_string() })
465}
466
467pub async fn connection(http: &reqwest::Client, who: &Caller) -> Result<Connection, BrokerError> {
469 let answer = call(http, who, reqwest::Method::GET, "/github/v1/connection", None).await?;
470 serde_json::from_value(answer).map_err(|_| BrokerError::Other { status: 200, error: "unreadable_answer".to_string() })
471}
472
473pub async fn installation_token(http: &reqwest::Client, who: &Caller, request: &InstallationRequest<'_>) -> Result<InstallationToken, BrokerError> {
475 let body = json!({
476 "installation_id": request.installation_id,
477 "repositories": request.repositories,
478 "permissions": request.permissions,
479 "agent_id": request.agent_id.chars().take(80).collect::<String>(),
480 });
481 let answer = call(http, who, reqwest::Method::POST, "/github/v1/installation-token", Some(&body)).await?;
482 serde_json::from_value(answer).map_err(|_| BrokerError::Other { status: 200, error: "unreadable_answer".to_string() })
483}
484
485pub async fn installations(http: &reqwest::Client, who: &Caller) -> Result<Vec<LinkedInstallation>, BrokerError> {
487 let answer = call(http, who, reqwest::Method::GET, "/github/v1/installations", None).await?;
488 let list = answer.get("installations").cloned().unwrap_or(Value::Array(Vec::new()));
489 serde_json::from_value(list).map_err(|_| BrokerError::Other { status: 200, error: "unreadable_answer".to_string() })
490}
491
492pub async fn installation_state(http: &reqwest::Client, who: &Caller) -> Result<InstallState, BrokerError> {
494 let answer = call(http, who, reqwest::Method::POST, "/github/v1/installations/state", None).await?;
495 serde_json::from_value(answer).map_err(|_| BrokerError::Other { status: 200, error: "unreadable_answer".to_string() })
496}
497
498pub async fn link_installation(
501 http: &reqwest::Client,
502 who: &Caller,
503 installation_id: u64,
504 state: &str,
505 user_token: &str,
506) -> Result<LinkedInstallation, BrokerError> {
507 let body = json!({ "installation_id": installation_id, "state": state, "access_token": user_token });
508 let answer = call(http, who, reqwest::Method::POST, "/github/v1/installations/link", Some(&body)).await?;
509 serde_json::from_value(answer).map_err(|_| BrokerError::Other { status: 200, error: "unreadable_answer".to_string() })
510}
511
512pub async fn unlink_installation(http: &reqwest::Client, who: &Caller, installation_id: u64) -> Result<(), BrokerError> {
514 call(http, who, reqwest::Method::DELETE, &format!("/github/v1/installations/{installation_id}/link"), None).await.map(|_| ())
515}
516
517pub async fn revalidate(http: &reqwest::Client, who: &Caller, user_token: &str) -> Result<Revalidated, BrokerError> {
519 let body = json!({ "access_token": user_token });
520 let answer = call(http, who, reqwest::Method::POST, "/github/v1/links/revalidate", Some(&body)).await?;
521 serde_json::from_value(answer).map_err(|_| BrokerError::Other { status: 200, error: "unreadable_answer".to_string() })
522}
523
524pub async fn caller(mstore: &std::sync::Arc<crate::backend::storage::store::Store>) -> Result<Caller, BrokerError> {
526 let scheduler = crate::broker::get_global().ok_or_else(|| BrokerError::NotSignedIn("AgentMux Cloud isn't running yet".to_string()))?;
527 let bearer = crate::muxbus::cloud_subscriber::load_valid_token(mstore, &scheduler)
528 .await
529 .ok_or_else(|| BrokerError::NotSignedIn(NO_VALID_SIGN_IN.to_string()))?;
530 let wan = mstore
533 .wan_identity()
534 .or_else(crate::backend::storage::wan_identity::global)
535 .ok_or_else(|| BrokerError::NotSignedIn("this install has no identity yet".to_string()))?;
536 let instance = wan
537 .instance_ensure(&crate::backend::reactive::registry::local_host_label())
538 .map_err(|e| BrokerError::NotSignedIn(format!("this install's key can't be read: {e}")))?;
539 Ok(Caller {
540 base: crate::muxbus::relay::rest_base_url().trim_end_matches('/').to_string(),
541 bearer,
542 instance_id: instance.instance_id,
543 seed: instance.private_key,
544 })
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 const SEED: [u8; 32] = [7; 32];
554 const TS: &str = "1793147000000";
555
556 #[test]
557 fn the_signature_matches_the_brokers_golden_vector_for_a_post() {
558 let body = br#"{"grant":"refresh","refresh_token":"ghr_TESTREFRESHTOKEN0123456789"}"#;
559 let material = signature_material("POST", "/github/v1/token", TS, body);
560 assert_eq!(
561 material,
562 "amx-github-broker-v1\u{1}POST\u{1}/github/v1/token\u{1}1793147000000\u{1}6013f538617ee04e04a5006f92e3949bef75ac92b53711ae2bfc8dd80c3295dd"
563 );
564 assert_eq!(
565 sign(&SEED, &material),
566 "6C23T7rCDfmmdBCIzChNl2+XzIWBNqBGPzvz3Ltdr03IC5omlnL4TwQqZyu4REun+DVtWEa33oyHHQ+1KSr5Bw=="
567 );
568 }
569
570 #[test]
571 fn the_signature_matches_the_brokers_golden_vector_for_a_get_with_no_body() {
572 let material = signature_material("get", "/github/v1/connection", TS, b"");
573 assert!(material.ends_with("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"));
574 assert!(material.contains("\u{1}GET\u{1}"), "the method is signed in upper case");
575 assert_eq!(
576 sign(&SEED, &material),
577 "olMcFNqD771CqWvmPe8Gsv9xhy8pFalbnCSNfbooHHK6T4SalUe6Dt5yIcjmxtjLYYufLBTpFhBELJr9/gkrBQ=="
578 );
579 }
580
581 #[test]
582 fn a_failed_answer_becomes_what_the_desktop_does_next() {
583 let body = |v: Value| v;
584 assert_eq!(error_for(401, &body(json!({ "error": "reauthorize" }))), BrokerError::Reauthorize);
585 assert_eq!(error_for(403, &body(json!({ "error": "blocked" }))), BrokerError::Blocked);
586 assert_eq!(error_for(403, &body(json!({ "error": "not_connected" }))), BrokerError::NotConnected);
587 assert_eq!(error_for(404, &body(json!({ "error": "not_connected" }))), BrokerError::NotConnected);
588 assert_eq!(error_for(403, &body(json!({ "error": "revoked" }))), BrokerError::NotLive("revoked".into()));
589 assert!(matches!(error_for(401, &body(json!({ "error": "install_signature_expired" }))), BrokerError::InstallNotApproved(c) if c == "install_signature_expired"));
590 assert!(matches!(error_for(403, &body(json!({ "error": "install_unknown" }))), BrokerError::InstallNotApproved(_)));
591 assert!(matches!(error_for(503, &body(json!({ "error": "github_unavailable" }))), BrokerError::Unavailable(_)));
592 assert!(matches!(error_for(429, &Value::Null), BrokerError::Unavailable(_)));
593 assert_eq!(error_for(418, &Value::Null), BrokerError::Other { status: 418, error: String::new() });
594 }
595
596 #[test]
597 fn a_user_mismatch_names_both_users_and_a_refresh_s_means_reauthorize() {
598 let answer = json!({
599 "error": "github_user_mismatch",
600 "current": { "github_user_id": 1, "login": "old" },
601 "new": { "github_user_id": 2, "login": "new" },
602 });
603 assert_eq!(
604 error_for(409, &answer),
605 BrokerError::UserMismatch {
606 current: GithubUser { github_user_id: 1, login: "old".into() },
607 new: GithubUser { github_user_id: 2, login: "new".into() },
608 }
609 );
610 assert_eq!(error_for(409, &json!({ "error": "github_user_mismatch" })), BrokerError::Reauthorize);
612 }
613
614 #[test]
615 fn a_grant_reads_as_the_broker_sends_it_and_never_prints_a_token() {
616 let g = grant_of(json!({
617 "access_token": "ghu_SECRET", "refresh_token": "ghr_SECRET",
618 "expires_at_ms": 5, "refresh_expires_at_ms": 9, "github_user_id": 42, "login": "octo",
619 }))
620 .unwrap();
621 assert!(g.identity_checked, "absent means the identity was checked");
622 assert_eq!((g.github_user_id, g.login.as_str()), (42, "octo"));
623 assert!(!format!("{g:?}").contains("SECRET"));
624 let unchecked = grant_of(json!({
625 "access_token": "a", "refresh_token": "r", "expires_at_ms": 1, "refresh_expires_at_ms": 2,
626 "github_user_id": 42, "login": "octo", "identity_checked": false,
627 }))
628 .unwrap();
629 assert!(!unchecked.identity_checked);
630 }
631
632 #[test]
633 fn a_code_body_carries_replace_only_when_the_user_agreed() {
634 let plain = code_body("c", "v", "http://127.0.0.1:1/callback", false);
635 assert!(plain.get("replace").is_none());
636 assert_eq!(code_body("c", "v", "http://127.0.0.1:1/callback", true)["replace"], json!(true));
637 }
638
639 async fn stub(reply: &'static str) -> (String, tokio::task::JoinHandle<(String, String, String, String)>) {
643 use tokio::io::{AsyncReadExt, AsyncWriteExt};
644 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
645 let base = format!("http://{}", listener.local_addr().unwrap());
646 let task = tokio::spawn(async move {
647 let (mut stream, _) = listener.accept().await.unwrap();
648 let mut data = Vec::new();
649 let mut buf = [0u8; 4096];
650 loop {
651 let n = stream.read(&mut buf).await.unwrap();
652 data.extend_from_slice(&buf[..n]);
653 let text = String::from_utf8_lossy(&data).to_string();
654 if let Some(end) = text.find("\r\n\r\n") {
655 let len = text
656 .lines()
657 .find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0)))
658 .unwrap_or(0);
659 if data.len() >= end + 4 + len {
660 break;
661 }
662 }
663 if n == 0 {
664 break;
665 }
666 }
667 let text = String::from_utf8_lossy(&data).to_string();
668 let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
669 let header = |name: &str| {
670 head.lines()
671 .find_map(|l| {
672 let (k, v) = l.split_once(':')?;
673 k.eq_ignore_ascii_case(name).then(|| v.trim().to_string())
674 })
675 .unwrap_or_default()
676 };
677 let line = head.lines().next().unwrap_or_default().to_string();
678 let out = (line, header("x-amx-ts"), header("x-amx-sig"), body.to_string());
679 stream
680 .write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", reply.len(), reply).as_bytes())
681 .await
682 .unwrap();
683 out
684 });
685 (base, task)
686 }
687
688 fn caller_at(base: String) -> Caller {
689 Caller { base, bearer: "cloud-token".into(), instance_id: "a".repeat(26), seed: SEED }
690 }
691
692 #[tokio::test]
693 async fn a_refresh_signs_the_exact_bytes_it_sends() {
694 let (base, task) = stub(r#"{"access_token":"a","refresh_token":"r2","expires_at_ms":1,"refresh_expires_at_ms":2,"github_user_id":42,"login":"octo"}"#).await;
695 let grant = refresh(&reqwest::Client::new(), &caller_at(base), "ghr_OLD").await.unwrap();
696 assert_eq!(grant.refresh_token, "r2");
697 let (line, ts, sig, body) = task.await.unwrap();
698 assert_eq!(line, "POST /github/v1/token HTTP/1.1");
699 assert_eq!(body, r#"{"grant":"refresh","refresh_token":"ghr_OLD"}"#);
700 assert_eq!(sig, sign(&SEED, &signature_material("POST", "/github/v1/token", &ts, body.as_bytes())));
701 }
702
703 #[test]
704 fn the_new_refusals_map_to_what_the_desktop_does_next() {
705 let e = |status, v: Value| error_for(status, &v);
706 assert_eq!(e(403, json!({"error":"install_not_approved"})), BrokerError::InstallNotApproved("install_not_approved".into()));
707 assert_eq!(e(403, json!({"error":"not_linked"})), BrokerError::NotLinked);
708 assert_eq!(e(403, json!({"error":"link_stale"})), BrokerError::LinkStale);
709 assert_eq!(e(403, json!({"error":"repository_not_visible","repository":"secret-repo"})), BrokerError::RepositoryNotVisible("secret-repo".into()));
710 assert_eq!(e(403, json!({"error":"permission_not_allowed","permission":"workflows"})), BrokerError::PermissionNotAllowed("workflows".into()));
711 assert_eq!(e(400, json!({"error":"bad_request","message":"x"})), BrokerError::BadRequest("x".into()));
712 assert_eq!(e(503, json!({"error":"github_not_configured"})), BrokerError::NotConfigured);
713 assert_eq!(e(403, json!({"error":"install_suspended"})), BrokerError::InstallSuspended);
714 assert_eq!(e(403, json!({"error":"permission_not_granted","permission":"workflows"})), BrokerError::PermissionNotGranted("workflows".into()));
715 assert_eq!(e(502, json!({"error":"github_rejected"})), BrokerError::GithubRejected);
716 assert!(matches!(e(503, json!({"error":"github_unavailable"})), BrokerError::Unavailable(_)));
718 assert!(matches!(e(429, json!({"error":"rate_limited"})), BrokerError::Unavailable(_)));
719 let long = format!("a\u{7}{}", "b".repeat(300));
721 match e(403, json!({"error":"repository_not_visible","repository":long})) {
722 BrokerError::RepositoryNotVisible(r) => assert!(r.len() <= 100 && !r.contains('\u{7}'), "{r}"),
723 other => panic!("{other:?}"),
724 }
725 }
726
727 #[tokio::test]
728 async fn an_installation_token_is_a_signed_post_that_names_the_repositories_and_permissions() {
729 let (base, task) = stub(r#"{"token":"ghs_SECRET","expires_at":"2026-10-28T10:00:00Z","permissions":{"contents":"write"},"repository_ids":[9],"app":{"slug":"muxagent","bot_user_id":77}}"#).await;
730 let permissions = std::collections::BTreeMap::from([("contents".to_string(), "write".to_string())]);
731 let repositories = vec!["repo".to_string()];
732 let request = InstallationRequest { installation_id: 5, repositories: &repositories, permissions: &permissions, agent_id: "korp" };
733 let minted = installation_token(&reqwest::Client::new(), &caller_at(base), &request).await.unwrap();
734 assert_eq!((minted.app.slug.as_str(), minted.app.bot_user_id, minted.repository_ids.clone()), ("muxagent", 77, vec![9]));
735 assert_eq!(minted.expires_at_epoch(), Some(1_793_181_600));
736 assert!(!format!("{minted:?}").contains("ghs_SECRET"), "the token must stay out of logs");
737 let (line, ts, sig, body) = task.await.unwrap();
738 assert_eq!(line, "POST /github/v1/installation-token HTTP/1.1");
739 let sent: Value = serde_json::from_str(&body).unwrap();
740 assert_eq!(sent["installation_id"], 5);
741 assert_eq!(sent["repositories"], json!(["repo"]));
742 assert_eq!(sent["permissions"], json!({"contents":"write"}));
743 assert_eq!(sent["agent_id"], "korp");
744 assert_eq!(sig, sign(&SEED, &signature_material("POST", "/github/v1/installation-token", &ts, body.as_bytes())));
745 }
746
747 #[tokio::test]
748 async fn the_installations_list_reads_the_links() {
749 let (base, task) = stub(r#"{"installations":[{"installation_id":5,"github_account":{"id":1,"login":"Octo-Org","type":"Organization"},"repository_selection":"selected","installation_status":"active","link_status":"active","visible_count":2,"visible_repository_ids":[1,2],"verified_at_ms":10,"linked_at_ms":5}]}"#).await;
750 let list = installations(&reqwest::Client::new(), &caller_at(base)).await.unwrap();
751 assert_eq!(list.len(), 1);
752 assert!(list[0].is_usable());
753 assert_eq!(list[0].github_account.login, "Octo-Org");
754 let (line, _, _, body) = task.await.unwrap();
755 assert_eq!((line.as_str(), body.as_str()), ("GET /github/v1/installations HTTP/1.1", ""));
756 }
757
758 #[tokio::test]
759 async fn a_connection_check_is_a_signed_get_with_no_body() {
760 let (base, task) = stub(r#"{"connected":true,"github_user_id":42,"login":"octo","status":"active"}"#).await;
761 let c = connection(&reqwest::Client::new(), &caller_at(base)).await.unwrap();
762 assert_eq!((c.connected, c.login.as_deref(), c.status.as_str()), (true, Some("octo"), "active"));
763 let (line, ts, sig, body) = task.await.unwrap();
764 assert_eq!(line, "GET /github/v1/connection HTTP/1.1");
765 assert_eq!(body, "");
766 assert_eq!(sig, sign(&SEED, &signature_material("GET", "/github/v1/connection", &ts, b"")));
767 }
768}