agentmux_srv_core/identity/
github_trip.rs1use serde_json::Value;
16use sha2::{Digest, Sha256};
17
18pub const CALLBACK_PATH: &str = "/github-callback";
20
21fn relay_url(relay_base: &str, path: &str) -> String {
23 format!("{}{path}", relay_base.trim_end_matches('/'))
24}
25
26pub fn callback_uri(relay_base: &str) -> String {
28 relay_url(relay_base, CALLBACK_PATH)
29}
30
31pub fn relay_key(state: &str) -> String {
33 hex::encode(Sha256::digest(state.as_bytes()))
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Polled {
39 Pending,
41 Ready { code: String, installation_id: u64, setup_action: String },
43 Failed(String),
45 Gone,
47}
48
49pub fn parse_poll(status: u16, body: &Value) -> Polled {
51 if status == 404 {
52 return Polled::Gone;
53 }
54 if !(200..300).contains(&status) {
55 return Polled::Pending;
56 }
57 match body.get("status").and_then(Value::as_str) {
58 Some("ready") => {
59 let code = body.get("code").and_then(Value::as_str).filter(|c| !c.is_empty());
60 let installation_id = body.get("installation_id").and_then(Value::as_u64).filter(|id| *id > 0);
61 let action = body.get("setup_action").and_then(Value::as_str).filter(|a| !a.is_empty());
62 match (code, installation_id, action) {
63 (Some(code), Some(installation_id), Some(action)) => {
64 Polled::Ready { code: code.to_string(), installation_id, setup_action: action.to_string() }
65 }
66 _ => Polled::Failed("the relay's answer was incomplete".to_string()),
67 }
68 }
69 Some("failed") => Polled::Failed(body.get("error").and_then(Value::as_str).unwrap_or("unknown").to_string()),
70 _ => Polled::Pending,
71 }
72}
73
74pub async fn register(http: &reqwest::Client, relay_base: &str, key: &str) -> Result<(), String> {
76 let reply = http
77 .post(relay_url(relay_base, "/api/login-relay/github"))
78 .json(&serde_json::json!({ "key": key }))
79 .send()
80 .await
81 .map_err(|e| format!("could not reach AgentMux Cloud's relay: {}", e.without_url()))?;
82 let status = reply.status();
83 if status.is_success() {
84 return Ok(());
85 }
86 Err(format!("AgentMux Cloud's relay refused the connection ({status})"))
87}
88
89pub async fn poll_once(http: &reqwest::Client, relay_base: &str, key: &str) -> Polled {
91 let Ok(reply) = http.get(relay_url(relay_base, &format!("/api/login-relay/github/{key}"))).send().await else {
92 return Polled::Pending;
93 };
94 let status = reply.status().as_u16();
95 let body: Value = reply.json().await.unwrap_or(Value::Null);
96 parse_poll(status, &body)
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102 use serde_json::json;
103
104 #[test]
105 fn the_callback_is_the_relays_hosted_page() {
106 assert_eq!(callback_uri("https://muxbus.example.test"), "https://muxbus.example.test/github-callback");
107 assert_eq!(callback_uri("https://muxbus.example.test/"), "https://muxbus.example.test/github-callback");
108 }
109
110 #[test]
111 fn a_base_with_a_trailing_slash_gives_the_same_addresses() {
112 for base in ["https://muxbus.example.test", "https://muxbus.example.test/"] {
113 assert_eq!(relay_url(base, "/api/login-relay/github"), "https://muxbus.example.test/api/login-relay/github");
114 }
115 }
116
117 #[test]
118 fn the_key_is_the_sha256_hex_of_the_state_and_never_the_state() {
119 assert_eq!(relay_key("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
120 let state = "kJ3-Gh_7xQ0aBcDeFgHiJkLmNoPqRsTuVwXyZ012345";
121 assert!(!relay_key(state).contains(state));
122 assert_eq!(relay_key(state).len(), 64);
123 }
124
125 #[test]
126 fn a_broker_that_does_not_say_it_is_ready_for_a_trip_is_not_one() {
127 use crate::muxbus::github_broker::InstallState;
128 let older: InstallState = serde_json::from_value(json!({ "state": "s", "install_url": "https://github.com/apps/x" })).unwrap();
129 assert!(!older.one_trip);
130 let ready: InstallState = serde_json::from_value(json!({ "state": "s", "install_url": "https://github.com/apps/x", "one_trip": true })).unwrap();
131 assert!(ready.one_trip);
132 }
133
134 #[test]
135 fn a_ready_answer_needs_the_code_the_installation_and_the_action() {
136 let ready = json!({ "status": "ready", "code": "c1", "installation_id": 4242, "setup_action": "install" });
137 assert_eq!(parse_poll(200, &ready), Polled::Ready { code: "c1".into(), installation_id: 4242, setup_action: "install".into() });
138 for missing in ["code", "installation_id", "setup_action"] {
139 let mut cut = ready.clone();
140 cut.as_object_mut().unwrap().remove(missing);
141 assert!(matches!(parse_poll(200, &cut), Polled::Failed(_)), "{missing}");
142 }
143 assert!(matches!(parse_poll(200, &json!({ "status": "ready", "code": "", "installation_id": 1, "setup_action": "install" })), Polled::Failed(_)));
144 assert!(matches!(parse_poll(200, &json!({ "status": "ready", "code": "c", "installation_id": 0, "setup_action": "install" })), Polled::Failed(_)));
145 assert!(matches!(parse_poll(200, &json!({ "status": "ready", "code": "c", "installation_id": "4242", "setup_action": "install" })), Polled::Failed(_)));
146 }
147
148 #[test]
149 fn pending_failed_and_gone_read_as_what_they_are() {
150 assert_eq!(parse_poll(200, &json!({ "status": "pending" })), Polled::Pending);
151 assert_eq!(parse_poll(200, &json!({ "status": "failed", "error": "access_denied" })), Polled::Failed("access_denied".into()));
152 assert_eq!(parse_poll(200, &json!({ "status": "failed" })), Polled::Failed("unknown".into()));
153 assert_eq!(parse_poll(404, &Value::Null), Polled::Gone);
154 }
155
156 #[test]
157 fn a_server_hiccup_or_an_unknown_answer_is_asked_again_never_taken_for_a_code() {
158 assert_eq!(parse_poll(500, &json!({ "status": "ready", "code": "c", "installation_id": 1, "setup_action": "install" })), Polled::Pending);
159 assert_eq!(parse_poll(429, &Value::Null), Polled::Pending);
160 assert_eq!(parse_poll(200, &Value::Null), Polled::Pending);
161 assert_eq!(parse_poll(200, &json!({ "status": "something-new" })), Polled::Pending);
162 }
163}