Skip to main content

agentmux_srv_core/identity/
github_trip.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one-trip first connect with GitHub, desktop side: the relay half.
5//!
6//! GitHub's install page takes no `redirect_uri`, so after the person installs the App and
7//! authorizes it, GitHub sends the browser to the App's first callback URL: the cloud relay's hosted
8//! page `/github-callback`. The page hands `{code, installation_id, setup_action}` to the relay under
9//! the SHA-256 of the install `state` the broker issued; this module registers that trip before the
10//! browser opens and polls for the outcome. The code goes to the broker, which holds the App's
11//! client secret and checks the `state` is one this account was issued; nothing here reads it.
12//!
13//! The poll key is the hash, never the state itself, so a poll address in a log is no use to anyone.
14
15use serde_json::Value;
16use sha2::{Digest, Sha256};
17
18/// Where the relay's hosted page is, and where GitHub is told to send the browser.
19pub const CALLBACK_PATH: &str = "/github-callback";
20
21/// An address on the relay, whether or not its base ends in a slash.
22fn relay_url(relay_base: &str, path: &str) -> String {
23    format!("{}{path}", relay_base.trim_end_matches('/'))
24}
25
26/// The address the install page's callback lands on.
27pub fn callback_uri(relay_base: &str) -> String {
28    relay_url(relay_base, CALLBACK_PATH)
29}
30
31/// The relay's key for a trip: the SHA-256 hex of the install `state`.
32pub fn relay_key(state: &str) -> String {
33    hex::encode(Sha256::digest(state.as_bytes()))
34}
35
36/// What the relay answered to a poll.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Polled {
39    /// Registered, nothing back yet (or a hiccup worth asking again about).
40    Pending,
41    /// GitHub's authorization, with the installation it came with.
42    Ready { code: String, installation_id: u64, setup_action: String },
43    /// GitHub reported a refusal (the person said no, or it failed); the words are GitHub's.
44    Failed(String),
45    /// The relay has no such trip: it expired or was already collected.
46    Gone,
47}
48
49/// Reads a poll's answer. Anything the relay should not send is read as "ask again", never as a code.
50pub 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
74/// Tell the relay a trip is coming, before the browser opens (a flow nobody registered is refused).
75pub 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
89/// Ask the relay once. A network error or a server error reads as "not yet": the caller asks again.
90pub 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}