KeiSeiKit-1.0/_primitives/_rust/kei-auth-apple/src/error.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

73 lines
2.4 KiB
Rust

// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 <author org>
//
//! Local error type for the Apple Sign-In auth provider.
//!
//! Mapped into [`kei_runtime_core::Error`] via `From<Error>` so the trait
//! impls can use `?` against the runtime-core `Result`.
use kei_runtime_core::DnaError;
use thiserror::Error;
/// Crate-local result alias.
pub type Result<T> = std::result::Result<T, Error>;
/// Crate-local error variants.
#[derive(Debug, Error)]
pub enum Error {
/// Transport / TLS / timeout failure from `reqwest`.
#[error("http: {0}")]
Http(#[from] reqwest::Error),
/// Non-success HTTP status with the (best-effort) body text, or
/// other Apple-side API protocol failure.
#[error("api: {0}")]
Api(String),
/// id_token shape / base64 / utf8 / json failure during unverified decode.
/// Only used in `#[cfg(test)]` paths; production uses [`Error::JwtVerify`].
#[error("jwt decode: {0}")]
JwtDecode(String),
/// ES256 signature verification against Apple JWKS failed, or a required
/// claim (`iss`, `aud`, `exp`, `iat`) was invalid.
#[error("jwt verify: {0}")]
JwtVerify(String),
/// id_token decoded but a required claim (e.g. `sub`) was missing.
#[error("missing claim: {0}")]
MissingClaim(String),
/// DNA construction or parse failure.
#[error("dna: {0}")]
Dna(#[from] DnaError),
/// Local IO (env var read, etc.).
#[error("io: {0}")]
Io(#[from] std::io::Error),
/// JSON serialize / deserialize failure.
#[error("serde: {0}")]
Serde(#[from] serde_json::Error),
}
impl From<Error> for kei_runtime_core::Error {
fn from(e: Error) -> Self {
match e {
Error::Http(re) => kei_runtime_core::Error::Network(re.to_string()),
Error::Api(msg) => kei_runtime_core::Error::Provider(msg),
Error::JwtDecode(msg) => {
kei_runtime_core::Error::Provider(format!("jwt decode: {msg}"))
}
Error::JwtVerify(msg) => {
kei_runtime_core::Error::Auth(format!("jwt verify: {msg}"))
}
Error::MissingClaim(c) => {
kei_runtime_core::Error::Provider(format!("missing claim: {c}"))
}
Error::Dna(de) => kei_runtime_core::Error::Dna(de),
Error::Io(io) => kei_runtime_core::Error::Io(io),
Error::Serde(se) => kei_runtime_core::Error::Provider(format!("serde: {se}")),
}
}
}