Skip to content

World's first open-source enterprise world model.

44.3 KB
Raw Blame
//! 单点登录:窄范围的 OIDC 授权码流程(PKCE、一次性 state、nonce、
//! issuer/audience 与 RS256 校验)。
//!
//! **身份提供方的一个 subject 由账号本人绑定。** 人先用密码登录,再在账户页走一遍
//! SSO;回调核对「完成这次流程的就是发起绑定的那个已登录的人」才写 `oidc_identities`。
//! 从前是管理员把任意 subject 填给任意账号——那等于给了管理员一条冒充任何人
//! (包括别的管理员)登录的路:绑定不经本人、本人看不见、改密码也断不掉,之后的
//! 操作在台账上记成被冒充的人(0014:身份来自本人)。管理员现在只能看与解绑。
//!
//! 默认绝不按身份提供方的 email 这类可变声明自动关联,首次登录也不自动开账号。
//! 例外是部署列了 `UTOPIA_OIDC_ALLOWED_DOMAINS`:那些域名里核实过的 email 首次登录时
//! 关联已有账号或开一个(0069:身份提供方对这些域名说了算)。
//!
//! **另一个应用可以拿它刚登录到的 ID token 换一个会话**(`exchange`,0066):同一个
//! 身份提供方、受信的 audience 列表、十分钟内签发、只换一次,映射规则与登录相同。

use crate::{
    auth::{self, AuthUser},
    error::ApiResult,
    state::AppState,
};
use axum::{
    extract::{Path, Query, State},
    http::HeaderMap,
    response::Redirect,
    Json,
};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use jsonwebtoken::{decode, decode_header, jwk::JwkSet, Algorithm, DecodingKey, Validation};
use serde::Deserialize;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use utopia_core::AppError;
use uuid::Uuid;

const FLOW_COOKIE: &str = "utopia_oidc_state";
/// HTTPS 下用 `__Host-` 前缀:浏览器只接受 Secure、Path=/、不带 Domain 的这个名字,
/// 同站点的兄弟子域名或明文链路就种不进来。否则攻击者先种一个自己的 state,
/// 再把受害者带到自己的回调地址上,受害者就登进了攻击者的账号(登录 CSRF)
const FLOW_COOKIE_HOST: &str = "__Host-utopia_oidc_state";
const FLOW_TTL_SECS: u64 = 600;
/// 同时在途的登录流程上限。`start` 不需要登录,每一次都会落一行、问一次身份提供方;
/// 没有上限的话,一个脚本就能把表撑大、把身份提供方对这个部署的限流打满
const MAX_PENDING_FLOWS: i64 = 1000;
/// 发现文档、JWKS、令牌响应的体积上限。它们来自身份提供方,但一个出了问题的
/// 身份提供方不该能把服务器的内存吃掉
const DOC_LIMIT: usize = 256 * 1024;
const TOKEN_LIMIT: usize = 64 * 1024;
/// 发现文档与 JWKS 的缓存时长。轮换密钥时 `kid` 找不到会强制刷新一次
const CACHE_TTL: Duration = Duration::from_secs(600);
/// 同一地址两次强制刷新之间至少隔这么久。`kid` 由请求方写,`exchange` 又不需要登录:
/// 不设冷却的话,编一个 `kid` 就能让服务器每次都去问一遍身份提供方
const FORCE_COOLDOWN: Duration = Duration::from_secs(60);

struct Config {
    issuer: String,
    client_id: String,
    secret: Option<String>,
    redirect: String,
    /// `exchange` 收哪些 client 的 ID token。空 = 不开放换会话。与 Utopia 共用一个
    /// client 的部署把 Utopia 自己的 client id 写进来
    exchange_audiences: Vec<String>,
    /// 这些域名里核实过的 email 首次登录时按 email 关联已有账号,没有就开一个
    /// (`UTOPIA_OIDC_ALLOWED_DOMAINS`)。空 = 只认本人绑定过的 subject
    allowed_domains: Vec<String>,
    /// 本地开发:允许 issuer 与各端点走回环地址上的明文 HTTP。只认 localhost /
    /// 127.0.0.1 / ::1,公网地址照旧只能 HTTPS
    loopback_http: bool,
}

fn config() -> Result<Config, AppError> {
    let get = |key: &str| {
        std::env::var(key)
            .ok()
            .filter(|v| !v.trim().is_empty())
            .ok_or_else(|| AppError::Validation("SSO is not configured".into()))
    };
    let c = Config {
        issuer: get("UTOPIA_OIDC_ISSUER")?,
        client_id: get("UTOPIA_OIDC_CLIENT_ID")?,
        secret: std::env::var("UTOPIA_OIDC_CLIENT_SECRET")
            .ok()
            .filter(|s| !s.is_empty()),
        redirect: get("UTOPIA_OIDC_REDIRECT_URI")?,
        exchange_audiences: std::env::var("UTOPIA_OIDC_EXCHANGE_AUDIENCES")
            .unwrap_or_default()
            .split(',')
            .map(str::trim)
            .filter(|a| !a.is_empty())
            .map(String::from)
            .collect(),
        allowed_domains: std::env::var("UTOPIA_OIDC_ALLOWED_DOMAINS")
            .unwrap_or_default()
            .split(',')
            .map(|d| d.trim().to_lowercase())
            .filter(|d| !d.is_empty())
            .collect(),
        loopback_http: std::env::var("UTOPIA_OIDC_ALLOW_LOOPBACK_HTTP")
            .is_ok_and(|v| matches!(v.trim(), "1" | "true")),
    };
    secure_url(&c.issuer, c.loopback_http)?;
    secure_url(&c.redirect, true)?;
    Ok(c)
}

fn secure_url(s: &str, loopback: bool) -> Result<reqwest::Url, AppError> {
    let url = reqwest::Url::parse(s).map_err(|_| AppError::Validation("Invalid SSO URL".into()))?;
    if !url.username().is_empty()
        || url.password().is_some()
        || url.fragment().is_some()
        || !(url.scheme() == "https"
            || (loopback
                && url.scheme() == "http"
                && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))))
    {
        return Err(AppError::Validation(
            "SSO endpoints require HTTPS (localhost callback may use HTTP)".into(),
        ));
    }
    Ok(url)
}

/// 一次拒绝:`code` 回给界面(登录页 / 账户页按它措辞),`reason` 只进日志与台账
struct Refusal {
    code: &'static str,
    reason: String,
}

fn refuse(code: &'static str, reason: impl Into<String>) -> Refusal {
    Refusal {
        code,
        reason: reason.into(),
    }
}

impl From<sqlx::Error> for Refusal {
    fn from(e: sqlx::Error) -> Self {
        refuse("unavailable", format!("database: {e}"))
    }
}

fn client() -> Result<reqwest::Client, Refusal> {
    reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .map_err(|e| refuse("unavailable", format!("http client: {e}")))
}

/// 读一个限了体积的 JSON 响应。先看 Content-Length,再边读边数——
/// 不报长度的响应一样截得住
async fn read_json(mut resp: reqwest::Response, limit: usize) -> Result<Value, String> {
    if !resp.status().is_success() {
        return Err(format!("status {}", resp.status()));
    }
    if resp.content_length().is_some_and(|n| n > limit as u64) {
        return Err(format!("response larger than {limit} bytes"));
    }
    let mut body = Vec::new();
    while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
        body.extend_from_slice(&chunk);
        if body.len() > limit {
            return Err(format!("response larger than {limit} bytes"));
        }
    }
    serde_json::from_slice(&body).map_err(|e| format!("not JSON: {e}"))
}

type Cache = tokio::sync::Mutex<HashMap<String, (Instant, Value)>>;

fn cache() -> &'static Cache {
    static CACHE: std::sync::OnceLock<Cache> = std::sync::OnceLock::new();
    CACHE.get_or_init(Default::default)
}

/// 发现文档与 JWKS 按地址缓存。`start` 不需要登录,不缓存的话每一次匿名请求
/// 都会让服务器去问一次身份提供方
async fn cached_json(url: &reqwest::Url, force: bool) -> Result<Value, Refusal> {
    let key = url.to_string();
    let force = force && force_allowed(&key).await;
    if !force {
        if let Some((at, v)) = cache().lock().await.get(&key) {
            if at.elapsed() < CACHE_TTL {
                return Ok(v.clone());
            }
        }
    }
    let resp = client()?
        .get(url.clone())
        .send()
        .await
        .map_err(|e| refuse("unavailable", format!("fetch {key}: {e}")))?;
    let v = read_json(resp, DOC_LIMIT)
        .await
        .map_err(|e| refuse("unavailable", format!("fetch {key}: {e}")))?;
    cache()
        .lock()
        .await
        .insert(key, (Instant::now(), v.clone()));
    Ok(v)
}

/// 这一次强制刷新放不放行:冷却期内的一律退回读缓存。先记下时刻再去取,
/// 同时到的一批请求里只有一个真去问身份提供方
async fn force_allowed(key: &str) -> bool {
    static LAST: std::sync::OnceLock<tokio::sync::Mutex<HashMap<String, Instant>>> =
        std::sync::OnceLock::new();
    let mut last = LAST.get_or_init(Default::default).lock().await;
    if last
        .get(key)
        .is_some_and(|at| at.elapsed() < FORCE_COOLDOWN)
    {
        return false;
    }
    last.insert(key.to_string(), Instant::now());
    true
}

async fn metadata(c: &Config) -> Result<Value, Refusal> {
    let url = secure_url(
        &format!(
            "{}/.well-known/openid-configuration",
            c.issuer.trim_end_matches('/')
        ),
        c.loopback_http,
    )
    .map_err(|_| refuse("unavailable", "issuer URL"))?;
    let meta = cached_json(&url, false).await?;
    if meta["issuer"] != c.issuer {
        return Err(refuse(
            "unavailable",
            "discovery document names a different issuer",
        ));
    }
    Ok(meta)
}

fn endpoint(c: &Config, meta: &Value, key: &str) -> Result<reqwest::Url, Refusal> {
    let raw = meta[key]
        .as_str()
        .ok_or_else(|| refuse("unavailable", format!("discovery has no {key}")))?;
    secure_url(raw, c.loopback_http)
        .map_err(|_| refuse("unavailable", format!("{key} is not HTTPS")))
}

fn flow_cookie(value: String, secure: bool) -> Cookie<'static> {
    let (name, path) = if secure {
        (FLOW_COOKIE_HOST, "/")
    } else {
        (FLOW_COOKIE, "/api/v1/auth/oidc")
    };
    Cookie::build((name, value))
        .path(path)
        .http_only(true)
        .same_site(SameSite::Lax)
        .secure(secure)
        .max_age(
            Duration::from_secs(FLOW_TTL_SECS)
                .try_into()
                .expect("ten minutes fits cookie duration"),
        )
        .build()
}

/// 当前请求带着的已登录会话(cookie),停用的账号不算
async fn session_user(s: &AppState, jar: &CookieJar) -> Option<Uuid> {
    let token = jar.get(auth::COOKIE_NAME)?.value().to_string();
    let id = auth::decode_user_id(s, &token).ok()?;
    utopia_store::accounts::find_user_by_id(&s.pool, id)
        .await
        .ok()
        .flatten()
        .map(|u| u.id)
}

/// RFC 6749 §2.3.1:client id 与 secret 先按表单编码,再放进 Basic 头。
/// 不编码的话含 `:`、`%`、`+` 的 secret 在严格的身份提供方那里认证失败
fn form_encode(s: &str) -> String {
    url::form_urlencoded::byte_serialize(s.as_bytes()).collect()
}

pub async fn status(State(s): State<AppState>) -> Json<Value> {
    Json(json!({"enabled": config().is_ok(), "password_login": password_login(&s)}))
}

/// 密码登录实际开没开:`UTOPIA_PASSWORD_LOGIN=false` 只在 SSO 配好时生效。
/// 没有 SSO 还关掉密码,谁都进不来——那就当这个开关没设,与登录页同一条规则
pub fn password_login(s: &AppState) -> bool {
    s.password_login || config().is_err()
}

/// 启动时把关掉密码登录的两种后果说出来:没配 SSO 时这个开关不生效;
/// 没有允许名单时只有绑定过身份的人进得来,新人既注册不了也开不了户
pub fn warn_about_password_login(s: &AppState) {
    if s.password_login {
        return;
    }
    match config() {
        Err(_) => {
            tracing::warn!("UTOPIA_PASSWORD_LOGIN=false 被忽略:没配单点登录,关掉密码就谁都进不来")
        }
        Ok(c) if c.allowed_domains.is_empty() => tracing::warn!(
            "密码登录已关、UTOPIA_OIDC_ALLOWED_DOMAINS 为空:只有绑定过身份的人能登录"
        ),
        Ok(_) => {}
    }
}

#[derive(Deserialize)]
pub struct StartQuery {
    #[serde(default)]
    link: Option<String>,
}

/// 浏览器导航过来的:出错一律带着代码跳回页面,不给人看一段 JSON
fn back_to(page: &str, code: &str) -> Redirect {
    Redirect::to(&format!("{page}?sso_error={code}"))
}

pub async fn start(
    State(s): State<AppState>,
    headers: HeaderMap,
    jar: CookieJar,
    Query(q): Query<StartQuery>,
) -> (CookieJar, Redirect) {
    let linking = q.link.as_deref().is_some_and(|v| matches!(v, "1" | "true"));
    let page = if linking { "/account" } else { "/login" };
    match begin(&s, &jar, linking).await {
        Ok((state, url)) => {
            let secure = auth::behind_tls(&headers, s.cookie_secure);
            (
                jar.add(flow_cookie(state, secure)),
                Redirect::to(url.as_str()),
            )
        }
        Err(r) => {
            tracing::warn!(code = r.code, reason = %r.reason, "单点登录没能开始");
            (jar, back_to(page, r.code))
        }
    }
}

async fn begin(
    s: &AppState,
    jar: &CookieJar,
    linking: bool,
) -> Result<(String, reqwest::Url), Refusal> {
    let c = config().map_err(|_| refuse("unavailable", "not configured"))?;
    // 绑定只替已登录的本人发起:流程上记下是谁,回调时再核对一次
    let link_user = if linking {
        Some(
            session_user(s, jar)
                .await
                .ok_or_else(|| refuse("session", "link started without a session"))?,
        )
    } else {
        None
    };
    sqlx::query("DELETE FROM oidc_flows WHERE expires_at < now()")
        .execute(&s.pool)
        .await?;
    let pending: i64 = sqlx::query_scalar("SELECT count(*) FROM oidc_flows")
        .fetch_one(&s.pool)
        .await?;
    if pending >= MAX_PENDING_FLOWS {
        return Err(refuse("busy", format!("{pending} sign-ins in progress")));
    }
    let meta = metadata(&c).await?;
    let mut url = endpoint(&c, &meta, "authorization_endpoint")?;
    let state = auth::generate_jwt_secret();
    let nonce = auth::generate_jwt_secret();
    let verifier = auth::generate_jwt_secret();
    let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
    sqlx::query(
        "INSERT INTO oidc_flows (state, nonce, verifier, link_user_id, expires_at)
         VALUES ($1, $2, $3, $4, now() + make_interval(secs => $5))",
    )
    .bind(&state)
    .bind(&nonce)
    .bind(&verifier)
    .bind(link_user)
    .bind(FLOW_TTL_SECS as f64)
    .execute(&s.pool)
    .await?;
    url.query_pairs_mut().extend_pairs([
        ("response_type", "code"),
        ("scope", "openid profile email"),
        ("client_id", &c.client_id),
        ("redirect_uri", &c.redirect),
        ("state", &state),
        ("nonce", &nonce),
        ("code_challenge", &challenge),
        ("code_challenge_method", "S256"),
    ]);
    Ok((state, url))
}

#[derive(Deserialize)]
pub struct Callback {
    code: Option<String>,
    state: Option<String>,
    /// 人在身份提供方那边点了取消,或者它拒绝了这次请求
    error: Option<String>,
}

#[derive(Clone, Deserialize)]
struct Claims {
    sub: String,
    /// 登录拿到的令牌带着本次流程的 nonce;换会话的令牌是别人的流程签的,未必有
    #[serde(default)]
    nonce: Option<String>,
    iat: i64,
    #[serde(default)]
    azp: Option<String>,
    aud: Value,
    #[serde(default)]
    email: Option<String>,
    /// 每个令牌都要过这里:有的身份提供方发字符串 `"true"`,严格按 bool 解析会让所有人
    /// 都登不进来。只有 `true` / `"true"` 算核实过,其它一律不算
    #[serde(default, deserialize_with = "lenient_true")]
    email_verified: bool,
    #[serde(default)]
    name: Option<String>,
}

fn lenient_true<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
    Ok(match Value::deserialize(d)? {
        Value::Bool(b) => b,
        Value::String(v) => v == "true",
        _ => false,
    })
}

/// 开户用的显示名:`name` 声明去掉首尾空白、最多 64 个字符;空的就用 email 的本地部分
fn display_name(claim: Option<&str>, email: &str) -> String {
    let name: String = claim.unwrap_or_default().trim().chars().take(64).collect();
    if name.is_empty() {
        email.split('@').next().unwrap_or_default().to_string()
    } else {
        name
    }
}

/// 能自动开户或按 email 关联的那个 email:身份提供方核实过,而且域名在允许名单里。
/// 名单空着就永远是 `None`——默认仍然只认本人绑定过的 subject
fn provisioned_email(claims: &Claims, allowed_domains: &[String]) -> Option<String> {
    let email = claims.email.as_deref()?.trim().to_lowercase();
    let (_, domain) = email.rsplit_once('@')?;
    (claims.email_verified && allowed_domains.iter().any(|d| d == domain)).then_some(email)
}

/// 按 `kid` 找钥匙;令牌不带 `kid` 时,只有 JWKS 里恰好一把 RSA 钥匙才用它
fn pick_key<'a>(keys: &'a JwkSet, kid: Option<&str>) -> Option<&'a jsonwebtoken::jwk::Jwk> {
    match kid {
        Some(kid) => keys.find(kid),
        None => {
            let mut rsa = keys
                .keys
                .iter()
                .filter(|k| matches!(k.algorithm, jsonwebtoken::jwk::AlgorithmParameters::RSA(_)));
            match (rsa.next(), rsa.next()) {
                (Some(only), None) => Some(only),
                _ => None,
            }
        }
    }
}

fn verify_token(
    c: &Config,
    id_token: &str,
    keys: &JwkSet,
    nonce: &str,
) -> Result<Claims, AppError> {
    let claims = verify_for(c, id_token, keys, &[c.client_id.as_str()])?;
    if claims.nonce.as_deref() != Some(nonce) {
        return Err(AppError::Unauthorized);
    }
    Ok(claims)
}

/// 签名、issuer、有效期与 audience:令牌得是配置的 issuer 签给 `audiences` 之一的。
/// `azp` 出现时(或 audience 不止一个时)也必须在其中
fn verify_for(
    c: &Config,
    id_token: &str,
    keys: &JwkSet,
    audiences: &[&str],
) -> Result<Claims, AppError> {
    let header = decode_header(id_token).map_err(|_| AppError::Unauthorized)?;
    if header.alg != Algorithm::RS256 {
        return Err(AppError::Unauthorized);
    }
    let key = pick_key(keys, header.kid.as_deref()).ok_or(AppError::Unauthorized)?;
    let mut validation = Validation::new(Algorithm::RS256);
    validation.validate_nbf = true;
    validation.set_issuer(&[&c.issuer]);
    validation.set_audience(audiences);
    validation.set_required_spec_claims(&["exp", "iss", "aud", "sub", "iat"]);
    let claims = decode::<Claims>(
        id_token,
        &DecodingKey::from_jwk(key).map_err(|_| AppError::Unauthorized)?,
        &validation,
    )
    .map_err(|_| AppError::Unauthorized)?
    .claims;
    let trusted = |a: &String| audiences.contains(&a.as_str());
    if claims.sub.is_empty()
        || claims.iat > chrono::Utc::now().timestamp() + 60
        || claims.azp.as_ref().is_some_and(|a| !trusted(a))
        || (claims.aud.as_array().is_some_and(|a| a.len() > 1)
            && !claims.azp.as_ref().is_some_and(trusted))
    {
        return Err(AppError::Unauthorized);
    }
    Ok(claims)
}

/// 换会话的 ID token 最多多旧:它是登录一完成就拿来换的
const EXCHANGE_MAX_AGE_SECS: i64 = 600;

/// 一个刚签发的、签给受信 audience 之一的 ID token
fn verify_exchange_token(c: &Config, id_token: &str, keys: &JwkSet) -> Result<Claims, AppError> {
    let audiences: Vec<&str> = c.exchange_audiences.iter().map(String::as_str).collect();
    let claims = verify_for(c, id_token, keys, &audiences)?;
    if claims.iat < chrono::Utc::now().timestamp() - EXCHANGE_MAX_AGE_SECS {
        return Err(AppError::Unauthorized);
    }
    Ok(claims)
}

#[derive(Deserialize)]
pub struct Exchange {
    id_token: String,
}

/// 另一个应用(client id 在 `UTOPIA_OIDC_EXCHANGE_AUDIENCES` 里)让它的用户在同一个
/// 身份提供方登录,再拿刚到手的 ID token 换一个 Utopia 会话,以那个人的身份调这里的
/// API。映射与 SSO 登录相同:本人绑定过的身份,或者允许名单里的域名(0069)。
/// 没配 SSO 或没配受信 audience 时就当这个端点不存在
pub async fn exchange(
    State(s): State<AppState>,
    Json(body): Json<Exchange>,
) -> ApiResult<Json<Value>> {
    let Some(c) = config().ok().filter(|c| !c.exchange_audiences.is_empty()) else {
        return Err(AppError::NotFound.into());
    };
    let unavailable = |r: Refusal| {
        tracing::warn!(reason = %r.reason, "SSO exchange: identity provider unavailable");
        AppError::invalid("oidc_unavailable", "The identity provider is unavailable")
    };
    let meta = metadata(&c).await.map_err(unavailable)?;
    let jwks_url = endpoint(&c, &meta, "jwks_uri").map_err(unavailable)?;
    let parse = |v: Value| {
        serde_json::from_value::<JwkSet>(v).map_err(|e| refuse("unavailable", format!("jwks: {e}")))
    };
    let mut keys =
        parse(cached_json(&jwks_url, false).await.map_err(unavailable)?).map_err(unavailable)?;
    let kid = decode_header(&body.id_token).ok().and_then(|h| h.kid);
    if pick_key(&keys, kid.as_deref()).is_none() {
        keys =
            parse(cached_json(&jwks_url, true).await.map_err(unavailable)?).map_err(unavailable)?;
    }
    let claims = verify_exchange_token(&c, &body.id_token, &keys)?;

    // 一次性:令牌的哈希落一行,活过令牌还能被接受的每一刻;插不进去就是换过了。
    // 只按 `iat` 算:十分钟的新鲜度没有宽限,而 `exp` 的校验有 60 秒宽限——按 `exp` 记的话,
    // 过期后的那一分钟里行已经扫掉、令牌却还验得过,能再换一次。多留的一分钟给应用和库的钟差
    sqlx::query("DELETE FROM oidc_exchanges WHERE expires_at < now()")
        .execute(&s.pool)
        .await?;
    let until = claims.iat + EXCHANGE_MAX_AGE_SECS + 60;
    let spent = sqlx::query(
        "INSERT INTO oidc_exchanges (token_hash, expires_at) VALUES ($1, to_timestamp($2))
         ON CONFLICT DO NOTHING",
    )
    .bind(
        Sha256::digest(body.id_token.as_bytes())
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect::<String>(),
    )
    .bind(until as f64)
    .execute(&s.pool)
    .await?;
    if spent.rows_affected() == 0 {
        return Err(
            AppError::invalid("oidc_replayed", "This ID token has already been exchanged").into(),
        );
    }

    let user_id = account_of(&s, &c, &claims).await.map_err(|r| {
        tracing::warn!(code = r.code, reason = %r.reason, "SSO exchange refused");
        AppError::invalid(
            "oidc_unavailable",
            "The identity could not be mapped to an account",
        )
    })?;
    let user_id = user_id.ok_or_else(|| {
        AppError::invalid(
            "oidc_unlinked",
            "This SSO identity is not linked to a Utopia account",
        )
    })?;
    let (token, expires_at) = auth::issue_session(&s, user_id)?;
    let _ = utopia_store::audit::record(
        &s.pool,
        None,
        user_id,
        "auth.oidc_exchange",
        "user",
        Some(user_id),
        json!({"issuer": c.issuer, "client": claims.azp.or_else(|| claims.aud.as_str().map(String::from))}),
    )
    .await;
    Ok(Json(json!({"token": token, "expires_at": expires_at})))
}

/// 回调办成的是哪一件事
enum Done {
    SignedIn(Uuid),
    Linked,
}

pub async fn callback(
    State(s): State<AppState>,
    headers: HeaderMap,
    jar: CookieJar,
    Query(q): Query<Callback>,
) -> (CookieJar, Redirect) {
    let secure = auth::behind_tls(&headers, s.cookie_secure);
    let mut linking = false;
    // 先读后删:CookieJar 删掉的 cookie 再 `get` 就取不到了
    let outcome = finish(&s, &jar, q, &mut linking).await;
    let jar = jar
        .remove(flow_cookie(String::new(), true))
        .remove(flow_cookie(String::new(), false));
    match outcome {
        Ok(Done::SignedIn(user_id)) => match auth::issue_token(&s, user_id) {
            Ok(token) => (jar.add(auth::auth_cookie(token, secure)), Redirect::to("/")),
            Err(e) => {
                tracing::warn!(error = %e, "单点登录签发会话失败");
                (jar, back_to("/login", "unavailable"))
            }
        },
        Ok(Done::Linked) => (jar, Redirect::to("/account?sso=linked")),
        Err(r) => {
            tracing::warn!(code = r.code, reason = %r.reason, "单点登录被拒");
            // 失败也进台账,与密码登录的 `auth.login_failed` 同一个口径
            let _ = utopia_store::audit::record_opt(
                &s.pool,
                None,
                None,
                if linking {
                    "auth.oidc_link_failed"
                } else {
                    "auth.oidc_login_failed"
                },
                "user",
                None,
                json!({"reason": r.code, "detail": r.reason}),
            )
            .await;
            (
                jar,
                back_to(if linking { "/account" } else { "/login" }, r.code),
            )
        }
    }
}

async fn finish(
    s: &AppState,
    jar: &CookieJar,
    q: Callback,
    linking: &mut bool,
) -> Result<Done, Refusal> {
    if let Some(e) = q.error {
        return Err(refuse("cancelled", format!("provider returned {e}")));
    }
    let c = config().map_err(|_| refuse("unavailable", "not configured"))?;
    let (code, state) = match (q.code, q.state) {
        (Some(code), Some(state)) => (code, state),
        _ => return Err(refuse("invalid", "callback without code or state")),
    };
    let cookie = jar
        .get(FLOW_COOKIE_HOST)
        .or_else(|| jar.get(FLOW_COOKIE))
        .ok_or_else(|| refuse("session", "no state cookie in this browser"))?;
    use subtle::ConstantTimeEq;
    if !bool::from(cookie.value().as_bytes().ct_eq(state.as_bytes())) {
        return Err(refuse("session", "state does not match this browser"));
    }
    let flow: Option<(String, String, Option<Uuid>)> = sqlx::query_as(
        "DELETE FROM oidc_flows WHERE state = $1 AND expires_at > now()
         RETURNING nonce, verifier, link_user_id",
    )
    .bind(&state)
    .fetch_optional(&s.pool)
    .await?;
    let (nonce, verifier, link_user) =
        flow.ok_or_else(|| refuse("expired", "unknown or expired state"))?;
    *linking = link_user.is_some();

    let meta = metadata(&c).await?;
    let mut req = client()?
        .post(endpoint(&c, &meta, "token_endpoint")?)
        .form(&[
            ("grant_type", "authorization_code"),
            ("code", code.as_str()),
            ("redirect_uri", c.redirect.as_str()),
            ("client_id", c.client_id.as_str()),
            ("code_verifier", verifier.as_str()),
        ]);
    if let Some(secret) = &c.secret {
        req = req.basic_auth(form_encode(&c.client_id), Some(form_encode(secret)));
    }
    let resp = req
        .send()
        .await
        .map_err(|e| refuse("unavailable", format!("token endpoint: {e}")))?;
    let tokens = read_json(resp, TOKEN_LIMIT)
        .await
        .map_err(|e| refuse("denied", format!("token endpoint: {e}")))?;
    let id_token = tokens["id_token"]
        .as_str()
        .ok_or_else(|| refuse("denied", "token response has no id_token"))?;

    let jwks_url = endpoint(&c, &meta, "jwks_uri")?;
    let parse = |v: Value| {
        serde_json::from_value::<JwkSet>(v).map_err(|e| refuse("unavailable", format!("jwks: {e}")))
    };
    let mut keys = parse(cached_json(&jwks_url, false).await?)?;
    // 身份提供方轮换了密钥:缓存里没有这个 kid 就强制刷新一次,再不认就是真不认
    let kid = decode_header(id_token).ok().and_then(|h| h.kid);
    if pick_key(&keys, kid.as_deref()).is_none() {
        keys = parse(cached_json(&jwks_url, true).await?)?;
    }
    let claims = verify_token(&c, id_token, &keys, &nonce)
        .map_err(|_| refuse("denied", "id_token failed verification"))?;

    match link_user {
        Some(user_id) => {
            // 完成绑定的必须还是发起绑定的那个人:流程是在他登录着的时候开始的,
            // 回调时同一个浏览器里得还是他的会话
            if session_user(s, jar).await != Some(user_id) {
                return Err(refuse(
                    "session",
                    "link finished outside the starting session",
                ));
            }
            link(s, &c, user_id, &claims.sub).await?;
            Ok(Done::Linked)
        }
        None => {
            let user_id = account_of(s, &c, &claims).await?.ok_or_else(|| {
                refuse("unlinked", format!("subject {} is not linked", claims.sub))
            })?;
            let _ = utopia_store::audit::record(
                &s.pool,
                None,
                user_id,
                "auth.oidc_login",
                "user",
                Some(user_id),
                json!({"issuer": c.issuer}),
            )
            .await;
            Ok(Done::SignedIn(user_id))
        }
    }
}

/// 这个 subject 登进哪个账号:本人绑定过的优先;没绑定、而 email 落在允许的域名里,
/// 就按 email 找账号(找不到开一个)并替他绑上
async fn account_of(s: &AppState, c: &Config, claims: &Claims) -> Result<Option<Uuid>, Refusal> {
    let linked: Option<Uuid> = sqlx::query_scalar(
        "SELECT i.user_id FROM oidc_identities i JOIN users u ON u.id = i.user_id
          WHERE i.issuer = $1 AND i.subject = $2 AND u.deactivated_at IS NULL",
    )
    .bind(&c.issuer)
    .bind(&claims.sub)
    .fetch_optional(&s.pool)
    .await?;
    let Some(email) = linked
        .is_none()
        .then(|| provisioned_email(claims, &c.allowed_domains))
        .flatten()
    else {
        return Ok(linked);
    };
    let provisioned = utopia_store::accounts::account_for_sso(
        &s.pool,
        &c.issuer,
        &claims.sub,
        &email,
        &display_name(claims.name.as_deref(), &email),
    )
    .await
    .map_err(|e| match e {
        AppError::CodedConflict { code, message } => refuse(code, message),
        e => refuse("unavailable", format!("provision: {e}")),
    })?;
    let Some(user) = provisioned else {
        tracing::warn!(%email, "单点登录:这个 email 属于一个停用的账号,不开新号");
        return Ok(None);
    };
    let _ = utopia_store::audit::record(
        &s.pool,
        None,
        user.id,
        "auth.oidc_link",
        "user",
        Some(user.id),
        json!({"issuer": c.issuer, "subject": claims.sub, "by": "allowed_domain"}),
    )
    .await;
    Ok(Some(user.id))
}

async fn link(s: &AppState, c: &Config, user_id: Uuid, subject: &str) -> Result<(), Refusal> {
    let holder: Option<Uuid> = sqlx::query_scalar(
        "SELECT user_id FROM oidc_identities WHERE issuer = $1 AND subject = $2",
    )
    .bind(&c.issuer)
    .bind(subject)
    .fetch_optional(&s.pool)
    .await?;
    match holder {
        Some(h) if h == user_id => return Ok(()),
        Some(_) => return Err(refuse("taken", "subject already linked to another account")),
        None => {}
    }
    let inserted =
        sqlx::query("INSERT INTO oidc_identities (issuer, subject, user_id) VALUES ($1, $2, $3)")
            .bind(&c.issuer)
            .bind(subject)
            .bind(user_id)
            .execute(&s.pool)
            .await;
    match inserted {
        Ok(_) => {}
        // 两个约束各对应一种撞车:subject 被别人抢先绑了,或者这个账号已经有一个
        Err(sqlx::Error::Database(db)) if db.is_unique_violation() => {
            let code = if db.constraint().is_some_and(|n| n.contains("user")) {
                "already_linked"
            } else {
                "taken"
            };
            return Err(refuse(code, db.message().to_string()));
        }
        Err(e) => return Err(e.into()),
    }
    let _ = utopia_store::audit::record(
        &s.pool,
        None,
        user_id,
        "auth.oidc_link",
        "user",
        Some(user_id),
        json!({"issuer": c.issuer, "subject": subject}),
    )
    .await;
    Ok(())
}

/// 我自己的绑定:账户页用
pub async fn me(State(s): State<AppState>, AuthUser(u): AuthUser) -> ApiResult<Json<Value>> {
    let Ok(c) = config() else {
        return Ok(Json(json!({"enabled": false, "linked": false})));
    };
    let subject: Option<String> = sqlx::query_scalar(
        "SELECT subject FROM oidc_identities WHERE issuer = $1 AND user_id = $2",
    )
    .bind(&c.issuer)
    .bind(u.id)
    .fetch_optional(&s.pool)
    .await?;
    Ok(Json(
        json!({"enabled": true, "linked": subject.is_some(), "subject": subject}),
    ))
}

/// 解绑我自己的身份
pub async fn unlink_me(State(s): State<AppState>, AuthUser(u): AuthUser) -> ApiResult<Json<Value>> {
    let c = config()?;
    let done = sqlx::query("DELETE FROM oidc_identities WHERE issuer = $1 AND user_id = $2")
        .bind(&c.issuer)
        .bind(u.id)
        .execute(&s.pool)
        .await?;
    if done.rows_affected() == 0 {
        return Err(AppError::NotFound.into());
    }
    let _ = utopia_store::audit::record(
        &s.pool,
        None,
        u.id,
        "auth.oidc_unlink",
        "user",
        Some(u.id),
        json!({"issuer": c.issuer, "by": "self"}),
    )
    .await;
    Ok(Json(json!({"ok": true})))
}

pub async fn identities(
    State(s): State<AppState>,
    AuthUser(u): AuthUser,
) -> ApiResult<Json<Value>> {
    if !u.is_admin {
        return Err(AppError::Forbidden.into());
    };
    let c = config()?;
    let rows: Vec<Value> = sqlx::query_scalar(
        "SELECT jsonb_build_object('user_id', i.user_id, 'subject', i.subject, 'email', u.email)
           FROM oidc_identities i JOIN users u ON u.id = i.user_id
          WHERE i.issuer = $1 AND u.org_id = $2 ORDER BY u.email",
    )
    .bind(&c.issuer)
    .bind(u.org_id)
    .fetch_all(&s.pool)
    .await?;
    Ok(Json(
        json!({"issuer": c.issuer, "client_id": c.client_id, "redirect_uri": c.redirect, "identities": rows}),
    ))
}

/// 管理员解绑。**只有解绑,没有替人绑定**(见模块说明)。解绑不会让已签发的会话
/// 失效——会话是无状态的 JWT,要立刻切断访问得停用账号
pub async fn unbind(
    State(s): State<AppState>,
    AuthUser(u): AuthUser,
    Path(id): Path<Uuid>,
) -> ApiResult<Json<Value>> {
    if !u.is_admin {
        return Err(AppError::Forbidden.into());
    };
    let c = config()?;
    let done = sqlx::query(
        "DELETE FROM oidc_identities WHERE issuer = $1 AND user_id = $2
          AND user_id IN (SELECT id FROM users WHERE org_id = $3)",
    )
    .bind(&c.issuer)
    .bind(id)
    .bind(u.org_id)
    .execute(&s.pool)
    .await?;
    if done.rows_affected() == 0 {
        return Err(AppError::NotFound.into());
    }
    let _ = utopia_store::audit::record(
        &s.pool,
        None,
        u.id,
        "auth.oidc_unlink",
        "user",
        Some(id),
        json!({"issuer": c.issuer, "by": "admin"}),
    )
    .await;
    Ok(Json(json!({"ok": true})))
}

#[cfg(test)]
mod tests {
    #[test]
    fn email_verified_is_true_only_for_true_or_the_string_true() {
        let verified = |v: serde_json::Value| {
            let mut claims = serde_json::json!({"sub": "p", "iat": 0, "aud": "a"});
            if !v.is_null() {
                claims["email_verified"] = v;
            }
            serde_json::from_value::<super::Claims>(claims)
                .map(|c| c.email_verified)
                .ok()
        };
        let cases = [
            serde_json::json!(true),
            serde_json::json!("true"),
            serde_json::json!("TRUE"),
            serde_json::json!(false),
            serde_json::json!("false"),
            serde_json::json!(1),
            serde_json::Value::Null,
        ];
        assert_eq!(
            cases.map(verified),
            [
                Some(true),
                Some(true),
                Some(false),
                Some(false),
                Some(false),
                Some(false),
                Some(false)
            ]
        );
    }

    #[test]
    fn a_display_name_is_trimmed_capped_at_64_and_falls_back_to_the_local_part() {
        let long = "名".repeat(70);
        assert_eq!(
            [
                super::display_name(Some("  Ann Lee \n"), "[email protected]"),
                super::display_name(Some("   "), "[email protected]"),
                super::display_name(None, "[email protected]"),
                super::display_name(Some(&long), "[email protected]"),
            ],
            [
                "Ann Lee".to_string(),
                "bea".into(),
                "cid".into(),
                "名".repeat(64)
            ]
        );
    }

    #[test]
    fn only_local_callbacks_can_use_http() {
        assert!(super::secure_url("http://localhost:1516/callback", true).is_ok());
        assert!(super::secure_url("http://[::1]:1516/callback", true).is_ok());
        assert!(super::secure_url("http://example.org/callback", true).is_err());
        assert!(super::secure_url("http://localhost:1516", false).is_err());
        assert!(super::secure_url("https://user:[email protected]", false).is_err());
    }

    #[test]
    fn a_client_secret_is_form_encoded_before_basic_auth() {
        assert_eq!(super::form_encode("abc"), "abc");
        assert_eq!(super::form_encode("a:b%c+d e"), "a%3Ab%25c%2Bd+e");
    }

    #[tokio::test]
    async fn a_response_over_its_limit_is_refused() {
        let big = axum::http::Response::new(vec![b' '; 2048]);
        assert!(super::read_json(reqwest::Response::from(big), 1024)
            .await
            .is_err());
        let ok = axum::http::Response::new(br#"{"a":1}"#.to_vec());
        assert_eq!(
            super::read_json(reqwest::Response::from(ok), 1024)
                .await
                .unwrap()["a"],
            1
        );
    }

    #[tokio::test]
    async fn a_forced_refresh_waits_out_its_cooldown() {
        let key = "https://id.example.test/cooldown-test";
        assert!(super::force_allowed(key).await);
        assert!(!super::force_allowed(key).await);
        assert!(super::force_allowed("https://id.example.test/another").await);
    }

    #[test]
    fn only_a_verified_email_in_an_allowed_domain_gets_an_account() {
        let claims = |email: &str, verified: bool| {
            serde_json::from_value::<super::Claims>(serde_json::json!({
                "sub": "person-1", "iat": 0, "aud": "utopia-test",
                "email": email, "email_verified": verified,
            }))
            .unwrap()
        };
        let allowed = vec!["re-cinq.com".to_string()];
        assert_eq!(
            super::provisioned_email(&claims("[email protected]", true), &allowed),
            Some("[email protected]".to_string())
        );
        assert_eq!(
            super::provisioned_email(&claims("[email protected]", false), &allowed),
            None
        );
        assert_eq!(
            super::provisioned_email(&claims("[email protected]", true), &allowed),
            None
        );
        assert_eq!(
            super::provisioned_email(&claims("[email protected]", true), &allowed),
            None
        );
        assert_eq!(
            super::provisioned_email(&claims("[email protected]", true), &[]),
            None
        );
    }

    fn config() -> super::Config {
        super::Config {
            issuer: "https://id.example.test".into(),
            client_id: "utopia-test".into(),
            secret: None,
            redirect: "https://utopia.example.test/api/v1/auth/oidc/callback".into(),
            exchange_audiences: vec!["sibling-app".into(), "utopia-test".into()],
            allowed_domains: vec![],
            loopback_http: false,
        }
    }

    // This key is generated solely for these tests and is never used by the app.
    #[test]
    fn verifies_signature_issuer_audience_nonce_and_expiry() {
        use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
        use serde_json::json;
        let c = config();
        let key = EncodingKey::from_rsa_pem(include_bytes!(
            "../../tests/fixtures/oidc_test_only_key.pem"
        ))
        .unwrap();
        let keys: jsonwebtoken::jwk::JwkSet = serde_json::from_str(include_str!(
            "../../tests/fixtures/oidc_test_only_jwks.json"
        ))
        .unwrap();
        let now = chrono::Utc::now().timestamp();
        let valid = json!({"iss":c.issuer,"aud":c.client_id,"sub":"person-123","nonce":"expected","iat":now,"exp":now+300});
        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some("fixture".into());
        let token = encode(&header, &valid, &key).unwrap();
        assert!(super::verify_token(&c, &token, &keys, "expected").is_ok());
        assert!(super::verify_token(&c, &token, &keys, "wrong").is_err());
        for (field, value) in [
            ("iss", json!("https://other.example.test")),
            ("aud", json!("other-client")),
            ("exp", json!(now - 3600)),
            ("iat", json!(now + 3600)),
            ("azp", json!("other-client")),
            ("sub", json!("")),
        ] {
            let mut invalid = valid.clone();
            invalid[field] = value;
            let token = encode(&header, &invalid, &key).unwrap();
            assert!(
                super::verify_token(&c, &token, &keys, "expected").is_err(),
                "accepted invalid {field}"
            );
        }
        let fake = encode(
            &Header::default(),
            &valid,
            &EncodingKey::from_secret(b"not-an-rsa-key"),
        )
        .unwrap();
        assert!(super::verify_token(&c, &fake, &keys, "expected").is_err());
        header.kid = Some("unknown-key".into());
        assert!(super::verify_token(
            &c,
            &encode(&header, &valid, &key).unwrap(),
            &keys,
            "expected"
        )
        .is_err());

        // 不带 kid:JWKS 里只有一把 RSA 钥匙时用它,多于一把就不猜
        header.kid = None;
        let no_kid = encode(&header, &valid, &key).unwrap();
        assert!(super::verify_token(&c, &no_kid, &keys, "expected").is_ok());
        let mut two = keys.clone();
        let mut second = two.keys[0].clone();
        second.common.key_id = Some("other".into());
        two.keys.push(second);
        assert!(super::verify_token(&c, &no_kid, &two, "expected").is_err());
    }

    #[test]
    fn exchange_accepts_only_fresh_tokens_of_a_trusted_client() {
        use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
        use serde_json::json;
        let c = config();
        let key = EncodingKey::from_rsa_pem(include_bytes!(
            "../../tests/fixtures/oidc_test_only_key.pem"
        ))
        .unwrap();
        let keys: jsonwebtoken::jwk::JwkSet = serde_json::from_str(include_str!(
            "../../tests/fixtures/oidc_test_only_jwks.json"
        ))
        .unwrap();
        let now = chrono::Utc::now().timestamp();
        let valid = json!({"iss":c.issuer,"aud":c.client_id,"sub":"person-123","nonce":"theirs","iat":now,"exp":now+300});
        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some("fixture".into());
        let sign = |claims: &serde_json::Value| encode(&header, claims, &key).unwrap();
        assert_eq!(
            super::verify_exchange_token(&c, &sign(&valid), &keys)
                .unwrap()
                .sub,
            "person-123"
        );
        for (field, value) in [
            ("aud", json!("other-client")),
            ("aud", json!([c.client_id, "other-client"])),
            ("azp", json!("other-client")),
            ("iat", json!(now - 3600)),
            ("exp", json!(now - 3600)),
            ("iss", json!("https://other.example.test")),
        ] {
            let mut invalid = valid.clone();
            invalid[field] = value;
            assert!(
                super::verify_exchange_token(&c, &sign(&invalid), &keys).is_err(),
                "accepted invalid {field}"
            );
        }
        let mut multi = valid.clone();
        multi["aud"] = json!([c.client_id, "other-client"]);
        multi["azp"] = json!(c.client_id);
        assert!(super::verify_exchange_token(&c, &sign(&multi), &keys).is_ok());

        // 另一个应用用它自己的 client id;不在受信列表里的照样不认
        let mut sibling = valid.clone();
        sibling["aud"] = json!("sibling-app");
        assert!(super::verify_exchange_token(&c, &sign(&sibling), &keys).is_ok());
        let closed = super::Config {
            exchange_audiences: Vec::new(),
            ..config()
        };
        assert!(super::verify_exchange_token(&closed, &sign(&valid), &keys).is_err());
    }
}