Skip to main content

agentmux_srv_core/muxbus/
pkce.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! PKCE Authorization Code flow for Cognito desktop login.
5//!
6//! Flow (cloud-relayed callback — no loopback listener; see
7//! docs/specs/SPEC_MUXBUS_CLOUD_RELAYED_LOGIN_CALLBACK_2026_08_15.md):
8//!   1. Generate code_verifier + code_challenge (S256).
9//!   2. Register the flow's state with the muxbus login relay.
10//!   3. Open browser to Cognito hosted UI; it redirects to the hosted
11//!      /desktop-callback page, which posts {state, code} to the relay.
12//!   4. Poll the relay for the code (single-read on the relay side).
13//!   5. Exchange code for tokens via /oauth2/token (PKCE verifier never
14//!      left this process).
15//!   6. Decode email from id_token claims (no re-verification needed —
16//!      we fetched the token directly from Cognito).
17
18use base64::Engine as _;
19use sha2::{Digest, Sha256};
20
21use crate::backend::storage::muxbus::MuxBusCredentials;
22use crate::util::open_browser;
23
24pub const LOGIN_TIMEOUT_SECS: u64 = 300;
25
26#[derive(Debug)]
27pub struct PkceResult {
28    pub credentials: MuxBusCredentials,
29}
30
31/// Base URL of the muxbus REST API hosting the login relay.
32///
33/// Single definition shared with the tier-4 outbound relay
34/// (`crate::muxbus::relay::rest_base_url`) — two copies of "where is the
35/// cloud" is precisely the drift the network DRYness pass set out to remove.
36use crate::muxbus::relay::rest_base_url as relay_base_url;
37
38// Only one login flow may exist per process. Two concurrent flows both bind
39// the fixed callback port, and (on Windows, where SO_REUSEADDR permits binding
40// a port another live socket already holds) the browser's redirect lands on
41// whichever listener the OS picks — a 400 state-mismatch coin flip. The newest
42// attempt is the one the user actually wants: abort the predecessor.
43//
44// Each flow gets a monotonic generation id (NEXT_LOGIN_ID), stored alongside
45// its abort handle. A prior design tracked "was this abort a user Cancel?"
46// in a single shared CANCELLED_BY_USER flag instead of per-attempt — that
47// was a real bug (Codex + reagent review, PR #2661, 2026-08-19): if flow A
48// is cancelled but a *different* flow B starts and is itself superseded by
49// C before A's own `task.await` resumes, nothing guarantees which of A/B
50// reads the shared flag first — the two flows' error messages could swap.
51// Keying the cancellation record on the generation id makes that
52// structurally impossible: each flow only ever looks up its OWN id.
53static NEXT_LOGIN_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
54static ACTIVE_LOGIN: std::sync::Mutex<Option<(u64, tokio::task::AbortHandle)>> =
55    std::sync::Mutex::new(None);
56static CANCELLED_IDS: std::sync::Mutex<Vec<u64>> = std::sync::Mutex::new(Vec::new());
57
58/// Abort the in-flight login flow, if any. Returns false if there was none
59/// (a harmless no-op — the UI can call this without checking state first).
60pub fn cancel_active_login() -> bool {
61    let mut guard = ACTIVE_LOGIN.lock().unwrap();
62    match guard.take() {
63        Some((id, handle)) => {
64            // ACTIVE_LOGIN is only ever overwritten by the NEXT login's
65            // critical section — nothing clears it when a flow resolves
66            // naturally (`Ok` or a real, non-cancelled `Err`). So this can
67            // find a stale entry whose task already finished on its own,
68            // possibly long ago; `AbortHandle::abort()` on a finished task
69            // is a documented no-op. Reporting `true` here for that case
70            // would tell the caller "cancelled" for a login that actually
71            // succeeded/failed by itself, and would push `id` into
72            // CANCELLED_IDS, which nothing on the natural-completion path
73            // in `run_pkce_login` ever pops — leaking one entry per
74            // occurrence for the life of the process (reagent P1, PR
75            // #2661, re-review 2026-08-19). Checking `is_finished()` first
76            // closes the common case (a stale entry sitting there for any
77            // length of time before this call). A narrower race remains —
78            // the task can still finish in the gap between this check and
79            // `abort()` below taking effect — closed instead by
80            // `run_pkce_login` cleaning up its own id on every resolution
81            // path, not just the cancelled one.
82            if handle.is_finished() {
83                return false;
84            }
85            CANCELLED_IDS.lock().unwrap().push(id);
86            handle.abort();
87            true
88        }
89        None => false,
90    }
91}
92
93/// `identity_provider` (a Cognito provider name, already checked by the
94/// caller) sends the browser straight to that provider; `None` opens
95/// Cognito's own page.
96pub async fn run_pkce_login(
97    cognito_domain: &str,
98    client_id: &str,
99    identity_provider: Option<String>,
100    http_client: &reqwest::Client,
101) -> Result<PkceResult, String> {
102    let my_id = NEXT_LOGIN_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
103
104    // Abort-predecessor and register-successor must be one critical section:
105    // with separate lock acquisitions, two concurrent muxbus.login RPCs can
106    // both take() None and neither aborts the other (reagent P1 on this PR).
107    // tokio::spawn is synchronous and non-blocking, so holding the std mutex
108    // across it is fine — the guard never spans an await.
109    let task = {
110        let mut guard = ACTIVE_LOGIN.lock().unwrap();
111        if let Some((_, prev)) = guard.take() {
112            prev.abort();
113        }
114        let task = tokio::spawn(run_pkce_login_inner(
115            cognito_domain.to_string(),
116            client_id.to_string(),
117            identity_provider,
118            http_client.clone(),
119        ));
120        *guard = Some((my_id, task.abort_handle()));
121        task
122    };
123    match task.await {
124        Ok(r) => {
125            // The flow resolved naturally. `cancel_active_login()`'s
126            // `is_finished()` guard closes the common case, but a narrow
127            // race remains: the task can complete in the gap between that
128            // check and its `abort()` call taking effect (tokio: an abort
129            // request against an already-completing task is ignored, the
130            // task "will run to completion" per its own docs), which would
131            // have pushed `my_id` into CANCELLED_IDS just before this arm
132            // runs. Nothing else on this path ever pops it — clean it up
133            // here so it can't leak.
134            CANCELLED_IDS.lock().unwrap().retain(|&id| id != my_id);
135            r
136        }
137        Err(e) if e.is_cancelled() => {
138            let mut cancelled = CANCELLED_IDS.lock().unwrap();
139            if let Some(pos) = cancelled.iter().position(|&id| id == my_id) {
140                cancelled.remove(pos);
141                Err("sign-in cancelled".to_string())
142            } else {
143                Err("this login attempt was superseded by a newer one".to_string())
144            }
145        }
146        Err(e) => {
147            // Same residual-race cleanup as the Ok(r) arm above, for a
148            // flow that failed on its own (not via cancellation).
149            CANCELLED_IDS.lock().unwrap().retain(|&id| id != my_id);
150            Err(format!("login task failed: {e}"))
151        }
152    }
153}
154
155async fn run_pkce_login_inner(
156    cognito_domain: String,
157    client_id: String,
158    identity_provider: Option<String>,
159    http_client: reqwest::Client,
160) -> Result<PkceResult, String> {
161    // 1. Generate code_verifier (43–128 chars of URL-safe chars)
162    let v1 = uuid::Uuid::new_v4();
163    let v2 = uuid::Uuid::new_v4();
164    let mut raw = [0u8; 32];
165    raw[..16].copy_from_slice(v1.as_bytes());
166    raw[16..].copy_from_slice(v2.as_bytes());
167    let code_verifier = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw);
168
169    // 2. code_challenge = BASE64URL(SHA-256(code_verifier))
170    let mut hasher = Sha256::new();
171    hasher.update(code_verifier.as_bytes());
172    let digest = hasher.finalize();
173    let code_challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest);
174
175    // 3. State (CSRF)
176    let state = uuid::Uuid::new_v4().to_string();
177
178    // 4. Register the flow with the cloud relay BEFORE opening the browser.
179    //    The hosted /desktop-callback page (agentmux-cloud's login-relay page)
180    //    posts {state, code} there; step 7 polls it back out. No loopback
181    //    listener: the browser never touches 127.0.0.1, and concurrent
182    //    instances can't collide — each flow polls its own state key.
183    //    See docs/specs/SPEC_MUXBUS_CLOUD_RELAYED_LOGIN_CALLBACK_2026_08_15.md.
184    let relay_base = relay_base_url();
185    let redirect_uri = format!("{relay_base}/desktop-callback");
186    let create_resp = http_client
187        .post(format!("{relay_base}/api/login-relay"))
188        .json(&serde_json::json!({ "state": state }))
189        .send()
190        .await
191        .map_err(|e| format!("could not reach the login relay: {e}"))?;
192    if !create_resp.status().is_success() {
193        let status = create_resp.status();
194        let body = create_resp.text().await.unwrap_or_default();
195        return Err(format!("login relay refused the flow ({status}): {body}"));
196    }
197
198    // 5. Build auth URL
199    let auth_url = authorize_url(
200        &cognito_domain,
201        &client_id,
202        &redirect_uri,
203        &code_challenge,
204        &state,
205        identity_provider.as_deref(),
206    );
207
208    // 6. Open browser (suppressed under test — the supersede test drives
209    //    real flows that would otherwise launch real browser windows)
210    if !cfg!(any(test, feature = "test-support")) {
211        open_browser(&auth_url);
212    }
213
214    tracing::info!(
215        cognito_domain = cognito_domain,
216        relay = relay_base,
217        "muxbus: PKCE login started, awaiting relayed browser callback"
218    );
219
220    // 7. Poll the relay until the code arrives (5-min overall timeout, matching
221    //    the relay record's TTL). Transient relay/network errors are tolerated
222    //    and re-polled; a 404 is fatal — the flow expired or was already
223    //    consumed (single-read on the relay side).
224    let code = tokio::time::timeout(
225        std::time::Duration::from_secs(LOGIN_TIMEOUT_SECS),
226        async {
227            loop {
228                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
229                let resp = match http_client
230                    .get(format!("{relay_base}/api/login-relay/{state}"))
231                    .send()
232                    .await
233                {
234                    Ok(r) => r,
235                    Err(_) => continue, // transient network problem — keep polling
236                };
237                if resp.status() == reqwest::StatusCode::NOT_FOUND {
238                    return Err(
239                        "login attempt expired or was completed elsewhere — please try again"
240                            .to_string(),
241                    );
242                }
243                if !resp.status().is_success() {
244                    continue; // transient server error — keep polling
245                }
246                let body: serde_json::Value = match resp.json().await {
247                    Ok(v) => v,
248                    Err(_) => continue,
249                };
250                match body["status"].as_str() {
251                    Some("ready") => match body["code"].as_str() {
252                        Some(c) => return Ok(c.to_string()),
253                        None => return Err("relay returned ready without a code".to_string()),
254                    },
255                    // Cognito denial forwarded by the hosted page — fail fast
256                    // rather than polling out the rest of the 5 minutes.
257                    Some("failed") => {
258                        let err = body["error"].as_str().unwrap_or("unknown");
259                        return Err(format!("Cognito returned error: {err}"));
260                    }
261                    // "pending" or anything unrecognized — keep polling until
262                    // the overall timeout says otherwise.
263                    _ => continue,
264                }
265            }
266        },
267    )
268    .await
269    .map_err(|_| "login timed out (5 min) — please try again".to_string())??;
270
271    // 8. Exchange code for tokens
272    let token_url = format!("{cognito_domain}/oauth2/token");
273    let params = [
274        ("grant_type", "authorization_code"),
275        ("client_id", client_id.as_str()),
276        ("code", &code),
277        ("redirect_uri", &redirect_uri),
278        ("code_verifier", &code_verifier),
279    ];
280
281    let resp = http_client
282        .post(&token_url)
283        .form(&params)
284        .send()
285        .await
286        .map_err(|e| format!("token exchange request failed: {e}"))?;
287
288    if !resp.status().is_success() {
289        let body = resp.text().await.unwrap_or_default();
290        return Err(format!("token exchange failed: {body}"));
291    }
292
293    let token_json: serde_json::Value = resp
294        .json()
295        .await
296        .map_err(|e| format!("token response parse failed: {e}"))?;
297
298    let access_token = token_json["access_token"]
299        .as_str()
300        .unwrap_or("")
301        .to_string();
302    let refresh_token = token_json["refresh_token"]
303        .as_str()
304        .unwrap_or("")
305        .to_string();
306    let id_token = token_json["id_token"].as_str().unwrap_or("").to_string();
307    let expires_in = token_json["expires_in"].as_i64().unwrap_or(3600);
308    let expires_at = (agentmux_common::time::now_secs())
309        + expires_in;
310
311    // 9. Extract email + sub from id_token payload (no re-verification needed)
312    let (user_email, user_sub) = extract_jwt_claims(&id_token);
313
314    tracing::info!(
315        email = user_email,
316        "muxbus: PKCE login succeeded"
317    );
318
319    Ok(PkceResult {
320        credentials: MuxBusCredentials {
321            cognito_domain: cognito_domain.to_string(),
322            client_id: client_id.to_string(),
323            access_token,
324            refresh_token,
325            id_token,
326            expires_at,
327            user_email,
328            user_sub,
329        },
330    })
331}
332
333/// Typed so callers (the credential broker's registered `refresh` closure)
334/// can distinguish "worth retrying" from "this refresh_token is dead, only
335/// a fresh login fixes it" without string-sniffing an error message.
336/// `Rejected` specifically means the token endpoint responded but rejected
337/// the request (Cognito's `invalid_grant`-class 4xx for a revoked/expired
338/// refresh_token) — the credential itself is the problem. `Network`/
339/// `ParseFailed` mean the ATTEMPT failed, not the credential.
340#[derive(Debug)]
341pub enum RefreshTokenError {
342    NoRefreshToken,
343    Network(String),
344    Rejected { status: u16, body: String },
345    ParseFailed(String),
346}
347
348impl std::fmt::Display for RefreshTokenError {
349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350        match self {
351            RefreshTokenError::NoRefreshToken => write!(f, "no refresh token stored"),
352            RefreshTokenError::Network(e) => write!(f, "refresh request failed: {e}"),
353            RefreshTokenError::Rejected { status, body } => {
354                write!(f, "token refresh failed ({status}): {body}")
355            }
356            RefreshTokenError::ParseFailed(e) => write!(f, "refresh response parse failed: {e}"),
357        }
358    }
359}
360
361/// How long a token refresh may take, the answer's body included. The shared
362/// client sets no request timeout of its own, and a request that never
363/// answered held the refresh (and every caller queued behind it) for hours.
364pub const REFRESH_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
365
366pub async fn refresh_token(
367    creds: &MuxBusCredentials,
368    http_client: &reqwest::Client,
369) -> Result<MuxBusCredentials, RefreshTokenError> {
370    refresh_token_within(creds, http_client, REFRESH_REQUEST_TIMEOUT).await
371}
372
373pub(crate) async fn refresh_token_within(
374    creds: &MuxBusCredentials,
375    http_client: &reqwest::Client,
376    timeout: std::time::Duration,
377) -> Result<MuxBusCredentials, RefreshTokenError> {
378    if creds.refresh_token.is_empty() {
379        return Err(RefreshTokenError::NoRefreshToken);
380    }
381    let token_url = format!("{}/oauth2/token", creds.cognito_domain);
382    let params = [
383        ("grant_type", "refresh_token"),
384        ("client_id", creds.client_id.as_str()),
385        ("refresh_token", creds.refresh_token.as_str()),
386    ];
387    let sent = http_client.post(&token_url).form(&params).timeout(timeout).send().await;
388    crate::connectivity::report_http(crate::connectivity::Service::Muxbus, &sent);
389    let resp = sent.map_err(|e| RefreshTokenError::Network(e.to_string()))?;
390    if !resp.status().is_success() {
391        let status = resp.status().as_u16();
392        let body = resp.text().await.unwrap_or_default();
393        return Err(RefreshTokenError::Rejected { status, body });
394    }
395    let json: serde_json::Value = resp
396        .json()
397        .await
398        .map_err(|e| RefreshTokenError::ParseFailed(e.to_string()))?;
399
400    let access_token = json["access_token"].as_str().unwrap_or("").to_string();
401    let expires_in = json["expires_in"].as_i64().unwrap_or(3600);
402    let expires_at = (agentmux_common::time::now_secs())
403        + expires_in;
404    // Cognito doesn't rotate refresh_token on refresh — keep existing
405    let new_id_token = json["id_token"]
406        .as_str()
407        .map(|s| s.to_string())
408        .unwrap_or_else(|| creds.id_token.clone());
409
410    Ok(MuxBusCredentials {
411        cognito_domain: creds.cognito_domain.clone(),
412        client_id: creds.client_id.clone(),
413        access_token,
414        refresh_token: creds.refresh_token.clone(),
415        id_token: new_id_token,
416        expires_at,
417        user_email: creds.user_email.clone(),
418        user_sub: creds.user_sub.clone(),
419    })
420}
421
422/// Cognito's `/oauth2/authorize` URL for one flow. `identity_provider` is
423/// added only when given.
424fn authorize_url(
425    cognito_domain: &str,
426    client_id: &str,
427    redirect_uri: &str,
428    code_challenge: &str,
429    state: &str,
430    identity_provider: Option<&str>,
431) -> String {
432    let scopes = "openid+email+profile+https%3A%2F%2Fmuxbus.agentmux.ai%2Fread+https%3A%2F%2Fmuxbus.agentmux.ai%2Fwrite";
433    let mut url = format!(
434        "{cognito_domain}/oauth2/authorize\
435         ?response_type=code\
436         &client_id={client_id}\
437         &redirect_uri={redirect_uri_enc}\
438         &scope={scopes}\
439         &code_challenge={code_challenge}\
440         &code_challenge_method=S256\
441         &state={state}",
442        redirect_uri_enc = percent_encode(redirect_uri),
443    );
444    if let Some(provider) = identity_provider {
445        url.push_str("&identity_provider=");
446        url.push_str(&percent_encode(provider));
447    }
448    url
449}
450
451fn percent_encode(s: &str) -> String {
452    let mut out = String::with_capacity(s.len() * 3);
453    for b in s.bytes() {
454        match b {
455            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'
456            | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
457            _ => {
458                out.push('%');
459                out.push_str(&format!("{b:02X}"));
460            }
461        }
462    }
463    out
464}
465
466/// The `sub` claim of a Cognito token (unverified decode: this names the
467/// account a token we already hold belongs to, it doesn't authenticate it).
468/// Empty if the token isn't a JWT or has no `sub`.
469pub(crate) fn token_sub(token: &str) -> String {
470    extract_jwt_claims(token).1
471}
472
473fn extract_jwt_claims(token: &str) -> (String, String) {
474    let payload = token.splitn(3, '.').nth(1).unwrap_or("");
475    let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
476        .decode(payload)
477        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(payload))
478        .unwrap_or_default();
479    let json: serde_json::Value =
480        serde_json::from_slice(&decoded).unwrap_or_default();
481    let email = json["email"].as_str().unwrap_or("").to_string();
482    let sub = json["sub"].as_str().unwrap_or("").to_string();
483    (email, sub)
484}
485
486
487/// Serializes every test that touches process-global state: the login statics
488/// above and the `AGENTMUX_MUXBUS_REST_URL` / `AGENTMUX_MUXBUS_WS_URL`
489/// environment overrides (`cloud_subscriber`'s session test shares it).
490#[cfg(any(test, feature = "test-support"))]
491pub(crate) static TEST_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496    use tokio::io::{AsyncReadExt, AsyncWriteExt};
497
498    /// Minimal fake login relay: 201 on POST /api/login-relay, an eternally
499    /// "pending" JSON body on GET polls. Keeps real flows parked at the
500    /// poll stage with zero external network dependency.
501    async fn spawn_fake_relay() -> String {
502        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
503        let addr = listener.local_addr().unwrap();
504        tokio::spawn(async move {
505            loop {
506                let Ok((mut stream, _)) = listener.accept().await else { return };
507                tokio::spawn(async move {
508                    let mut buf = [0u8; 2048];
509                    let Ok(n) = stream.read(&mut buf).await else { return };
510                    let req = std::str::from_utf8(&buf[..n]).unwrap_or("");
511                    let body = if req.starts_with("POST /api/login-relay") {
512                        r#"{"status":"pending","ttl_seconds":300}"#
513                    } else {
514                        r#"{"status":"pending"}"#
515                    };
516                    let resp = format!(
517                        "HTTP/1.1 {} 
518Content-Type: application/json
519Content-Length: {}
520Connection: close
521
522{}",
523                        if req.starts_with("POST") { "201 Created" } else { "200 OK" },
524                        body.len(),
525                        body
526                    );
527                    let _ = stream.write_all(resp.as_bytes()).await;
528                });
529            }
530        });
531        format!("http://{addr}")
532    }
533
534    /// Like `spawn_fake_relay`, but GET polls report `"failed"` immediately
535    /// — lets a test drive a flow to a *natural* (non-cancelled) resolution
536    /// quickly, instead of waiting out the real 5-minute timeout.
537    async fn spawn_fake_failing_relay() -> String {
538        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
539        let addr = listener.local_addr().unwrap();
540        tokio::spawn(async move {
541            loop {
542                let Ok((mut stream, _)) = listener.accept().await else { return };
543                tokio::spawn(async move {
544                    let mut buf = [0u8; 2048];
545                    let Ok(n) = stream.read(&mut buf).await else { return };
546                    let req = std::str::from_utf8(&buf[..n]).unwrap_or("");
547                    let body = if req.starts_with("POST /api/login-relay") {
548                        r#"{"status":"pending","ttl_seconds":300}"#
549                    } else {
550                        r#"{"status":"failed","error":"access_denied"}"#
551                    };
552                    let resp = format!(
553                        "HTTP/1.1 {}
554Content-Type: application/json
555Content-Length: {}
556Connection: close
557
558{}",
559                        if req.starts_with("POST") { "201 Created" } else { "200 OK" },
560                        body.len(),
561                        body
562                    );
563                    let _ = stream.write_all(resp.as_bytes()).await;
564                });
565            }
566        });
567        format!("http://{addr}")
568    }
569
570    // ACTIVE_LOGIN / CANCELLED_IDS are process-global statics — by
571    // design, only one login flow may exist per process. Cargo runs tests
572    // in this file on parallel threads of the same process by default, so
573    // any two tests that drive a real flow through those statics race each
574    // other unless serialized here.
575    use super::TEST_SERIAL;
576
577    // The superseded-login guarantee: starting flow B while flow A is pending
578    // must abort A rather than leaving two flows both polling (and both able
579    // to open browser tabs). Uses the real run_pkce_login entry so the
580    // abort-registry path itself is exercised; the fake relay keeps both
581    // flows parked at the poll stage.
582    #[tokio::test(flavor = "multi_thread")]
583    async fn second_login_supersedes_first() {
584        let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
585        let relay = spawn_fake_relay().await;
586        std::env::set_var("AGENTMUX_MUXBUS_REST_URL", &relay);
587
588        let http = reqwest::Client::new();
589        let flow_a = tokio::spawn({
590            let http = http.clone();
591            async move { run_pkce_login("http://127.0.0.1:1", "test-client", None, &http).await }
592        });
593        // Give A time to register + start polling before B supersedes it.
594        tokio::time::sleep(std::time::Duration::from_millis(400)).await;
595
596        let flow_b = tokio::spawn({
597            let http = http.clone();
598            async move { run_pkce_login("http://127.0.0.1:1", "test-client", None, &http).await }
599        });
600        tokio::time::sleep(std::time::Duration::from_millis(400)).await;
601
602        let a = tokio::time::timeout(std::time::Duration::from_secs(2), flow_a)
603            .await
604            .expect("flow A should resolve promptly after being superseded")
605            .expect("flow A task must not panic");
606        assert!(
607            a.as_ref().is_err_and(|e| e.contains("superseded")),
608            "flow A should report being superseded, got: {a:?}"
609        );
610        assert!(!flow_b.is_finished(), "flow B should still be polling the relay");
611
612        // Cleanup: abort B's inner flow via the registry.
613        if let Some((_, h)) = ACTIVE_LOGIN.lock().unwrap().take() {
614            h.abort();
615        }
616        flow_b.abort();
617        std::env::remove_var("AGENTMUX_MUXBUS_REST_URL");
618    }
619
620    // A user-initiated Cancel must resolve the pending flow immediately
621    // (not wait out LOGIN_TIMEOUT_SECS) and report a "cancelled" error
622    // distinct from the supersede case above — otherwise the UI has no way
623    // to tell "you cancelled this" from "a newer login attempt replaced
624    // this", which is what the Cancel buttons (`useMuxBusStatus` in
625    // frontend/app/view/accounts/AgentMuxConnectPanel.tsx, also used by
626    // frontend/app/statusbar/HostPopover.tsx) need to show a quiet,
627    // non-error reset instead of a scary banner.
628    #[tokio::test(flavor = "multi_thread")]
629    async fn manual_cancel_resolves_promptly_with_cancelled_error() {
630        let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
631        let relay = spawn_fake_relay().await;
632        std::env::set_var("AGENTMUX_MUXBUS_REST_URL", &relay);
633
634        let http = reqwest::Client::new();
635        let flow = tokio::spawn({
636            let http = http.clone();
637            async move { run_pkce_login("http://127.0.0.1:1", "test-client", None, &http).await }
638        });
639        // Give the flow time to register + start polling before cancelling.
640        tokio::time::sleep(std::time::Duration::from_millis(400)).await;
641
642        assert!(cancel_active_login(), "expected an active login to cancel");
643
644        let result = tokio::time::timeout(std::time::Duration::from_secs(2), flow)
645            .await
646            .expect("cancel should resolve the flow promptly, not after the 5-min timeout")
647            .expect("flow task must not panic");
648        assert!(
649            result.as_ref().is_err_and(|e| e.contains("cancelled")),
650            "expected a cancellation error, got: {result:?}"
651        );
652
653        std::env::remove_var("AGENTMUX_MUXBUS_REST_URL");
654    }
655
656    #[test]
657    fn the_authorize_url_names_a_provider_only_when_one_was_chosen() {
658        let url = |provider| {
659            authorize_url("https://auth.example.test", "client", "https://relay.example.test/desktop-callback", "chal", "st", provider)
660        };
661        let email = url(None);
662        assert!(email.starts_with("https://auth.example.test/oauth2/authorize?response_type=code&client_id=client&"));
663        assert!(email.contains("&redirect_uri=https%3A%2F%2Frelay.example.test%2Fdesktop-callback&"));
664        assert!(email.ends_with("&code_challenge=chal&code_challenge_method=S256&state=st"));
665        assert!(!email.contains("identity_provider"));
666
667        assert_eq!(url(Some("SignInWithApple")), format!("{email}&identity_provider=SignInWithApple"));
668        assert!(url(Some("A&b=c")).ends_with("&identity_provider=A%26b%3Dc"), "the value is encoded");
669    }
670
671    // Cancelling with no active login is a harmless no-op the UI can call
672    // defensively without checking state first.
673    #[tokio::test]
674    async fn cancel_with_no_active_login_is_a_noop() {
675        let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
676        assert!(!cancel_active_login());
677    }
678
679    // Regression test for a real bug caught in code review (Codex + reagent,
680    // 2026-08-19, PR #2661): the original fix tracked "was this abort a user
681    // Cancel?" in a single process-global flag. Flow A gets cancelled by the
682    // user (flag set), then — before A's own `task.await` resumes and reads
683    // the flag — flow B starts and is itself superseded by flow C. Nothing
684    // guarantees which task's continuation the executor resumes first, so
685    // whichever of A/B checks the flag first "steals" it: the two flows'
686    // error messages ("cancelled" vs "superseded") can end up swapped. Fixed
687    // by keying the cancellation record on a per-attempt generation id
688    // instead of a single shared flag, so each flow can only ever observe
689    // its OWN cancellation record — this test asserts that invariant
690    // directly rather than trying to force a specific race outcome (which
691    // isn't reliably controllable from a test).
692    #[tokio::test(flavor = "multi_thread")]
693    async fn cancelling_one_flow_never_leaks_into_a_concurrent_unrelated_flow() {
694        let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
695        let relay = spawn_fake_relay().await;
696        std::env::set_var("AGENTMUX_MUXBUS_REST_URL", &relay);
697        let http = reqwest::Client::new();
698
699        // Flow A: the user-cancel path.
700        let flow_a = tokio::spawn({
701            let http = http.clone();
702            async move { run_pkce_login("http://127.0.0.1:1", "test-client", None, &http).await }
703        });
704        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
705        assert!(cancel_active_login(), "expected flow A to be active and cancellable");
706
707        // Flow B, then C superseding B — the "superseded" path, unrelated to
708        // A's cancel. Started immediately after A's cancel so A's own
709        // task.await may not have resumed yet when B/C run.
710        let flow_b = tokio::spawn({
711            let http = http.clone();
712            async move { run_pkce_login("http://127.0.0.1:1", "test-client", None, &http).await }
713        });
714        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
715        let flow_c = tokio::spawn({
716            let http = http.clone();
717            async move { run_pkce_login("http://127.0.0.1:1", "test-client", None, &http).await }
718        });
719        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
720
721        let a = tokio::time::timeout(std::time::Duration::from_secs(2), flow_a)
722            .await
723            .expect("flow A should resolve promptly")
724            .expect("flow A task must not panic");
725        let b = tokio::time::timeout(std::time::Duration::from_secs(2), flow_b)
726            .await
727            .expect("flow B should resolve promptly after being superseded by C")
728            .expect("flow B task must not panic");
729
730        assert!(
731            a.as_ref().is_err_and(|e| e.contains("cancelled")),
732            "flow A was user-cancelled, got: {a:?}"
733        );
734        assert!(
735            b.as_ref().is_err_and(|e| e.contains("superseded")),
736            "flow B was superseded by C (never cancelled), got: {b:?}"
737        );
738
739        // Cleanup: abort C's inner flow via the registry.
740        if let Some((_, h)) = ACTIVE_LOGIN.lock().unwrap().take() {
741            h.abort();
742        }
743        flow_c.abort();
744        std::env::remove_var("AGENTMUX_MUXBUS_REST_URL");
745    }
746
747    // Regression test for reagent's P1 re-review (PR #2661, 2026-08-19):
748    // ACTIVE_LOGIN was never cleared when a flow resolved naturally (`Ok`
749    // or a real, non-cancelled `Err`), so a `muxbus.login.cancel` call any
750    // time afterward found a stale entry pointing at a finished task's
751    // (harmless, no-op) AbortHandle — reporting a misleading "cancelled"
752    // success for a login that had already succeeded/failed on its own,
753    // and leaking one u64 into CANCELLED_IDS forever (nothing on the
754    // natural-completion path ever popped it). Fixed by having
755    // cancel_active_login() check AbortHandle::is_finished() before
756    // treating a take() as a real cancellation, plus having run_pkce_login
757    // clean up its own id from CANCELLED_IDS on every resolution path, not
758    // just the cancelled one.
759    #[tokio::test(flavor = "multi_thread")]
760    async fn cancelling_after_natural_completion_is_a_noop_and_does_not_leak() {
761        let _serial = TEST_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
762        let relay = spawn_fake_failing_relay().await;
763        std::env::set_var("AGENTMUX_MUXBUS_REST_URL", &relay);
764
765        let http = reqwest::Client::new();
766        let result = run_pkce_login("http://127.0.0.1:1", "test-client", None, &http).await;
767        assert!(
768            result.as_ref().is_err_and(|e| e.contains("Cognito returned error")),
769            "expected the flow to fail on its own via the relay's failed status, got: {result:?}"
770        );
771
772        // The flow already resolved naturally — a cancel call now must be a
773        // no-op, not a misleading "cancelled" success.
774        assert!(
775            !cancel_active_login(),
776            "cancelling an already-resolved login must report nothing to cancel"
777        );
778        assert!(
779            CANCELLED_IDS.lock().unwrap().is_empty(),
780            "a naturally-resolved flow must never leave a CANCELLED_IDS entry behind"
781        );
782
783        std::env::remove_var("AGENTMUX_MUXBUS_REST_URL");
784    }
785}