Skip to main content

yang_base/action/
step_up.rs

1//! 敏感 Action 的短期 step-up challenge/proof。
2//!
3//! Step-up 使用独立 HMAC 密钥域,证明绑定已认证主体、Action 全限定引用和资源指纹。
4//! 前端确认框不能替代本模块;业务必须通过 [`CredentialVerifier`] 重新校验凭据后,
5//! 才能调用 [`StepUpManager::complete_challenge`]。
6
7use super::auth::{CredentialVerifier, LoginInput};
8use super::{ActionContext, ApiResponse};
9use crate::definition::ActionRef;
10use crate::error::BaseError;
11use crate::router::{Middleware, MiddlewareRole, Next};
12use async_trait::async_trait;
13use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
14use serde::{Deserialize, Serialize};
15use sha2::{Digest, Sha256};
16use std::collections::{HashMap, HashSet};
17use std::fmt;
18use std::sync::{Arc, Mutex};
19use std::time::{Duration, SystemTime, UNIX_EPOCH};
20use uuid::Uuid;
21use yang_base_derive::Action;
22
23/// 默认 challenge 有效期:2 分钟。
24pub const DEFAULT_STEP_UP_CHALLENGE_TTL: Duration = Duration::from_secs(120);
25/// 默认 proof 有效期:5 分钟。
26pub const DEFAULT_STEP_UP_PROOF_TTL: Duration = Duration::from_secs(300);
27const MAX_STEP_UP_CHALLENGE_TTL: Duration = Duration::from_secs(300);
28const MAX_STEP_UP_PROOF_TTL: Duration = Duration::from_secs(600);
29const MIN_STEP_UP_SECRET_BYTES: usize = 32;
30
31/// 敏感 Action 提交 step-up proof 的固定请求头。
32pub const STEP_UP_PROOF_HEADER: &str = "x-step-up-proof";
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36enum StepUpTokenKind {
37    Challenge,
38    Proof,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42struct StepUpClaims {
43    iss: String,
44    sub: String,
45    aud: String,
46    exp: u64,
47    iat: u64,
48    jti: String,
49    kind: StepUpTokenKind,
50    action: String,
51    resource_hash: String,
52    challenge_jti: Option<String>,
53}
54
55/// 等待业务重新校验凭据的短期 challenge。
56#[derive(Clone, Serialize, schemars::JsonSchema)]
57pub struct StepUpChallenge {
58    /// 必须原样提交给重认证 Action 的签名 challenge。
59    pub challenge: String,
60    /// 从签发时刻起的有效秒数。
61    pub expires_in: u64,
62}
63
64impl fmt::Debug for StepUpChallenge {
65    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66        formatter
67            .debug_struct("StepUpChallenge")
68            .field(
69                "challenge",
70                &format_args!("[REDACTED:{}]", self.challenge.len()),
71            )
72            .field("expires_in", &self.expires_in)
73            .finish()
74    }
75}
76
77/// 凭据重认证成功后签发的短期 proof。
78#[derive(Clone, Serialize, schemars::JsonSchema)]
79pub struct StepUpProof {
80    /// 提交给敏感 Action 的签名 proof。
81    pub proof: String,
82    /// 从重认证成功时刻起的有效秒数。
83    pub expires_in: u64,
84}
85
86impl fmt::Debug for StepUpProof {
87    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88        formatter
89            .debug_struct("StepUpProof")
90            .field("proof", &format_args!("[REDACTED:{}]", self.proof.len()))
91            .field("expires_in", &self.expires_in)
92            .finish()
93    }
94}
95
96/// 已验证 proof 的服务端信息。
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct StepUpVerification {
99    /// 绑定的认证主体。
100    pub subject: String,
101    /// 绑定的全限定 Action 引用。
102    pub action: String,
103    /// 资源标识的 SHA-256 指纹;原始资源不会写入 Token。
104    pub resource_hash: String,
105    /// 完成重认证的 Unix 时间戳。
106    pub authenticated_at: u64,
107    /// proof 过期 Unix 时间戳。
108    pub expires_at: u64,
109    /// proof 的唯一 ID,供审计关联。
110    pub proof_id: String,
111}
112
113/// 完成 step-up challenge 的输入。
114#[derive(Clone, Deserialize, schemars::JsonSchema)]
115#[serde(deny_unknown_fields)]
116pub struct StepUpCompleteInput {
117    /// 敏感 Action 返回的签名 challenge。
118    pub challenge: String,
119    /// 要重新校验的业务凭据。
120    pub credentials: LoginInput,
121}
122
123/// 内置 step-up 重认证 Action。
124///
125/// Action 只负责编排签名 challenge 与业务 [`CredentialVerifier`];限流、失败计数和
126/// 锁定仍必须由 verifier 使用共享存储实现,避免框架猜测账号体系。
127#[derive(Action)]
128#[action(
129    name = "step_up_complete",
130    display_name = "完成敏感操作重认证",
131    description = "重新校验凭据并把 step-up challenge 升级为一次性 proof",
132    method = "POST",
133    path = "/step-up/complete",
134    public
135)]
136pub struct StepUpCompleteAction<V: CredentialVerifier> {
137    manager: Arc<StepUpManager>,
138    verifier: V,
139}
140
141impl<V: CredentialVerifier> StepUpCompleteAction<V> {
142    /// 使用共享 step-up 管理器和业务凭据校验器创建 Action。
143    pub fn new(manager: Arc<StepUpManager>, verifier: V) -> Self {
144        Self { manager, verifier }
145    }
146}
147
148#[async_trait]
149impl<V: CredentialVerifier> super::TypedHandler for StepUpCompleteAction<V> {
150    type Input = StepUpCompleteInput;
151    type Output = StepUpProof;
152
153    async fn handle(
154        &self,
155        context: ActionContext,
156        input: Self::Input,
157    ) -> Result<Self::Output, BaseError> {
158        self.manager
159            .complete_challenge(
160                &context,
161                &self.verifier,
162                &input.credentials,
163                &input.challenge,
164            )
165            .await
166    }
167}
168
169/// step-up proof 的一次性消费存储。
170///
171/// 实现必须以 proof ID 为键执行原子“首次写入成功”语义,并至少保留到 proof
172/// 过期。返回 `false` 表示该 proof 已被消费。
173#[async_trait]
174pub trait StepUpProofStore: Send + Sync + 'static {
175    /// 尝试消费一个已完成签名与绑定校验的 proof。
176    async fn consume(&self, proof: &StepUpVerification) -> Result<bool, BaseError>;
177}
178
179/// 单进程一次性 proof 存储。
180///
181/// 适用于单实例服务和测试;多实例部署必须改用 [`RedisStepUpProofStore`],否则
182/// 不同进程无法共享已消费状态。
183#[derive(Debug, Default)]
184pub struct InMemoryStepUpProofStore {
185    consumed: Mutex<HashMap<String, u64>>,
186}
187
188#[async_trait]
189impl StepUpProofStore for InMemoryStepUpProofStore {
190    async fn consume(&self, proof: &StepUpVerification) -> Result<bool, BaseError> {
191        let now = unix_timestamp()?;
192        let mut consumed = self.consumed.lock().map_err(|_| {
193            BaseError::ConfigError("step-up proof 内存消费存储锁已损坏".to_string())
194        })?;
195        consumed.retain(|_, expires_at| *expires_at > now);
196        if consumed.contains_key(&proof.proof_id) {
197            return Ok(false);
198        }
199        consumed.insert(proof.proof_id.clone(), proof.expires_at);
200        Ok(true)
201    }
202}
203
204/// 基于 Redis `SET NX EX` 的多实例一次性 proof 存储。
205#[derive(Clone)]
206pub struct RedisStepUpProofStore {
207    cache: yang_db::RedisClient,
208    key_prefix: String,
209}
210
211impl RedisStepUpProofStore {
212    /// 创建 Redis proof 存储。
213    pub fn new(cache: yang_db::RedisClient) -> Self {
214        Self {
215            cache,
216            key_prefix: "yang:step-up:proof-used:".to_string(),
217        }
218    }
219
220    /// 覆盖 Redis key 前缀,便于应用隔离命名空间。
221    pub fn with_key_prefix(mut self, key_prefix: impl Into<String>) -> Result<Self, BaseError> {
222        let key_prefix = key_prefix.into();
223        if key_prefix.trim().is_empty() {
224            return Err(BaseError::ConfigError(
225                "step-up proof Redis key 前缀不能为空".to_string(),
226            ));
227        }
228        self.key_prefix = key_prefix;
229        Ok(self)
230    }
231}
232
233#[async_trait]
234impl StepUpProofStore for RedisStepUpProofStore {
235    async fn consume(&self, proof: &StepUpVerification) -> Result<bool, BaseError> {
236        let now = unix_timestamp()?;
237        let ttl = proof.expires_at.saturating_sub(now).max(1);
238        let ttl = i64::try_from(ttl)
239            .map_err(|_| BaseError::ConfigError("step-up proof Redis TTL 超出范围".to_string()))?;
240        self.cache
241            .set_nx_ex(format!("{}{}", self.key_prefix, proof.proof_id), "1", ttl)
242            .await
243            .map_err(BaseError::from)
244    }
245}
246
247/// 从当前可信请求状态解析 proof 必须绑定的稳定资源标识。
248///
249/// 实现者可以读取路径参数等客户端候选,但必须结合服务端事实完成规范化与授权相关
250/// 校验,返回例如 `org_user:42` 的稳定标识。不得把客户端自报的“已验证资源”直接
251/// 原样返回。解析失败必须 fail-closed。
252///
253/// # 收窄 proof 重放窗口
254///
255/// proof 在 TTL 内对同一资源标识可重放。资源标识越粗,重放面越大:仅绑定
256/// `transfer:account:42` 意味着重认证一次即可在该账户上重复发起任意金额的转账。
257/// 资源标识应把**操作参数指纹**纳入标识,例如金额、目标账户等关键参数的 hash
258/// (`transfer:account:42:sha256(amount=100,to=account:7)`),使 proof 只覆盖一次
259/// 确定的操作语义,任何参数变化都会使 proof 失效并触发新的 challenge。
260#[async_trait]
261pub trait StepUpResourceResolver: Send + Sync + 'static {
262    /// 解析当前请求实际操作的稳定资源标识。
263    async fn resolve(&self, context: &ActionContext) -> Result<String, BaseError>;
264}
265
266/// 为一个确定 Action 强制执行短期重认证的中间件。
267///
268/// 中间件必须注册在身份认证中间件之后。它只拦截构造时绑定的 Action;当前实际
269/// Action 身份由 `Registry` 在派发边界覆盖注入,不能由客户端声明。缺少 proof 时
270/// 返回携带短期 challenge 的 [`BaseError::StepUpRequired`];存在但无效的 proof
271/// 直接拒绝,不降级为新 challenge。
272///
273/// # 约束范围(重要)
274///
275/// step-up 仅约束 `Registry::dispatch` 路径(HTTP 传输与显式 dispatch 均经此路径)。
276/// `Registry::call` / `Plugins::api_run` 等内部调用**不经过中间件链**,敏感 Action
277/// 被内部调用时不会触发 step-up(仅保留权限校验)。这是有意的语义划分:内部调用方
278/// 是受信代码,如需重认证必须自行编排 `StepUpManager`。该语义由
279/// `internal_call_bypasses_step_up_middleware_by_design` 测试锁定,改动前请先评审。
280pub struct StepUpMiddleware<R> {
281    manager: Arc<StepUpManager>,
282    action: ActionRef,
283    resolver: R,
284    proof_store: Arc<dyn StepUpProofStore>,
285}
286
287impl<R> StepUpMiddleware<R>
288where
289    R: StepUpResourceResolver,
290{
291    /// 绑定管理器、目标 Action 与服务端资源解析器。
292    pub fn new(manager: Arc<StepUpManager>, action: ActionRef, resolver: R) -> Self {
293        Self {
294            manager,
295            action,
296            resolver,
297            proof_store: Arc::new(InMemoryStepUpProofStore::default()),
298        }
299    }
300
301    /// 覆盖一次性 proof 存储。
302    ///
303    /// 多实例部署应传入 [`RedisStepUpProofStore`],保证所有实例共享消费状态。
304    #[must_use]
305    pub fn with_proof_store<S>(mut self, proof_store: S) -> Self
306    where
307        S: StepUpProofStore,
308    {
309        self.proof_store = Arc::new(proof_store);
310        self
311    }
312}
313
314#[async_trait]
315impl<R> Middleware for StepUpMiddleware<R>
316where
317    R: StepUpResourceResolver,
318{
319    fn role(&self) -> MiddlewareRole {
320        MiddlewareRole::StepUpProtection
321    }
322
323    fn target_action(&self) -> Option<&ActionRef> {
324        Some(&self.action)
325    }
326
327    async fn handle(
328        &self,
329        context: ActionContext,
330        next: Next<'_>,
331    ) -> Result<ApiResponse, BaseError> {
332        let (module, action) = context
333            .dispatch_target()
334            .ok_or_else(|| BaseError::ConfigError("step-up 中间件缺少可信派发目标".to_string()))?;
335        if module != self.action.module().as_str() || action != self.action.action().as_str() {
336            return next.run(context).await;
337        }
338
339        let subject = context
340            .authenticated_user()
341            .ok_or_else(|| BaseError::Unauthorized("step-up 需要已认证用户".to_string()))?
342            .id
343            .to_string();
344        let resource = self.resolver.resolve(&context).await?;
345        if resource.trim().is_empty() {
346            return Err(BaseError::ConfigError(
347                "step-up 资源解析器返回了空标识".to_string(),
348            ));
349        }
350
351        match context.request.get_header(STEP_UP_PROOF_HEADER) {
352            Some(proof) => {
353                let verification =
354                    self.manager
355                        .verify_proof(proof, &subject, &self.action, &resource)?;
356                if !self.proof_store.consume(&verification).await? {
357                    tracing::warn!(
358                        proof_id = %verification.proof_id,
359                        subject = %verification.subject,
360                        action = %verification.action,
361                        resource_hash = %verification.resource_hash,
362                        "step-up proof 重放被拒绝"
363                    );
364                    return Err(invalid_step_up("proof 已被消费"));
365                }
366                next.run(context).await
367            }
368            None => Err(BaseError::StepUpRequired(self.manager.issue_challenge(
369                subject,
370                &self.action,
371                &resource,
372            )?)),
373        }
374    }
375}
376
377/// 独立签名域的 step-up challenge/proof 管理器。
378pub struct StepUpManager {
379    encoding_key: EncodingKey,
380    decoding_key: DecodingKey,
381    header: Header,
382    validation: Validation,
383    issuer: String,
384    audience: String,
385    challenge_ttl: u64,
386    proof_ttl: u64,
387}
388
389impl StepUpManager {
390    /// 使用 HS256 和安全默认短时限创建管理器。
391    ///
392    /// `secret` 必须至少 32 字节,且应与 access/refresh token 使用不同密钥。
393    pub fn new(
394        secret: impl AsRef<[u8]>,
395        issuer: impl Into<String>,
396        audience: impl Into<String>,
397    ) -> Result<Self, BaseError> {
398        let secret = secret.as_ref();
399        if secret.len() < MIN_STEP_UP_SECRET_BYTES {
400            return Err(BaseError::ConfigError(
401                "step-up HMAC 密钥至少需要 32 字节".to_string(),
402            ));
403        }
404        let issuer = issuer.into();
405        let audience = audience.into();
406        if issuer.trim().is_empty() || audience.trim().is_empty() {
407            return Err(BaseError::ConfigError(
408                "step-up issuer/audience 不能为空".to_string(),
409            ));
410        }
411        let mut header = Header::new(Algorithm::HS256);
412        header.typ = Some("step-up+jwt".to_string());
413        Ok(Self {
414            encoding_key: EncodingKey::from_secret(secret),
415            decoding_key: DecodingKey::from_secret(secret),
416            header,
417            validation: step_up_validation(&issuer, &audience),
418            issuer,
419            audience,
420            challenge_ttl: DEFAULT_STEP_UP_CHALLENGE_TTL.as_secs(),
421            proof_ttl: DEFAULT_STEP_UP_PROOF_TTL.as_secs(),
422        })
423    }
424
425    /// 覆盖 challenge/proof 时限;分别硬限制为 5/10 分钟。
426    pub fn with_ttls(
427        mut self,
428        challenge_ttl: Duration,
429        proof_ttl: Duration,
430    ) -> Result<Self, BaseError> {
431        validate_ttl("challenge", challenge_ttl, MAX_STEP_UP_CHALLENGE_TTL)?;
432        validate_ttl("proof", proof_ttl, MAX_STEP_UP_PROOF_TTL)?;
433        self.challenge_ttl = challenge_ttl.as_secs();
434        self.proof_ttl = proof_ttl.as_secs();
435        Ok(self)
436    }
437
438    /// 为已认证主体和确定的 Action/资源签发 challenge。
439    pub fn issue_challenge(
440        &self,
441        subject: impl Into<String>,
442        action: &ActionRef,
443        resource: &str,
444    ) -> Result<StepUpChallenge, BaseError> {
445        self.issue_challenge_at(
446            subject.into(),
447            action.to_string(),
448            resource,
449            unix_timestamp()?,
450        )
451    }
452
453    /// 重新校验凭据并把 challenge 升级为 proof。
454    ///
455    /// `CredentialVerifier` 返回的 subject 必须与 challenge 完全一致;先解析 challenge,
456    /// 再调用业务 verifier,避免用无效 Token 触发昂贵的密码哈希。
457    ///
458    /// # 限流(实现方必须)
459    ///
460    /// 本方法是凭据猜测的在线入口,**实现方必须**为完成 challenge 的端点配置速率
461    /// 限制与失败计数,本管理器自身不做限流。接线要点:
462    ///
463    /// - 在调用方(重认证 Action 或 [`CredentialVerifier`] 实现内)按
464    ///   `subject + 客户端标识`(如来源 IP、设备指纹)计数连续失败;
465    /// - 超过阈值后按指数退避或直接锁定,并返回 `Unauthorized`,不得泄露锁定原因;
466    /// - 计数与锁定状态应经 `ctx.tools()` 中的共享存储(如 Redis)实现,
467    ///   多实例部署下才有一致的限流视图;
468    /// - `CredentialVerifier` 返回的失败与 challenge 解析失败都应计入失败次数。
469    pub async fn complete_challenge<V>(
470        &self,
471        context: &ActionContext,
472        verifier: &V,
473        credentials: &LoginInput,
474        challenge: &str,
475    ) -> Result<StepUpProof, BaseError>
476    where
477        V: CredentialVerifier,
478    {
479        let challenge = self.decode_kind(challenge, StepUpTokenKind::Challenge)?;
480        let verified = verifier.verify(context, credentials).await?;
481        if verified.subject != challenge.sub {
482            return Err(invalid_step_up("重认证主体与 challenge 不一致"));
483        }
484        self.issue_proof_at(challenge, unix_timestamp()?)
485    }
486
487    /// 校验 proof 与当前主体、Action 和资源是否完全一致。
488    ///
489    /// 成功与失败都会发出审计事件(均含 subject/action/resource_hash,不记录
490    /// proof Token 原文)。成功事件含 proof_id;失败事件按可解码性分两类:
491    /// 签名可解码、因绑定维度不匹配被拒时,额外记录签名背书的
492    /// `claimed_proof_id`/`claimed_resource_hash`(重放取证的关键字段);
493    /// 伪造或过期的 Token 无法解码,没有可信 proof_id,失败事件不含
494    /// `claimed_*` 字段。
495    pub fn verify_proof(
496        &self,
497        proof: &str,
498        subject: &str,
499        action: &ActionRef,
500        resource: &str,
501    ) -> Result<StepUpVerification, BaseError> {
502        let expected_action = action.to_string();
503        let expected_resource = resource_fingerprint(resource);
504        let claims = match self.decode_kind(proof, StepUpTokenKind::Proof) {
505            Ok(claims) => claims,
506            Err(error) => {
507                tracing::warn!(
508                    subject = %subject,
509                    action = %expected_action,
510                    resource_hash = %expected_resource,
511                    reason = %error,
512                    "step-up proof 验证失败"
513                );
514                return Err(error);
515            }
516        };
517        if claims.sub != subject
518            || claims.action != expected_action
519            || claims.resource_hash != expected_resource
520            || claims.challenge_jti.is_none()
521        {
522            let error = invalid_step_up("proof 绑定目标不一致");
523            tracing::warn!(
524                claimed_proof_id = %claims.jti,
525                claimed_resource_hash = %claims.resource_hash,
526                subject = %subject,
527                action = %expected_action,
528                resource_hash = %expected_resource,
529                reason = %error,
530                "step-up proof 验证失败"
531            );
532            return Err(error);
533        }
534        let verification = StepUpVerification {
535            subject: claims.sub,
536            action: claims.action,
537            resource_hash: claims.resource_hash,
538            authenticated_at: claims.iat,
539            expires_at: claims.exp,
540            proof_id: claims.jti,
541        };
542        tracing::info!(
543            proof_id = %verification.proof_id,
544            subject = %verification.subject,
545            action = %verification.action,
546            resource_hash = %verification.resource_hash,
547            "step-up proof 验证成功"
548        );
549        Ok(verification)
550    }
551
552    fn issue_challenge_at(
553        &self,
554        subject: String,
555        action: String,
556        resource: &str,
557        now: u64,
558    ) -> Result<StepUpChallenge, BaseError> {
559        if subject.trim().is_empty() || action.trim().is_empty() || resource.trim().is_empty() {
560            return Err(BaseError::ConfigError(
561                "step-up subject/action/resource 不能为空".to_string(),
562            ));
563        }
564        let claims = StepUpClaims {
565            iss: self.issuer.clone(),
566            sub: subject,
567            aud: self.audience.clone(),
568            exp: now.checked_add(self.challenge_ttl).ok_or_else(|| {
569                BaseError::ConfigError("step-up challenge 过期时间溢出".to_string())
570            })?,
571            iat: now,
572            jti: Uuid::new_v4().to_string(),
573            kind: StepUpTokenKind::Challenge,
574            action,
575            resource_hash: resource_fingerprint(resource),
576            challenge_jti: None,
577        };
578        let challenge = self.encode(&claims)?;
579        tracing::info!(
580            challenge_id = %claims.jti,
581            subject = %claims.sub,
582            action = %claims.action,
583            resource_hash = %claims.resource_hash,
584            "step-up challenge 已签发"
585        );
586        Ok(StepUpChallenge {
587            challenge,
588            expires_in: self.challenge_ttl,
589        })
590    }
591
592    fn issue_proof_at(&self, challenge: StepUpClaims, now: u64) -> Result<StepUpProof, BaseError> {
593        let claims = StepUpClaims {
594            iss: self.issuer.clone(),
595            sub: challenge.sub,
596            aud: self.audience.clone(),
597            exp: now
598                .checked_add(self.proof_ttl)
599                .ok_or_else(|| BaseError::ConfigError("step-up proof 过期时间溢出".to_string()))?,
600            iat: now,
601            jti: Uuid::new_v4().to_string(),
602            kind: StepUpTokenKind::Proof,
603            action: challenge.action,
604            resource_hash: challenge.resource_hash,
605            challenge_jti: Some(challenge.jti),
606        };
607        let proof = self.encode(&claims)?;
608        tracing::info!(
609            proof_id = %claims.jti,
610            challenge_id = %claims.challenge_jti.as_deref().unwrap_or_default(),
611            subject = %claims.sub,
612            action = %claims.action,
613            resource_hash = %claims.resource_hash,
614            "step-up challenge 已完成"
615        );
616        Ok(StepUpProof {
617            proof,
618            expires_in: self.proof_ttl,
619        })
620    }
621
622    fn encode(&self, claims: &StepUpClaims) -> Result<String, BaseError> {
623        encode(&self.header, claims, &self.encoding_key)
624            .map_err(|_| BaseError::ConfigError("step-up Token 签发失败".to_string()))
625    }
626
627    fn decode_kind(
628        &self,
629        token: &str,
630        expected: StepUpTokenKind,
631    ) -> Result<StepUpClaims, BaseError> {
632        let claims = decode::<StepUpClaims>(token, &self.decoding_key, &self.validation)
633            .map_err(|_| invalid_step_up("Token 无效或已过期"))?
634            .claims;
635        if claims.kind != expected {
636            return Err(invalid_step_up("Token 类型不匹配"));
637        }
638        Ok(claims)
639    }
640}
641
642fn step_up_validation(issuer: &str, audience: &str) -> Validation {
643    let mut validation = Validation::new(Algorithm::HS256);
644    validation.algorithms = vec![Algorithm::HS256];
645    validation.set_issuer(&[issuer]);
646    validation.set_audience(&[audience]);
647    validation.required_spec_claims = ["exp", "iss", "aud", "sub"]
648        .into_iter()
649        .map(str::to_string)
650        .collect::<HashSet<_>>();
651    validation.leeway = 0;
652    validation
653}
654
655fn validate_ttl(name: &str, value: Duration, maximum: Duration) -> Result<(), BaseError> {
656    if value.is_zero() || value > maximum {
657        return Err(BaseError::ConfigError(format!(
658            "step-up {name} TTL 必须在 1..={} 秒",
659            maximum.as_secs()
660        )));
661    }
662    Ok(())
663}
664
665fn unix_timestamp() -> Result<u64, BaseError> {
666    SystemTime::now()
667        .duration_since(UNIX_EPOCH)
668        .map(|duration| duration.as_secs())
669        .map_err(|error| BaseError::ConfigError(format!("系统时钟异常: {error}")))
670}
671
672fn resource_fingerprint(resource: &str) -> String {
673    const HEX: &[u8; 16] = b"0123456789abcdef";
674    let digest = Sha256::digest(resource.as_bytes());
675    let mut output = String::with_capacity(digest.len() * 2);
676    for byte in digest {
677        output.push(HEX[usize::from(byte >> 4)] as char);
678        output.push(HEX[usize::from(byte & 0x0f)] as char);
679    }
680    output
681}
682
683fn invalid_step_up(reason: &str) -> BaseError {
684    BaseError::Unauthorized(format!("step-up 验证失败: {reason}"))
685}
686
687#[cfg(test)]
688mod tests {
689    use super::super::auth::VerifiedSubject;
690    use super::*;
691    use crate::action::{Request, TypedHandler, User};
692    use crate::definition::{
693        ActionName, ActionSpec, AddonName, AddonSpec, AppBuilder, HttpMethod, ModuleName,
694        ModuleSpec, RouteSpec,
695    };
696    use crate::tools::ToolsBuilder;
697    use async_trait::async_trait;
698    use schemars::JsonSchema;
699    use serde::{Deserialize, Serialize};
700    use std::sync::Arc;
701
702    const SECRET: &str = "step-up-test-secret-must-be-at-least-32-bytes";
703
704    struct TestVerifier;
705
706    #[derive(Debug, Default, Deserialize, JsonSchema)]
707    #[serde(deny_unknown_fields)]
708    struct EmptyInput {}
709
710    #[derive(Debug, Serialize, JsonSchema)]
711    struct ProbeOutput {
712        operation: &'static str,
713    }
714
715    #[derive(Action)]
716    #[action(name = "delete", display_name = "删除用户")]
717    struct DeleteProbe;
718
719    #[async_trait]
720    impl TypedHandler for DeleteProbe {
721        type Input = EmptyInput;
722        type Output = ProbeOutput;
723
724        async fn handle(
725            &self,
726            _context: ActionContext,
727            _input: Self::Input,
728        ) -> Result<Self::Output, BaseError> {
729            Ok(ProbeOutput {
730                operation: "delete",
731            })
732        }
733    }
734
735    #[derive(Action)]
736    #[action(name = "read", display_name = "读取用户")]
737    struct ReadProbe;
738
739    #[async_trait]
740    impl TypedHandler for ReadProbe {
741        type Input = EmptyInput;
742        type Output = ProbeOutput;
743
744        async fn handle(
745            &self,
746            _context: ActionContext,
747            _input: Self::Input,
748        ) -> Result<Self::Output, BaseError> {
749            Ok(ProbeOutput { operation: "read" })
750        }
751    }
752
753    struct PathResourceResolver;
754
755    #[async_trait]
756    impl StepUpResourceResolver for PathResourceResolver {
757        async fn resolve(&self, context: &ActionContext) -> Result<String, BaseError> {
758            let raw = context
759                .request
760                .get_path_param("id")
761                .ok_or_else(|| BaseError::ParamMissing("id".to_string()))?;
762            let id = raw.parse::<u64>().map_err(|_| {
763                BaseError::ParamInvalid("id".to_string(), "必须是正整数".to_string())
764            })?;
765            if id == 0 {
766                return Err(BaseError::ParamInvalid(
767                    "id".to_string(),
768                    "必须是正整数".to_string(),
769                ));
770            }
771            Ok(format!("org_user:{id}"))
772        }
773    }
774
775    #[async_trait]
776    impl CredentialVerifier for TestVerifier {
777        async fn verify(
778            &self,
779            _context: &ActionContext,
780            input: &LoginInput,
781        ) -> Result<VerifiedSubject, BaseError> {
782            if input.password == "correct-password" {
783                Ok(VerifiedSubject::new(input.username.clone()))
784            } else {
785                Err(BaseError::Unauthorized("凭据错误".to_string()))
786            }
787        }
788    }
789
790    fn manager() -> StepUpManager {
791        StepUpManager::new(SECRET, "yang-test", "yang-sensitive-actions")
792            .expect("测试 step-up manager 应构建成功")
793    }
794
795    fn action_ref(name: &str) -> ActionRef {
796        ActionRef::new(
797            ModuleName::new("org.user").expect("测试 Module 名称应有效"),
798            ActionName::new(name).expect("测试 Action 名称应有效"),
799        )
800    }
801
802    fn context() -> ActionContext {
803        ActionContext::new(
804            Request::new(serde_json::json!({})),
805            Arc::new(ToolsBuilder::new().build().expect("测试 Tools 应构建成功")),
806        )
807    }
808
809    fn test_app(manager: Arc<StepUpManager>) -> crate::definition::BuiltApp {
810        test_app_with_target(manager, action_ref("delete")).expect("step-up 测试应用应构建成功")
811    }
812
813    fn test_app_with_target(
814        manager: Arc<StepUpManager>,
815        target: ActionRef,
816    ) -> Result<crate::definition::BuiltApp, crate::definition::BuildError> {
817        let module_name = ModuleName::new("org.user").expect("测试 Module 名称应有效");
818        let module = ModuleSpec::new(module_name)
819            .middleware(StepUpMiddleware::new(manager, target, PathResourceResolver))
820            .action(
821                ActionSpec::new(
822                    ActionName::new("delete").expect("测试 Action 名称应有效"),
823                    RouteSpec::new(
824                        HttpMethod::Delete,
825                        "/api/v1/org/users/{id}",
826                        "org.user.delete",
827                    ),
828                ),
829                DeleteProbe,
830            )
831            .action(
832                ActionSpec::new(
833                    ActionName::new("read").expect("测试 Action 名称应有效"),
834                    RouteSpec::new(HttpMethod::Get, "/api/v1/org/users/{id}", "org.user.read"),
835                ),
836                ReadProbe,
837            );
838        AppBuilder::new()
839            .addon(
840                AddonSpec::new(AddonName::new("org").expect("测试 Addon 名称应有效"))
841                    .module(module),
842            )
843            .build(Arc::new(
844                ToolsBuilder::new().build().expect("测试 Tools 应构建成功"),
845            ))
846    }
847
848    async fn dispatch_as(
849        app: &crate::definition::BuiltApp,
850        action: &str,
851        request: Request,
852        user: Option<User>,
853    ) -> Result<ApiResponse, BaseError> {
854        let handle = app
855            .registry()
856            .resolve(&action_ref(action))
857            .expect("测试 Action 应已注册");
858        let mut context = app.context(request).with_module("client.forged");
859        if let Some(user) = user {
860            context = context.with_user(user);
861        }
862        app.dispatch_context(handle, context).await
863    }
864
865    fn credentials(subject: &str, password: &str) -> LoginInput {
866        LoginInput {
867            username: subject.to_string(),
868            password: password.to_string(),
869            extra: serde_json::Value::Null,
870        }
871    }
872
873    #[tokio::test]
874    async fn challenge_requires_reauthentication_and_proof_binds_every_dimension() {
875        let manager = manager();
876        let action = action_ref("delete");
877        let resource = "org_user:42";
878        let challenge = manager
879            .issue_challenge("7", &action, resource)
880            .expect("challenge 应签发成功");
881        assert_eq!(
882            challenge.expires_in,
883            DEFAULT_STEP_UP_CHALLENGE_TTL.as_secs()
884        );
885        assert!(
886            !challenge.challenge.contains(resource),
887            "原始资源标识不得写入 Token"
888        );
889
890        let bad_credentials = manager
891            .complete_challenge(
892                &context(),
893                &TestVerifier,
894                &credentials("7", "wrong-password"),
895                &challenge.challenge,
896            )
897            .await;
898        assert!(matches!(bad_credentials, Err(BaseError::Unauthorized(_))));
899
900        let proof = manager
901            .complete_challenge(
902                &context(),
903                &TestVerifier,
904                &credentials("7", "correct-password"),
905                &challenge.challenge,
906            )
907            .await
908            .expect("正确凭据应完成 challenge");
909        assert_eq!(proof.expires_in, DEFAULT_STEP_UP_PROOF_TTL.as_secs());
910        let verified = manager
911            .verify_proof(&proof.proof, "7", &action, resource)
912            .expect("proof 全部绑定维度一致时应通过");
913        assert_eq!(verified.subject, "7");
914        assert_eq!(verified.action, "org.user.delete");
915        assert_eq!(verified.resource_hash.len(), 64);
916        assert!(verified.authenticated_at < verified.expires_at);
917
918        for mismatch in [
919            manager.verify_proof(&proof.proof, "8", &action, resource),
920            manager.verify_proof(&proof.proof, "7", &action_ref("disable"), resource),
921            manager.verify_proof(&proof.proof, "7", &action, "org_user:43"),
922        ] {
923            assert!(
924                matches!(mismatch, Err(BaseError::Unauthorized(_))),
925                "跨主体/Action/资源复用必须失败"
926            );
927        }
928    }
929
930    #[tokio::test]
931    async fn middleware_challenges_then_accepts_only_exact_subject_action_and_resource() {
932        let manager = Arc::new(manager());
933        let app = test_app(Arc::clone(&manager));
934        let request = || Request::new(serde_json::json!({})).path_param("id", "42");
935        let user = User::new(7, "member");
936
937        let missing = dispatch_as(&app, "delete", request(), Some(user.clone())).await;
938        let challenge = match missing {
939            Err(BaseError::StepUpRequired(challenge)) => challenge,
940            other => panic!("缺少 proof 应返回 step-up challenge,实际为: {other:?}"),
941        };
942        assert_eq!(BaseError::StepUpRequired(challenge.clone()).code(), 700010);
943
944        let proof = manager
945            .complete_challenge(
946                &context(),
947                &TestVerifier,
948                &credentials("7", "correct-password"),
949                &challenge.challenge,
950            )
951            .await
952            .expect("正确凭据应换取 proof");
953        let proof_request = || request().header(STEP_UP_PROOF_HEADER, &proof.proof);
954        let response = dispatch_as(&app, "delete", proof_request(), Some(user.clone()))
955            .await
956            .expect("完全绑定的 proof 应允许敏感 Action");
957        assert_eq!(response.data.expect("应返回 data")["operation"], "delete");
958
959        let replay = dispatch_as(&app, "delete", proof_request(), Some(user)).await;
960        assert!(
961            matches!(replay, Err(BaseError::Unauthorized(ref message)) if message.contains("已被消费")),
962            "同一 proof 第二次提交必须被原子消费边界拒绝: {replay:?}"
963        );
964    }
965
966    #[tokio::test]
967    async fn middleware_fails_closed_without_downgrading_invalid_proofs() {
968        let manager = Arc::new(manager());
969        let app = test_app(Arc::clone(&manager));
970        let user = User::new(7, "member");
971        let challenge = manager
972            .issue_challenge("7", &action_ref("delete"), "org_user:42")
973            .expect("challenge 应签发成功");
974        let proof = manager
975            .complete_challenge(
976                &context(),
977                &TestVerifier,
978                &credentials("7", "correct-password"),
979                &challenge.challenge,
980            )
981            .await
982            .expect("proof 应签发成功");
983
984        for request in [
985            Request::new(serde_json::json!({}))
986                .path_param("id", "42")
987                .header(STEP_UP_PROOF_HEADER, ""),
988            Request::new(serde_json::json!({}))
989                .path_param("id", "43")
990                .header(STEP_UP_PROOF_HEADER, &proof.proof),
991        ] {
992            let result = dispatch_as(&app, "delete", request, Some(user.clone())).await;
993            assert!(
994                matches!(result, Err(BaseError::Unauthorized(_))),
995                "空 proof 与跨资源 proof 必须直接拒绝,不能降级为 challenge: {result:?}"
996            );
997        }
998
999        let unauthenticated = dispatch_as(
1000            &app,
1001            "delete",
1002            Request::new(serde_json::json!({})).path_param("id", "42"),
1003            None,
1004        )
1005        .await;
1006        assert!(matches!(unauthenticated, Err(BaseError::Unauthorized(_))));
1007
1008        for invalid_id in [None, Some("0"), Some("not-a-number")] {
1009            let mut request = Request::new(serde_json::json!({}));
1010            if let Some(id) = invalid_id {
1011                request = request.path_param("id", id);
1012            }
1013            let result = dispatch_as(&app, "delete", request, Some(user.clone())).await;
1014            assert!(
1015                matches!(
1016                    result,
1017                    Err(BaseError::ParamMissing(_)) | Err(BaseError::ParamInvalid(_, _))
1018                ),
1019                "资源解析必须 fail-closed: {result:?}"
1020            );
1021        }
1022    }
1023
1024    #[tokio::test]
1025    async fn middleware_uses_registry_target_and_skips_unrelated_actions() {
1026        let manager = Arc::new(manager());
1027        let app = test_app(manager);
1028        let user = User::new(7, "member");
1029
1030        let response = dispatch_as(
1031            &app,
1032            "read",
1033            Request::new(serde_json::json!({})).path_param("id", "42"),
1034            Some(user),
1035        )
1036        .await
1037        .expect("非目标 Action 不应被 step-up 拦截");
1038        assert_eq!(response.data.expect("应返回 data")["operation"], "read");
1039    }
1040
1041    /// 锁定语义:step-up 仅约束 dispatch 路径;`Registry::call`/`Plugins::api_run`
1042    /// 内部调用不经过中间件链,敏感 Action 无需 proof 即可执行。
1043    /// 若日后调整该语义,必须同步修改 `StepUpMiddleware` 与 `Registry::call` 的文档。
1044    #[tokio::test]
1045    async fn internal_call_bypasses_step_up_middleware_by_design() {
1046        let manager = Arc::new(manager());
1047        let app = test_app(manager);
1048        let handle = app
1049            .registry()
1050            .resolve_typed::<EmptyInput, ProbeOutput>(&action_ref("delete"))
1051            .expect("敏感 Action 应可解析为强类型句柄");
1052
1053        // Registry::call:无 proof 直接成功(policy 仍要求已认证用户)
1054        let context = app
1055            .context(Request::new(serde_json::json!({})))
1056            .with_user(User::new(7, "member"));
1057        let output = app
1058            .registry()
1059            .call(handle, context, EmptyInput {})
1060            .await
1061            .expect("内部 call 不经过 step-up 中间件,应无需 proof 直接成功");
1062        assert_eq!(output.operation, "delete");
1063
1064        // Plugins::api_run:同一内部路径,同样不经过 step-up 中间件
1065        let context = app
1066            .context(Request::new(serde_json::json!({})))
1067            .with_user(User::new(7, "member"));
1068        let output = context
1069            .plugins()
1070            .expect("测试上下文应已绑定 Registry")
1071            .api_run(handle, EmptyInput {})
1072            .await
1073            .expect("api_run 不经过 step-up 中间件,应无需 proof 直接成功");
1074        assert_eq!(output.operation, "delete");
1075    }
1076
1077    #[test]
1078    fn app_rejects_missing_or_cross_module_step_up_targets() {
1079        let manager = Arc::new(manager());
1080        let missing = test_app_with_target(Arc::clone(&manager), action_ref("destroy"));
1081        assert!(matches!(
1082            missing,
1083            Err(crate::definition::BuildError::InvalidReference {
1084                kind: "Middleware Action",
1085                reference,
1086            }) if reference == "org.user.destroy"
1087        ));
1088
1089        let cross_module = ActionRef::new(
1090            ModuleName::new("other.user").expect("测试 Module 名称应有效"),
1091            ActionName::new("delete").expect("测试 Action 名称应有效"),
1092        );
1093        let cross = test_app_with_target(manager, cross_module);
1094        assert!(matches!(
1095            cross,
1096            Err(crate::definition::BuildError::InvalidReference {
1097                kind: "Middleware Action",
1098                reference,
1099            }) if reference == "other.user.delete"
1100        ));
1101    }
1102
1103    #[tokio::test]
1104    async fn challenge_cannot_be_completed_as_another_subject_or_used_as_proof() {
1105        let manager = manager();
1106        let action = action_ref("delete");
1107        let challenge = manager
1108            .issue_challenge("7", &action, "org_user:42")
1109            .expect("challenge 应签发成功");
1110
1111        let cross_subject = manager
1112            .complete_challenge(
1113                &context(),
1114                &TestVerifier,
1115                &credentials("8", "correct-password"),
1116                &challenge.challenge,
1117            )
1118            .await;
1119        assert!(matches!(cross_subject, Err(BaseError::Unauthorized(_))));
1120        assert!(matches!(
1121            manager.verify_proof(&challenge.challenge, "7", &action, "org_user:42"),
1122            Err(BaseError::Unauthorized(_))
1123        ));
1124    }
1125
1126    #[tokio::test]
1127    async fn tampered_expired_and_wrong_kind_tokens_are_rejected() {
1128        let manager = manager();
1129        let action = action_ref("delete");
1130        let resource = "org_user:42";
1131        let challenge = manager
1132            .issue_challenge("7", &action, resource)
1133            .expect("challenge 应签发成功");
1134        let proof = manager
1135            .complete_challenge(
1136                &context(),
1137                &TestVerifier,
1138                &credentials("7", "correct-password"),
1139                &challenge.challenge,
1140            )
1141            .await
1142            .expect("proof 应签发成功");
1143
1144        let tampered = tamper_signature(&proof.proof);
1145        assert!(matches!(
1146            manager.verify_proof(&tampered, "7", &action, resource),
1147            Err(BaseError::Unauthorized(_))
1148        ));
1149        let valid_claims = manager
1150            .decode_kind(&proof.proof, StepUpTokenKind::Proof)
1151            .expect("测试 proof 应可解析");
1152        let wrong_algorithm = jsonwebtoken::encode(
1153            &Header::new(Algorithm::HS512),
1154            &valid_claims,
1155            &EncodingKey::from_secret(SECRET.as_bytes()),
1156        )
1157        .expect("错误算法测试 Token 应可签发");
1158        assert!(matches!(
1159            manager.verify_proof(&wrong_algorithm, "7", &action, resource),
1160            Err(BaseError::Unauthorized(_))
1161        ));
1162        let mut wrong_domain_claims = valid_claims;
1163        wrong_domain_claims.aud = "another-audience".to_string();
1164        let wrong_domain = manager
1165            .encode(&wrong_domain_claims)
1166            .expect("错误域测试 Token 应可签发");
1167        assert!(matches!(
1168            manager.verify_proof(&wrong_domain, "7", &action, resource),
1169            Err(BaseError::Unauthorized(_))
1170        ));
1171        let proof_as_challenge = manager
1172            .complete_challenge(
1173                &context(),
1174                &TestVerifier,
1175                &credentials("7", "correct-password"),
1176                &proof.proof,
1177            )
1178            .await;
1179        assert!(matches!(
1180            proof_as_challenge,
1181            Err(BaseError::Unauthorized(_))
1182        ));
1183
1184        let expired_challenge = manager
1185            .encode(&claims(
1186                &manager,
1187                StepUpTokenKind::Challenge,
1188                1,
1189                None,
1190                &action,
1191                resource,
1192            ))
1193            .expect("过期 challenge 测试 Token 应编码成功");
1194        let expired = manager
1195            .complete_challenge(
1196                &context(),
1197                &TestVerifier,
1198                &credentials("7", "correct-password"),
1199                &expired_challenge,
1200            )
1201            .await;
1202        assert!(matches!(expired, Err(BaseError::Unauthorized(_))));
1203
1204        let expired_proof = manager
1205            .encode(&claims(
1206                &manager,
1207                StepUpTokenKind::Proof,
1208                1,
1209                Some("challenge-id".to_string()),
1210                &action,
1211                resource,
1212            ))
1213            .expect("过期 proof 测试 Token 应编码成功");
1214        assert!(matches!(
1215            manager.verify_proof(&expired_proof, "7", &action, resource),
1216            Err(BaseError::Unauthorized(_))
1217        ));
1218    }
1219
1220    /// 审计事件:challenge 签发、challenge 完成、proof 验证成功/失败四处
1221    /// 必须发出 tracing 事件,携带 proof_id/subject/action/resource_hash,
1222    /// 且不得泄露 challenge/proof Token 与资源原文。
1223    #[tokio::test]
1224    async fn audit_events_cover_the_full_sensitive_lifecycle() {
1225        use std::io::Write;
1226        use std::sync::Mutex;
1227
1228        // 自定义 MakeWriter:将 tracing fmt 输出捕获到内存缓冲区(同 transport_axum 的 warn 捕获模式)
1229        struct BufWriter {
1230            buf: Arc<Mutex<Vec<u8>>>,
1231        }
1232        impl Write for BufWriter {
1233            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1234                self.buf.lock().expect("缓冲区锁不应中毒").write(buf)
1235            }
1236            fn flush(&mut self) -> std::io::Result<()> {
1237                self.buf.lock().expect("缓冲区锁不应中毒").flush()
1238            }
1239        }
1240        struct BufMakeWriter {
1241            buf: Arc<Mutex<Vec<u8>>>,
1242        }
1243        impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for BufMakeWriter {
1244            type Writer = BufWriter;
1245            fn make_writer(&'a self) -> Self::Writer {
1246                BufWriter {
1247                    buf: self.buf.clone(),
1248                }
1249            }
1250        }
1251
1252        let buf = Arc::new(Mutex::new(Vec::new()));
1253        let subscriber = tracing_subscriber::fmt()
1254            .with_writer(BufMakeWriter { buf: buf.clone() })
1255            .with_ansi(false)
1256            .finish();
1257        // 必须用全局默认订阅器,而非线程局部 `set_default`:
1258        // 并行测试会在无订阅器的线程上命中同一 callsite,把兴趣缓存为 never,
1259        // 线程局部订阅器无法再重建这些缓存(tracing 的 JustOne 快路径),
1260        // 导致事件被静默跳过、断言 flaky。全局默认在注册时重建全部 callsite,
1261        // 且作为所有线程的回退默认参与后续 callsite 注册,语义确定。
1262        // 代价:进程内其他测试的事件也会进入缓冲区,故断言一律用 contains。
1263        tracing::subscriber::set_global_default(subscriber)
1264            .expect("step-up 审计测试要求全局默认订阅器未被占用");
1265
1266        let manager = manager();
1267        let action = action_ref("delete");
1268        let resource = "org_user:42";
1269        let challenge = manager
1270            .issue_challenge("7", &action, resource)
1271            .expect("challenge 应签发成功");
1272        let proof = manager
1273            .complete_challenge(
1274                &context(),
1275                &TestVerifier,
1276                &credentials("7", "correct-password"),
1277                &challenge.challenge,
1278            )
1279            .await
1280            .expect("proof 应签发成功");
1281        let verified = manager
1282            .verify_proof(&proof.proof, "7", &action, resource)
1283            .expect("proof 应验证成功");
1284        let rejected = manager.verify_proof(&proof.proof, "7", &action, "org_user:43");
1285        assert!(matches!(rejected, Err(BaseError::Unauthorized(_))));
1286        let tampered = tamper_signature(&proof.proof);
1287        assert!(matches!(
1288            manager.verify_proof(&tampered, "7", &action, resource),
1289            Err(BaseError::Unauthorized(_))
1290        ));
1291
1292        let output = String::from_utf8(buf.lock().expect("缓冲区锁不应中毒").clone())
1293            .expect("审计输出应为 UTF-8");
1294        for event in [
1295            "step-up challenge 已签发",
1296            "step-up challenge 已完成",
1297            "step-up proof 验证成功",
1298            "step-up proof 验证失败",
1299        ] {
1300            assert!(output.contains(event), "缺少审计事件 {event}: {output}");
1301        }
1302        assert!(
1303            output.contains(&verified.proof_id),
1304            "审计事件应携带 proof_id: {output}"
1305        );
1306        assert!(
1307            output.contains("subject=7"),
1308            "审计事件应携带 subject: {output}"
1309        );
1310        assert!(
1311            output.contains("org.user.delete"),
1312            "审计事件应携带 action: {output}"
1313        );
1314        assert!(
1315            output.contains(&verified.resource_hash),
1316            "审计事件应携带 resource_hash: {output}"
1317        );
1318        // 绑定不匹配(重放攻击面):失败事件必须记录签名背书的真实声明,供取证关联
1319        let failure_lines: Vec<&str> = output
1320            .lines()
1321            .filter(|line| line.contains("step-up proof 验证失败"))
1322            .collect();
1323        assert!(
1324            failure_lines
1325                .iter()
1326                .any(|line| line.contains(&format!("claimed_proof_id={}", verified.proof_id))),
1327            "绑定不匹配失败事件应记录 claimed_proof_id: {output}"
1328        );
1329        assert!(
1330            failure_lines
1331                .iter()
1332                .any(|line| line
1333                    .contains(&format!("claimed_resource_hash={}", verified.resource_hash))),
1334            "绑定不匹配失败事件应记录 claimed_resource_hash: {output}"
1335        );
1336        // 伪造 Token 无法解码:没有可信 proof_id,失败事件不得虚构 claimed_* 字段
1337        assert!(
1338            failure_lines
1339                .iter()
1340                .any(|line| line.contains("无效或已过期") && !line.contains("claimed_proof_id")),
1341            "不可解码的失败事件不应携带 claimed_proof_id: {output}"
1342        );
1343        assert!(
1344            !output.contains(resource),
1345            "审计事件不得携带资源原文: {output}"
1346        );
1347        assert!(
1348            !output.contains(&proof.proof),
1349            "审计事件不得携带 proof Token 原文"
1350        );
1351        assert!(
1352            !output.contains(&challenge.challenge),
1353            "审计事件不得携带 challenge Token 原文"
1354        );
1355    }
1356
1357    #[test]
1358    fn manager_rejects_weak_secrets_empty_domains_and_long_ttls() {
1359        assert!(matches!(
1360            StepUpManager::new("short", "issuer", "audience"),
1361            Err(BaseError::ConfigError(_))
1362        ));
1363        assert!(matches!(
1364            StepUpManager::new(SECRET, "", "audience"),
1365            Err(BaseError::ConfigError(_))
1366        ));
1367        assert!(matches!(
1368            manager().with_ttls(Duration::ZERO, DEFAULT_STEP_UP_PROOF_TTL),
1369            Err(BaseError::ConfigError(_))
1370        ));
1371        assert!(matches!(
1372            manager().with_ttls(
1373                DEFAULT_STEP_UP_CHALLENGE_TTL,
1374                MAX_STEP_UP_PROOF_TTL + Duration::from_secs(1),
1375            ),
1376            Err(BaseError::ConfigError(_))
1377        ));
1378        assert!(matches!(
1379            manager().issue_challenge("7", &action_ref("delete"), ""),
1380            Err(BaseError::ConfigError(_))
1381        ));
1382    }
1383
1384    fn claims(
1385        manager: &StepUpManager,
1386        kind: StepUpTokenKind,
1387        exp: u64,
1388        challenge_jti: Option<String>,
1389        action: &ActionRef,
1390        resource: &str,
1391    ) -> StepUpClaims {
1392        StepUpClaims {
1393            iss: manager.issuer.clone(),
1394            sub: "7".to_string(),
1395            aud: manager.audience.clone(),
1396            exp,
1397            iat: 0,
1398            jti: "expired-token-id".to_string(),
1399            kind,
1400            action: action.to_string(),
1401            resource_hash: resource_fingerprint(resource),
1402            challenge_jti,
1403        }
1404    }
1405
1406    fn tamper_signature(token: &str) -> String {
1407        let mut bytes = token.as_bytes().to_vec();
1408        let signature = bytes
1409            .iter()
1410            .rposition(|byte| *byte == b'.')
1411            .map(|index| index + 1)
1412            .expect("JWT 应包含签名段");
1413        bytes[signature] = if bytes[signature] == b'A' { b'B' } else { b'A' };
1414        String::from_utf8(bytes).expect("JWT 应是 UTF-8 ASCII")
1415    }
1416}