1use 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::{
14 decode, decode_header, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation,
15};
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18use std::collections::{HashMap, HashSet};
19use std::fmt;
20use std::sync::{Arc, Mutex};
21use std::time::{Duration, SystemTime, UNIX_EPOCH};
22use uuid::Uuid;
23use yang_base_derive::Action;
24
25pub const DEFAULT_STEP_UP_CHALLENGE_TTL: Duration = Duration::from_secs(120);
27pub const DEFAULT_STEP_UP_PROOF_TTL: Duration = Duration::from_secs(300);
29const MAX_STEP_UP_CHALLENGE_TTL: Duration = Duration::from_secs(300);
30const MAX_STEP_UP_PROOF_TTL: Duration = Duration::from_secs(600);
31const MIN_STEP_UP_SECRET_BYTES: usize = 32;
32const MAX_STEP_UP_RETIRING_KEYS: usize = 8;
33
34pub const STEP_UP_PROOF_HEADER: &str = "x-step-up-proof";
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39enum StepUpTokenKind {
40 Challenge,
41 Proof,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
45struct StepUpClaims {
46 iss: String,
47 sub: String,
48 aud: String,
49 exp: u64,
50 iat: u64,
51 jti: String,
52 kind: StepUpTokenKind,
53 action: String,
54 resource_hash: String,
55 challenge_jti: Option<String>,
56}
57
58#[derive(Clone, Serialize, schemars::JsonSchema)]
60pub struct StepUpChallenge {
61 pub challenge: String,
63 pub expires_in: u64,
65}
66
67impl fmt::Debug for StepUpChallenge {
68 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
69 formatter
70 .debug_struct("StepUpChallenge")
71 .field(
72 "challenge",
73 &format_args!("[REDACTED:{}]", self.challenge.len()),
74 )
75 .field("expires_in", &self.expires_in)
76 .finish()
77 }
78}
79
80#[derive(Clone, Serialize, schemars::JsonSchema)]
82pub struct StepUpProof {
83 pub proof: String,
85 pub expires_in: u64,
87}
88
89impl fmt::Debug for StepUpProof {
90 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
91 formatter
92 .debug_struct("StepUpProof")
93 .field("proof", &format_args!("[REDACTED:{}]", self.proof.len()))
94 .field("expires_in", &self.expires_in)
95 .finish()
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct StepUpVerification {
102 pub subject: String,
104 pub action: String,
106 pub resource_hash: String,
108 pub authenticated_at: u64,
110 pub expires_at: u64,
112 pub proof_id: String,
114}
115
116#[derive(Clone, Deserialize, schemars::JsonSchema)]
118#[serde(deny_unknown_fields)]
119pub struct StepUpCompleteInput {
120 pub challenge: String,
122 pub credentials: LoginInput,
124}
125
126#[derive(Action)]
131#[action(
132 name = "step_up_complete",
133 display_name = "完成敏感操作重认证",
134 description = "重新校验凭据并把 step-up challenge 升级为一次性 proof",
135 method = "POST",
136 path = "/step-up/complete",
137 public
138)]
139pub struct StepUpCompleteAction<V: CredentialVerifier> {
140 manager: Arc<StepUpManager>,
141 verifier: V,
142}
143
144impl<V: CredentialVerifier> StepUpCompleteAction<V> {
145 pub fn new(manager: Arc<StepUpManager>, verifier: V) -> Self {
147 Self { manager, verifier }
148 }
149}
150
151#[async_trait]
152impl<V: CredentialVerifier> super::TypedHandler for StepUpCompleteAction<V> {
153 type Input = StepUpCompleteInput;
154 type Output = StepUpProof;
155
156 async fn handle(
157 &self,
158 context: ActionContext,
159 input: Self::Input,
160 ) -> Result<Self::Output, BaseError> {
161 self.manager
162 .complete_challenge(
163 &context,
164 &self.verifier,
165 &input.credentials,
166 &input.challenge,
167 )
168 .await
169 }
170}
171
172#[async_trait]
177pub trait StepUpProofStore: Send + Sync + 'static {
178 async fn consume(&self, proof: &StepUpVerification) -> Result<bool, BaseError>;
180}
181
182#[derive(Debug, Default)]
187pub struct InMemoryStepUpProofStore {
188 consumed: Mutex<HashMap<String, u64>>,
189}
190
191#[async_trait]
192impl StepUpProofStore for InMemoryStepUpProofStore {
193 async fn consume(&self, proof: &StepUpVerification) -> Result<bool, BaseError> {
194 let now = unix_timestamp()?;
195 let mut consumed = self.consumed.lock().map_err(|_| {
196 BaseError::ConfigError("step-up proof 内存消费存储锁已损坏".to_string())
197 })?;
198 consumed.retain(|_, expires_at| *expires_at > now);
199 if consumed.contains_key(&proof.proof_id) {
200 return Ok(false);
201 }
202 consumed.insert(proof.proof_id.clone(), proof.expires_at);
203 Ok(true)
204 }
205}
206
207#[derive(Clone)]
209pub struct RedisStepUpProofStore {
210 cache: yang_db::RedisClient,
211 key_prefix: String,
212}
213
214impl RedisStepUpProofStore {
215 pub fn new(cache: yang_db::RedisClient) -> Self {
217 Self {
218 cache,
219 key_prefix: "yang:step-up:proof-used:".to_string(),
220 }
221 }
222
223 pub fn with_key_prefix(mut self, key_prefix: impl Into<String>) -> Result<Self, BaseError> {
225 let key_prefix = key_prefix.into();
226 if key_prefix.trim().is_empty() {
227 return Err(BaseError::ConfigError(
228 "step-up proof Redis key 前缀不能为空".to_string(),
229 ));
230 }
231 self.key_prefix = key_prefix;
232 Ok(self)
233 }
234}
235
236#[async_trait]
237impl StepUpProofStore for RedisStepUpProofStore {
238 async fn consume(&self, proof: &StepUpVerification) -> Result<bool, BaseError> {
239 let now = unix_timestamp()?;
240 let ttl = proof.expires_at.saturating_sub(now).max(1);
241 let ttl = i64::try_from(ttl)
242 .map_err(|_| BaseError::ConfigError("step-up proof Redis TTL 超出范围".to_string()))?;
243 self.cache
244 .set_nx_ex(format!("{}{}", self.key_prefix, proof.proof_id), "1", ttl)
245 .await
246 .map_err(BaseError::from)
247 }
248}
249
250#[async_trait]
264pub trait StepUpResourceResolver: Send + Sync + 'static {
265 async fn resolve(&self, context: &ActionContext) -> Result<String, BaseError>;
267}
268
269pub struct StepUpMiddleware<R> {
284 manager: Arc<StepUpManager>,
285 action: ActionRef,
286 resolver: R,
287 proof_store: Arc<dyn StepUpProofStore>,
288}
289
290impl<R> StepUpMiddleware<R>
291where
292 R: StepUpResourceResolver,
293{
294 pub fn new(manager: Arc<StepUpManager>, action: ActionRef, resolver: R) -> Self {
296 Self {
297 manager,
298 action,
299 resolver,
300 proof_store: Arc::new(InMemoryStepUpProofStore::default()),
301 }
302 }
303
304 #[must_use]
308 pub fn with_proof_store<S>(mut self, proof_store: S) -> Self
309 where
310 S: StepUpProofStore,
311 {
312 self.proof_store = Arc::new(proof_store);
313 self
314 }
315}
316
317#[async_trait]
318impl<R> Middleware for StepUpMiddleware<R>
319where
320 R: StepUpResourceResolver,
321{
322 fn role(&self) -> MiddlewareRole {
323 MiddlewareRole::StepUpProtection
324 }
325
326 fn target_action(&self) -> Option<&ActionRef> {
327 Some(&self.action)
328 }
329
330 async fn handle(
331 &self,
332 context: ActionContext,
333 next: Next<'_>,
334 ) -> Result<ApiResponse, BaseError> {
335 let (module, action) = context
336 .dispatch_target()
337 .ok_or_else(|| BaseError::ConfigError("step-up 中间件缺少可信派发目标".to_string()))?;
338 if module != self.action.module().as_str() || action != self.action.action().as_str() {
339 return next.run(context).await;
340 }
341
342 let subject = context
343 .authenticated_user()
344 .ok_or_else(|| BaseError::Unauthorized("step-up 需要已认证用户".to_string()))?
345 .id
346 .to_string();
347 let resource = self.resolver.resolve(&context).await?;
348 if resource.trim().is_empty() {
349 return Err(BaseError::ConfigError(
350 "step-up 资源解析器返回了空标识".to_string(),
351 ));
352 }
353
354 match context.request.get_header(STEP_UP_PROOF_HEADER) {
355 Some(proof) => {
356 let verification =
357 self.manager
358 .verify_proof(proof, &subject, &self.action, &resource)?;
359 if !self.proof_store.consume(&verification).await? {
360 tracing::warn!(
361 proof_id = %verification.proof_id,
362 subject = %verification.subject,
363 action = %verification.action,
364 resource_hash = %verification.resource_hash,
365 "step-up proof 重放被拒绝"
366 );
367 return Err(invalid_step_up("proof 已被消费"));
368 }
369 next.run(context).await
370 }
371 None => Err(BaseError::StepUpRequired(self.manager.issue_challenge(
372 subject,
373 &self.action,
374 &resource,
375 )?)),
376 }
377 }
378}
379
380pub struct StepUpManager {
382 encoding_key: EncodingKey,
383 decoding_keys: HashMap<String, DecodingKey>,
384 legacy_decoding_key: Option<DecodingKey>,
385 header: Header,
386 validation: Validation,
387 issuer: String,
388 audience: String,
389 challenge_ttl: u64,
390 proof_ttl: u64,
391}
392
393impl StepUpManager {
394 pub fn new(
398 secret: impl AsRef<[u8]>,
399 issuer: impl Into<String>,
400 audience: impl Into<String>,
401 ) -> Result<Self, BaseError> {
402 let secret = secret.as_ref();
403 if secret.len() < MIN_STEP_UP_SECRET_BYTES {
404 return Err(BaseError::ConfigError(
405 "step-up HMAC 密钥至少需要 32 字节".to_string(),
406 ));
407 }
408 let issuer = issuer.into();
409 let audience = audience.into();
410 if issuer.trim().is_empty() || audience.trim().is_empty() {
411 return Err(BaseError::ConfigError(
412 "step-up issuer/audience 不能为空".to_string(),
413 ));
414 }
415 let mut header = Header::new(Algorithm::HS256);
416 header.typ = Some("step-up+jwt".to_string());
417 Ok(Self {
418 encoding_key: EncodingKey::from_secret(secret),
419 decoding_keys: HashMap::new(),
420 legacy_decoding_key: Some(DecodingKey::from_secret(secret)),
421 header,
422 validation: step_up_validation(&issuer, &audience),
423 issuer,
424 audience,
425 challenge_ttl: DEFAULT_STEP_UP_CHALLENGE_TTL.as_secs(),
426 proof_ttl: DEFAULT_STEP_UP_PROOF_TTL.as_secs(),
427 })
428 }
429
430 pub fn new_with_keyring<I, K, S>(
436 active_kid: impl Into<String>,
437 active_secret: impl AsRef<[u8]>,
438 retiring_keys: I,
439 issuer: impl Into<String>,
440 audience: impl Into<String>,
441 ) -> Result<Self, BaseError>
442 where
443 I: IntoIterator<Item = (K, S)>,
444 K: Into<String>,
445 S: AsRef<[u8]>,
446 {
447 let active_kid = active_kid.into();
448 validate_step_up_kid(&active_kid)?;
449 let active_secret = active_secret.as_ref();
450 validate_step_up_secret(active_secret)?;
451
452 let retiring_keys = retiring_keys.into_iter().collect::<Vec<_>>();
453 if retiring_keys.len() > MAX_STEP_UP_RETIRING_KEYS {
454 return Err(BaseError::ConfigError(format!(
455 "step-up retiring keys 最多允许 {MAX_STEP_UP_RETIRING_KEYS} 把"
456 )));
457 }
458 let mut decoding_keys = HashMap::with_capacity(retiring_keys.len() + 1);
459 decoding_keys.insert(active_kid.clone(), DecodingKey::from_secret(active_secret));
460 let mut seen_secrets = HashSet::with_capacity(retiring_keys.len() + 1);
461 seen_secrets.insert(active_secret.to_vec());
462 for (kid, secret) in retiring_keys {
463 let kid = kid.into();
464 validate_step_up_kid(&kid)?;
465 let secret = secret.as_ref();
466 validate_step_up_secret(secret)?;
467 if decoding_keys.contains_key(&kid) {
468 return Err(BaseError::ConfigError(format!(
469 "step-up key id 重复: {kid}"
470 )));
471 }
472 if !seen_secrets.insert(secret.to_vec()) {
473 return Err(BaseError::ConfigError(
474 "step-up active/retiring keys 不得复用同一密钥".to_string(),
475 ));
476 }
477 decoding_keys.insert(kid, DecodingKey::from_secret(secret));
478 }
479
480 let issuer = issuer.into();
481 let audience = audience.into();
482 if issuer.trim().is_empty() || audience.trim().is_empty() {
483 return Err(BaseError::ConfigError(
484 "step-up issuer/audience 不能为空".to_string(),
485 ));
486 }
487 let mut header = Header::new(Algorithm::HS256);
488 header.typ = Some("step-up+jwt".to_string());
489 header.kid = Some(active_kid);
490 Ok(Self {
491 encoding_key: EncodingKey::from_secret(active_secret),
492 decoding_keys,
493 legacy_decoding_key: None,
494 header,
495 validation: step_up_validation(&issuer, &audience),
496 issuer,
497 audience,
498 challenge_ttl: DEFAULT_STEP_UP_CHALLENGE_TTL.as_secs(),
499 proof_ttl: DEFAULT_STEP_UP_PROOF_TTL.as_secs(),
500 })
501 }
502
503 pub fn with_ttls(
505 mut self,
506 challenge_ttl: Duration,
507 proof_ttl: Duration,
508 ) -> Result<Self, BaseError> {
509 validate_ttl("challenge", challenge_ttl, MAX_STEP_UP_CHALLENGE_TTL)?;
510 validate_ttl("proof", proof_ttl, MAX_STEP_UP_PROOF_TTL)?;
511 self.challenge_ttl = challenge_ttl.as_secs();
512 self.proof_ttl = proof_ttl.as_secs();
513 Ok(self)
514 }
515
516 pub fn issue_challenge(
518 &self,
519 subject: impl Into<String>,
520 action: &ActionRef,
521 resource: &str,
522 ) -> Result<StepUpChallenge, BaseError> {
523 self.issue_challenge_at(
524 subject.into(),
525 action.to_string(),
526 resource,
527 unix_timestamp()?,
528 )
529 }
530
531 pub async fn complete_challenge<V>(
548 &self,
549 context: &ActionContext,
550 verifier: &V,
551 credentials: &LoginInput,
552 challenge: &str,
553 ) -> Result<StepUpProof, BaseError>
554 where
555 V: CredentialVerifier,
556 {
557 let challenge = self.decode_kind(challenge, StepUpTokenKind::Challenge)?;
558 let verified = verifier.verify(context, credentials).await?;
559 if verified.subject != challenge.sub {
560 return Err(invalid_step_up("重认证主体与 challenge 不一致"));
561 }
562 self.issue_proof_at(challenge, unix_timestamp()?)
563 }
564
565 pub fn verify_proof(
574 &self,
575 proof: &str,
576 subject: &str,
577 action: &ActionRef,
578 resource: &str,
579 ) -> Result<StepUpVerification, BaseError> {
580 let expected_action = action.to_string();
581 let expected_resource = resource_fingerprint(resource);
582 let claims = match self.decode_kind(proof, StepUpTokenKind::Proof) {
583 Ok(claims) => claims,
584 Err(error) => {
585 tracing::warn!(
586 subject = %subject,
587 action = %expected_action,
588 resource_hash = %expected_resource,
589 reason = %error,
590 "step-up proof 验证失败"
591 );
592 return Err(error);
593 }
594 };
595 if claims.sub != subject
596 || claims.action != expected_action
597 || claims.resource_hash != expected_resource
598 || claims.challenge_jti.is_none()
599 {
600 let error = invalid_step_up("proof 绑定目标不一致");
601 tracing::warn!(
602 claimed_proof_id = %claims.jti,
603 claimed_resource_hash = %claims.resource_hash,
604 subject = %subject,
605 action = %expected_action,
606 resource_hash = %expected_resource,
607 reason = %error,
608 "step-up proof 验证失败"
609 );
610 return Err(error);
611 }
612 let verification = StepUpVerification {
613 subject: claims.sub,
614 action: claims.action,
615 resource_hash: claims.resource_hash,
616 authenticated_at: claims.iat,
617 expires_at: claims.exp,
618 proof_id: claims.jti,
619 };
620 tracing::info!(
621 proof_id = %verification.proof_id,
622 subject = %verification.subject,
623 action = %verification.action,
624 resource_hash = %verification.resource_hash,
625 "step-up proof 验证成功"
626 );
627 Ok(verification)
628 }
629
630 fn issue_challenge_at(
631 &self,
632 subject: String,
633 action: String,
634 resource: &str,
635 now: u64,
636 ) -> Result<StepUpChallenge, BaseError> {
637 if subject.trim().is_empty() || action.trim().is_empty() || resource.trim().is_empty() {
638 return Err(BaseError::ConfigError(
639 "step-up subject/action/resource 不能为空".to_string(),
640 ));
641 }
642 let claims = StepUpClaims {
643 iss: self.issuer.clone(),
644 sub: subject,
645 aud: self.audience.clone(),
646 exp: now.checked_add(self.challenge_ttl).ok_or_else(|| {
647 BaseError::ConfigError("step-up challenge 过期时间溢出".to_string())
648 })?,
649 iat: now,
650 jti: Uuid::new_v4().to_string(),
651 kind: StepUpTokenKind::Challenge,
652 action,
653 resource_hash: resource_fingerprint(resource),
654 challenge_jti: None,
655 };
656 let challenge = self.encode(&claims)?;
657 tracing::info!(
658 challenge_id = %claims.jti,
659 subject = %claims.sub,
660 action = %claims.action,
661 resource_hash = %claims.resource_hash,
662 "step-up challenge 已签发"
663 );
664 Ok(StepUpChallenge {
665 challenge,
666 expires_in: self.challenge_ttl,
667 })
668 }
669
670 fn issue_proof_at(&self, challenge: StepUpClaims, now: u64) -> Result<StepUpProof, BaseError> {
671 let claims = StepUpClaims {
672 iss: self.issuer.clone(),
673 sub: challenge.sub,
674 aud: self.audience.clone(),
675 exp: now
676 .checked_add(self.proof_ttl)
677 .ok_or_else(|| BaseError::ConfigError("step-up proof 过期时间溢出".to_string()))?,
678 iat: now,
679 jti: Uuid::new_v4().to_string(),
680 kind: StepUpTokenKind::Proof,
681 action: challenge.action,
682 resource_hash: challenge.resource_hash,
683 challenge_jti: Some(challenge.jti),
684 };
685 let proof = self.encode(&claims)?;
686 tracing::info!(
687 proof_id = %claims.jti,
688 challenge_id = %claims.challenge_jti.as_deref().unwrap_or_default(),
689 subject = %claims.sub,
690 action = %claims.action,
691 resource_hash = %claims.resource_hash,
692 "step-up challenge 已完成"
693 );
694 Ok(StepUpProof {
695 proof,
696 expires_in: self.proof_ttl,
697 })
698 }
699
700 fn encode(&self, claims: &StepUpClaims) -> Result<String, BaseError> {
701 encode(&self.header, claims, &self.encoding_key)
702 .map_err(|_| BaseError::ConfigError("step-up Token 签发失败".to_string()))
703 }
704
705 fn decode_kind(
706 &self,
707 token: &str,
708 expected: StepUpTokenKind,
709 ) -> Result<StepUpClaims, BaseError> {
710 let header = decode_header(token).map_err(|_| invalid_step_up("Token header 无效"))?;
711 if header.alg != Algorithm::HS256 || header.typ.as_deref() != Some("step-up+jwt") {
712 return Err(invalid_step_up("Token header 不匹配"));
713 }
714 let decoding_key = match header.kid.as_deref() {
715 Some(kid) => self
716 .decoding_keys
717 .get(kid)
718 .ok_or_else(|| invalid_step_up("Token kid 未知"))?,
719 None => self
720 .legacy_decoding_key
721 .as_ref()
722 .ok_or_else(|| invalid_step_up("Token 缺少 kid"))?,
723 };
724 let claims = decode::<StepUpClaims>(token, decoding_key, &self.validation)
725 .map_err(|_| invalid_step_up("Token 无效或已过期"))?
726 .claims;
727 if claims.kind != expected {
728 return Err(invalid_step_up("Token 类型不匹配"));
729 }
730 Ok(claims)
731 }
732}
733
734fn validate_step_up_secret(secret: &[u8]) -> Result<(), BaseError> {
735 if secret.len() < MIN_STEP_UP_SECRET_BYTES {
736 return Err(BaseError::ConfigError(
737 "step-up HMAC 密钥至少需要 32 字节".to_string(),
738 ));
739 }
740 Ok(())
741}
742
743fn validate_step_up_kid(kid: &str) -> Result<(), BaseError> {
744 if kid.is_empty()
745 || kid.len() > 64
746 || !kid
747 .bytes()
748 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
749 {
750 return Err(BaseError::ConfigError(
751 "step-up key id 必须是 1..=64 位 ASCII 字母、数字、- 或 _".to_string(),
752 ));
753 }
754 Ok(())
755}
756
757fn step_up_validation(issuer: &str, audience: &str) -> Validation {
758 let mut validation = Validation::new(Algorithm::HS256);
759 validation.algorithms = vec![Algorithm::HS256];
760 validation.set_issuer(&[issuer]);
761 validation.set_audience(&[audience]);
762 validation.required_spec_claims = ["exp", "iss", "aud", "sub"]
763 .into_iter()
764 .map(str::to_string)
765 .collect::<HashSet<_>>();
766 validation.leeway = 0;
767 validation
768}
769
770fn validate_ttl(name: &str, value: Duration, maximum: Duration) -> Result<(), BaseError> {
771 if value.is_zero() || value > maximum {
772 return Err(BaseError::ConfigError(format!(
773 "step-up {name} TTL 必须在 1..={} 秒",
774 maximum.as_secs()
775 )));
776 }
777 Ok(())
778}
779
780fn unix_timestamp() -> Result<u64, BaseError> {
781 SystemTime::now()
782 .duration_since(UNIX_EPOCH)
783 .map(|duration| duration.as_secs())
784 .map_err(|error| BaseError::ConfigError(format!("系统时钟异常: {error}")))
785}
786
787fn resource_fingerprint(resource: &str) -> String {
788 const HEX: &[u8; 16] = b"0123456789abcdef";
789 let digest = Sha256::digest(resource.as_bytes());
790 let mut output = String::with_capacity(digest.len() * 2);
791 for byte in digest {
792 output.push(HEX[usize::from(byte >> 4)] as char);
793 output.push(HEX[usize::from(byte & 0x0f)] as char);
794 }
795 output
796}
797
798fn invalid_step_up(reason: &str) -> BaseError {
799 BaseError::Unauthorized(format!("step-up 验证失败: {reason}"))
800}
801
802#[cfg(test)]
803mod tests {
804 use super::super::auth::VerifiedSubject;
805 use super::*;
806 use crate::action::{Request, TypedHandler, User};
807 use crate::definition::{
808 ActionName, ActionSpec, AddonName, AddonSpec, AppBuilder, HttpMethod, ModuleName,
809 ModuleSpec, RouteSpec,
810 };
811 use crate::tools::ToolsBuilder;
812 use async_trait::async_trait;
813 use schemars::JsonSchema;
814 use serde::{Deserialize, Serialize};
815 use std::sync::Arc;
816
817 const SECRET: &str = "step-up-test-secret-must-be-at-least-32-bytes";
818
819 struct TestVerifier;
820
821 #[derive(Debug, Default, Deserialize, JsonSchema)]
822 #[serde(deny_unknown_fields)]
823 struct EmptyInput {}
824
825 #[derive(Debug, Serialize, JsonSchema)]
826 struct ProbeOutput {
827 operation: &'static str,
828 }
829
830 #[derive(Action)]
831 #[action(name = "delete", display_name = "删除用户")]
832 struct DeleteProbe;
833
834 #[async_trait]
835 impl TypedHandler for DeleteProbe {
836 type Input = EmptyInput;
837 type Output = ProbeOutput;
838
839 async fn handle(
840 &self,
841 _context: ActionContext,
842 _input: Self::Input,
843 ) -> Result<Self::Output, BaseError> {
844 Ok(ProbeOutput {
845 operation: "delete",
846 })
847 }
848 }
849
850 #[derive(Action)]
851 #[action(name = "read", display_name = "读取用户")]
852 struct ReadProbe;
853
854 #[async_trait]
855 impl TypedHandler for ReadProbe {
856 type Input = EmptyInput;
857 type Output = ProbeOutput;
858
859 async fn handle(
860 &self,
861 _context: ActionContext,
862 _input: Self::Input,
863 ) -> Result<Self::Output, BaseError> {
864 Ok(ProbeOutput { operation: "read" })
865 }
866 }
867
868 struct PathResourceResolver;
869
870 #[async_trait]
871 impl StepUpResourceResolver for PathResourceResolver {
872 async fn resolve(&self, context: &ActionContext) -> Result<String, BaseError> {
873 let raw = context
874 .request
875 .get_path_param("id")
876 .ok_or_else(|| BaseError::ParamMissing("id".to_string()))?;
877 let id = raw.parse::<u64>().map_err(|_| {
878 BaseError::ParamInvalid("id".to_string(), "必须是正整数".to_string())
879 })?;
880 if id == 0 {
881 return Err(BaseError::ParamInvalid(
882 "id".to_string(),
883 "必须是正整数".to_string(),
884 ));
885 }
886 Ok(format!("org_user:{id}"))
887 }
888 }
889
890 #[async_trait]
891 impl CredentialVerifier for TestVerifier {
892 async fn verify(
893 &self,
894 _context: &ActionContext,
895 input: &LoginInput,
896 ) -> Result<VerifiedSubject, BaseError> {
897 if input.password == "correct-password" {
898 Ok(VerifiedSubject::new(input.username.clone()))
899 } else {
900 Err(BaseError::Unauthorized("凭据错误".to_string()))
901 }
902 }
903 }
904
905 fn manager() -> StepUpManager {
906 StepUpManager::new(SECRET, "yang-test", "yang-sensitive-actions")
907 .expect("测试 step-up manager 应构建成功")
908 }
909
910 fn action_ref(name: &str) -> ActionRef {
911 ActionRef::new(
912 ModuleName::new("org.user").expect("测试 Module 名称应有效"),
913 ActionName::new(name).expect("测试 Action 名称应有效"),
914 )
915 }
916
917 fn context() -> ActionContext {
918 ActionContext::new(
919 Request::new(serde_json::json!({})),
920 Arc::new(ToolsBuilder::new().build().expect("测试 Tools 应构建成功")),
921 )
922 }
923
924 fn test_app(manager: Arc<StepUpManager>) -> crate::definition::BuiltApp {
925 test_app_with_target(manager, action_ref("delete")).expect("step-up 测试应用应构建成功")
926 }
927
928 fn test_app_with_target(
929 manager: Arc<StepUpManager>,
930 target: ActionRef,
931 ) -> Result<crate::definition::BuiltApp, crate::definition::BuildError> {
932 let module_name = ModuleName::new("org.user").expect("测试 Module 名称应有效");
933 let module = ModuleSpec::new(module_name)
934 .middleware(StepUpMiddleware::new(manager, target, PathResourceResolver))
935 .action(
936 ActionSpec::new(
937 ActionName::new("delete").expect("测试 Action 名称应有效"),
938 RouteSpec::new(
939 HttpMethod::Delete,
940 "/api/v1/org/users/{id}",
941 "org.user.delete",
942 ),
943 ),
944 DeleteProbe,
945 )
946 .action(
947 ActionSpec::new(
948 ActionName::new("read").expect("测试 Action 名称应有效"),
949 RouteSpec::new(HttpMethod::Get, "/api/v1/org/users/{id}", "org.user.read"),
950 ),
951 ReadProbe,
952 );
953 AppBuilder::new()
954 .addon(
955 AddonSpec::new(AddonName::new("org").expect("测试 Addon 名称应有效"))
956 .module(module),
957 )
958 .build(Arc::new(
959 ToolsBuilder::new().build().expect("测试 Tools 应构建成功"),
960 ))
961 }
962
963 async fn dispatch_as(
964 app: &crate::definition::BuiltApp,
965 action: &str,
966 request: Request,
967 user: Option<User>,
968 ) -> Result<ApiResponse, BaseError> {
969 let handle = app
970 .registry()
971 .resolve(&action_ref(action))
972 .expect("测试 Action 应已注册");
973 let mut context = app.context(request).with_module("client.forged");
974 if let Some(user) = user {
975 context = context.with_user(user);
976 }
977 app.dispatch_context(handle, context).await
978 }
979
980 fn credentials(subject: &str, password: &str) -> LoginInput {
981 LoginInput {
982 username: subject.to_string(),
983 password: password.to_string(),
984 extra: serde_json::Value::Null,
985 }
986 }
987
988 #[tokio::test]
989 async fn challenge_requires_reauthentication_and_proof_binds_every_dimension() {
990 let manager = manager();
991 let action = action_ref("delete");
992 let resource = "org_user:42";
993 let challenge = manager
994 .issue_challenge("7", &action, resource)
995 .expect("challenge 应签发成功");
996 assert_eq!(
997 challenge.expires_in,
998 DEFAULT_STEP_UP_CHALLENGE_TTL.as_secs()
999 );
1000 assert!(
1001 !challenge.challenge.contains(resource),
1002 "原始资源标识不得写入 Token"
1003 );
1004
1005 let bad_credentials = manager
1006 .complete_challenge(
1007 &context(),
1008 &TestVerifier,
1009 &credentials("7", "wrong-password"),
1010 &challenge.challenge,
1011 )
1012 .await;
1013 assert!(matches!(bad_credentials, Err(BaseError::Unauthorized(_))));
1014
1015 let proof = manager
1016 .complete_challenge(
1017 &context(),
1018 &TestVerifier,
1019 &credentials("7", "correct-password"),
1020 &challenge.challenge,
1021 )
1022 .await
1023 .expect("正确凭据应完成 challenge");
1024 assert_eq!(proof.expires_in, DEFAULT_STEP_UP_PROOF_TTL.as_secs());
1025 let verified = manager
1026 .verify_proof(&proof.proof, "7", &action, resource)
1027 .expect("proof 全部绑定维度一致时应通过");
1028 assert_eq!(verified.subject, "7");
1029 assert_eq!(verified.action, "org.user.delete");
1030 assert_eq!(verified.resource_hash.len(), 64);
1031 assert!(verified.authenticated_at < verified.expires_at);
1032
1033 for mismatch in [
1034 manager.verify_proof(&proof.proof, "8", &action, resource),
1035 manager.verify_proof(&proof.proof, "7", &action_ref("disable"), resource),
1036 manager.verify_proof(&proof.proof, "7", &action, "org_user:43"),
1037 ] {
1038 assert!(
1039 matches!(mismatch, Err(BaseError::Unauthorized(_))),
1040 "跨主体/Action/资源复用必须失败"
1041 );
1042 }
1043 }
1044
1045 #[tokio::test]
1046 async fn middleware_challenges_then_accepts_only_exact_subject_action_and_resource() {
1047 let manager = Arc::new(manager());
1048 let app = test_app(Arc::clone(&manager));
1049 let request = || Request::new(serde_json::json!({})).path_param("id", "42");
1050 let user = User::new(7, "member");
1051
1052 let missing = dispatch_as(&app, "delete", request(), Some(user.clone())).await;
1053 let challenge = match missing {
1054 Err(BaseError::StepUpRequired(challenge)) => challenge,
1055 other => panic!("缺少 proof 应返回 step-up challenge,实际为: {other:?}"),
1056 };
1057 assert_eq!(BaseError::StepUpRequired(challenge.clone()).code(), 700010);
1058
1059 let proof = manager
1060 .complete_challenge(
1061 &context(),
1062 &TestVerifier,
1063 &credentials("7", "correct-password"),
1064 &challenge.challenge,
1065 )
1066 .await
1067 .expect("正确凭据应换取 proof");
1068 let proof_request = || request().header(STEP_UP_PROOF_HEADER, &proof.proof);
1069 let response = dispatch_as(&app, "delete", proof_request(), Some(user.clone()))
1070 .await
1071 .expect("完全绑定的 proof 应允许敏感 Action");
1072 assert_eq!(response.data.expect("应返回 data")["operation"], "delete");
1073
1074 let replay = dispatch_as(&app, "delete", proof_request(), Some(user)).await;
1075 assert!(
1076 matches!(replay, Err(BaseError::Unauthorized(ref message)) if message.contains("已被消费")),
1077 "同一 proof 第二次提交必须被原子消费边界拒绝: {replay:?}"
1078 );
1079 }
1080
1081 #[tokio::test]
1082 async fn middleware_fails_closed_without_downgrading_invalid_proofs() {
1083 let manager = Arc::new(manager());
1084 let app = test_app(Arc::clone(&manager));
1085 let user = User::new(7, "member");
1086 let challenge = manager
1087 .issue_challenge("7", &action_ref("delete"), "org_user:42")
1088 .expect("challenge 应签发成功");
1089 let proof = manager
1090 .complete_challenge(
1091 &context(),
1092 &TestVerifier,
1093 &credentials("7", "correct-password"),
1094 &challenge.challenge,
1095 )
1096 .await
1097 .expect("proof 应签发成功");
1098
1099 for request in [
1100 Request::new(serde_json::json!({}))
1101 .path_param("id", "42")
1102 .header(STEP_UP_PROOF_HEADER, ""),
1103 Request::new(serde_json::json!({}))
1104 .path_param("id", "43")
1105 .header(STEP_UP_PROOF_HEADER, &proof.proof),
1106 ] {
1107 let result = dispatch_as(&app, "delete", request, Some(user.clone())).await;
1108 assert!(
1109 matches!(result, Err(BaseError::Unauthorized(_))),
1110 "空 proof 与跨资源 proof 必须直接拒绝,不能降级为 challenge: {result:?}"
1111 );
1112 }
1113
1114 let unauthenticated = dispatch_as(
1115 &app,
1116 "delete",
1117 Request::new(serde_json::json!({})).path_param("id", "42"),
1118 None,
1119 )
1120 .await;
1121 assert!(matches!(unauthenticated, Err(BaseError::Unauthorized(_))));
1122
1123 for invalid_id in [None, Some("0"), Some("not-a-number")] {
1124 let mut request = Request::new(serde_json::json!({}));
1125 if let Some(id) = invalid_id {
1126 request = request.path_param("id", id);
1127 }
1128 let result = dispatch_as(&app, "delete", request, Some(user.clone())).await;
1129 assert!(
1130 matches!(
1131 result,
1132 Err(BaseError::ParamMissing(_)) | Err(BaseError::ParamInvalid(_, _))
1133 ),
1134 "资源解析必须 fail-closed: {result:?}"
1135 );
1136 }
1137 }
1138
1139 #[tokio::test]
1140 async fn middleware_uses_registry_target_and_skips_unrelated_actions() {
1141 let manager = Arc::new(manager());
1142 let app = test_app(manager);
1143 let user = User::new(7, "member");
1144
1145 let response = dispatch_as(
1146 &app,
1147 "read",
1148 Request::new(serde_json::json!({})).path_param("id", "42"),
1149 Some(user),
1150 )
1151 .await
1152 .expect("非目标 Action 不应被 step-up 拦截");
1153 assert_eq!(response.data.expect("应返回 data")["operation"], "read");
1154 }
1155
1156 #[tokio::test]
1160 async fn internal_call_bypasses_step_up_middleware_by_design() {
1161 let manager = Arc::new(manager());
1162 let app = test_app(manager);
1163 let handle = app
1164 .registry()
1165 .resolve_typed::<EmptyInput, ProbeOutput>(&action_ref("delete"))
1166 .expect("敏感 Action 应可解析为强类型句柄");
1167
1168 let context = app
1170 .context(Request::new(serde_json::json!({})))
1171 .with_user(User::new(7, "member"));
1172 let output = app
1173 .registry()
1174 .call(handle, context, EmptyInput {})
1175 .await
1176 .expect("内部 call 不经过 step-up 中间件,应无需 proof 直接成功");
1177 assert_eq!(output.operation, "delete");
1178
1179 let context = app
1181 .context(Request::new(serde_json::json!({})))
1182 .with_user(User::new(7, "member"));
1183 let output = context
1184 .plugins()
1185 .expect("测试上下文应已绑定 Registry")
1186 .api_run(handle, EmptyInput {})
1187 .await
1188 .expect("api_run 不经过 step-up 中间件,应无需 proof 直接成功");
1189 assert_eq!(output.operation, "delete");
1190 }
1191
1192 #[test]
1193 fn app_rejects_missing_or_cross_module_step_up_targets() {
1194 let manager = Arc::new(manager());
1195 let missing = test_app_with_target(Arc::clone(&manager), action_ref("destroy"));
1196 assert!(matches!(
1197 missing,
1198 Err(crate::definition::BuildError::InvalidReference {
1199 kind: "Middleware Action",
1200 reference,
1201 }) if reference == "org.user.destroy"
1202 ));
1203
1204 let cross_module = ActionRef::new(
1205 ModuleName::new("other.user").expect("测试 Module 名称应有效"),
1206 ActionName::new("delete").expect("测试 Action 名称应有效"),
1207 );
1208 let cross = test_app_with_target(manager, cross_module);
1209 assert!(matches!(
1210 cross,
1211 Err(crate::definition::BuildError::InvalidReference {
1212 kind: "Middleware Action",
1213 reference,
1214 }) if reference == "other.user.delete"
1215 ));
1216 }
1217
1218 #[tokio::test]
1219 async fn challenge_cannot_be_completed_as_another_subject_or_used_as_proof() {
1220 let manager = manager();
1221 let action = action_ref("delete");
1222 let challenge = manager
1223 .issue_challenge("7", &action, "org_user:42")
1224 .expect("challenge 应签发成功");
1225
1226 let cross_subject = manager
1227 .complete_challenge(
1228 &context(),
1229 &TestVerifier,
1230 &credentials("8", "correct-password"),
1231 &challenge.challenge,
1232 )
1233 .await;
1234 assert!(matches!(cross_subject, Err(BaseError::Unauthorized(_))));
1235 assert!(matches!(
1236 manager.verify_proof(&challenge.challenge, "7", &action, "org_user:42"),
1237 Err(BaseError::Unauthorized(_))
1238 ));
1239 }
1240
1241 #[tokio::test]
1242 async fn tampered_expired_and_wrong_kind_tokens_are_rejected() {
1243 let manager = manager();
1244 let action = action_ref("delete");
1245 let resource = "org_user:42";
1246 let challenge = manager
1247 .issue_challenge("7", &action, resource)
1248 .expect("challenge 应签发成功");
1249 let proof = manager
1250 .complete_challenge(
1251 &context(),
1252 &TestVerifier,
1253 &credentials("7", "correct-password"),
1254 &challenge.challenge,
1255 )
1256 .await
1257 .expect("proof 应签发成功");
1258
1259 let tampered = tamper_signature(&proof.proof);
1260 assert!(matches!(
1261 manager.verify_proof(&tampered, "7", &action, resource),
1262 Err(BaseError::Unauthorized(_))
1263 ));
1264 let valid_claims = manager
1265 .decode_kind(&proof.proof, StepUpTokenKind::Proof)
1266 .expect("测试 proof 应可解析");
1267 let wrong_algorithm = jsonwebtoken::encode(
1268 &Header::new(Algorithm::HS512),
1269 &valid_claims,
1270 &EncodingKey::from_secret(SECRET.as_bytes()),
1271 )
1272 .expect("错误算法测试 Token 应可签发");
1273 assert!(matches!(
1274 manager.verify_proof(&wrong_algorithm, "7", &action, resource),
1275 Err(BaseError::Unauthorized(_))
1276 ));
1277 let mut wrong_domain_claims = valid_claims;
1278 wrong_domain_claims.aud = "another-audience".to_string();
1279 let wrong_domain = manager
1280 .encode(&wrong_domain_claims)
1281 .expect("错误域测试 Token 应可签发");
1282 assert!(matches!(
1283 manager.verify_proof(&wrong_domain, "7", &action, resource),
1284 Err(BaseError::Unauthorized(_))
1285 ));
1286 let proof_as_challenge = manager
1287 .complete_challenge(
1288 &context(),
1289 &TestVerifier,
1290 &credentials("7", "correct-password"),
1291 &proof.proof,
1292 )
1293 .await;
1294 assert!(matches!(
1295 proof_as_challenge,
1296 Err(BaseError::Unauthorized(_))
1297 ));
1298
1299 let expired_challenge = manager
1300 .encode(&claims(
1301 &manager,
1302 StepUpTokenKind::Challenge,
1303 1,
1304 None,
1305 &action,
1306 resource,
1307 ))
1308 .expect("过期 challenge 测试 Token 应编码成功");
1309 let expired = manager
1310 .complete_challenge(
1311 &context(),
1312 &TestVerifier,
1313 &credentials("7", "correct-password"),
1314 &expired_challenge,
1315 )
1316 .await;
1317 assert!(matches!(expired, Err(BaseError::Unauthorized(_))));
1318
1319 let expired_proof = manager
1320 .encode(&claims(
1321 &manager,
1322 StepUpTokenKind::Proof,
1323 1,
1324 Some("challenge-id".to_string()),
1325 &action,
1326 resource,
1327 ))
1328 .expect("过期 proof 测试 Token 应编码成功");
1329 assert!(matches!(
1330 manager.verify_proof(&expired_proof, "7", &action, resource),
1331 Err(BaseError::Unauthorized(_))
1332 ));
1333 }
1334
1335 #[tokio::test]
1339 async fn audit_events_cover_the_full_sensitive_lifecycle() {
1340 use std::io::Write;
1341 use std::sync::Mutex;
1342
1343 struct BufWriter {
1345 buf: Arc<Mutex<Vec<u8>>>,
1346 }
1347 impl Write for BufWriter {
1348 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1349 self.buf.lock().expect("缓冲区锁不应中毒").write(buf)
1350 }
1351 fn flush(&mut self) -> std::io::Result<()> {
1352 self.buf.lock().expect("缓冲区锁不应中毒").flush()
1353 }
1354 }
1355 struct BufMakeWriter {
1356 buf: Arc<Mutex<Vec<u8>>>,
1357 }
1358 impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for BufMakeWriter {
1359 type Writer = BufWriter;
1360 fn make_writer(&'a self) -> Self::Writer {
1361 BufWriter {
1362 buf: self.buf.clone(),
1363 }
1364 }
1365 }
1366
1367 let buf = Arc::new(Mutex::new(Vec::new()));
1368 let subscriber = tracing_subscriber::fmt()
1369 .with_writer(BufMakeWriter { buf: buf.clone() })
1370 .with_ansi(false)
1371 .finish();
1372 tracing::subscriber::set_global_default(subscriber)
1379 .expect("step-up 审计测试要求全局默认订阅器未被占用");
1380
1381 let manager = manager();
1382 let action = action_ref("delete");
1383 let resource = "org_user:42";
1384 let challenge = manager
1385 .issue_challenge("7", &action, resource)
1386 .expect("challenge 应签发成功");
1387 let proof = manager
1388 .complete_challenge(
1389 &context(),
1390 &TestVerifier,
1391 &credentials("7", "correct-password"),
1392 &challenge.challenge,
1393 )
1394 .await
1395 .expect("proof 应签发成功");
1396 let verified = manager
1397 .verify_proof(&proof.proof, "7", &action, resource)
1398 .expect("proof 应验证成功");
1399 let rejected = manager.verify_proof(&proof.proof, "7", &action, "org_user:43");
1400 assert!(matches!(rejected, Err(BaseError::Unauthorized(_))));
1401 let tampered = tamper_signature(&proof.proof);
1402 assert!(matches!(
1403 manager.verify_proof(&tampered, "7", &action, resource),
1404 Err(BaseError::Unauthorized(_))
1405 ));
1406
1407 let output = String::from_utf8(buf.lock().expect("缓冲区锁不应中毒").clone())
1408 .expect("审计输出应为 UTF-8");
1409 for event in [
1410 "step-up challenge 已签发",
1411 "step-up challenge 已完成",
1412 "step-up proof 验证成功",
1413 "step-up proof 验证失败",
1414 ] {
1415 assert!(output.contains(event), "缺少审计事件 {event}: {output}");
1416 }
1417 assert!(
1418 output.contains(&verified.proof_id),
1419 "审计事件应携带 proof_id: {output}"
1420 );
1421 assert!(
1422 output.contains("subject=7"),
1423 "审计事件应携带 subject: {output}"
1424 );
1425 assert!(
1426 output.contains("org.user.delete"),
1427 "审计事件应携带 action: {output}"
1428 );
1429 assert!(
1430 output.contains(&verified.resource_hash),
1431 "审计事件应携带 resource_hash: {output}"
1432 );
1433 let failure_lines: Vec<&str> = output
1435 .lines()
1436 .filter(|line| line.contains("step-up proof 验证失败"))
1437 .collect();
1438 assert!(
1439 failure_lines
1440 .iter()
1441 .any(|line| line.contains(&format!("claimed_proof_id={}", verified.proof_id))),
1442 "绑定不匹配失败事件应记录 claimed_proof_id: {output}"
1443 );
1444 assert!(
1445 failure_lines
1446 .iter()
1447 .any(|line| line
1448 .contains(&format!("claimed_resource_hash={}", verified.resource_hash))),
1449 "绑定不匹配失败事件应记录 claimed_resource_hash: {output}"
1450 );
1451 assert!(
1453 failure_lines
1454 .iter()
1455 .any(|line| line.contains("无效或已过期") && !line.contains("claimed_proof_id")),
1456 "不可解码的失败事件不应携带 claimed_proof_id: {output}"
1457 );
1458 assert!(
1459 !output.contains(resource),
1460 "审计事件不得携带资源原文: {output}"
1461 );
1462 assert!(
1463 !output.contains(&proof.proof),
1464 "审计事件不得携带 proof Token 原文"
1465 );
1466 assert!(
1467 !output.contains(&challenge.challenge),
1468 "审计事件不得携带 challenge Token 原文"
1469 );
1470 }
1471
1472 #[test]
1473 fn manager_rejects_weak_secrets_empty_domains_and_long_ttls() {
1474 assert!(matches!(
1475 StepUpManager::new("short", "issuer", "audience"),
1476 Err(BaseError::ConfigError(_))
1477 ));
1478 assert!(matches!(
1479 StepUpManager::new(SECRET, "", "audience"),
1480 Err(BaseError::ConfigError(_))
1481 ));
1482 assert!(matches!(
1483 manager().with_ttls(Duration::ZERO, DEFAULT_STEP_UP_PROOF_TTL),
1484 Err(BaseError::ConfigError(_))
1485 ));
1486 assert!(matches!(
1487 manager().with_ttls(
1488 DEFAULT_STEP_UP_CHALLENGE_TTL,
1489 MAX_STEP_UP_PROOF_TTL + Duration::from_secs(1),
1490 ),
1491 Err(BaseError::ConfigError(_))
1492 ));
1493 assert!(matches!(
1494 manager().issue_challenge("7", &action_ref("delete"), ""),
1495 Err(BaseError::ConfigError(_))
1496 ));
1497 assert!(matches!(
1498 StepUpManager::new_with_keyring(
1499 "invalid kid",
1500 SECRET,
1501 std::iter::empty::<(&str, &str)>(),
1502 "issuer",
1503 "audience"
1504 ),
1505 Err(BaseError::ConfigError(_))
1506 ));
1507 assert!(matches!(
1508 StepUpManager::new_with_keyring(
1509 "active",
1510 SECRET,
1511 [("retiring", SECRET)],
1512 "issuer",
1513 "audience"
1514 ),
1515 Err(BaseError::ConfigError(_))
1516 ));
1517 }
1518
1519 #[tokio::test]
1520 async fn keyring_rotates_without_breaking_retiring_challenges() {
1521 const OLD_SECRET: &str = "old-step-up-secret-must-be-at-least-32-bytes";
1522 const NEW_SECRET: &str = "new-step-up-secret-must-be-at-least-32-bytes";
1523 let old = StepUpManager::new_with_keyring(
1524 "old-key",
1525 OLD_SECRET,
1526 std::iter::empty::<(&str, &str)>(),
1527 "yang-test",
1528 "yang-sensitive-actions",
1529 )
1530 .expect("旧 keyring 应有效");
1531 let action = action_ref("delete");
1532 let challenge = old
1533 .issue_challenge("7", &action, "org_user:42")
1534 .expect("旧 key 应可签发 challenge");
1535 assert_eq!(
1536 decode_header(&challenge.challenge)
1537 .expect("challenge header 应可解码")
1538 .kid
1539 .as_deref(),
1540 Some("old-key")
1541 );
1542
1543 let rotated = StepUpManager::new_with_keyring(
1544 "new-key",
1545 NEW_SECRET,
1546 [("old-key", OLD_SECRET)],
1547 "yang-test",
1548 "yang-sensitive-actions",
1549 )
1550 .expect("轮换 keyring 应有效");
1551 let context = context();
1552 let proof = rotated
1553 .complete_challenge(
1554 &context,
1555 &TestVerifier,
1556 &credentials("7", "correct-password"),
1557 &challenge.challenge,
1558 )
1559 .await
1560 .expect("retiring key 的未过期 challenge 应可完成");
1561 assert_eq!(
1562 decode_header(&proof.proof)
1563 .expect("proof header 应可解码")
1564 .kid
1565 .as_deref(),
1566 Some("new-key")
1567 );
1568 rotated
1569 .verify_proof(&proof.proof, "7", &action, "org_user:42")
1570 .expect("新 proof 应由 active key 验证");
1571
1572 let retired = StepUpManager::new_with_keyring(
1573 "new-key",
1574 NEW_SECRET,
1575 std::iter::empty::<(&str, &str)>(),
1576 "yang-test",
1577 "yang-sensitive-actions",
1578 )
1579 .expect("移除旧 key 后 keyring 仍应有效");
1580 assert!(retired
1581 .complete_challenge(
1582 &context,
1583 &TestVerifier,
1584 &credentials("7", "correct-password"),
1585 &challenge.challenge,
1586 )
1587 .await
1588 .is_err());
1589 }
1590
1591 fn claims(
1592 manager: &StepUpManager,
1593 kind: StepUpTokenKind,
1594 exp: u64,
1595 challenge_jti: Option<String>,
1596 action: &ActionRef,
1597 resource: &str,
1598 ) -> StepUpClaims {
1599 StepUpClaims {
1600 iss: manager.issuer.clone(),
1601 sub: "7".to_string(),
1602 aud: manager.audience.clone(),
1603 exp,
1604 iat: 0,
1605 jti: "expired-token-id".to_string(),
1606 kind,
1607 action: action.to_string(),
1608 resource_hash: resource_fingerprint(resource),
1609 challenge_jti,
1610 }
1611 }
1612
1613 fn tamper_signature(token: &str) -> String {
1614 let mut bytes = token.as_bytes().to_vec();
1615 let signature = bytes
1616 .iter()
1617 .rposition(|byte| *byte == b'.')
1618 .map(|index| index + 1)
1619 .expect("JWT 应包含签名段");
1620 bytes[signature] = if bytes[signature] == b'A' { b'B' } else { b'A' };
1621 String::from_utf8(bytes).expect("JWT 应是 UTF-8 ASCII")
1622 }
1623}