Skip to main content

fakecloud_core/
auth.rs

1//! Authentication and authorization primitives shared across services.
2//!
3//! This module defines the opt-in modes for SigV4 signature verification and
4//! IAM policy enforcement, plus the reserved "root bypass" identity that
5//! short-circuits both checks when enabled.
6//!
7//! Neither feature is enforced at this layer — the types are plumbed through
8//! [`crate::dispatch::DispatchConfig`] and consulted later by dispatch and
9//! service handlers once the corresponding batches land. See
10//! `/docs/reference/security` (added in a later batch) for the user-facing
11//! contract.
12
13use std::collections::{BTreeMap, HashMap};
14use std::fmt;
15use std::net::IpAddr;
16use std::str::FromStr;
17use std::sync::Arc;
18
19use chrono::{DateTime, Utc};
20
21/// Kind of principal a set of credentials resolves to.
22///
23/// Used to drive IAM policy evaluation (Phase 2) and the `GetCallerIdentity`
24/// response shape. Inferred from the credential's storage path in
25/// [`IamState`] and — for STS temporary credentials — from the ARN form
26/// `arn:aws:sts::<account>:assumed-role/...` or `federated-user/...`.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
28pub enum PrincipalType {
29    /// An IAM user access key (AKID created via `CreateAccessKey`).
30    User,
31    /// An assumed role session issued by `AssumeRole` /
32    /// `AssumeRoleWithWebIdentity` / `AssumeRoleWithSAML`.
33    AssumedRole,
34    /// Credentials issued by `GetFederationToken` — i.e. a federated user.
35    FederatedUser,
36    /// The account root identity. Reserved for explicit `...:root` ARNs
37    /// only; do not return this from a generic fallback because root
38    /// principals bypass IAM enforcement (see `Principal::is_root`).
39    Root,
40    /// The ARN didn't match any known shape. Treated as a non-root,
41    /// non-bypassable principal so a malformed or unexpected ARN can never
42    /// silently grant elevated permissions during IAM evaluation.
43    Unknown,
44}
45
46impl PrincipalType {
47    pub fn as_str(self) -> &'static str {
48        match self {
49            PrincipalType::User => "user",
50            PrincipalType::AssumedRole => "assumed-role",
51            PrincipalType::FederatedUser => "federated-user",
52            PrincipalType::Root => "root",
53            PrincipalType::Unknown => "unknown",
54        }
55    }
56
57    /// Classify a principal from its ARN. Returns [`PrincipalType::Unknown`]
58    /// for ARNs that don't match any of the well-known principal shapes —
59    /// **never** [`PrincipalType::Root`] as a fallback, because root
60    /// bypasses IAM enforcement and silently treating malformed ARNs as
61    /// root would let unexpected inputs grant elevated permissions
62    /// (identified by cubic in PR #391 review).
63    pub fn from_arn(arn: &str) -> Self {
64        if arn.ends_with(":root") {
65            PrincipalType::Root
66        } else if arn.contains(":user/") {
67            PrincipalType::User
68        } else if arn.contains(":assumed-role/") {
69            PrincipalType::AssumedRole
70        } else if arn.contains(":federated-user/") {
71            PrincipalType::FederatedUser
72        } else {
73            PrincipalType::Unknown
74        }
75    }
76}
77
78/// Identity of the caller making a request, once its credentials have been
79/// resolved. Attached to [`crate::service::AwsRequest::principal`] so
80/// handlers can make identity-based decisions without re-parsing the
81/// Authorization header.
82///
83/// `account_id` is always sourced from the credential itself (via
84/// [`CredentialResolver`]), never from global config — #381 note.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Principal {
87    pub arn: String,
88    pub user_id: String,
89    pub account_id: String,
90    pub principal_type: PrincipalType,
91    /// Optional source identity string, carried through from
92    /// `AssumeRole`'s `SourceIdentity` parameter. Reserved for later
93    /// batches that wire session policies and auditing.
94    pub source_identity: Option<String>,
95    /// Tags on the calling principal (IAM user or assumed role).
96    /// Populated at credential-resolution time from `IamState`.
97    /// Used for `aws:PrincipalTag/<key>` condition evaluation.
98    pub tags: Option<HashMap<String, String>>,
99}
100
101impl Principal {
102    /// Is this caller the account's root identity? Root bypasses IAM
103    /// evaluation, matching AWS.
104    pub fn is_root(&self) -> bool {
105        matches!(self.principal_type, PrincipalType::Root) || self.arn.ends_with(":root")
106    }
107}
108
109/// Credentials resolved from an access key ID.
110///
111/// Returned by [`CredentialResolver::resolve`]. Holds both the secret access
112/// key (needed for SigV4 verification) and the resolved [`Principal`]
113/// (needed for IAM enforcement and `GetCallerIdentity` consolidation).
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct ResolvedCredential {
116    pub secret_access_key: String,
117    pub session_token: Option<String>,
118    pub principal: Principal,
119    /// Session policies passed to the STS call that minted this credential.
120    /// Empty for IAM user access keys.
121    pub session_policies: Vec<String>,
122    /// True iff the underlying STS credential was minted with MFA. Drives
123    /// `aws:MultiFactorAuthPresent` for downstream IAM evaluation. Always
124    /// false for raw IAM user access keys.
125    pub mfa_present: bool,
126    /// Wall-clock time at which the underlying STS credential was issued.
127    /// Drives `aws:TokenIssueTime` and `aws:MultiFactorAuthAge` (the latter
128    /// computed at evaluation time as `now - token_issued_at` when
129    /// [`Self::mfa_present`] is true). `None` for raw IAM user access keys
130    /// — AWS does not expose `aws:TokenIssueTime` for long-lived credentials.
131    pub token_issued_at: Option<DateTime<Utc>>,
132    /// `aws:FederatedProvider` — SAML provider ARN for AssumeRoleWithSAML,
133    /// OIDC provider ARN for AssumeRoleWithWebIdentity. `None` for raw IAM
134    /// user keys, plain AssumeRole, GetSessionToken, GetFederationToken.
135    pub federated_provider: Option<String>,
136}
137
138impl ResolvedCredential {
139    /// Convenience accessors for the flat fields batch 3 callers use. Kept
140    /// as methods rather than re-adding the fields to avoid making the
141    /// shape inconsistent with [`Principal`] itself.
142    pub fn principal_arn(&self) -> &str {
143        &self.principal.arn
144    }
145
146    pub fn user_id(&self) -> &str {
147        &self.principal.user_id
148    }
149
150    pub fn account_id(&self) -> &str {
151        &self.principal.account_id
152    }
153}
154
155/// Abstraction over "given an access key ID, return the secret and resolved
156/// principal." Implemented by the IAM crate against `IamState`; the core
157/// crate depends only on the trait so there's no circular dependency.
158///
159/// Implementations must be cheap to clone-share via `Arc` and must be
160/// thread-safe — dispatch calls them from an axum handler under a tokio
161/// worker.
162pub trait CredentialResolver: Send + Sync {
163    /// Resolve `access_key_id` to its secret access key and principal.
164    /// Returns `None` when the AKID is unknown or its underlying credential
165    /// has expired.
166    fn resolve(&self, access_key_id: &str) -> Option<ResolvedCredential>;
167}
168
169/// One IAM action that the dispatch layer should evaluate against the
170/// caller's effective policy set.
171///
172/// Produced by [`crate::service::AwsService::iam_action_for`] on services
173/// that opt into enforcement. The `resource` is a fully-qualified AWS ARN
174/// built from `request.principal.account_id` so multi-account isolation
175/// (#381) becomes a state-partitioning change rather than a cross-cutting
176/// rewrite.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct IamAction {
179    /// IAM service prefix, e.g. `"s3"`, `"sqs"`, `"iam"`.
180    pub service: &'static str,
181    /// AWS action name, e.g. `"GetObject"`, `"SendMessage"`.
182    pub action: &'static str,
183    /// Fully-qualified ARN of the target resource.
184    pub resource: String,
185}
186
187impl IamAction {
188    /// Compose the canonical `service:Action` string the evaluator
189    /// matches against.
190    pub fn action_string(&self) -> String {
191        format!("{}:{}", self.service, self.action)
192    }
193}
194
195/// Result of evaluating a request against an identity's effective policy
196/// set. Abstract over the concrete evaluator [`Decision`] in
197/// `fakecloud-iam::evaluator` so `fakecloud-core` can consume it without
198/// depending on `fakecloud-iam`.
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200pub enum IamDecision {
201    Allow,
202    ImplicitDeny,
203    ExplicitDeny,
204}
205
206impl IamDecision {
207    pub fn is_allow(self) -> bool {
208        matches!(self, IamDecision::Allow)
209    }
210}
211
212/// Request-time values consulted when a policy statement carries a
213/// `Condition` block. Populated at dispatch time from the resolved
214/// [`Principal`] and the incoming HTTP request, then handed to
215/// [`IamPolicyEvaluator::evaluate`].
216///
217/// Lives in `fakecloud-core` (not `fakecloud-iam`) so the trait can
218/// reference it without creating a circular crate dependency. All
219/// fields are optional — a missing field means the key wasn't knowable
220/// at dispatch time, and any operator that references it safe-fails to
221/// `false` (unless the operator carries the `IfExists` suffix, in which
222/// case it evaluates to `true`, matching AWS).
223///
224/// The `service_keys` map is reserved for service-specific condition
225/// keys (`s3:prefix`, `sqs:MessageAttribute`, …) which Phase 2 ships
226/// empty; service-specific support lands in a follow-up batch without
227/// a signature change.
228#[derive(Debug, Clone, Default)]
229pub struct ConditionContext {
230    /// `aws:username` — username segment of an IAM user ARN, or `None`
231    /// for assumed roles / federated users where AWS does not set the key.
232    pub aws_username: Option<String>,
233    /// `aws:userid` — the unique `AIDA...`/`AROA...` identifier.
234    pub aws_userid: Option<String>,
235    /// `aws:PrincipalArn` — full principal ARN.
236    pub aws_principal_arn: Option<String>,
237    /// `aws:PrincipalAccount` — 12-digit account ID sourced from the
238    /// credential, not global config (#381 multi-account alignment).
239    pub aws_principal_account: Option<String>,
240    /// `aws:PrincipalType` — `"User"`, `"AssumedRole"`, etc.
241    pub aws_principal_type: Option<String>,
242    /// `aws:SourceIp` — remote address of the HTTP connection.
243    pub aws_source_ip: Option<IpAddr>,
244    /// `aws:CurrentTime` — evaluation timestamp (UTC).
245    pub aws_current_time: Option<DateTime<Utc>>,
246    /// `aws:EpochTime` — same moment as `aws_current_time` in seconds
247    /// since the Unix epoch.
248    pub aws_epoch_time: Option<i64>,
249    /// `aws:SecureTransport` — `true` iff the request came in over TLS.
250    pub aws_secure_transport: Option<bool>,
251    /// `aws:RequestedRegion` — region extracted from SigV4 / config.
252    pub aws_requested_region: Option<String>,
253    /// `aws:MultiFactorAuthPresent` — true iff the caller supplied an
254    /// MFA credential when minting the session (AssumeRole with
255    /// SerialNumber + TokenCode, or a long-lived user credential
256    /// re-asserted via STS GetSessionToken with MFA).
257    pub aws_mfa_present: Option<bool>,
258    /// `aws:MultiFactorAuthAge` — seconds since MFA was asserted on
259    /// the session.
260    pub aws_mfa_age_seconds: Option<i64>,
261    /// `aws:CalledVia` — the chain of service principals that have
262    /// re-invoked downstream services on the caller's behalf
263    /// (e.g. `["cloudformation.amazonaws.com"]`). Multi-value key.
264    pub aws_called_via: Vec<String>,
265    /// `aws:SourceVpce` — VPC endpoint id when the request transited
266    /// a VPC interface endpoint.
267    pub aws_source_vpce: Option<String>,
268    /// `aws:SourceVpc` — VPC id when the request originated inside a
269    /// VPC.
270    pub aws_source_vpc: Option<String>,
271    /// `aws:VpcSourceIp` — private source IP inside the VPC (distinct
272    /// from `aws:SourceIp` which is the public NAT/Edge IP).
273    pub aws_vpc_source_ip: Option<IpAddr>,
274    /// `aws:FederatedProvider` — `cognito-identity.amazonaws.com`,
275    /// `accounts.google.com`, or the SAML-provider ARN, depending on
276    /// how the credential was minted.
277    pub aws_federated_provider: Option<String>,
278    /// `aws:TokenIssueTime` — when the temporary credential
279    /// underlying this session was issued (UTC).
280    pub aws_token_issue_time: Option<DateTime<Utc>>,
281    /// Service-specific keys (`s3:prefix`, `sqs:MessageAttribute`, …).
282    pub service_keys: BTreeMap<String, Vec<String>>,
283    /// `aws:ResourceTag/<key>` — tags on the target resource.
284    /// Populated by [`crate::service::AwsService::resource_tags_for`].
285    /// `None` means the service doesn't expose resource tags for ABAC.
286    pub resource_tags: Option<HashMap<String, String>>,
287    /// `aws:RequestTag/<key>` — tags sent in the request body/headers.
288    /// Populated by [`crate::service::AwsService::request_tags_from`].
289    /// Also drives `aws:TagKeys` (the list of request tag keys).
290    pub request_tags: Option<HashMap<String, String>>,
291    /// `aws:PrincipalTag/<key>` — tags on the calling IAM user or role.
292    /// Populated from [`Principal::tags`] at dispatch time.
293    pub principal_tags: Option<HashMap<String, String>>,
294}
295
296/// Whether two condition key names are the same key: the `service:name`
297/// part compares case-insensitively, and anything after the first `/` (a tag
298/// key in `aws:RequestTag/<key>`) compares exactly.
299fn same_condition_key(a: &str, b: &str) -> bool {
300    fn split(k: &str) -> (&str, &str) {
301        match k.find('/') {
302            Some(i) => (&k[..i], &k[i..]),
303            None => (k, ""),
304        }
305    }
306    let ((a_name, a_tail), (b_name, b_tail)) = (split(a), split(b));
307    a_name.eq_ignore_ascii_case(b_name) && a_tail == b_tail
308}
309
310impl ConditionContext {
311    /// Resolve a condition key (e.g. `"aws:username"`) to the list of
312    /// context values. Returns `None` if the key is not populated.
313    /// Key names are matched case-insensitively — AWS treats
314    /// `aws:username` and `AWS:UserName` as the same key.
315    pub fn lookup(&self, key: &str) -> Option<Vec<String>> {
316        let lower = key.to_ascii_lowercase();
317        let one = |s: &str| Some(vec![s.to_string()]);
318
319        // ABAC tag-based keys: case-insensitive prefix, case-sensitive
320        // tag key (the part after the slash). AWS treats "Environment"
321        // and "environment" as distinct tag keys.
322        //
323        // Prefix lengths: "aws:resourcetag/" = 16, "aws:requesttag/" = 15,
324        //                 "aws:principaltag/" = 17
325        let tagged = if lower.starts_with("aws:resourcetag/") {
326            let tag_key = &key[16..]; // preserve original case
327            Some(
328                self.resource_tags
329                    .as_ref()
330                    .and_then(|tags| tags.get(tag_key))
331                    .map(|v| vec![v.clone()]),
332            )
333        } else if lower.starts_with("aws:requesttag/") {
334            let tag_key = &key[15..];
335            Some(
336                self.request_tags
337                    .as_ref()
338                    .and_then(|tags| tags.get(tag_key))
339                    .map(|v| vec![v.clone()]),
340            )
341        } else if lower.starts_with("aws:principaltag/") {
342            let tag_key = &key[17..];
343            Some(
344                self.principal_tags
345                    .as_ref()
346                    .and_then(|tags| tags.get(tag_key))
347                    .map(|v| vec![v.clone()]),
348            )
349        } else if lower == "aws:tagkeys" {
350            Some(
351                self.request_tags
352                    .as_ref()
353                    .map(|tags| tags.keys().cloned().collect()),
354            )
355        } else {
356            None
357        };
358        if let Some(tagged) = tagged {
359            // Tag keys are case-sensitive after the prefix, so a plain entry
360            // must match the key exactly.
361            return tagged.or_else(|| {
362                self.service_keys
363                    .iter()
364                    .find(|(entry, _)| same_condition_key(entry, key))
365                    .map(|(_, vs)| vs.clone())
366            });
367        }
368
369        let typed = match lower.as_str() {
370            "aws:username" => self.aws_username.as_deref().and_then(one),
371            "aws:userid" => self.aws_userid.as_deref().and_then(one),
372            "aws:principalarn" => self.aws_principal_arn.as_deref().and_then(one),
373            "aws:principalaccount" => self.aws_principal_account.as_deref().and_then(one),
374            "aws:principaltype" => self.aws_principal_type.as_deref().and_then(one),
375            "aws:sourceip" => self.aws_source_ip.map(|ip| vec![ip.to_string()]),
376            "aws:currenttime" => self
377                .aws_current_time
378                .map(|t| vec![t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)]),
379            "aws:epochtime" => self.aws_epoch_time.map(|e| vec![e.to_string()]),
380            "aws:securetransport" => self.aws_secure_transport.map(|b| vec![b.to_string()]),
381            "aws:requestedregion" => self.aws_requested_region.as_deref().and_then(one),
382            "aws:multifactorauthpresent" => self.aws_mfa_present.map(|b| vec![b.to_string()]),
383            "aws:multifactorauthage" => self.aws_mfa_age_seconds.map(|s| vec![s.to_string()]),
384            "aws:calledvia" => {
385                if self.aws_called_via.is_empty() {
386                    None
387                } else {
388                    Some(self.aws_called_via.clone())
389                }
390            }
391            "aws:sourcevpce" => self.aws_source_vpce.as_deref().and_then(one),
392            "aws:sourcevpc" => self.aws_source_vpc.as_deref().and_then(one),
393            "aws:vpcsourceip" => self.aws_vpc_source_ip.map(|ip| vec![ip.to_string()]),
394            "aws:federatedprovider" => self.aws_federated_provider.as_deref().and_then(one),
395            "aws:tokenissuetime" => self
396                .aws_token_issue_time
397                .map(|t| vec![t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)]),
398            _ => None,
399        };
400        // A key with no typed value -- a service-specific key, or a global key
401        // supplied as a plain entry (a policy simulator's ContextEntries) --
402        // comes from `service_keys`. An entry with an empty value list means
403        // the key applies to the request but carries no values, which set
404        // operators distinguish from a key that was never populated.
405        typed.or_else(|| {
406            self.service_keys.get(&lower).cloned().or_else(|| {
407                self.service_keys
408                    .iter()
409                    .find(|(k, _)| k.eq_ignore_ascii_case(key))
410                    .map(|(_, vs)| vs.clone())
411            })
412        })
413    }
414}
415
416/// Abstraction over "given a principal, an action, and request-time
417/// condition keys, say Allow / Deny". Implemented by `fakecloud-iam`
418/// against `IamState` + the evaluator. Dispatch calls this for every
419/// request when `FAKECLOUD_IAM != off` and the target service opts in.
420pub trait IamPolicyEvaluator: Send + Sync {
421    /// Evaluate `action` against the identity policies attached to
422    /// `principal`, using `context` for `Condition` block resolution.
423    /// `session_policies` are the raw JSON session-policy documents
424    /// from the STS call that minted the caller's credential (empty
425    /// for IAM user access keys). `scps` are the inherited SCP
426    /// documents (root-OU first, account-direct last) that form the
427    /// top-of-chain allow-list ceiling; `None` means no org exists
428    /// for this principal or the principal is exempt (management,
429    /// service-linked role) and the layer is a pass-through.
430    fn evaluate(
431        &self,
432        principal: &Principal,
433        action: &IamAction,
434        context: &ConditionContext,
435        session_policies: &[String],
436        scps: Option<&[String]>,
437    ) -> IamDecision;
438
439    /// Evaluate with resource-policy + session-policy intersection.
440    /// `scps` follows the same semantics as in [`Self::evaluate`].
441    #[allow(clippy::too_many_arguments)]
442    fn evaluate_with_resource_policy(
443        &self,
444        principal: &Principal,
445        action: &IamAction,
446        context: &ConditionContext,
447        resource_policy_json: Option<&str>,
448        resource_account_id: &str,
449        session_policies: &[String],
450        scps: Option<&[String]>,
451    ) -> IamDecision;
452
453    /// Evaluate `action` for an **anonymous** (unsigned) caller against a
454    /// resource-based policy in isolation. Anonymous requests carry no
455    /// identity, so the resource policy is the sole authorization source:
456    /// the request is allowed only if the policy explicitly grants the
457    /// action to a wildcard principal (`Principal:"*"` / `{"AWS":"*"}`).
458    ///
459    /// `resource_policy_json` is the raw policy document (S3 bucket policy
460    /// today); `None` or a non-public policy yields [`IamDecision::ImplicitDeny`].
461    /// ACL-based public grants are evaluated separately by the dispatcher
462    /// via [`ResourcePolicyProvider::public_acl_allows`].
463    ///
464    /// The default implementation returns [`IamDecision::ImplicitDeny`] so
465    /// evaluators that don't support anonymous access never silently grant.
466    fn evaluate_anonymous(
467        &self,
468        _action: &IamAction,
469        _context: &ConditionContext,
470        _resource_policy_json: Option<&str>,
471    ) -> IamDecision {
472        IamDecision::ImplicitDeny
473    }
474}
475
476/// Abstraction over "given a principal, return the inherited SCP
477/// documents that form the top-of-chain allow-list ceiling for the
478/// principal's account". Implemented by `fakecloud-organizations`.
479///
480/// Returning `None` means SCPs do not apply (no org exists for this
481/// fakecloud process, or the principal is the management account, or
482/// the principal is a service-linked role, or the account is not
483/// enrolled in the organization). Dispatch plumbs the returned slice
484/// straight into [`IamPolicyEvaluator`].
485///
486/// The ordered list puts root-OU-attached policies first, then each
487/// descendant OU down to the account's parent, and account-direct
488/// attachments last — the evaluator treats each entry as a separate
489/// gate that must allow (intersection), matching AWS SCP semantics.
490pub trait ScpResolver: Send + Sync {
491    fn scps_for(&self, principal: &Principal) -> Option<Vec<String>>;
492}
493
494/// Abstraction over "does the organization topology permit `caller_account` to
495/// mint centralized-root (`sts:AssumeRoot`) credentials for `target_account`".
496/// Implemented by `fakecloud-organizations`, which owns the membership graph
497/// the IAM/STS crate has no visibility into.
498///
499/// Returns `true` only when an organization exists, `target_account` is a
500/// member of it, and `caller_account` is that org's management account (or a
501/// registered delegated administrator for centralized root access). Any other
502/// case — no org, target not enrolled, caller not privileged — returns
503/// `false`, so a bare `sts:AssumeRoot` grant can no longer escalate to root
504/// over an arbitrary account. Same-account AssumeRoot is handled by the caller
505/// and never consults this resolver.
506pub trait OrgMembershipResolver: Send + Sync {
507    fn can_assume_root_into(&self, caller_account: &str, target_account: &str) -> bool;
508}
509
510/// Abstraction over "given a service + a fully-qualified resource ARN,
511/// return the resource-based policy attached to that resource, if any."
512///
513/// Implemented by resource-owning services (S3 for bucket policies in
514/// the initial rollout; SNS topic policies, KMS key policies, and
515/// Lambda resource policies are separate future wirings) and plumbed
516/// through [`crate::dispatch::DispatchConfig`] alongside
517/// [`IamPolicyEvaluator`]. Dispatch fetches the policy for the target
518/// resource and hands it to the evaluator so cross-account Allow/Deny
519/// semantics can be computed.
520///
521/// Implementations must be cheap to clone-share via `Arc` and must be
522/// thread-safe — dispatch calls them on every enforced request.
523///
524/// Returning `None` means "no resource policy attached / resource
525/// doesn't exist / this provider doesn't handle that service." Returning
526/// `Some(json)` yields the raw JSON document as stored by the
527/// resource's CRUD handlers; parsing happens inside the evaluator so a
528/// malformed document logs a debug audit event and falls through to
529/// "no resource policy" rather than silently allowing.
530pub trait ResourcePolicyProvider: Send + Sync {
531    /// Fetch the resource-based policy document attached to
532    /// `resource_arn` on `service`. Both arguments are lowercase-ish
533    /// (`"s3"`, `"arn:aws:s3:::my-bucket"`); implementations should
534    /// match the service prefix they own and return `None` for
535    /// anything else so providers can be composed safely.
536    fn resource_policy(&self, service: &str, resource_arn: &str) -> Option<String>;
537
538    /// Resolve the 12-digit account that owns `resource_arn` on `service`,
539    /// when the ARN itself does not carry it. S3 ARNs have an empty account
540    /// field (`arn:aws:s3:::bucket`), so without this the dispatcher would
541    /// fall back to the caller's account and treat every S3 request as
542    /// same-account — letting account A reach account B's bucket without B's
543    /// bucket policy granting it (bug-audit 2026-05-28, 5.3). Providers whose
544    /// ARNs already carry the account (SQS/SNS/Lambda/…) return `None` and let
545    /// the dispatcher parse it from the ARN. Default `None`.
546    fn resource_owner_account(&self, _service: &str, _resource_arn: &str) -> Option<String> {
547        None
548    }
549
550    /// Whether a **public-read ACL** on `resource_arn` grants `action` to
551    /// an anonymous (unsigned) caller. Distinct from a bucket policy: S3
552    /// ACLs are a separate grant surface, so an object/bucket with an
553    /// `AllUsers` group grant is publicly readable even without a bucket
554    /// policy. `action` is the bare AWS action name (`"GetObject"`,
555    /// `"ListBucket"`, …).
556    ///
557    /// Implementations must honor `PublicAccessBlock` (a bucket with
558    /// `IgnorePublicAcls` set is not public via ACL). Default `false` so
559    /// providers that don't model ACLs never grant anonymous access.
560    fn public_acl_allows(&self, _service: &str, _resource_arn: &str, _action: &str) -> bool {
561        false
562    }
563}
564
565/// Failure mode for IAM PassRole trust-policy validation.
566///
567/// Exists in `fakecloud-core` so service crates (Lambda, ECS, …) can
568/// surface a wire-shaped error without taking a dependency on
569/// `fakecloud-iam`. The server crate wires the concrete validator that
570/// reads the IAM state.
571#[derive(Debug, Clone, PartialEq, Eq)]
572pub enum PassRoleError {
573    /// No role with this ARN exists in the IAM state.
574    RoleNotFound(String),
575    /// Role exists but its `AssumeRolePolicyDocument` does not allow the
576    /// service principal to call `sts:AssumeRole`. Real AWS returns
577    /// `InvalidParameterValueException` in this shape.
578    TrustPolicyDenies {
579        role_arn: String,
580        service_principal: String,
581    },
582    /// Role's `AssumeRolePolicyDocument` could not be parsed as JSON.
583    InvalidTrustPolicy(String),
584}
585
586impl std::fmt::Display for PassRoleError {
587    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
588        match self {
589            Self::RoleNotFound(arn) => write!(f, "role not found: {arn}"),
590            Self::TrustPolicyDenies {
591                role_arn,
592                service_principal,
593            } => write!(
594                f,
595                "Role's trust policy does not allow {service_principal} to assume the role: {role_arn}"
596            ),
597            Self::InvalidTrustPolicy(arn) => {
598                write!(f, "invalid trust policy on role {arn}")
599            }
600        }
601    }
602}
603
604impl std::error::Error for PassRoleError {}
605
606/// Validator that checks whether a role can be passed to a given
607/// service. Used by Lambda / ECS / EC2 etc. to reject `CreateFunction`,
608/// `RegisterTaskDefinition`, etc. when the supplied role's trust policy
609/// doesn't allow the service principal — matching the `iam:PassRole`
610/// trust-side behavior real AWS enforces unconditionally (separate from
611/// identity-policy `iam:PassRole`, which sits behind the IAM evaluator).
612pub trait RoleTrustValidator: Send + Sync {
613    fn validate(
614        &self,
615        account_id: &str,
616        role_arn: &str,
617        service_principal: &str,
618    ) -> Result<(), PassRoleError>;
619}
620
621/// Temporary credentials for an assumed-role session, as a compute service
622/// hands them to the code it runs (Lambda's execution-role environment, for
623/// example).
624#[derive(Clone, Debug)]
625pub struct SessionCredentials {
626    pub access_key_id: String,
627    pub secret_access_key: String,
628    pub session_token: String,
629    pub expiration: DateTime<Utc>,
630    /// Account the session is registered under, so it can be revoked there.
631    pub account_id: String,
632}
633
634/// Issues assumed-role session credentials on behalf of a compute service,
635/// registered so that requests signed with them resolve to
636/// `arn:<partition>:sts::<account>:assumed-role/<role>/<session>` (and verify
637/// under `--verify-sigv4`). Implemented over IAM state; services that run
638/// user code under a role take it as an optional hook so they stay decoupled
639/// from the IAM crate.
640pub trait SessionCredentialIssuer: Send + Sync {
641    /// Mint credentials for `role_arn` with the given session name, valid for
642    /// `duration`.
643    fn issue(
644        &self,
645        role_arn: &str,
646        session_name: &str,
647        duration: chrono::Duration,
648    ) -> SessionCredentials;
649
650    /// Unregister credentials once the code they were issued to has stopped.
651    /// Idempotent.
652    fn revoke(&self, credentials: &SessionCredentials);
653}
654
655/// Composite [`ResourcePolicyProvider`] that delegates to a list of
656/// sub-providers in order, returning the first `Some` hit.
657///
658/// Each concrete provider (`S3ResourcePolicyProvider`,
659/// `SnsResourcePolicyProvider`, `LambdaResourcePolicyProvider`, …)
660/// already gates on its own service prefix and returns `None` for
661/// anything it doesn't own, so composition is short-circuit and
662/// order-independent. Server bootstrap builds one of these holding
663/// every resource-owning service and passes it to
664/// [`crate::dispatch::DispatchConfig::resource_policy_provider`].
665///
666/// This is the extension point for future resource-owning services:
667/// adding KMS key policies (or anything else) is a one-line push at
668/// bootstrap, never a core-crate refactor.
669pub struct MultiResourcePolicyProvider {
670    providers: Vec<Arc<dyn ResourcePolicyProvider>>,
671}
672
673impl MultiResourcePolicyProvider {
674    /// Build a composite from a list of providers.
675    pub fn new(providers: Vec<Arc<dyn ResourcePolicyProvider>>) -> Self {
676        Self { providers }
677    }
678
679    /// Shared constructor returning the composite as an
680    /// `Arc<dyn ResourcePolicyProvider>`, matching the signature of
681    /// `DispatchConfig::resource_policy_provider`.
682    pub fn shared(
683        providers: Vec<Arc<dyn ResourcePolicyProvider>>,
684    ) -> Arc<dyn ResourcePolicyProvider> {
685        Arc::new(Self::new(providers))
686    }
687
688    /// Number of sub-providers held by this composite. Used by tests.
689    pub fn len(&self) -> usize {
690        self.providers.len()
691    }
692
693    /// True when no sub-providers are registered.
694    pub fn is_empty(&self) -> bool {
695        self.providers.is_empty()
696    }
697}
698
699impl ResourcePolicyProvider for MultiResourcePolicyProvider {
700    fn resource_policy(&self, service: &str, resource_arn: &str) -> Option<String> {
701        self.providers
702            .iter()
703            .find_map(|p| p.resource_policy(service, resource_arn))
704    }
705
706    fn resource_owner_account(&self, service: &str, resource_arn: &str) -> Option<String> {
707        self.providers
708            .iter()
709            .find_map(|p| p.resource_owner_account(service, resource_arn))
710    }
711
712    fn public_acl_allows(&self, service: &str, resource_arn: &str, action: &str) -> bool {
713        self.providers
714            .iter()
715            .any(|p| p.public_acl_allows(service, resource_arn, action))
716    }
717}
718
719/// How IAM identity policies are evaluated for incoming requests.
720///
721/// Default is [`IamMode::Off`] — existing behavior, policies are stored but
722/// never consulted. [`IamMode::Soft`] evaluates and logs denied decisions via
723/// the `fakecloud::iam::audit` tracing target without failing the request, and
724/// [`IamMode::Strict`] returns an `AccessDeniedException` in the protocol-
725/// correct shape.
726#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
727pub enum IamMode {
728    /// Do not evaluate IAM policies.
729    #[default]
730    Off,
731    /// Evaluate policies and log audit events for denied requests, but allow
732    /// the request to proceed.
733    Soft,
734    /// Evaluate policies and reject denied requests with `AccessDeniedException`.
735    Strict,
736}
737
738impl IamMode {
739    /// Returns true when policy evaluation should occur at all.
740    pub fn is_enabled(self) -> bool {
741        !matches!(self, IamMode::Off)
742    }
743
744    /// Returns true when denied decisions should fail the request.
745    pub fn is_strict(self) -> bool {
746        matches!(self, IamMode::Strict)
747    }
748
749    pub fn as_str(self) -> &'static str {
750        match self {
751            IamMode::Off => "off",
752            IamMode::Soft => "soft",
753            IamMode::Strict => "strict",
754        }
755    }
756}
757
758impl fmt::Display for IamMode {
759    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760        f.write_str(self.as_str())
761    }
762}
763
764/// Parse error for [`IamMode`] from string.
765#[derive(Debug)]
766pub struct ParseIamModeError(String);
767
768impl fmt::Display for ParseIamModeError {
769    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
770        write!(
771            f,
772            "invalid IAM mode `{}`; expected one of: off, soft, strict",
773            self.0
774        )
775    }
776}
777
778impl std::error::Error for ParseIamModeError {}
779
780impl FromStr for IamMode {
781    type Err = ParseIamModeError;
782
783    fn from_str(s: &str) -> Result<Self, Self::Err> {
784        match s.trim().to_ascii_lowercase().as_str() {
785            "off" | "none" | "disabled" => Ok(IamMode::Off),
786            "soft" | "audit" | "warn" => Ok(IamMode::Soft),
787            "strict" | "enforce" | "deny" => Ok(IamMode::Strict),
788            other => Err(ParseIamModeError(other.to_string())),
789        }
790    }
791}
792
793/// Reserved root-identity convention.
794///
795/// Any access key whose ID begins with `test` (case-insensitive) is treated as
796/// the de-facto root bypass. This matches the long-standing community
797/// convention used by LocalStack and Floci: `test`/`test` credentials should
798/// always "just work" for local development.
799///
800/// When SigV4 verification or IAM enforcement is enabled, callers using a
801/// bypass AKID skip both checks. We emit a one-time startup WARN whenever
802/// enforcement is turned on so users understand that unsigned `test` clients
803/// will silently receive positive results.
804pub fn is_root_bypass(access_key_id: &str) -> bool {
805    access_key_id
806        .trim()
807        .get(..4)
808        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("test"))
809}
810
811#[cfg(test)]
812mod tests {
813    use super::*;
814
815    #[test]
816    fn iam_mode_default_is_off() {
817        assert_eq!(IamMode::default(), IamMode::Off);
818        assert!(!IamMode::default().is_enabled());
819    }
820
821    #[test]
822    fn iam_mode_from_str_accepts_primary_values() {
823        assert_eq!(IamMode::from_str("off").unwrap(), IamMode::Off);
824        assert_eq!(IamMode::from_str("soft").unwrap(), IamMode::Soft);
825        assert_eq!(IamMode::from_str("strict").unwrap(), IamMode::Strict);
826    }
827
828    #[test]
829    fn iam_mode_from_str_is_case_insensitive_and_trimmed() {
830        assert_eq!(IamMode::from_str(" OFF ").unwrap(), IamMode::Off);
831        assert_eq!(IamMode::from_str("Soft").unwrap(), IamMode::Soft);
832        assert_eq!(IamMode::from_str("STRICT").unwrap(), IamMode::Strict);
833    }
834
835    #[test]
836    fn iam_mode_from_str_accepts_aliases() {
837        assert_eq!(IamMode::from_str("disabled").unwrap(), IamMode::Off);
838        assert_eq!(IamMode::from_str("audit").unwrap(), IamMode::Soft);
839        assert_eq!(IamMode::from_str("enforce").unwrap(), IamMode::Strict);
840    }
841
842    #[test]
843    fn iam_mode_from_str_rejects_garbage() {
844        assert!(IamMode::from_str("").is_err());
845        assert!(IamMode::from_str("allow").is_err());
846        assert!(IamMode::from_str("yes").is_err());
847    }
848
849    #[test]
850    fn iam_mode_display_roundtrips() {
851        for mode in [IamMode::Off, IamMode::Soft, IamMode::Strict] {
852            assert_eq!(IamMode::from_str(&mode.to_string()).unwrap(), mode);
853        }
854    }
855
856    #[test]
857    fn iam_mode_flags() {
858        assert!(!IamMode::Off.is_enabled());
859        assert!(!IamMode::Off.is_strict());
860        assert!(IamMode::Soft.is_enabled());
861        assert!(!IamMode::Soft.is_strict());
862        assert!(IamMode::Strict.is_enabled());
863        assert!(IamMode::Strict.is_strict());
864    }
865
866    #[test]
867    fn root_bypass_matches_test_prefix() {
868        assert!(is_root_bypass("test"));
869        assert!(is_root_bypass("TEST"));
870        assert!(is_root_bypass("Test"));
871        assert!(is_root_bypass("testAccessKey"));
872        assert!(is_root_bypass("TESTAKIAIOSFODNN7EXAMPLE"));
873    }
874
875    #[test]
876    fn root_bypass_does_not_panic_on_multibyte_input() {
877        // Byte index 4 falls inside a multi-byte UTF-8 character; must not panic.
878        assert!(!is_root_bypass("té"));
879        assert!(!is_root_bypass("日本語キー"));
880        assert!(!is_root_bypass("🔑🔑"));
881    }
882
883    #[test]
884    fn principal_type_from_arn_classifies_known_shapes() {
885        assert_eq!(
886            PrincipalType::from_arn("arn:aws:iam::123456789012:user/alice"),
887            PrincipalType::User
888        );
889        assert_eq!(
890            PrincipalType::from_arn("arn:aws:sts::123456789012:assumed-role/R/s"),
891            PrincipalType::AssumedRole
892        );
893        assert_eq!(
894            PrincipalType::from_arn("arn:aws:sts::123456789012:federated-user/bob"),
895            PrincipalType::FederatedUser
896        );
897        assert_eq!(
898            PrincipalType::from_arn("arn:aws:iam::123456789012:root"),
899            PrincipalType::Root
900        );
901    }
902
903    #[test]
904    fn principal_type_unparseable_is_unknown_not_root() {
905        // Identified by cubic on PR #391: falling back to Root would let
906        // malformed or unexpected ARNs bypass IAM enforcement, since
907        // Principal::is_root short-circuits evaluation. The fallback must
908        // be the non-bypassable Unknown variant.
909        assert_eq!(
910            PrincipalType::from_arn("not-an-arn"),
911            PrincipalType::Unknown
912        );
913        assert_eq!(PrincipalType::from_arn(""), PrincipalType::Unknown);
914        assert_eq!(
915            PrincipalType::from_arn("arn:aws:iam::123456789012:something-weird"),
916            PrincipalType::Unknown
917        );
918
919        // And a Principal built from an Unknown ARN must not be treated
920        // as root for enforcement decisions.
921        let p = Principal {
922            arn: "garbage".to_string(),
923            user_id: "x".to_string(),
924            account_id: "123456789012".to_string(),
925            principal_type: PrincipalType::Unknown,
926            source_identity: None,
927            tags: None,
928        };
929        assert!(!p.is_root());
930    }
931
932    #[test]
933    fn principal_is_root_covers_root_type_and_arn_suffix() {
934        let p = Principal {
935            arn: "arn:aws:iam::123456789012:root".to_string(),
936            user_id: "AIDAROOT".to_string(),
937            account_id: "123456789012".to_string(),
938            principal_type: PrincipalType::Root,
939            source_identity: None,
940            tags: None,
941        };
942        assert!(p.is_root());
943
944        let user = Principal {
945            arn: "arn:aws:iam::123456789012:user/alice".to_string(),
946            user_id: "AIDAALICE".to_string(),
947            account_id: "123456789012".to_string(),
948            principal_type: PrincipalType::User,
949            source_identity: None,
950            tags: None,
951        };
952        assert!(!user.is_root());
953    }
954
955    #[test]
956    fn resolved_credential_accessors_forward_to_principal() {
957        let rc = ResolvedCredential {
958            secret_access_key: "s".into(),
959            session_token: None,
960            principal: Principal {
961                arn: "arn:aws:iam::123456789012:user/alice".into(),
962                user_id: "AIDAALICE".into(),
963                account_id: "123456789012".into(),
964                principal_type: PrincipalType::User,
965                source_identity: None,
966                tags: None,
967            },
968            session_policies: Vec::new(),
969            mfa_present: false,
970            token_issued_at: None,
971            federated_provider: None,
972        };
973        assert_eq!(rc.principal_arn(), "arn:aws:iam::123456789012:user/alice");
974        assert_eq!(rc.user_id(), "AIDAALICE");
975        assert_eq!(rc.account_id(), "123456789012");
976    }
977
978    #[test]
979    fn root_bypass_rejects_non_test_keys() {
980        assert!(!is_root_bypass(""));
981        assert!(!is_root_bypass("   "));
982        assert!(!is_root_bypass("AKIAIOSFODNN7EXAMPLE"));
983        assert!(!is_root_bypass("FKIA123456"));
984        assert!(!is_root_bypass("tes"));
985        assert!(!is_root_bypass("tst"));
986    }
987
988    // --- MultiResourcePolicyProvider composite -------------------------
989
990    /// Test provider that returns a canned document for one
991    /// (service, arn) pair and `None` for everything else.
992    struct FakeProvider {
993        service: &'static str,
994        arn: &'static str,
995        policy: &'static str,
996    }
997
998    impl ResourcePolicyProvider for FakeProvider {
999        fn resource_policy(&self, service: &str, resource_arn: &str) -> Option<String> {
1000            if service.eq_ignore_ascii_case(self.service) && resource_arn == self.arn {
1001                Some(self.policy.to_string())
1002            } else {
1003                None
1004            }
1005        }
1006    }
1007
1008    fn fake(
1009        service: &'static str,
1010        arn: &'static str,
1011        policy: &'static str,
1012    ) -> Arc<dyn ResourcePolicyProvider> {
1013        Arc::new(FakeProvider {
1014            service,
1015            arn,
1016            policy,
1017        })
1018    }
1019
1020    #[test]
1021    fn multi_provider_empty_always_returns_none() {
1022        let m = MultiResourcePolicyProvider::new(vec![]);
1023        assert!(m.is_empty());
1024        assert_eq!(m.len(), 0);
1025        assert_eq!(m.resource_policy("s3", "arn:aws:s3:::x"), None);
1026    }
1027
1028    #[test]
1029    fn multi_provider_delegates_to_single_child() {
1030        let m = MultiResourcePolicyProvider::new(vec![fake("s3", "arn:aws:s3:::b", r#"{"v":1}"#)]);
1031        assert_eq!(m.len(), 1);
1032        assert_eq!(
1033            m.resource_policy("s3", "arn:aws:s3:::b").as_deref(),
1034            Some(r#"{"v":1}"#)
1035        );
1036        assert_eq!(m.resource_policy("s3", "arn:aws:s3:::missing"), None);
1037        assert_eq!(m.resource_policy("sns", "arn:aws:s3:::b"), None);
1038    }
1039
1040    #[test]
1041    fn multi_provider_hits_first_matching_child() {
1042        let m = MultiResourcePolicyProvider::new(vec![
1043            fake("s3", "arn:aws:s3:::b", r#"{"v":"s3"}"#),
1044            fake("sns", "arn:aws:sns:us-east-1:123:t", r#"{"v":"sns"}"#),
1045        ]);
1046        assert_eq!(
1047            m.resource_policy("s3", "arn:aws:s3:::b").as_deref(),
1048            Some(r#"{"v":"s3"}"#)
1049        );
1050        assert_eq!(
1051            m.resource_policy("sns", "arn:aws:sns:us-east-1:123:t")
1052                .as_deref(),
1053            Some(r#"{"v":"sns"}"#)
1054        );
1055    }
1056
1057    #[test]
1058    fn multi_provider_is_order_independent_when_services_differ() {
1059        // Because each concrete provider gates on its own service
1060        // prefix, swapping the order must never change the result.
1061        let children: Vec<Arc<dyn ResourcePolicyProvider>> = vec![
1062            fake("s3", "arn:aws:s3:::b", "s3-doc"),
1063            fake("sns", "arn:aws:sns:us-east-1:123:t", "sns-doc"),
1064            fake(
1065                "lambda",
1066                "arn:aws:lambda:us-east-1:123:function:f",
1067                "lam-doc",
1068            ),
1069        ];
1070        let forward = MultiResourcePolicyProvider::new(children.clone());
1071        let reversed = MultiResourcePolicyProvider::new({
1072            let mut v = children.clone();
1073            v.reverse();
1074            v
1075        });
1076        for (svc, arn) in [
1077            ("s3", "arn:aws:s3:::b"),
1078            ("sns", "arn:aws:sns:us-east-1:123:t"),
1079            ("lambda", "arn:aws:lambda:us-east-1:123:function:f"),
1080        ] {
1081            assert_eq!(
1082                forward.resource_policy(svc, arn),
1083                reversed.resource_policy(svc, arn),
1084                "service {svc}"
1085            );
1086        }
1087    }
1088
1089    #[test]
1090    fn multi_provider_returns_none_for_unhandled_service() {
1091        let m = MultiResourcePolicyProvider::new(vec![fake("s3", "arn:aws:s3:::b", "doc")]);
1092        assert_eq!(
1093            m.resource_policy("kms", "arn:aws:kms:us-east-1:123:key/k"),
1094            None
1095        );
1096        assert_eq!(m.resource_policy("iam", "arn:aws:iam::123:role/r"), None);
1097    }
1098
1099    #[test]
1100    fn multi_provider_shared_wraps_in_arc() {
1101        let arc = MultiResourcePolicyProvider::shared(vec![fake("s3", "arn:aws:s3:::b", "doc")]);
1102        assert_eq!(
1103            arc.resource_policy("s3", "arn:aws:s3:::b").as_deref(),
1104            Some("doc")
1105        );
1106    }
1107
1108    // --- ABAC tag condition key lookup ------------------------------------
1109
1110    #[test]
1111    fn lookup_mfa_present_emits_bool_string() {
1112        let ctx = ConditionContext {
1113            aws_mfa_present: Some(true),
1114            ..Default::default()
1115        };
1116        assert_eq!(
1117            ctx.lookup("aws:MultiFactorAuthPresent"),
1118            Some(vec!["true".to_string()])
1119        );
1120        let ctx = ConditionContext {
1121            aws_mfa_present: Some(false),
1122            ..Default::default()
1123        };
1124        assert_eq!(
1125            ctx.lookup("aws:multifactorauthpresent"),
1126            Some(vec!["false".to_string()])
1127        );
1128    }
1129
1130    #[test]
1131    fn lookup_mfa_age_emits_seconds() {
1132        let ctx = ConditionContext {
1133            aws_mfa_age_seconds: Some(900),
1134            ..Default::default()
1135        };
1136        assert_eq!(
1137            ctx.lookup("aws:MultiFactorAuthAge"),
1138            Some(vec!["900".to_string()])
1139        );
1140    }
1141
1142    #[test]
1143    fn lookup_called_via_returns_full_chain() {
1144        let ctx = ConditionContext {
1145            aws_called_via: vec![
1146                "cloudformation.amazonaws.com".to_string(),
1147                "lambda.amazonaws.com".to_string(),
1148            ],
1149            ..Default::default()
1150        };
1151        assert_eq!(
1152            ctx.lookup("aws:CalledVia"),
1153            Some(vec![
1154                "cloudformation.amazonaws.com".to_string(),
1155                "lambda.amazonaws.com".to_string(),
1156            ])
1157        );
1158    }
1159
1160    #[test]
1161    fn lookup_called_via_empty_returns_none() {
1162        let ctx = ConditionContext::default();
1163        assert_eq!(ctx.lookup("aws:CalledVia"), None);
1164    }
1165
1166    #[test]
1167    fn lookup_source_vpc_keys() {
1168        let ctx = ConditionContext {
1169            aws_source_vpc: Some("vpc-123".to_string()),
1170            aws_source_vpce: Some("vpce-456".to_string()),
1171            aws_vpc_source_ip: Some("10.0.1.5".parse::<IpAddr>().unwrap()),
1172            ..Default::default()
1173        };
1174        assert_eq!(
1175            ctx.lookup("aws:SourceVpc"),
1176            Some(vec!["vpc-123".to_string()])
1177        );
1178        assert_eq!(
1179            ctx.lookup("aws:SourceVpce"),
1180            Some(vec!["vpce-456".to_string()])
1181        );
1182        assert_eq!(
1183            ctx.lookup("aws:VpcSourceIp"),
1184            Some(vec!["10.0.1.5".to_string()])
1185        );
1186    }
1187
1188    #[test]
1189    fn lookup_federated_provider_and_token_issue_time() {
1190        use chrono::TimeZone;
1191        let ctx = ConditionContext {
1192            aws_federated_provider: Some("cognito-identity.amazonaws.com".to_string()),
1193            aws_token_issue_time: Some(
1194                chrono::Utc.with_ymd_and_hms(2026, 4, 30, 12, 0, 0).unwrap(),
1195            ),
1196            ..Default::default()
1197        };
1198        assert_eq!(
1199            ctx.lookup("aws:FederatedProvider"),
1200            Some(vec!["cognito-identity.amazonaws.com".to_string()])
1201        );
1202        assert_eq!(
1203            ctx.lookup("aws:TokenIssueTime"),
1204            Some(vec!["2026-04-30T12:00:00Z".to_string()])
1205        );
1206    }
1207
1208    fn abac_context() -> ConditionContext {
1209        ConditionContext {
1210            resource_tags: Some(
1211                [("Environment", "prod"), ("CostCenter", "42")]
1212                    .iter()
1213                    .map(|(k, v)| (k.to_string(), v.to_string()))
1214                    .collect(),
1215            ),
1216            request_tags: Some(
1217                [("Project", "web"), ("Team", "platform")]
1218                    .iter()
1219                    .map(|(k, v)| (k.to_string(), v.to_string()))
1220                    .collect(),
1221            ),
1222            principal_tags: Some(
1223                [("Department", "eng"), ("Role", "developer")]
1224                    .iter()
1225                    .map(|(k, v)| (k.to_string(), v.to_string()))
1226                    .collect(),
1227            ),
1228            ..Default::default()
1229        }
1230    }
1231
1232    #[test]
1233    fn lookup_resource_tag_case_sensitive_key() {
1234        let ctx = abac_context();
1235        assert_eq!(
1236            ctx.lookup("aws:ResourceTag/Environment"),
1237            Some(vec!["prod".to_string()])
1238        );
1239        // Different case -> different tag key -> None
1240        assert_eq!(ctx.lookup("aws:ResourceTag/environment"), None);
1241    }
1242
1243    #[test]
1244    fn lookup_resource_tag_prefix_case_insensitive() {
1245        let ctx = abac_context();
1246        // Prefix is case-insensitive per AWS
1247        assert_eq!(
1248            ctx.lookup("AWS:resourcetag/Environment"),
1249            Some(vec!["prod".to_string()])
1250        );
1251        assert_eq!(
1252            ctx.lookup("Aws:RESOURCETAG/CostCenter"),
1253            Some(vec!["42".to_string()])
1254        );
1255    }
1256
1257    #[test]
1258    fn lookup_request_tag() {
1259        let ctx = abac_context();
1260        assert_eq!(
1261            ctx.lookup("aws:RequestTag/Project"),
1262            Some(vec!["web".to_string()])
1263        );
1264        assert_eq!(ctx.lookup("aws:RequestTag/project"), None);
1265    }
1266
1267    #[test]
1268    fn lookup_principal_tag() {
1269        let ctx = abac_context();
1270        assert_eq!(
1271            ctx.lookup("aws:PrincipalTag/Department"),
1272            Some(vec!["eng".to_string()])
1273        );
1274        assert_eq!(ctx.lookup("aws:PrincipalTag/department"), None);
1275    }
1276
1277    #[test]
1278    fn lookup_tag_keys_returns_all_request_tag_keys() {
1279        let ctx = abac_context();
1280        let mut keys = ctx.lookup("aws:TagKeys").unwrap();
1281        keys.sort();
1282        assert_eq!(keys, vec!["Project", "Team"]);
1283    }
1284
1285    #[test]
1286    fn lookup_tag_keys_case_insensitive() {
1287        let ctx = abac_context();
1288        assert!(ctx.lookup("AWS:TAGKEYS").is_some());
1289        assert!(ctx.lookup("aws:tagkeys").is_some());
1290    }
1291
1292    #[test]
1293    fn lookup_tag_none_when_field_not_set() {
1294        let ctx = ConditionContext::default();
1295        assert_eq!(ctx.lookup("aws:ResourceTag/Foo"), None);
1296        assert_eq!(ctx.lookup("aws:RequestTag/Foo"), None);
1297        assert_eq!(ctx.lookup("aws:PrincipalTag/Foo"), None);
1298        assert_eq!(ctx.lookup("aws:TagKeys"), None);
1299    }
1300
1301    #[test]
1302    fn lookup_tag_missing_key_returns_none() {
1303        let ctx = abac_context();
1304        assert_eq!(ctx.lookup("aws:ResourceTag/NonExistent"), None);
1305        assert_eq!(ctx.lookup("aws:RequestTag/NonExistent"), None);
1306        assert_eq!(ctx.lookup("aws:PrincipalTag/NonExistent"), None);
1307    }
1308}