KeiSeiKit-1.0/_primitives/_rust/kei-auth-apple/src/client.rs
Parfii-bot 8b0401b9db feat(auth): JWT verification + OAuth CSRF + PKCE + secret redaction
Group B — auth-crate security hardening (post-audit Sonnet test-retest 2026-05-02).

kei-auth-apple:
- jwt.rs: full ES256 JWKS signature verification (jsonwebtoken crate);
          validates iss == https://appleid.apple.com, aud == client_id, exp, iat;
          decode_id_token_unverified is now cfg(test)-only.
          Module docstring promised this since v0.1 — now actually implemented.
- claims.rs (new): IdTokenClaims + AudClaim extracted from jwt.rs.
- error.rs: JwtVerify, JwtDecode, MissingClaim variants.
- client.rs: client_secret_jwt: SecretString (was String); exchange_code accepts
              code_verifier: Option<&str> for PKCE.
- provider.rs: verify() does CSRF expected_state ConstantTimeEq + JWT verification;
                build_auth_url accepts state + verifier and emits PKCE code_challenge.
- tests/apple_smoke.rs + helpers/: 6 tests including malformed-JWT + non-Apple OAuth +
                                     400-mapping + provider_verify_csrf_mismatch_rejected.

kei-auth-google:
- pkce.rs (new): pkce_challenge + url_encode (RFC 7636 §B.1 test vector covered).
- client.rs: client_secret: SecretString; exchange_code accepts code_verifier.
- provider.rs: verify() rejects on state mismatch; build_auth_url emits S256 challenge.
- tests/google_smoke.rs: 7 tests including CSRF mismatch.

kei-auth:
- main.rs: resolve_token() supports stdin (-) and KEI_AUTH_TOKEN env. Token positional
            arg leaked via /proc/<pid>/cmdline + shell history; same fix that v0.14.1
            applied to --key.
- main.rs::key(): hard fail if KEI_AUTH_KEY len < 32 bytes (mirror of magiclink).
- tokens.rs::verify(): query_row(...).optional()? instead of .ok() — DB errors now
                        propagate instead of being swallowed as "token unknown".

kei-runtime-core:
- secrets.rs (new, 81 LOC): SecretString newtype with redacted Debug + zeroize-on-Drop.
                              Required by every auth crate that holds secret material.
- traits/auth.rs: AuthChallenge::Password.password is now SecretString;
                   OAuthCode { state, expected_state }.
- error.rs: CsrfStateMismatch variant.

Test results: 48 passed; 0 failed across kei-auth, kei-auth-apple, kei-auth-google,
kei-auth-magiclink, kei-runtime-core. cargo check --workspace clean.

Findings consensus: Apple JWT unverified + OAuth state CSRF appeared in all 3
audit waves (Wave-1 + Wave-A + Wave-B); PKCE absence + secret-derive-Debug appeared
only in Wave-A retest, would have been missed by single-pass audit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 21:39:18 +08:00

139 lines
4.8 KiB
Rust

// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 <author org>
//
//! Thin async OAuth client for Apple Sign-In code exchange.
//!
//! Implements only the `POST /auth/token` step (RFC 6749 §4.1.3
//! Authorization Code grant) against the Apple ID endpoint. Apple's
//! `client_secret` is itself an ES256-signed JWT — this cube does NOT
//! sign it; the caller MUST supply a pre-built JWT.
use crate::error::{Error, Result};
use kei_runtime_core::SecretString;
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use std::time::Duration;
/// Default authorization endpoint (browser-facing redirect target).
pub const DEFAULT_AUTHORIZE_URL: &str = "https://appleid.apple.com/auth/authorize";
/// Default token endpoint (server-side code exchange POST).
pub const DEFAULT_TOKEN_URL: &str = "https://appleid.apple.com/auth/token";
/// Per-request timeout.
pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
/// Apple `/auth/token` response shape (RFC 6749 + Apple-specific fields).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TokenResponse {
pub access_token: String,
pub expires_in: i64,
pub id_token: String,
#[serde(default)]
pub refresh_token: Option<String>,
#[serde(default)]
pub token_type: Option<String>,
}
/// REST client for the Apple `/auth/token` endpoint. Cheap to clone.
#[derive(Debug, Clone)]
pub struct AppleAuthClient {
http: Client,
token_url: String,
client_id: String,
/// Wrapped in `SecretString` so logs never reveal the JWT.
client_secret_jwt: SecretString,
redirect_uri: String,
}
impl AppleAuthClient {
/// Build with explicit values (use [`DEFAULT_TOKEN_URL`] in prod).
pub fn with_url(
token_url: impl Into<String>,
client_id: impl Into<String>,
client_secret_jwt: impl Into<String>,
redirect_uri: impl Into<String>,
) -> Result<Self> {
let http = Client::builder()
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
.build()?;
Ok(Self {
http,
token_url: token_url.into(),
client_id: client_id.into(),
client_secret_jwt: SecretString::new(client_secret_jwt),
redirect_uri: redirect_uri.into(),
})
}
/// Read all three required values from env, default token URL.
///
/// Required env:
/// - `APPLE_OAUTH_CLIENT_ID`
/// - `APPLE_CLIENT_SECRET_JWT`
/// - `APPLE_OAUTH_REDIRECT_URI`
pub fn from_env() -> Result<Self> {
let client_id = std::env::var("APPLE_OAUTH_CLIENT_ID").map_err(|_| {
Error::Api("APPLE_OAUTH_CLIENT_ID env var not set".into())
})?;
let client_secret_jwt = std::env::var("APPLE_CLIENT_SECRET_JWT").map_err(|_| {
Error::Api("APPLE_CLIENT_SECRET_JWT env var not set".into())
})?;
let redirect_uri = std::env::var("APPLE_OAUTH_REDIRECT_URI").map_err(|_| {
Error::Api("APPLE_OAUTH_REDIRECT_URI env var not set".into())
})?;
Self::with_url(DEFAULT_TOKEN_URL, client_id, client_secret_jwt, redirect_uri)
}
/// Borrow `client_id` (used by `build_auth_url`).
pub fn client_id(&self) -> &str {
&self.client_id
}
/// Borrow `redirect_uri` (used by `build_auth_url`).
pub fn redirect_uri(&self) -> &str {
&self.redirect_uri
}
/// POST application/x-www-form-urlencoded body to `/auth/token`.
///
/// If `code_verifier` is `Some`, it is included as the PKCE
/// `code_verifier` parameter per RFC 7636 §4.5.
pub async fn exchange_code(
&self,
code: &str,
code_verifier: Option<&str>,
) -> Result<TokenResponse> {
let secret = self.client_secret_jwt.expose();
let mut form: Vec<(&str, &str)> = vec![
("client_id", self.client_id.as_str()),
("client_secret", secret),
("code", code),
("redirect_uri", self.redirect_uri.as_str()),
("grant_type", "authorization_code"),
];
if let Some(cv) = code_verifier {
form.push(("code_verifier", cv));
}
let resp = self
.http
.post(&self.token_url)
.header("accept", "application/json")
.form(&form)
.send()
.await?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
return Err(classify(status, body));
}
let bytes = resp.bytes().await?;
if bytes.is_empty() {
return Err(Error::Api("empty body where token JSON expected".into()));
}
let parsed: TokenResponse = serde_json::from_slice(&bytes)?;
Ok(parsed)
}
}
fn classify(status: StatusCode, body: String) -> Error {
Error::Api(format!("http {}: {}", status, body))
}