Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/oauth.rs

Raw
//! Host-owned OAuth authorization boundary (`SMH-SPEC-SPEC0001`, `SMH-SPEC-PLUG0001`).
//!
//! Tokens stay inside this module and its protected store.
//! A guest supplies policy, never token requests or token response bytes.

mod google;
#[cfg(test)]
mod lifecycle_tests;
/// Durable login entry point and explicit fixture isolation.
pub mod login;
/// Opaque selected subscription credential authority.
pub mod source;
mod store;
#[cfg(test)]
mod tests;

use crate::oauth_crypto::{challenge, encode, verify_identity};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use smith::tool::CancelHandle;
use std::io::{Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::time::{Duration, Instant};

pub use store::ProfileStore;

const CALLBACK_BYTES_MAX: usize = 8 * 1024;
const LOGIN_TIMEOUT: Duration = Duration::from_secs(120);

/// Explicit credential validation semantics, never inferred from a token response.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum LoginFlow {
    /// Dynamic registration with cryptographically verified remote identity.
    DynamicOidc,
    /// Fixed public client with host-generated local identity, not a verified account.
    FixedClientPkceOpaque,
    /// Google installed-app form PKCE with Code Assist admission.
    GoogleInstalledPkce,
}

impl LoginFlow {
    const fn display(self) -> &'static str {
        match self {
            Self::DynamicOidc => "ChatGPT",
            Self::FixedClientPkceOpaque => "Claude",
            Self::GoogleInstalledPkce => "Google",
        }
    }
}

/// Declarative public-client policy supplied by a sandboxed credential guest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoginPolicy {
    /// Explicit validation semantics.
    pub flow: LoginFlow,
    /// Billing connection namespace, separate from issuer and profile.
    pub connection_id: String,
    /// Exact origin permitted for the token exchange.
    pub token_origin: String,
    /// Exact trusted issuer origin.
    pub issuer: String,
    /// Exact inference resource, separate from the issuer.
    pub resource: String,
    /// Initial dynamic-registration identity or fixed public-client identity, selected by flow.
    pub initial_client: String,
    /// Required dynamic issued-client prefix; empty for fixed-client flows.
    pub issued_prefix: String,
    /// Documented authorization path within the granted issuer origin.
    pub authorization_path: String,
    /// Documented token path within the granted issuer origin.
    pub token_path: String,
    /// Actual app display name.
    pub agent_name: String,
    /// Complete requested scope set.
    pub scopes: Vec<String>,
    /// Granted scopes required for this credential source to become usable.
    pub required_scopes: Vec<String>,
}

/// Nonsecret profile metadata; flow distinguishes verified OIDC identity from local opaque identity.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileMetadata {
    /// Credential validation semantics used to create this profile.
    pub flow: LoginFlow,
    /// Exact billing connection owning this profile.
    pub connection_id: String,
    /// Verified identity digest for OIDC, host-random opaque identifier for fixed-client flows.
    pub id: String,
    /// Verified issuer.
    pub issuer: String,
    /// Verified OIDC subject; empty for opaque local profiles.
    pub subject: String,
    /// Issued client ID bound to this registration.
    pub client_id: String,
    /// Workspace claim when the identity provider supplies one.
    pub workspace: Option<String>,
    /// Validated Code Assist project bound to this Google profile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code_assist_project: Option<google::CodeAssistProject>,
    /// Recognition label; opaque flows explicitly identify the account as unverified.
    pub label: String,
    /// Granted scopes, not merely requested scopes.
    pub scopes: Vec<String>,
    /// Access expiry as Unix seconds.
    pub expires_at: u64,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct TokenSet {
    access: String,
    refresh: String,
    identity: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Profile {
    metadata: ProfileMetadata,
    tokens: Option<TokenSet>,
    #[serde(default)]
    refresh_pending: bool,
}

/// Typed authorization outcome; explanations are static and redacted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AuthorizationFault {
    Authority,
    Cancelled,
    Deadline,
    Network,
    ExchangeUncertain,
    ReauthenticationRequired,
    Rejected(&'static str),
    Storage(&'static str),
}

impl AuthorizationFault {
    pub(crate) const fn message(self) -> &'static str {
        match self {
            Self::Authority => "OAuth policy is outside host authority",
            Self::Cancelled => "OAuth login cancelled",
            Self::Deadline => "OAuth login deadline exceeded",
            Self::Network => "credential HTTP request failed",
            Self::ExchangeUncertain => {
                "credential exchange uncertain; sign in again, never replay this code"
            }
            Self::ReauthenticationRequired => {
                "OAuth session unusable; explicitly reauthorize the selected profile"
            }
            Self::Rejected(message) | Self::Storage(message) => message,
        }
    }
}

impl From<crate::http::CredentialFault> for AuthorizationFault {
    fn from(fault: crate::http::CredentialFault) -> Self {
        use crate::http::CredentialFault;
        match fault {
            CredentialFault::Cancelled => Self::Cancelled,
            CredentialFault::Deadline => Self::Deadline,
            CredentialFault::Network => Self::Network,
            CredentialFault::ExchangeUncertain => Self::ExchangeUncertain,
            CredentialFault::InvalidGrant => Self::ReauthenticationRequired,
            CredentialFault::Rejected => Self::Rejected("credential endpoint rejected request"),
        }
    }
}

/// Host authority attached explicitly to an invocation, independent of guest policy.
pub struct LoginAuthority {
    policy: LoginPolicy,
    store: ProfileStore,
    selected: Option<ProfileMetadata>,
    dispatch: Option<(CancelHandle, Option<TokenSet>)>,
    configured_project: Option<google::CodeAssistProject>,
}

impl LoginAuthority {
    /// Bind an explicit noncredential Google Cloud project before login.
    /// # Errors
    /// Rejects malformed project IDs or use with another connection.
    pub fn with_google_project(mut self, project: &str) -> Result<Self, &'static str> {
        if self.policy.flow != LoginFlow::GoogleInstalledPkce {
            return Err("project requires Google subscription");
        }
        let project = google::CodeAssistProject::new(project)?;
        if self
            .selected
            .as_ref()
            .and_then(|metadata| metadata.code_assist_project.as_ref())
            .is_some_and(|selected| selected != &project)
        {
            return Err("configured Google project differs from selected profile");
        }
        self.configured_project = Some(project);
        Ok(self)
    }

    fn effective_google_project(&self) -> Option<&google::CodeAssistProject> {
        self.configured_project.as_ref().or_else(|| {
            self.selected
                .as_ref()
                .and_then(|metadata| metadata.code_assist_project.as_ref())
        })
    }

    /// Authorize exactly one policy and store, with no ambient issuer fallback.
    ///
    /// # Errors
    /// Rejects non-HTTPS issuers other than literal IPv4 loopback fixture origins.
    pub fn new(policy: LoginPolicy, store: ProfileStore) -> Result<Self, &'static str> {
        if policy.issuer.len() > 2048
            || policy.token_origin.len() > 2048
            || policy.resource.len() > 2048
        {
            return Err("OAuth authority URL bound exceeded");
        }
        validate_origin(&policy.issuer)?;
        validate_origin(&policy.token_origin)?;
        validate_endpoint_path(&policy.authorization_path)?;
        validate_endpoint_path(&policy.token_path)?;
        if policy.required_scopes.is_empty()
            || policy.required_scopes.len() > 16
            || policy
                .required_scopes
                .iter()
                .any(|scope| !policy.scopes.contains(scope))
            || policy.scopes.is_empty()
            || policy.scopes.len() > 16
            || policy.scopes.iter().any(|scope| {
                scope.is_empty() || scope.len() > 128 || scope.bytes().any(|byte| byte <= b' ')
            })
            || policy.agent_name.is_empty()
            || policy.agent_name.len() > 128
            || policy.connection_id.is_empty()
            || policy.connection_id.len() > 128
            || (policy.flow == LoginFlow::DynamicOidc
                && (policy.issued_prefix.is_empty() || policy.token_origin != policy.issuer))
            || (policy.flow != LoginFlow::DynamicOidc && !policy.issued_prefix.is_empty())
            || policy.issued_prefix.len() > 64
            || policy.initial_client.is_empty()
            || policy.initial_client.len() > 128
        {
            return Err("invalid OAuth policy bounds");
        }
        validate_origin(
            policy
                .resource
                .rsplit_once('/')
                .map_or(policy.resource.as_str(), |(origin, _)| origin),
        )?;
        Ok(Self {
            policy,
            store,
            selected: None,
            dispatch: None,
            configured_project: None,
        })
    }

    /// Bind reauthorization to one verified local registration, never an implicit account.
    /// # Errors
    /// Rejects missing profiles or issuer mismatch before browser presentation.
    pub fn select_profile(mut self, id: &str) -> Result<Self, &'static str> {
        let profile = self.store.list()?.into_iter().find(|profile| profile.id == id)
            .ok_or("selected OAuth profile not found; choose an existing profile or register explicitly")?;
        if !profile.matches_policy(&self.policy) {
            return Err("selected OAuth profile issuer mismatch");
        }
        self.selected = Some(profile);
        Ok(self)
    }

    pub(crate) fn end_session(
        &self,
        id: &str,
        cancel: &CancelHandle,
    ) -> Result<bool, AuthorizationFault> {
        if self
            .selected
            .as_ref()
            .is_none_or(|selected| selected.id != id)
        {
            return Err(AuthorizationFault::Authority);
        }
        self.store.end_session(id, &self.policy, cancel)
    }

    pub(crate) fn connection_id(&self) -> &str {
        &self.policy.connection_id
    }

    pub(crate) fn begin_dispatch(&mut self, cancel: CancelHandle) {
        self.dispatch = Some((cancel, None));
    }

    pub(crate) fn renew_for_dispatch(
        &mut self,
        id: &str,
        policy: &LoginPolicy,
    ) -> Result<(), AuthorizationFault> {
        if policy != &self.policy {
            return Err(AuthorizationFault::Authority);
        }
        let (cancel, _) = self
            .dispatch
            .as_ref()
            .ok_or(AuthorizationFault::Authority)?;
        let credential = self.renew(id, cancel)?;
        let (_, slot) = self
            .dispatch
            .as_mut()
            .ok_or(AuthorizationFault::Authority)?;
        *slot = Some(credential);
        Ok(())
    }

    pub(crate) fn take_credential(&mut self) -> Option<[String; 3]> {
        self.dispatch
            .take()
            .and_then(|(_, credential)| credential)
            .map(|tokens| [tokens.access, tokens.refresh, tokens.identity])
    }

    fn renew(&self, id: &str, cancel: &CancelHandle) -> Result<TokenSet, AuthorizationFault> {
        if self
            .selected
            .as_ref()
            .is_none_or(|selected| selected.id != id)
        {
            return Err(AuthorizationFault::Authority);
        }
        self.store.renew(id, &self.policy, cancel)
    }

    /// Execute one host-managed login after the caller durably admits its intent.
    ///
    /// # Errors
    /// All failures are static and token-free; uncertain code exchanges are never retried.
    pub(crate) fn authorize(
        &self,
        policy: &LoginPolicy,
        cancel: &CancelHandle,
    ) -> Result<ProfileMetadata, AuthorizationFault> {
        if policy != &self.policy {
            return Err(AuthorizationFault::Authority);
        }
        if cancel.is_cancelled() {
            return Err(AuthorizationFault::Cancelled);
        }
        let deadline = Instant::now() + LOGIN_TIMEOUT;
        let host_id = self.store.host_id().map_err(AuthorizationFault::Storage)?;
        let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
            .map_err(|_| AuthorizationFault::Rejected("OAuth callback bind failed"))?;
        let address = listener
            .local_addr()
            .map_err(|_| AuthorizationFault::Rejected("OAuth callback address failed"))?;
        let redirect = match policy.flow {
            LoginFlow::DynamicOidc => format!("http://127.0.0.1:{}/auth/callback", address.port()),
            LoginFlow::FixedClientPkceOpaque | LoginFlow::GoogleInstalledPkce => {
                format!("http://localhost:{}/callback", address.port())
            }
        };
        let pending = PendingLogin::new(&redirect).map_err(AuthorizationFault::Rejected)?;
        let keys = if policy.flow == LoginFlow::DynamicOidc {
            Some(discover_keys(policy, deadline, cancel)?)
        } else {
            None
        };
        let authorize = format!("{}{}", policy.issuer, policy.authorization_path);
        let selected_client = self
            .selected
            .as_ref()
            .map(|profile| profile.client_id.as_str());
        let query = pending.authorization_query(policy, selected_client, &host_id);
        let display = policy.flow.display();
        // This initial-registration URL contains no ID-token hint or reusable credential.
        writeln!(
            std::io::stdout().lock(),
            "Continue with {display}: {authorize}?{query}"
        )
        .map_err(|_| AuthorizationFault::Rejected("OAuth presentation failed"))?;
        std::io::stdout()
            .flush()
            .map_err(|_| AuthorizationFault::Rejected("OAuth presentation failed"))?;
        let request = receive_callback(listener, deadline, cancel).map_err(|message| {
            if cancel.is_cancelled() {
                AuthorizationFault::Cancelled
            } else if Instant::now() >= deadline {
                AuthorizationFault::Deadline
            } else {
                AuthorizationFault::Rejected(message)
            }
        })?;
        let callback = pending
            .callback(
                &request,
                &policy.issued_prefix,
                if policy.flow == LoginFlow::DynamicOidc {
                    selected_client
                } else {
                    Some(&policy.initial_client)
                },
            )
            .map_err(AuthorizationFault::Rejected)?;
        if cancel.is_cancelled() {
            return Err(AuthorizationFault::Cancelled);
        }
        let mut profile = pending.exchange(
            policy,
            self.selected.as_ref(),
            &callback,
            keys.as_deref(),
            deadline,
            cancel,
        )?;
        if policy.flow == LoginFlow::GoogleInstalledPkce {
            let access = &profile
                .tokens
                .as_ref()
                .ok_or(AuthorizationFault::Authority)?
                .access;
            profile.metadata.code_assist_project = Some(google::setup(
                policy,
                access,
                self.effective_google_project(),
                deadline,
                cancel,
            )?);
        }
        if self
            .selected
            .as_ref()
            .is_some_and(|selected| selected.id != profile.metadata.id)
        {
            return Err(AuthorizationFault::Rejected(
                "OAuth reauthorization identity does not match selected profile",
            ));
        }
        if cancel.is_cancelled() || Instant::now() >= deadline {
            return Err(AuthorizationFault::ExchangeUncertain);
        }
        self.store
            .save(profile)
            .map_err(AuthorizationFault::Storage)
    }
}

struct PendingLogin {
    state: String,
    nonce: String,
    verifier: String,
    redirect: String,
}

struct Callback {
    code: String,
    client_id: String,
}

impl PendingLogin {
    fn exchange(
        &self,
        policy: &LoginPolicy,
        selected: Option<&ProfileMetadata>,
        callback: &Callback,
        keys: Option<&str>,
        deadline: Instant,
        cancel: &CancelHandle,
    ) -> Result<Profile, AuthorizationFault> {
        let token = format!("{}{}", policy.token_origin, policy.token_path);
        if policy.flow == LoginFlow::GoogleInstalledPkce {
            let response = crate::http::CredentialHttp::post(
                &token,
                &form(&[
                    ("grant_type", "authorization_code"),
                    ("client_id", &policy.initial_client),
                    ("client_secret", google::CLIENT_SECRET),
                    ("code", &callback.code),
                    ("code_verifier", &self.verifier),
                    ("redirect_uri", &self.redirect),
                ]),
                deadline,
                cancel,
            )?;
            opaque_profile(policy, selected, &response, now()?)
                .map_err(AuthorizationFault::Rejected)
        } else if policy.flow != LoginFlow::DynamicOidc {
            let body = serde_json::json!({
                "grant_type": "authorization_code",
                "client_id": policy.initial_client,
                "code": callback.code,
                "state": self.state,
                "code_verifier": self.verifier,
                "redirect_uri": self.redirect,
            });
            let response = crate::http::CredentialHttp::post_json(&token, &body, deadline, cancel)?;
            opaque_profile(policy, selected, &response, now()?)
                .map_err(AuthorizationFault::Rejected)
        } else {
            let body = form(&[
                ("grant_type", "authorization_code"),
                ("client_id", &callback.client_id),
                ("code", &callback.code),
                ("code_verifier", &self.verifier),
                ("redirect_uri", &self.redirect),
                ("resource", &policy.resource),
            ]);
            let response = crate::http::CredentialHttp::post(&token, &body, deadline, cancel)?;
            let keys = crate::http::CredentialHttp::get(
                keys.ok_or(AuthorizationFault::Authority)?,
                deadline,
                cancel,
            )
            .map_err(|_| AuthorizationFault::ExchangeUncertain)?;
            validated_profile(
                policy,
                Some(&self.nonce),
                &callback.client_id,
                &response,
                &keys,
                now()?,
            )
            .map_err(AuthorizationFault::Rejected)
        }
    }

    fn authorization_query(
        &self,
        policy: &LoginPolicy,
        selected_client: Option<&str>,
        host_id: &str,
    ) -> String {
        let scope = policy.scopes.join(" ");
        let challenge_value = challenge(&self.verifier);
        if policy.flow == LoginFlow::GoogleInstalledPkce {
            return form(&[
                ("client_id", &policy.initial_client),
                ("response_type", "code"),
                ("redirect_uri", &self.redirect),
                ("scope", &scope),
                ("state", &self.state),
                ("access_type", "offline"),
                ("code_challenge_method", "S256"),
                ("code_challenge", &challenge_value),
            ]);
        }
        if policy.flow != LoginFlow::DynamicOidc {
            return form(&[
                ("code", "true"),
                ("client_id", &policy.initial_client),
                ("response_type", "code"),
                ("redirect_uri", &self.redirect),
                ("scope", &scope),
                ("state", &self.state),
                ("code_challenge_method", "S256"),
                ("code_challenge", &challenge_value),
            ]);
        }
        let mut parameters = vec![
            (
                "client_id",
                selected_client.unwrap_or(&policy.initial_client),
            ),
            ("ext_agent_host_id", host_id),
            ("response_type", "code"),
            ("redirect_uri", &self.redirect),
            ("scope", &scope),
            ("resource", &policy.resource),
            ("state", &self.state),
            ("nonce", &self.nonce),
            ("code_challenge_method", "S256"),
            ("code_challenge", &challenge_value),
        ];
        if selected_client.is_none() {
            parameters.push(("agent_name_hint", &policy.agent_name));
        }
        form(&parameters)
    }

    fn new(redirect: &str) -> Result<Self, &'static str> {
        Ok(Self {
            state: encode(&smith::entropy::bytes::<32>().map_err(|_| "OAuth entropy unavailable")?),
            nonce: encode(&smith::entropy::bytes::<32>().map_err(|_| "OAuth entropy unavailable")?),
            verifier: encode(
                &smith::entropy::bytes::<32>().map_err(|_| "OAuth entropy unavailable")?,
            ),
            redirect: redirect.to_string(),
        })
    }

    fn callback(
        &self,
        request: &str,
        prefix: &str,
        selected: Option<&str>,
    ) -> Result<Callback, &'static str> {
        if request.len() > CALLBACK_BYTES_MAX || !request.ends_with("\r\n\r\n") {
            return Err("invalid OAuth callback framing");
        }
        let line = request
            .lines()
            .next()
            .ok_or("missing OAuth callback request")?;
        let target = line
            .strip_prefix("GET ")
            .and_then(|line| line.strip_suffix(" HTTP/1.1"))
            .ok_or("invalid OAuth callback method")?;
        let path = self
            .redirect
            .split_once("://")
            .and_then(|(_, rest)| rest.split_once('/'))
            .map(|(_, path)| path)
            .ok_or("invalid OAuth redirect")?;
        let expected = format!("/{path}?");
        let query = target
            .strip_prefix(&expected)
            .ok_or("OAuth callback path mismatch")?;
        let host = self
            .redirect
            .strip_prefix("http://")
            .and_then(|url| url.split('/').next())
            .ok_or("invalid OAuth redirect")?;
        let hosts: Vec<_> = request
            .lines()
            .skip(1)
            .filter_map(|line| line.split_once(':'))
            .filter(|(name, _)| name.eq_ignore_ascii_case("host"))
            .collect();
        if hosts.len() != 1 || hosts[0].1.trim() != host {
            return Err("OAuth callback host mismatch");
        }
        let values = parse_form(query)?;
        let value = |name: &str| {
            values
                .iter()
                .find(|(key, _)| key == name)
                .map(|(_, value)| value.as_str())
        };
        if value("state") != Some(self.state.as_str()) {
            return Err("OAuth callback state mismatch");
        }
        if value("error").is_some() {
            return Err("OAuth authorization declined");
        }
        let code = value("code")
            .filter(|code| !code.is_empty())
            .ok_or("missing OAuth callback code")?;
        if selected.is_some() && value("client_id").is_some() && selected != value("client_id") {
            return Err("OAuth callback client differs from selected profile");
        }
        let client = value("client_id")
            .or(selected)
            .filter(|client| {
                (prefix.is_empty() && selected == Some(*client))
                    || (client.len() > prefix.len()
                        && client.len() <= 256
                        && client.starts_with(prefix)
                        && client.bytes().all(|byte| {
                            byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
                        }))
            })
            .ok_or("missing or invalid OAuth issued client id")?;
        Ok(Callback {
            code: code.to_string(),
            client_id: client.to_string(),
        })
    }
}

fn now() -> Result<u64, AuthorizationFault> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|time| time.as_secs())
        .map_err(|_| AuthorizationFault::Rejected("OAuth clock unavailable"))
}

fn revoke_session(
    policy: &LoginPolicy,
    client: &str,
    refresh: &str,
    cancel: &CancelHandle,
) -> Result<(), AuthorizationFault> {
    if policy.flow != LoginFlow::DynamicOidc {
        // No documented remote revocation endpoint: local clearing still runs.
        return Err(AuthorizationFault::Rejected(
            "remote revocation unavailable",
        ));
    }
    let deadline = Instant::now() + Duration::from_secs(15);
    let discovery = crate::http::CredentialHttp::get(
        &format!("{}/.well-known/openid-configuration", policy.issuer),
        deadline,
        cancel,
    )?;
    if discovery["issuer"].as_str() != Some(&policy.issuer) {
        return Err(AuthorizationFault::Authority);
    }
    let endpoint = endpoint(&discovery, "revocation_endpoint", &policy.issuer)
        .map_err(AuthorizationFault::Rejected)?;
    crate::http::CredentialHttp::revoke(
        &endpoint,
        &form(&[
            ("token", refresh),
            ("token_type_hint", "refresh_token"),
            ("client_id", client),
        ]),
        deadline,
        cancel,
    )?;
    Ok(())
}

fn refresh_profile(
    policy: &LoginPolicy,
    previous: &Profile,
    cancel: &CancelHandle,
) -> Result<Profile, AuthorizationFault> {
    let deadline = Instant::now() + Duration::from_secs(15);
    if policy.flow == LoginFlow::GoogleInstalledPkce {
        let tokens = previous
            .tokens
            .as_ref()
            .ok_or(AuthorizationFault::ReauthenticationRequired)?;
        let mut response = crate::http::CredentialHttp::post(
            &format!("{}{}", policy.token_origin, policy.token_path),
            &form(&[
                ("grant_type", "refresh_token"),
                ("client_id", &policy.initial_client),
                ("client_secret", google::CLIENT_SECRET),
                ("refresh_token", &tokens.refresh),
            ]),
            deadline,
            cancel,
        )?;
        google::retain_refresh(&mut response, &tokens.refresh)?;
        return opaque_profile(policy, Some(&previous.metadata), &response, now()?)
            .map_err(AuthorizationFault::Rejected);
    }
    if policy.flow != LoginFlow::DynamicOidc {
        let tokens = previous
            .tokens
            .as_ref()
            .ok_or(AuthorizationFault::ReauthenticationRequired)?;
        let response = crate::http::CredentialHttp::post_json(
            &format!("{}{}", policy.token_origin, policy.token_path),
            &serde_json::json!({
                "grant_type": "refresh_token",
                "client_id": policy.initial_client,
                "refresh_token": tokens.refresh,
            }),
            deadline,
            cancel,
        )?;
        return opaque_profile(policy, Some(&previous.metadata), &response, now()?)
            .map_err(AuthorizationFault::Rejected);
    }
    let discovery = crate::http::CredentialHttp::get(
        &format!("{}/.well-known/openid-configuration", policy.issuer),
        deadline,
        cancel,
    )?;
    if discovery["issuer"].as_str() != Some(&policy.issuer) {
        return Err(AuthorizationFault::Authority);
    }
    let keys =
        endpoint(&discovery, "jwks_uri", &policy.issuer).map_err(AuthorizationFault::Rejected)?;
    let tokens = previous
        .tokens
        .as_ref()
        .ok_or(AuthorizationFault::ReauthenticationRequired)?;
    let body = form(&[
        ("grant_type", "refresh_token"),
        ("client_id", &previous.metadata.client_id),
        ("refresh_token", &tokens.refresh),
        ("resource", &policy.resource),
    ]);
    let response = crate::http::CredentialHttp::post(
        &format!("{}{}", policy.issuer, policy.token_path),
        &body,
        deadline,
        cancel,
    )?;
    let keys = crate::http::CredentialHttp::get(&keys, deadline, cancel)
        .map_err(|_| AuthorizationFault::ExchangeUncertain)?;
    validated_profile(
        policy,
        None,
        &previous.metadata.client_id,
        &response,
        &keys,
        now()?,
    )
    .map_err(AuthorizationFault::Rejected)
}

fn credential_field<'a>(response: &'a Value, name: &str) -> Result<&'a str, &'static str> {
    response[name]
        .as_str()
        .filter(|text| {
            !text.is_empty()
                && text.len() <= 32 * 1024
                && !text.bytes().any(|byte| byte <= b' ' || byte == 127)
        })
        .ok_or("invalid OAuth credential field")
}

fn access_expiry(response: &Value, now: u64) -> Result<u64, &'static str> {
    response["expires_in"]
        .as_u64()
        .filter(|seconds| *seconds > 0 && *seconds <= 86400)
        .and_then(|seconds| now.checked_add(seconds))
        .ok_or("invalid OAuth access expiry")
}

fn validated_profile(
    policy: &LoginPolicy,
    nonce: Option<&str>,
    client: &str,
    response: &Value,
    keys: &Value,
    now: u64,
) -> Result<Profile, &'static str> {
    if policy.flow != LoginFlow::DynamicOidc {
        return Err("OAuth OIDC profile authority mismatch");
    }
    let access = credential_field(response, "access_token")?;
    let refresh = credential_field(response, "refresh_token")?;
    let identity = credential_field(response, "id_token")?;
    if response["token_type"]
        .as_str()
        .is_none_or(|kind| !kind.eq_ignore_ascii_case("Bearer"))
    {
        return Err("unsupported OAuth token type");
    }
    let expires = access_expiry(response, now)?;
    let scope = response["scope"]
        .as_str()
        .filter(|scope| scope.len() <= 2048)
        .ok_or("missing OAuth granted scope")?;
    let scopes: Vec<String> = scope.split_ascii_whitespace().map(str::to_string).collect();
    if policy
        .required_scopes
        .iter()
        .any(|scope| !scopes.contains(scope))
        || scopes.len() > 16
        || scopes.iter().any(|scope| !policy.scopes.contains(scope))
    {
        return Err("OAuth required scope not granted");
    }
    let claims = verify_identity(identity, keys)?;
    let audience = claims["aud"].as_str() == Some(client)
        || claims["aud"]
            .as_array()
            .is_some_and(|items| items.len() == 1 && items[0].as_str() == Some(client));
    if claims["iss"].as_str() != Some(policy.issuer.as_str())
        || !audience
        || claims
            .get("azp")
            .is_some_and(|value| value.as_str() != Some(client))
        || nonce.is_some_and(|nonce| claims["nonce"].as_str() != Some(nonce))
        || claims["exp"].as_u64().is_none_or(|expiry| expiry <= now)
        || claims
            .get("nbf")
            .is_some_and(|value| value.as_u64().is_none_or(|not_before| not_before > now))
        || claims
            .get("iat")
            .is_some_and(|value| value.as_u64().is_none_or(|issued| issued > now))
    {
        return Err("OAuth identity claims mismatch");
    }
    let metadata_text = |name: &str| {
        claims[name].as_str().filter(|text| {
            !text.is_empty() && text.len() <= 512 && !text.chars().any(char::is_control)
        })
    };
    let subject = metadata_text("sub").ok_or("missing OAuth subject")?;
    let workspace = metadata_text("workspace_id").map(str::to_string);
    let identity_key = serde_json::to_vec(&(&policy.issuer, subject, client, &workspace))
        .map_err(|_| "OAuth profile identity encoding failed")?;
    let profile = Profile {
        metadata: ProfileMetadata {
            flow: policy.flow,
            connection_id: policy.connection_id.clone(),
            id: smith::sha256::digest_hex(&identity_key),
            issuer: policy.issuer.clone(),
            subject: subject.to_string(),
            client_id: client.to_string(),
            workspace,
            code_assist_project: None,
            label: metadata_text("email").unwrap_or(subject).to_string(),
            scopes,
            expires_at: expires,
        },
        tokens: Some(TokenSet {
            access: access.to_string(),
            refresh: refresh.to_string(),
            identity: identity.to_string(),
        }),
        refresh_pending: false,
    };
    validate_metadata_secrecy(&profile)?;
    Ok(profile)
}

impl ProfileMetadata {
    fn matches_policy(&self, policy: &LoginPolicy) -> bool {
        if self.flow != LoginFlow::DynamicOidc && self.client_id != policy.initial_client {
            return false;
        }
        self.issuer == policy.issuer
            && self.connection_id == policy.connection_id
            && self.flow == policy.flow
    }
}

fn discover_keys(
    policy: &LoginPolicy,
    deadline: Instant,
    cancel: &CancelHandle,
) -> Result<String, AuthorizationFault> {
    let discovery = crate::http::CredentialHttp::get(
        &format!("{}/.well-known/openid-configuration", policy.issuer),
        deadline,
        cancel,
    )?;
    if discovery["issuer"].as_str() != Some(policy.issuer.as_str()) {
        return Err(AuthorizationFault::Rejected(
            "OAuth discovery issuer mismatch",
        ));
    }
    endpoint(&discovery, "jwks_uri", &policy.issuer).map_err(AuthorizationFault::Rejected)
}

fn opaque_profile(
    policy: &LoginPolicy,
    selected: Option<&ProfileMetadata>,
    response: &Value,
    now: u64,
) -> Result<Profile, &'static str> {
    if policy.flow == LoginFlow::DynamicOidc
        || selected.is_some_and(|profile| !profile.matches_policy(policy))
    {
        return Err("OAuth opaque profile authority mismatch");
    }
    let access = credential_field(response, "access_token")?;
    let refresh = credential_field(response, "refresh_token")?;
    if response.get("token_type").is_some_and(|kind| {
        kind.as_str()
            .is_none_or(|kind| !kind.eq_ignore_ascii_case("Bearer"))
    }) {
        return Err("unsupported OAuth token type");
    }
    let expires_at = access_expiry(response, now)?;
    // This flow returns no verified subject or ID token. Profile identity is local only.
    let id = match selected {
        Some(profile) => profile.id.clone(),
        None => smith::sha256::digest_hex(
            &smith::entropy::bytes::<32>().map_err(|_| "OAuth entropy unavailable")?,
        ),
    };
    let scopes = match response.get("scope") {
        None => selected.map_or_else(|| policy.scopes.clone(), |profile| profile.scopes.clone()),
        Some(scope) => {
            let scope = scope
                .as_str()
                .filter(|scope| scope.len() <= 2048)
                .ok_or("invalid OAuth granted scope")?;
            let scopes: Vec<String> = scope.split_ascii_whitespace().map(str::to_string).collect();
            if scopes.len() > 16
                || scopes.iter().any(|scope| !policy.scopes.contains(scope))
                || policy
                    .required_scopes
                    .iter()
                    .any(|scope| !scopes.contains(scope))
            {
                return Err("OAuth required scope not granted");
            }
            scopes
        }
    };
    let profile = Profile {
        metadata: ProfileMetadata {
            flow: policy.flow,
            connection_id: policy.connection_id.clone(),
            id,
            issuer: policy.issuer.clone(),
            subject: String::new(),
            client_id: policy.initial_client.clone(),
            workspace: None,
            code_assist_project: selected.and_then(|profile| profile.code_assist_project.clone()),
            label: if policy.flow == LoginFlow::GoogleInstalledPkce {
                "Local Google subscription profile (unverified account)"
            } else {
                "Local Claude subscription profile (unverified account)"
            }
            .into(),
            scopes,
            expires_at,
        },
        tokens: Some(TokenSet {
            access: access.into(),
            refresh: refresh.into(),
            identity: String::new(),
        }),
        refresh_pending: false,
    };
    validate_metadata_secrecy(&profile)?;
    Ok(profile)
}

fn validate_metadata_secrecy(profile: &Profile) -> Result<(), &'static str> {
    let Some(tokens) = &profile.tokens else {
        return Ok(());
    };
    let metadata =
        serde_json::to_vec(&profile.metadata).map_err(|_| "OAuth metadata encoding failed")?;
    for credential in [&tokens.access, &tokens.refresh, &tokens.identity]
        .into_iter()
        .filter(|credential| !credential.is_empty())
    {
        let mut sanitizer = crate::response_sanitizer::ResponseSanitizer::new(
            std::slice::from_ref(credential),
            b"<redacted>",
        )?;
        let prefix = sanitizer.push(&metadata)?;
        let tail = sanitizer.finish();
        if !prefix.iter().chain(&tail).eq(metadata.iter()) {
            return Err("OAuth metadata contains credential material");
        }
    }
    Ok(())
}

fn validate_origin(origin: &str) -> Result<(), &'static str> {
    crate::plugins::NetScope::parse(origin).map_err(|_| "invalid OAuth origin")?;
    let authority = origin.split_once("://").ok_or("invalid OAuth origin")?.1;
    if authority.is_empty()
        || authority
            .bytes()
            .any(|byte| matches!(byte, b'/' | b'?' | b'#' | b'@' | b'\\') || byte <= b' ')
        || !(origin.starts_with("https://")
            || origin
                .strip_prefix("http://127.0.0.1:")
                .is_some_and(|port| port.parse::<u16>().is_ok_and(|port| port > 0)))
    {
        return Err("invalid OAuth exact origin");
    }
    Ok(())
}

fn endpoint(document: &Value, name: &str, origin: &str) -> Result<String, &'static str> {
    let url = document[name]
        .as_str()
        .filter(|url| url.len() <= 2048)
        .ok_or("missing OAuth discovery endpoint")?;
    let path = url
        .strip_prefix(origin)
        .ok_or("OAuth discovery endpoint outside granted origin")?;
    validate_endpoint_path(path)?;
    Ok(url.to_string())
}

fn validate_endpoint_path(path: &str) -> Result<(), &'static str> {
    if path.len() > 2048
        || !path.starts_with('/')
        || path.starts_with("//")
        || path
            .bytes()
            .any(|byte| byte <= b' ' || matches!(byte, b'#' | b'?' | b'\\'))
    {
        return Err("OAuth endpoint outside granted origin");
    }
    Ok(())
}

fn form(values: &[(&str, &str)]) -> String {
    let mut result = String::new();
    for (index, (key, value)) in values.iter().enumerate() {
        if index != 0 {
            result.push('&');
        }
        for (part, text) in [*key, *value].into_iter().enumerate() {
            if part == 1 {
                result.push('=');
            }
            for byte in text.bytes() {
                if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
                    result.push(char::from(byte));
                } else {
                    const HEX: &[u8; 16] = b"0123456789ABCDEF";
                    result.push('%');
                    result.push(char::from(HEX[usize::from(byte >> 4)]));
                    result.push(char::from(HEX[usize::from(byte & 15)]));
                }
            }
        }
    }
    result
}

fn parse_form(query: &str) -> Result<Vec<(String, String)>, &'static str> {
    if query.len() > CALLBACK_BYTES_MAX {
        return Err("OAuth form exceeds byte bound");
    }
    let decode = |text: &str| -> Result<String, &'static str> {
        let mut bytes = Vec::with_capacity(text.len());
        let mut input = text.bytes();
        while let Some(byte) = input.next() {
            bytes.push(match byte {
                b'+' => b' ',
                b'%' => {
                    let high = input
                        .next()
                        .and_then(|byte| char::from(byte).to_digit(16))
                        .ok_or("invalid OAuth percent encoding")?;
                    let low = input
                        .next()
                        .and_then(|byte| char::from(byte).to_digit(16))
                        .ok_or("invalid OAuth percent encoding")?;
                    u8::try_from(high * 16 + low).map_err(|_| "invalid OAuth percent encoding")?
                }
                _ => byte,
            });
        }
        let value = String::from_utf8(bytes).map_err(|_| "invalid OAuth form UTF-8")?;
        if value.chars().any(char::is_control) {
            return Err("invalid OAuth form control character");
        }
        Ok(value)
    };
    let mut values = Vec::new();
    for item in query.split('&') {
        if values.len() == 16 {
            return Err("OAuth form item bound exceeded");
        }
        let (key, value) = item.split_once('=').ok_or("invalid OAuth form item")?;
        let key = decode(key)?;
        if values.iter().any(|(prior, _)| prior == &key) {
            return Err("duplicate OAuth callback parameter");
        }
        values.push((key, decode(value)?));
    }
    Ok(values)
}

fn receive_callback(
    listener: TcpListener,
    deadline: Instant,
    cancel: &CancelHandle,
) -> Result<String, &'static str> {
    let address = listener
        .local_addr()
        .map_err(|_| "OAuth callback address failed")?;
    let (send, receive) = std::sync::mpsc::sync_channel(1);
    let (accepted_send, accepted_receive) = std::sync::mpsc::sync_channel(1);
    let worker = std::thread::spawn(move || {
        let result = (|| {
            let (mut stream, _) = listener
                .accept()
                .map_err(|_| "OAuth callback accept failed")?;
            accepted_send
                .send(
                    stream
                        .try_clone()
                        .map_err(|_| "OAuth callback control setup failed")?,
                )
                .map_err(|_| "OAuth callback control receiver failed")?;
            stream
                .set_read_timeout(Some(Duration::from_secs(5)))
                .map_err(|_| "OAuth callback timeout setup failed")?;
            let mut bytes = Vec::new();
            let mut byte = [0];
            while bytes.len() <= CALLBACK_BYTES_MAX && !bytes.ends_with(b"\r\n\r\n") {
                if Instant::now() >= deadline {
                    return Err("OAuth callback deadline exceeded");
                }
                if stream
                    .read(&mut byte)
                    .map_err(|_| "OAuth callback read failed")?
                    == 0
                {
                    return Err("truncated OAuth callback");
                }
                bytes.push(byte[0]);
            }
            let _response = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 46\r\nConnection: close\r\n\r\nReturn to Smith to check authorization outcome.");
            String::from_utf8(bytes).map_err(|_| "invalid OAuth callback UTF-8")
        })();
        let _sent = send.send(result);
    });
    let mut control = None;
    let result = loop {
        if control.is_none() {
            control = accepted_receive.try_recv().ok();
        }
        if cancel.is_cancelled() {
            break Err("OAuth login cancelled");
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            break Err("OAuth callback deadline exceeded");
        }
        match receive.recv_timeout(remaining.min(Duration::from_millis(50))) {
            Ok(result) => break result,
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                break Err("OAuth callback worker failed");
            }
        }
    };
    if result.is_err() {
        let _wake = TcpStream::connect_timeout(&address, Duration::from_millis(100));
        if control.is_none() {
            control = accepted_receive.recv().ok();
        }
        if let Some(stream) = control {
            let _shutdown = stream.shutdown(Shutdown::Both);
        }
    }
    worker.join().map_err(|_| "OAuth callback worker failed")?;
    result
}