Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

46.8 KB
Raw Blame
//! Service implementation for the MCP OAuth broker.

#[cfg(test)]
mod test;

use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use sha2::{Digest, Sha256};
use std::{
    future::Future,
    sync::Arc,
    time::{Duration, SystemTime},
};

use super::{
    access_token_clients::AccessTokenClients,
    browser_binding::BrowserBinding,
    models::{
        AuthorizationStart, AuthorizeRequest, CallbackRequest, ClientDelivery,
        ClientRegistrationRequest, ClientRegistrationResponse, CodeDelivery, ConsentPrompt,
        EmailCodeRequest, EmailSignInStep, IssuedAuthorizationCode, PendingAuthorization,
        RefreshToken, RefreshTokenBinding, RegisteredClient, RevocationRequest, SignInMethod,
        TokenRequest, TokenResponse, UpstreamLogin, UpstreamTokens, UserConsent,
    },
    ports::{
        ClientRegistrationStore, EmailCodeError, EmailCodeProvider, OAuthProvider,
        RefreshTokenBindingStore, UpstreamGrantError,
    },
    redirect_uri::{RedirectTrust, RedirectUriPolicy},
};

pub(crate) const PENDING_AUTH_TTL: Duration = Duration::from_secs(10 * 60);
pub(crate) const AUTHORIZATION_CODE_TTL: Duration = Duration::from_secs(5 * 60);
/// How long a dynamic client registration survives without being used. Every
/// successful lookup extends it, so a client that keeps authorizing keeps its
/// registration and one that stops is eventually collected.
pub const CLIENT_REGISTRATION_TTL: Duration = Duration::from_secs(90 * 24 * 60 * 60);
/// How long a refresh token stays bound to its client. FusionAuth issues
/// refresh tokens on a 30-day sliding window and each broker refresh re-binds,
/// so a binding outlives every refresh token that can still be redeemed.
pub const REFRESH_TOKEN_BINDING_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
/// How long a grant revocation is remembered. A binding is re-armed for at
/// most `REFRESH_TOKEN_BINDING_TTL` from its last write, so a revocation kept
/// as long outlives every binding in the family it revokes.
pub const REVOKED_GRANT_TTL: Duration = REFRESH_TOKEN_BINDING_TTL;

/// Redirect URIs accepted per registration. Enough for a client that offers
/// several callbacks, low enough that open registration cannot be used to
/// store unbounded data.
const MAX_REDIRECT_URIS_PER_CLIENT: usize = 8;
/// Longest redirect URI accepted at registration.
const MAX_REDIRECT_URI_LEN: usize = 512;
/// Longest client name the consent screen shows before shortening it.
const MAX_CONSENT_CLIENT_NAME_CHARS: usize = 64;
/// What the consent screen calls a client whose name has nothing printable.
const UNNAMED_CLIENT: &str = "Unnamed app";

/// Domain interface for the MCP OAuth broker.
pub trait McpAuthProxyService: Clone + Send + Sync + 'static {
    /// Returns OAuth authorization server discovery metadata.
    fn authorization_server_metadata(&self) -> serde_json::Value;
    /// Returns protected-resource metadata for MCP clients.
    fn protected_resource_metadata(&self) -> serde_json::Value;
    /// Registers a public MCP client dynamically.
    fn register_client(
        &self,
        request: ClientRegistrationRequest,
    ) -> impl Future<Output = Result<ClientRegistrationResponse, RegisterClientError>> + Send;
    /// Starts an OAuth authorization flow for the browser holding `browser`:
    /// either the upstream sign-in to send it to, or the consent prompt to show
    /// first when the client's redirect URI needs the user's approval.
    fn start_authorization(
        &self,
        params: AuthorizeRequest,
        browser: BrowserBinding,
        consent: UserConsent,
    ) -> impl Future<Output = Result<AuthorizationStart, StartAuthorizationError>> + Send;
    /// Returns whether the user may carry the callback URL to the client
    /// themselves, because the client may be on another machine.
    fn allows_manual_delivery(&self, redirect_uri: &str) -> bool;
    /// Completes the upstream callback in the browser that started the flow
    /// and returns the client callback URL.
    fn complete_callback(
        &self,
        params: CallbackRequest,
        browser: Option<BrowserBinding>,
    ) -> impl Future<Output = Result<ClientDelivery, CompleteCallbackError>> + Send;
    /// Checks that an email sign-in session is live and belongs to `browser`.
    fn check_email_sign_in(
        &self,
        session_id: &str,
        browser: &BrowserBinding,
    ) -> impl Future<Output = Result<(), EmailSignInError>> + Send;
    /// Emails a sign-in code for a session, or names the single sign-on the
    /// address needs instead.
    fn request_email_code(
        &self,
        session_id: &str,
        email: &str,
        browser: &BrowserBinding,
    ) -> impl Future<Output = Result<EmailSignInStep, EmailSignInError>> + Send;
    /// Redeems an emailed code and completes the session. A wrong code leaves
    /// the session live, so the user can try again.
    fn verify_email_code(
        &self,
        session_id: &str,
        email: &str,
        code: &str,
        browser: &BrowserBinding,
    ) -> impl Future<Output = Result<ClientDelivery, EmailSignInError>> + Send;
    /// Exchanges a broker-issued code or refresh token for bearer credentials.
    fn exchange_token(
        &self,
        params: TokenRequest,
    ) -> impl Future<Output = Result<TokenResponse, TokenExchangeError>> + Send;
    /// Revokes the refresh token family a token belongs to (RFC 7009).
    fn revoke_token(
        &self,
        params: RevocationRequest,
    ) -> impl Future<Output = Result<(), RevokeTokenError>> + Send;
    /// Removes expired broker state when required by the backing store.
    fn cleanup_expired(&self) -> impl Future<Output = anyhow::Result<()>> + Send;
}

/// Storage for short-lived in-flight OAuth handshake state.
pub trait InflightAuthStore: Send + Sync {
    /// Inserts a pending authorization flow keyed by broker session ID.
    fn insert_pending(
        &self,
        session_id: &str,
        pending: PendingAuthorization,
    ) -> impl Future<Output = anyhow::Result<()>> + Send;

    /// Returns a live pending authorization flow without consuming it.
    fn find_pending(
        &self,
        session_id: &str,
    ) -> impl Future<Output = anyhow::Result<Option<PendingAuthorization>>> + Send;

    /// Removes and returns a pending authorization flow, if present.
    fn take_pending(
        &self,
        session_id: &str,
    ) -> impl Future<Output = anyhow::Result<Option<PendingAuthorization>>> + Send;

    /// Inserts a broker-issued authorization code.
    fn insert_issued(
        &self,
        code: &str,
        issued: IssuedAuthorizationCode,
    ) -> impl Future<Output = anyhow::Result<()>> + Send;

    /// Removes and returns a broker-issued authorization code, if present.
    fn take_issued(
        &self,
        code: &str,
    ) -> impl Future<Output = anyhow::Result<Option<IssuedAuthorizationCode>>> + Send;

    /// Removes expired entries when the backing store requires manual cleanup.
    fn cleanup_expired(&self) -> impl Future<Output = anyhow::Result<()>> + Send;
}

/// Dependencies and policy required to build the broker service.
pub struct McpAuthProxyServiceDeps<I> {
    /// Public base URL the broker is served from.
    pub public_url: String,
    /// The redirect URI destinations this deployment trusts.
    pub redirect_uri_policy: RedirectUriPolicy,
    /// Store for short-lived handshake state.
    pub inflight_auth: Arc<I>,
    /// Store for dynamically registered clients.
    pub client_registrations: Arc<dyn ClientRegistrationStore>,
    /// Store binding refresh tokens to the clients that obtained them.
    pub refresh_token_bindings: Arc<dyn RefreshTokenBindingStore>,
    /// Upstream OAuth provider the broker fronts.
    pub oauth_provider: Arc<dyn OAuthProvider>,
    /// Sends and redeems emailed sign-in codes.
    pub email_codes: Arc<dyn EmailCodeProvider>,
}

/// Streamable HTTP resource URL advertised in protected-resource metadata.
///
/// MCP clients require a `resource` field. When `MCP_PUBLIC_URL` is an origin
/// (the current Doppler value), append `/mcp`. When it already ends in `/mcp`
/// (a later gateway cutover), do not append again.
fn mcp_resource_url(public_url: &str) -> String {
    let base = public_url.trim_end_matches('/');
    if base.ends_with("/mcp") {
        base.to_owned()
    } else {
        format!("{base}/mcp")
    }
}

/// Domain service backing the MCP OAuth broker.
pub struct McpAuthProxyServiceImpl<I> {
    inflight_auth: Arc<I>,
    client_registrations: Arc<dyn ClientRegistrationStore>,
    refresh_token_bindings: Arc<dyn RefreshTokenBindingStore>,
    access_token_clients: AccessTokenClients,
    oauth_provider: Arc<dyn OAuthProvider>,
    email_codes: Arc<dyn EmailCodeProvider>,
    redirect_uri_policy: RedirectUriPolicy,
    public_url: String,
}

impl<I> Clone for McpAuthProxyServiceImpl<I> {
    fn clone(&self) -> Self {
        Self {
            inflight_auth: Arc::clone(&self.inflight_auth),
            client_registrations: Arc::clone(&self.client_registrations),
            refresh_token_bindings: Arc::clone(&self.refresh_token_bindings),
            access_token_clients: self.access_token_clients.clone(),
            oauth_provider: Arc::clone(&self.oauth_provider),
            email_codes: Arc::clone(&self.email_codes),
            redirect_uri_policy: self.redirect_uri_policy.clone(),
            public_url: self.public_url.clone(),
        }
    }
}

impl<I> McpAuthProxyServiceImpl<I>
where
    I: InflightAuthStore + 'static,
{
    /// Creates a new auth proxy service backed by an upstream OAuth provider.
    pub fn new(deps: McpAuthProxyServiceDeps<I>) -> Self {
        let McpAuthProxyServiceDeps {
            public_url,
            redirect_uri_policy,
            inflight_auth,
            client_registrations,
            refresh_token_bindings,
            oauth_provider,
            email_codes,
        } = deps;

        Self {
            inflight_auth,
            access_token_clients: AccessTokenClients::new(
                Arc::clone(&refresh_token_bindings),
                Arc::clone(&client_registrations),
            ),
            client_registrations,
            refresh_token_bindings,
            oauth_provider,
            email_codes,
            redirect_uri_policy,
            public_url,
        }
    }

    /// Issues the broker code for upstream tokens and returns the client
    /// callback URL carrying it.
    async fn issue_code(
        &self,
        pending: PendingAuthorization,
        tokens: UpstreamTokens,
    ) -> anyhow::Result<ClientDelivery> {
        // The client may sit on the broker code for up to `AUTHORIZATION_CODE_TTL`
        // before redeeming it, so record when the upstream token actually expires
        // and count down from that at token exchange rather than replaying a stale
        // `expires_in`.
        let access_token_expires_at = SystemTime::now()
            .checked_add(Duration::from_secs(tokens.expires_in))
            .ok_or_else(|| {
                anyhow::anyhow!("upstream expires_in {} is out of range", tokens.expires_in)
            })?;

        let issued_code = uuid::Uuid::new_v4().to_string();
        self.inflight_auth
            .insert_issued(
                &issued_code,
                IssuedAuthorizationCode {
                    client_id: pending.client_id,
                    access_token: tokens.access_token,
                    refresh_token: tokens.refresh_token,
                    code_challenge: pending.code_challenge,
                    redirect_uri: pending.client_redirect_uri.clone(),
                    access_token_expires_at,
                },
            )
            .await?;

        Ok(ClientDelivery {
            url: append_query_params(
                &pending.client_redirect_uri,
                &[("code", issued_code), ("state", pending.client_state)],
            ),
            method: pending.delivery,
        })
    }

    /// The live pending flow behind an email sign-in, provided this browser
    /// started it. The flow stays pending: only a redeemed code consumes it.
    async fn email_sign_in_session(
        &self,
        session_id: &str,
        browser: &BrowserBinding,
    ) -> Result<PendingAuthorization, EmailSignInError> {
        let pending = self
            .inflight_auth
            .find_pending(session_id)
            .await
            .map_err(EmailSignInError::InflightStore)?
            .ok_or(EmailSignInError::UnknownOrExpiredSession)?;

        let started_in_this_browser = pending
            .browser_binding_digest
            .as_deref()
            .is_some_and(|digest| browser.matches_digest(digest));
        if !started_in_this_browser {
            tracing::warn!(
                %session_id,
                client_id = %pending.client_id,
                "email sign-in submitted from a browser that did not start the flow"
            );
            return Err(EmailSignInError::DifferentBrowser);
        }

        Ok(pending)
    }

    /// The record of which client each issued access token went to, for the
    /// MCP route to label what a client writes.
    pub fn access_token_clients(&self) -> AccessTokenClients {
        self.access_token_clients.clone()
    }

    /// Records the client an access token was issued to. Like a failed
    /// rebind, a failed write costs only the label on that token's writes, so
    /// it is logged rather than withholding a token the user approved.
    async fn bind_access_token(&self, access_token: &str, binding: &RefreshTokenBinding) {
        self.access_token_clients
            .bind(access_token, binding)
            .await
            .unwrap_or_else(|error| {
                tracing::error!(
                    error=?error,
                    client_id = %binding.client_id,
                    "failed to record the client an access token was issued to"
                );
            });
    }

    /// Refreshes an upstream token for the client the refresh token belongs to.
    ///
    /// A public client has no credential to present, so the binding recorded
    /// when the token was issued is what ties the grant to a client. Rotating
    /// the binding on every refresh means a replayed token whose binding has
    /// already moved on finds nothing and is refused.
    async fn refresh_token_exchange(
        &self,
        params: TokenRequest,
    ) -> Result<TokenResponse, TokenExchangeError> {
        let client_id = params
            .client_id
            .ok_or(TokenExchangeError::ClientIdRequired)?;
        let refresh_token = params
            .refresh_token
            .ok_or(TokenExchangeError::RefreshTokenRequired)?;

        let presented_digest = refresh_token_digest(&refresh_token);
        let binding = self
            .refresh_token_bindings
            .binding(&presented_digest)
            .await
            .map_err(TokenExchangeError::RefreshTokenBindingStore)?
            .ok_or(TokenExchangeError::UnboundRefreshToken)?;

        if binding.client_id != client_id {
            tracing::warn!(
                %client_id,
                "refresh token presented by a client it was not issued to"
            );
            return Err(TokenExchangeError::ClientMismatch);
        }

        // A revocation that raced a refresh can leave a binding behind for the
        // token that refresh rotated to; the grant marker refuses it anyway.
        if self
            .refresh_token_bindings
            .is_grant_revoked(&binding.grant_id)
            .await
            .map_err(TokenExchangeError::RefreshTokenBindingStore)?
        {
            tracing::warn!(%client_id, grant_id = %binding.grant_id, "refresh token from a revoked grant");
            return Err(TokenExchangeError::RevokedGrant);
        }

        let tokens = self
            .oauth_provider
            .refresh_access_token(&refresh_token)
            .await
            .map_err(|error| {
                if let UpstreamGrantError::InvalidGrant { .. } = error {
                    tracing::warn!(
                        %client_id,
                        grant_id = %binding.grant_id,
                        %error,
                        "upstream refused the refresh token; the client must authorize again"
                    );
                } else {
                    tracing::error!(
                        %client_id,
                        grant_id = %binding.grant_id,
                        %error,
                        "upstream refresh token exchange failed"
                    );
                }
                TokenExchangeError::RefreshFailed(error)
            })?;

        let rotated_digest = refresh_token_digest(&tokens.refresh_token);
        // The upstream token is already issued at this point. A binding write
        // that fails costs the client its next refresh, which it recovers from
        // by authorizing again; discarding a token the user just approved
        // costs them the session outright. So log and hand the token over.
        let rebound = self
            .refresh_token_bindings
            .bind(&rotated_digest, &binding)
            .await
            .inspect_err(|error| {
                tracing::error!(error=?error, %client_id, "failed to bind rotated refresh token");
            })
            .is_ok();

        self.bind_access_token(tokens.access_token.as_str(), &binding)
            .await;

        if rebound && rotated_digest != presented_digest {
            self.refresh_token_bindings
                .unbind(&presented_digest)
                .await
                .unwrap_or_else(|error| {
                    tracing::error!(
                        error=?error,
                        %client_id,
                        "failed to drop superseded refresh token binding"
                    );
                });
        }

        Ok(TokenResponse {
            access_token: tokens.access_token,
            refresh_token: tokens.refresh_token,
            token_type: "Bearer",
            expires_in: tokens.expires_in,
        })
    }

    async fn exchange_authorization_code_token(
        &self,
        params: TokenRequest,
    ) -> Result<TokenResponse, TokenExchangeError> {
        // Read the client id before consuming the code, so a malformed request
        // does not spend a code that is still good.
        let client_id = params
            .client_id
            .as_deref()
            .ok_or(TokenExchangeError::ClientIdRequired)?;

        let issued = self
            .inflight_auth
            .take_issued(
                params
                    .code
                    .as_deref()
                    .ok_or(TokenExchangeError::CodeRequired)?,
            )
            .await
            .map_err(TokenExchangeError::InflightStore)?
            .ok_or(TokenExchangeError::InvalidOrExpiredCode)?;

        if client_id != issued.client_id {
            tracing::warn!(
                presented_client_id = %client_id,
                issued_client_id = %issued.client_id,
                "authorization code redeemed by a client it was not issued to"
            );
            return Err(TokenExchangeError::ClientMismatch);
        }

        match &params.redirect_uri {
            Some(uri) if *uri != issued.redirect_uri => {
                return Err(TokenExchangeError::RedirectUriMismatch);
            }
            None => return Err(TokenExchangeError::RedirectUriRequired),
            _ => {}
        }

        match params.code_verifier {
            Some(verifier) => {
                let digest = Sha256::digest(verifier.as_bytes());
                let computed = URL_SAFE_NO_PAD.encode(digest);
                if computed != issued.code_challenge {
                    return Err(TokenExchangeError::PkceVerificationFailed);
                }
            }
            None => return Err(TokenExchangeError::CodeVerifierRequired),
        }

        let binding = RefreshTokenBinding {
            client_id: issued.client_id,
            grant_id: uuid::Uuid::new_v4().to_string(),
        };
        self.refresh_token_bindings
            .bind(&refresh_token_digest(&issued.refresh_token), &binding)
            .await
            .map_err(TokenExchangeError::RefreshTokenBindingStore)?;
        self.bind_access_token(issued.access_token.as_str(), &binding)
            .await;

        Ok(TokenResponse {
            access_token: issued.access_token,
            refresh_token: issued.refresh_token,
            token_type: "Bearer",
            expires_in: seconds_until(issued.access_token_expires_at),
        })
    }
}

impl<I> McpAuthProxyService for McpAuthProxyServiceImpl<I>
where
    I: InflightAuthStore + 'static,
{
    /// Authorization server discovery metadata.
    fn authorization_server_metadata(&self) -> serde_json::Value {
        tracing::debug!("oauth-authorization-server metadata requested");
        let base = &self.public_url;
        serde_json::json!({
            "issuer": base,
            "authorization_endpoint": format!("{base}/authorize"),
            "token_endpoint": format!("{base}/token"),
            "registration_endpoint": format!("{base}/register"),
            "revocation_endpoint": format!("{base}/revoke"),
            "revocation_endpoint_auth_methods_supported": ["none"],
            "response_types_supported": ["code"],
            "grant_types_supported": ["authorization_code", "refresh_token"],
            "code_challenge_methods_supported": ["S256"],
        })
    }

    /// Protected resource metadata for MCP clients.
    fn protected_resource_metadata(&self) -> serde_json::Value {
        tracing::debug!("oauth-protected-resource metadata requested");
        let base = &self.public_url;
        serde_json::json!({
            "resource": mcp_resource_url(base),
            "authorization_server": base,
            "authorization_servers": [base],
        })
    }

    /// Handles dynamic client registration for public MCP clients.
    ///
    /// Registration is open, as MCP clients require, but it is not
    /// unconstrained: every submitted redirect URI must be one the redirect
    /// URI policy accepts at all, and the accepted set is persisted so later
    /// authorize requests have something to be checked against.
    async fn register_client(
        &self,
        request: ClientRegistrationRequest,
    ) -> Result<ClientRegistrationResponse, RegisterClientError> {
        if request.redirect_uris.is_empty() {
            return Err(RegisterClientError::RedirectUrisRequired);
        }
        if request.redirect_uris.len() > MAX_REDIRECT_URIS_PER_CLIENT {
            return Err(RegisterClientError::TooManyRedirectUris);
        }
        for uri in &request.redirect_uris {
            if uri.len() > MAX_REDIRECT_URI_LEN || self.redirect_uri_policy.trust(uri).is_none() {
                return Err(RegisterClientError::UnsupportedRedirectUri { uri: uri.clone() });
            }
        }

        let client = RegisteredClient {
            client_id: uuid::Uuid::new_v4().to_string(),
            client_name: request
                .client_name
                .unwrap_or_else(|| "mcp-client".to_owned()),
            redirect_uris: request.redirect_uris,
        };

        self.client_registrations
            .insert_client(&client)
            .await
            .map_err(RegisterClientError::ClientRegistrationStore)?;

        tracing::info!(
            client_id = %client.client_id,
            client_name = %client.client_name,
            redirect_uris = ?client.redirect_uris,
            "dynamic client registration"
        );

        Ok(ClientRegistrationResponse {
            client_id: client.client_id,
            client_name: client.client_name,
            redirect_uris: client.redirect_uris,
            grant_types: ["authorization_code", "refresh_token"],
            response_types: ["code"],
            token_endpoint_auth_method: "none",
        })
    }

    /// Starts an OAuth authorization flow.
    ///
    /// A redirect URI the deployment does not trust needs the user's approval
    /// first, so until the consent screen reports it the flow stops at the
    /// prompt and records nothing. The pending flow is bound to `browser`, so
    /// only the browser that was shown the prompt can finish it.
    fn start_authorization(
        &self,
        params: AuthorizeRequest,
        browser: BrowserBinding,
        consent: UserConsent,
    ) -> impl Future<Output = Result<AuthorizationStart, StartAuthorizationError>> + Send {
        let service = self.clone();
        async move {
            if params.response_type != "code" {
                return Err(StartAuthorizationError::UnsupportedResponseType);
            }
            if params.code_challenge_method != "S256" {
                return Err(StartAuthorizationError::UnsupportedCodeChallengeMethod);
            }
            // Applied ahead of the registered set so a registration made
            // before the policy was narrowed cannot still be used.
            let trust = service
                .redirect_uri_policy
                .trust(&params.redirect_uri)
                .ok_or(StartAuthorizationError::InvalidRedirectUri)?;

            let client = service
                .client_registrations
                .find_client(&params.client_id)
                .await
                .map_err(StartAuthorizationError::ClientRegistrationStore)?
                .ok_or(StartAuthorizationError::UnknownClient)?;

            if !client.permits_redirect_uri(&params.redirect_uri) {
                tracing::warn!(
                    client_id = %params.client_id,
                    "authorize request used a redirect_uri the client did not register"
                );
                return Err(StartAuthorizationError::UnregisteredRedirectUri);
            }

            let delivery = params.delivery.unwrap_or_default();
            if delivery == CodeDelivery::Manual
                && !service
                    .redirect_uri_policy
                    .allows_manual_delivery(&params.redirect_uri)
            {
                return Err(StartAuthorizationError::ManualDeliveryUnavailable);
            }

            // A loopback redirect is trusted because the code stays on the
            // user's machine. Showing it for them to carry elsewhere gives that
            // up, so the user approves it like any other destination.
            if trust == RedirectTrust::RequiresConsent || delivery == CodeDelivery::Manual {
                let redirect_host = redirect_host(&params.redirect_uri)
                    .ok_or(StartAuthorizationError::InvalidRedirectUri)?;

                if consent == UserConsent::NotAsked {
                    tracing::info!(
                        client_id = %client.client_id,
                        %redirect_host,
                        "asking the user to approve an MCP client"
                    );
                    return Ok(AuthorizationStart::ConsentRequired(ConsentPrompt {
                        client_name: consent_client_name(&client.client_name),
                        redirect_host,
                        delivery,
                    }));
                }

                tracing::info!(
                    client_id = %client.client_id,
                    %redirect_host,
                    "user approved an MCP client"
                );
            }

            let session_id = uuid::Uuid::new_v4().to_string();
            let sign_in = params.sign_in.unwrap_or_default();
            tracing::info!(
                %session_id,
                client_id = %client.client_id,
                %sign_in,
                %delivery,
                "starting OAuth authorize flow"
            );

            service
                .inflight_auth
                .insert_pending(
                    &session_id,
                    PendingAuthorization {
                        client_id: client.client_id,
                        code_challenge: params.code_challenge,
                        client_state: params.state,
                        client_redirect_uri: params.redirect_uri,
                        browser_binding_digest: Some(browser.digest()),
                        delivery,
                    },
                )
                .await
                .map_err(StartAuthorizationError::InflightStore)?;

            let login = match sign_in {
                SignInMethod::Email => {
                    return Ok(AuthorizationStart::EmailSignIn { session_id });
                }
                SignInMethod::Google => UpstreamLogin::Google,
                SignInMethod::Login => UpstreamLogin::LoginPage,
            };

            service
                .oauth_provider
                .construct_authorize_url(&session_id, login)
                .map(AuthorizationStart::SignIn)
                .map_err(StartAuthorizationError::ConstructAuthorizeUrl)
        }
    }

    fn allows_manual_delivery(&self, redirect_uri: &str) -> bool {
        self.redirect_uri_policy
            .allows_manual_delivery(redirect_uri)
    }

    /// Completes the upstream OAuth callback and returns the URL of the MCP
    /// client callback.
    ///
    /// The upstream signs in a user with an existing session without asking,
    /// so a sign-in link someone else started would otherwise complete
    /// silently in a victim's browser and send the victim's code to the
    /// starter's client. Requiring the browser binding of the browser that
    /// started the flow closes that.
    async fn complete_callback(
        &self,
        params: CallbackRequest,
        browser: Option<BrowserBinding>,
    ) -> Result<ClientDelivery, CompleteCallbackError> {
        let session_id = params
            .state
            .as_deref()
            .map(|state| state.trim_matches('"').to_string())
            .ok_or(CompleteCallbackError::MissingState)?;

        tracing::info!(%session_id, "oauth callback received");

        let pending = self
            .inflight_auth
            .take_pending(&session_id)
            .await
            .map_err(CompleteCallbackError::InflightStore)?
            .ok_or(CompleteCallbackError::UnknownOrExpiredSession)?;

        let started_in_this_browser = match &pending.browser_binding_digest {
            Some(digest) => browser.is_some_and(|browser| browser.matches_digest(digest)),
            None => {
                self.redirect_uri_policy.trust(&pending.client_redirect_uri)
                    == Some(RedirectTrust::Trusted)
            }
        };
        if !started_in_this_browser {
            tracing::warn!(
                %session_id,
                client_id = %pending.client_id,
                "oauth callback arrived in a browser that did not start the flow"
            );
            return Err(CompleteCallbackError::DifferentBrowser);
        }

        if let Some(error) = params.error {
            tracing::warn!(
                %session_id,
                %error,
                description = ?params.error_description,
                "upstream oauth returned error"
            );
            let mut params_to_append =
                vec![("error", error), ("state", pending.client_state.clone())];
            if let Some(desc) = params.error_description {
                params_to_append.push(("error_description", desc));
            }
            return Ok(ClientDelivery {
                url: append_query_params(&pending.client_redirect_uri, &params_to_append),
                method: pending.delivery,
            });
        }

        let code = params.code.ok_or(CompleteCallbackError::MissingCode)?;

        let tokens = self
            .oauth_provider
            .exchange_authorization_code(&code)
            .await
            .map_err(CompleteCallbackError::AuthorizationCodeExchangeFailed)?;

        self.issue_code(pending, tokens)
            .await
            .map_err(CompleteCallbackError::InflightStore)
    }

    #[tracing::instrument(
        name = "mcp_oauth.email_sign_in.check",
        skip_all,
        err(level = "warn"),
        fields(%session_id)
    )]
    async fn check_email_sign_in(
        &self,
        session_id: &str,
        browser: &BrowserBinding,
    ) -> Result<(), EmailSignInError> {
        self.email_sign_in_session(session_id, browser).await?;
        Ok(())
    }

    #[tracing::instrument(
        name = "mcp_oauth.email_sign_in.request_code",
        skip_all,
        err(level = "warn"),
        fields(%session_id, client_id = tracing::field::Empty)
    )]
    async fn request_email_code(
        &self,
        session_id: &str,
        email: &str,
        browser: &BrowserBinding,
    ) -> Result<EmailSignInStep, EmailSignInError> {
        let pending = self.email_sign_in_session(session_id, browser).await?;
        tracing::Span::current().record("client_id", pending.client_id.as_str());

        match self.email_codes.request_code(email.trim()).await? {
            EmailCodeRequest::Sent => Ok(EmailSignInStep::EnterCode),
            EmailCodeRequest::SsoRequired { idp_id } => self
                .oauth_provider
                .construct_authorize_url(
                    session_id,
                    UpstreamLogin::Sso {
                        idp_id: &idp_id,
                        email: email.trim(),
                    },
                )
                .map(EmailSignInStep::Sso)
                .map_err(EmailSignInError::ConstructAuthorizeUrl),
        }
    }

    /// The session is consumed only after the code redeems, so a mistyped code
    /// costs one of the upstream's attempts rather than the whole sign-in.
    #[tracing::instrument(
        name = "mcp_oauth.email_sign_in.verify_code",
        skip_all,
        err(level = "warn"),
        fields(%session_id, client_id = tracing::field::Empty)
    )]
    async fn verify_email_code(
        &self,
        session_id: &str,
        email: &str,
        code: &str,
        browser: &BrowserBinding,
    ) -> Result<ClientDelivery, EmailSignInError> {
        let pending = self.email_sign_in_session(session_id, browser).await?;
        tracing::Span::current().record("client_id", pending.client_id.as_str());

        let tokens = self
            .email_codes
            .redeem_code(email.trim(), code.trim())
            .await?;

        let pending = self
            .inflight_auth
            .take_pending(session_id)
            .await
            .map_err(EmailSignInError::InflightStore)?
            .ok_or(EmailSignInError::UnknownOrExpiredSession)?;

        self.issue_code(pending, tokens)
            .await
            .map_err(EmailSignInError::InflightStore)
    }

    /// Exchanges a broker-issued authorization code for an upstream bearer
    /// token after verifying redirect URI and PKCE.
    async fn exchange_token(
        &self,
        params: TokenRequest,
    ) -> Result<TokenResponse, TokenExchangeError> {
        match params.grant_type.as_str() {
            "authorization_code" => self.exchange_authorization_code_token(params).await,
            "refresh_token" => self.refresh_token_exchange(params).await,
            _ => Err(TokenExchangeError::UnsupportedGrantType),
        }
    }

    /// Revokes the refresh token family a token belongs to.
    ///
    /// Every step is idempotent and the binding is dropped last, so a client
    /// that gets an error can retry and finish the revocation. A token the
    /// broker does not know (never issued, expired, or already revoked) is not
    /// an error, as RFC 7009 section 2.2 requires.
    #[tracing::instrument(skip_all, err, fields(client_id = params.client_id.as_deref(), grant_id))]
    async fn revoke_token(&self, params: RevocationRequest) -> Result<(), RevokeTokenError> {
        let client_id = params.client_id.ok_or(RevokeTokenError::ClientIdRequired)?;
        let token = params.token.ok_or(RevokeTokenError::TokenRequired)?;

        let digest = refresh_token_digest(&token);
        let Some(binding) = self
            .refresh_token_bindings
            .binding(&digest)
            .await
            .map_err(RevokeTokenError::RefreshTokenBindingStore)?
        else {
            // Access tokens are FusionAuth JWTs, which the broker cannot
            // revoke; say so rather than reporting a revocation that did not
            // happen. Refresh tokens are opaque, so a JWT is never one.
            if token.as_str().split('.').count() == 3 {
                return Err(RevokeTokenError::UnsupportedTokenType);
            }
            tracing::info!("revocation of a token the broker does not hold");
            return Ok(());
        };
        tracing::Span::current().record("grant_id", binding.grant_id.as_str());

        if binding.client_id != client_id {
            tracing::warn!("revocation by a client the token was not issued to");
            return Err(RevokeTokenError::ClientMismatch);
        }

        self.refresh_token_bindings
            .revoke_grant(&binding.grant_id)
            .await
            .map_err(RevokeTokenError::RefreshTokenBindingStore)?;
        self.oauth_provider
            .revoke_refresh_token(&token)
            .await
            .map_err(RevokeTokenError::UpstreamRevocationFailed)?;
        self.refresh_token_bindings
            .unbind(&digest)
            .await
            .map_err(RevokeTokenError::RefreshTokenBindingStore)?;

        tracing::info!("refresh token grant revoked");
        Ok(())
    }

    /// Removes expired pending sessions and broker-issued codes.
    async fn cleanup_expired(&self) -> anyhow::Result<()> {
        self.inflight_auth.cleanup_expired().await
    }
}

/// Seconds from now until `deadline`, saturating at zero for a deadline that
/// has already passed.
fn seconds_until(deadline: SystemTime) -> u64 {
    deadline
        .duration_since(SystemTime::now())
        .map(|remaining| remaining.as_secs())
        .unwrap_or(0)
}

/// Digest used to key a refresh token binding, so the store never holds a
/// token that could be replayed if it were read.
fn refresh_token_digest(refresh_token: &RefreshToken) -> String {
    let digest = Sha256::digest(refresh_token.as_str().as_bytes());
    URL_SAFE_NO_PAD.encode(digest)
}

/// The host (and port, when not the default) a redirect URI delivers to, as
/// the consent screen names it. `url` renders internationalized hosts in
/// punycode, so a lookalike host cannot pass for the one it imitates.
fn redirect_host(uri: &str) -> Option<String> {
    let parsed = url::Url::parse(uri).ok()?;
    let host = parsed.host_str()?;

    match parsed.port() {
        Some(port) => Some(format!("{host}:{port}")),
        None => Some(host.to_owned()),
    }
}

/// The self-reported client name as the consent screen shows it: control,
/// bidirectional-override and zero-width characters dropped and length
/// capped, so a name cannot restyle or crowd out the rest of the prompt.
fn consent_client_name(client_name: &str) -> String {
    let printable: String = client_name
        .chars()
        .filter(|character| !character.is_control() && !is_invisible_formatting(*character))
        .collect();
    let trimmed = printable.trim();

    if trimmed.is_empty() {
        return UNNAMED_CLIENT.to_owned();
    }
    if trimmed.chars().count() <= MAX_CONSENT_CLIENT_NAME_CHARS {
        return trimmed.to_owned();
    }

    let mut shortened: String = trimmed
        .chars()
        .take(MAX_CONSENT_CLIENT_NAME_CHARS)
        .collect();
    shortened.push('\u{2026}');
    shortened
}

/// Characters that change how surrounding text renders without showing
/// themselves: bidirectional overrides and isolates, and zero-width marks.
fn is_invisible_formatting(character: char) -> bool {
    matches!(
        character,
        '\u{200B}'..='\u{200F}'
            | '\u{202A}'..='\u{202E}'
            | '\u{2060}'..='\u{2069}'
            | '\u{FEFF}'
    )
}

/// Appends query parameters to a redirect URI, keeping any query the client
/// registered on it.
fn append_query_params(uri: &str, params: &[(&str, String)]) -> String {
    let mut redirect = uri.to_owned();
    let mut separator = if uri.contains('?') { '&' } else { '?' };
    for (key, value) in params {
        redirect.push(separator);
        redirect.push_str(key);
        redirect.push('=');
        redirect.push_str(&urlencoding::encode(value));
        separator = '&';
    }
    redirect
}

/// Errors returned when registering a client.
#[derive(Debug, thiserror::Error)]
pub enum RegisterClientError {
    /// A client with no redirect URI could never complete a flow.
    #[error("at least one redirect_uri is required")]
    RedirectUrisRequired,
    /// More redirect URIs than the broker will store for one client.
    #[error("too many redirect_uris")]
    TooManyRedirectUris,
    /// A submitted redirect URI is not a destination this deployment trusts.
    #[error("redirect_uri is not an allowed destination")]
    UnsupportedRedirectUri {
        /// The rejected URI, for logging.
        uri: String,
    },
    /// The registration could not be persisted.
    #[error("failed to persist client registration")]
    ClientRegistrationStore(anyhow::Error),
}

/// Errors returned when starting authorization.
#[derive(Debug, thiserror::Error)]
pub enum StartAuthorizationError {
    /// Only authorization code flows are supported.
    #[error("unsupported response_type")]
    UnsupportedResponseType,
    /// Only S256 PKCE is supported.
    #[error("unsupported code_challenge_method")]
    UnsupportedCodeChallengeMethod,
    /// The redirect URI is not a destination this deployment trusts.
    #[error("redirect_uri is not an allowed destination")]
    InvalidRedirectUri,
    /// The redirect URI is not one this client registered.
    #[error("redirect_uri was not registered for this client")]
    UnregisteredRedirectUri,
    /// The client_id has no live registration.
    #[error("unknown client_id")]
    UnknownClient,
    /// Client registrations could not be read.
    #[error("failed to read client registrations")]
    ClientRegistrationStore(anyhow::Error),
    /// Inflight auth state could not be persisted.
    #[error("failed to persist inflight auth state")]
    InflightStore(anyhow::Error),
    /// Upstream authorize URL construction failed.
    #[error("failed to construct authorize URL")]
    ConstructAuthorizeUrl(anyhow::Error),
    /// The user asked to carry the code themselves, which only a loopback
    /// redirect URI this broker can safely show allows.
    #[error("redirect_uri cannot be delivered manually")]
    ManualDeliveryUnavailable,
}

/// Errors returned while signing in with an emailed code.
#[derive(Debug, thiserror::Error)]
pub enum EmailSignInError {
    /// The pending session was missing or expired.
    #[error("unknown or expired session")]
    UnknownOrExpiredSession,
    /// The form was submitted by a browser other than the one that started the
    /// flow.
    #[error("authorization was started in a different browser")]
    DifferentBrowser,
    /// The upstream refused or failed the step.
    #[error(transparent)]
    EmailCode(#[from] EmailCodeError),
    /// Inflight auth state could not be loaded or updated.
    #[error("failed to access inflight auth state")]
    InflightStore(anyhow::Error),
    /// Upstream authorize URL construction failed.
    #[error("failed to construct authorize URL")]
    ConstructAuthorizeUrl(anyhow::Error),
}

/// Errors returned when handling the upstream callback.
#[derive(Debug, thiserror::Error)]
pub enum CompleteCallbackError {
    /// Upstream callback omitted state.
    #[error("missing state parameter")]
    MissingState,
    /// Upstream callback omitted both the authorization code and an error code.
    #[error("missing code parameter")]
    MissingCode,
    /// Pending broker session was missing or expired.
    #[error("unknown or expired session")]
    UnknownOrExpiredSession,
    /// The callback arrived in a browser other than the one that started the
    /// flow.
    #[error("authorization was started in a different browser")]
    DifferentBrowser,
    /// Inflight auth state could not be loaded or updated.
    #[error("failed to access inflight auth state")]
    InflightStore(anyhow::Error),
    /// Upstream code exchange failed.
    #[error("authorization code exchange failed: {0}")]
    AuthorizationCodeExchangeFailed(UpstreamGrantError),
}

/// Errors returned when exchanging a broker-issued code for a bearer token.
#[derive(Debug, thiserror::Error)]
pub enum TokenExchangeError {
    /// Only authorization code exchanges are supported.
    #[error("unsupported grant_type")]
    UnsupportedGrantType,
    /// Authorization code is required for authorization_code grants.
    #[error("code required")]
    CodeRequired,
    /// Broker-issued code was missing or already used.
    #[error("invalid or expired code")]
    InvalidOrExpiredCode,
    /// Redirect URI did not match the authorization request.
    #[error("redirect_uri mismatch")]
    RedirectUriMismatch,
    /// Redirect URI must be provided for token exchange.
    #[error("redirect_uri required")]
    RedirectUriRequired,
    /// PKCE verifier was missing.
    #[error("code_verifier required")]
    CodeVerifierRequired,
    /// PKCE verification failed.
    #[error("PKCE verification failed")]
    PkceVerificationFailed,
    /// Refresh token is required for refresh_token grants.
    #[error("refresh_token required")]
    RefreshTokenRequired,
    /// The client_id was absent from the token request.
    #[error("client_id required")]
    ClientIdRequired,
    /// The grant was issued to a different client than the one presenting it.
    #[error("grant was not issued to this client")]
    ClientMismatch,
    /// The refresh token has no recorded client binding, so the broker cannot
    /// tell which client it belongs to.
    #[error("refresh token is not bound to a client")]
    UnboundRefreshToken,
    /// The refresh token belongs to a grant that has been revoked.
    #[error("refresh token has been revoked")]
    RevokedGrant,
    /// Inflight auth state could not be loaded or updated.
    #[error("failed to access inflight auth state")]
    InflightStore(anyhow::Error),
    /// Refresh token bindings could not be read or written.
    #[error("failed to access refresh token bindings")]
    RefreshTokenBindingStore(anyhow::Error),
    /// Upstream refresh failed. An [`UpstreamGrantError::InvalidGrant`] is
    /// the client's to fix by authorizing again; the rest are upstream or
    /// broker faults.
    #[error("refresh token exchange failed: {0}")]
    RefreshFailed(UpstreamGrantError),
}

/// Errors returned when revoking a token.
#[derive(Debug, thiserror::Error)]
pub enum RevokeTokenError {
    /// The client_id was absent, so the revoking client is unidentified.
    #[error("client_id required")]
    ClientIdRequired,
    /// The token parameter was absent.
    #[error("token required")]
    TokenRequired,
    /// The token is an access token, which the broker cannot revoke.
    #[error("access tokens cannot be revoked")]
    UnsupportedTokenType,
    /// The token was issued to a different client than the one revoking it.
    #[error("token was not issued to this client")]
    ClientMismatch,
    /// Refresh token bindings could not be read or written.
    #[error("failed to access refresh token bindings")]
    RefreshTokenBindingStore(anyhow::Error),
    /// The upstream provider did not revoke the refresh token.
    #[error("upstream refresh token revocation failed")]
    UpstreamRevocationFailed(anyhow::Error),
}