Skip to main content

agentmux_srv_core/muxbus/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4pub mod agent_credentials;
5pub mod cloud_installs;
6pub mod cloud_subscriber;
7pub mod delivery_status;
8pub mod discovery;
9pub mod host_adopt;
10pub mod github_broker;
11pub mod install_presence;
12pub mod wan_lease;
13pub mod pkce;
14pub mod relay;
15pub mod relay_watch;
16pub mod server_hooks;
17pub mod wan_presence;
18pub mod wan_publish;
19pub mod wan_key_revocation;
20pub mod wan_verify;
21pub mod ws_connect;
22
23use crate::backend::storage::muxbus::MuxBusCredentials;
24use crate::broker::CredentialState;
25
26/// Identifier MuxBus's single global credential set is registered under
27/// with both the broker scheduler (`crate::broker`) and the OS keychain
28/// (`backend::storage::muxbus`'s `secret_store` key) — deliberately the same
29/// string in both places so the two are trivially correlated in logs.
30pub const CREDENTIAL_ID: &str = "muxbus:global";
31
32/// Why the stored AgentMux Cloud sign-in can't work anymore, or `None` if it
33/// still can (docs/specs/SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.3).
34/// Stale means only a new sign-in helps:
35/// - the cloud publishes a different desktop client id than the one the
36///   credential was issued to (it belongs to a user pool the cloud has left);
37/// - or the broker's refresh was refused outright (`NeedsReauth` with
38///   `rejected`), and the stored token isn't fresh. A fresh one means someone
39///   signed in since, possibly from another channel sharing the store; the
40///   broker catches up on its next check.
41///
42/// Transient failures that merely piled up into `NeedsReauth` are not stale:
43/// the network coming back can still cure them.
44pub(crate) fn stale_sign_in_reason(
45    broker: Option<&CredentialState>,
46    creds: &MuxBusCredentials,
47    discovered: Option<&discovery::CloudSettings>,
48) -> Option<String> {
49    if discovery::client_id_superseded(discovered, &creds.client_id) {
50        return Some("the sign-in belongs to a user pool AgentMux Cloud no longer uses".to_string());
51    }
52    match broker {
53        Some(CredentialState::NeedsReauth { rejected: true, reason, .. })
54            if !(creds.is_valid() && !creds.nearly_expired()) =>
55        {
56            Some(format!("the sign-in was refused: {reason}"))
57        }
58        _ => None,
59    }
60}
61
62/// [`stale_sign_in_reason`] against the global broker and the cloud's
63/// published settings (cached, see `discovery::cloud_settings`).
64pub async fn stale_sign_in(creds: &MuxBusCredentials, http: &reqwest::Client) -> Option<String> {
65    let broker = crate::broker::get_global().and_then(|s| s.state(CREDENTIAL_ID));
66    let discovered = discovery::cloud_settings(http).await;
67    stale_sign_in_reason(broker.as_ref(), creds, discovered.as_ref())
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    fn creds(client_id: &str, expires_in: i64) -> MuxBusCredentials {
75        MuxBusCredentials {
76            client_id: client_id.to_string(),
77            access_token: "at".to_string(),
78            refresh_token: "rt".to_string(),
79            expires_at: agentmux_common::time::now_secs() + expires_in,
80            ..Default::default()
81        }
82    }
83
84    fn needs_reauth(rejected: bool) -> CredentialState {
85        CredentialState::NeedsReauth { since_unix: 0, reason: "invalid_grant".to_string(), rejected }
86    }
87
88    fn published(client_id: &str) -> discovery::CloudSettings {
89        let doc = format!(
90            r#"{{"version":1,"api":"https://a.test","ws":"wss://b.test","cognito":{{"domain":"https://c.test","clientId":"{client_id}"}}}}"#
91        );
92        // A local relay's document may name any host.
93        discovery::parse(&doc, "http://localhost:3100").unwrap()
94    }
95
96    #[test]
97    fn a_refused_refresh_is_stale_until_a_fresh_token_is_stored() {
98        let expired = creds("client", -10);
99        assert!(stale_sign_in_reason(Some(&needs_reauth(true)), &expired, None).is_some());
100        // Nearly expired counts too: that is when the refresh was attempted.
101        assert!(stale_sign_in_reason(Some(&needs_reauth(true)), &creds("client", 60), None).is_some());
102        // Signed in again (here or from another channel): not stale.
103        assert!(stale_sign_in_reason(Some(&needs_reauth(true)), &creds("client", 3600), None).is_none());
104    }
105
106    #[test]
107    fn piled_up_transient_failures_and_healthy_states_are_not_stale() {
108        let expired = creds("client", -10);
109        assert!(stale_sign_in_reason(Some(&needs_reauth(false)), &expired, None).is_none());
110        assert!(stale_sign_in_reason(Some(&CredentialState::Fresh), &expired, None).is_none());
111        let failed = CredentialState::Failed { consecutive_failures: 2, last_error: "net".to_string(), offline: false };
112        assert!(stale_sign_in_reason(Some(&failed), &expired, None).is_none());
113        assert!(stale_sign_in_reason(None, &expired, None).is_none());
114    }
115
116    #[test]
117    fn a_sign_in_from_a_client_the_cloud_no_longer_publishes_is_stale_even_while_its_token_lasts() {
118        let valid = creds("old-client", 3600);
119        let reason = stale_sign_in_reason(Some(&CredentialState::Fresh), &valid, Some(&published("new-client")));
120        assert!(reason.unwrap().contains("user pool"));
121        assert!(stale_sign_in_reason(Some(&CredentialState::Fresh), &valid, Some(&published("old-client"))).is_none());
122    }
123}