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