mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
7dc514b52f2c96bdd1ea32ae64a02703f85be2aa
95
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c17bd49096 |
fix(s3): check bucket policies for the actions IAM checks (#5913)
S3's own access check under floci.services.s3.enforce-auth, which evaluates bucket policies and ACLs, lagged behind IAM enforcement. It checked a version's tagging, ACL and annotation requests as the base actions, an object created with tags, an ACL or Object Lock settings as s3:PutObject alone, GetObjectAttributes without the read, and a write carrying If-Match without the read IAM checks for it. It offered a bucket policy none of the request's condition keys, and asked for s3:BypassGovernanceRetention on an annotation delete, which the user guide says the permission "does not apply to". The bucket-policy check now checks the actions IAM does: the version counterpart when a request names a versionId, the tagging, ACL, retention and legal-hold actions an object creation's settings need, a copy of a tagged source included, s3:GetObject beside s3:GetObjectAttributes and beside an If-Match write, and no bypass permission on an annotation delete. A signed request's bucket policy is offered the tag and Object Lock keys the request sets: an object creation's headers and the tagging, retention and legal-hold bodies, read by the same S3ObjectActions helpers IAM's condition resolver now uses. s3:BypassGovernanceRetention is asked for only by a request that overrides a governance lock, by IAM and by the bucket policy. The user guide's permissions table requires it "if you want to delete an object that's protected by governance mode" and to "bypass the governance mode of an Object Lock retention configuration", and DeleteObjects already asked for it only then. DeleteObject and PutObjectRetention asked for it whenever the header was sent; they now ask only for a delete that removes a version under a governance lock, not one that only adds a delete marker, and for a retention change that shortens or removes one. The IAM condition resolver now reads the object key from the path as it arrived, as S3Controller does, through the new S3ObjectKeys: the normalized path drops a key's leading slash, so the lock and the s3:ExistingObjectTag tags of "/doc" were looked up on "doc". A CopyObject replacing its source's tags reads x-amz-tagging from the query as well, as PutObject does, so it applies the tags both checks saw. An anonymous creation that a public bucket ACL's WRITE grant admits may still apply its ACL, tags and Object Lock settings, unless a public bucket policy decides their actions, since an ACL grant names no actions. The creation checks are told whether a request is a CopyObject rather than guessing it from x-amz-copy-source, which a CreateMultipartUpload ignores while it applies its own tags, so those tags are always checked, by IAM and by the bucket policy. With an access check on, a DeleteObject, a DeleteObjects entry and a PutObjectRetention hand S3Service the bypass only when they override a lock whose bypass permission the checks approved, IAM's decision travelling in RequestContext, so a lock set after the checks is refused rather than bypassed unchecked. Refs #5716 |
||
|
|
377c09733a |
fix(s3): check a presigned copy's source read against its credential (#5891)
Under IAM enforcement, CopyObject and UploadPartCopy also need s3:GetObject on the copy source, or s3:GetObjectVersion for a version, and S3Controller checks it itself, since the source appears only in the x-amz-copy-source header. It passed IAM the Authorization header, which a presigned request does not have, so IAM skipped the check. A user allowed to write one place could presign a copy of any object they cannot read into it. The check now uses the request's credential, the header's or a presigned URL's query credential, as the copied-tags check next to it already does. The S3 user guide says "The capabilities of a presigned URL are limited by the permissions of the user who created it." The test signer's presignedQuery also signs the parameters already in its URI's query, such as an UploadPartCopy's upload id, so a presigned part copy verifies, and refuses a URI that is already presigned. docs/services/iam.md lists the copy source check. |
||
|
|
66fce77bdc |
feat(iam): generate, claim and answer delegation requests (#5797)
IAM temporary delegation lets an AWS Partner ask a customer for scoped, time-limited access to the customer's account: the partner files a request, the customer claims and answers it, and an accepted request releases an exchange token the partner trades for credentials. Floci dispatched none of it, so all seven lifecycle operations answered UnsupportedOperation 400. The family was filed as a non-goal on the strength of CreateDelegationRequest stating "This API is not available for general use. In order to use this API, a caller first need to go through an onboarding process described in the partner onboarding documentation". That sentence appears exactly once in the whole API reference, and the partner user guide describes a generally available feature with a published lifecycle. The gate is an AWS-side account allowlist for ISV Accelerate partners, "Enable API access for your specified accounts", not a protocol behaviour, and an emulator has no allowlist. Answering NoSuchEntity because nothing can exist would emulate the feature's absence rather than the feature. This is the lifecycle half: Create, Associate, Accept, Reject, Update, Get and List. SendDelegationToken and STS GetDelegatedAccessToken are the token exchange and come next, so no request reaches FINALIZED yet, and GetHumanReadableSummary stays undispatched because its summary is LLM- generated on AWS. A delegation request is the one IAM record two accounts share, which decides how it is stored: keyed by id under the creating account and resolved across accounts on read, because the reference makes the id globally resolvable and decides access from the request's own owner fields. A request nobody owns "can be called by any account"; one naming a target account is readable only from there, which is why a partner loses sight of its own filing once it is aimed. Floci decides that at account granularity, there being no per- identity permission on a request to consult. ListDelegationRequests leaves out a request with no owner even when it names the listing account, as the reference states, so a partner does not list its own filings at all, which matches the guide telling partners to track state from the notifications. Expiry is applied when a request is next read rather than swept by a worker. Each state carries the window AWS publishes, a day for UNASSIGNED and a week for every other state including the terminal ones, and a request past its window reads back as EXPIRED. That needs no scheduler to be correct and no clock to be mocked globally, so the service takes its own Clock and the unit test advances that rather than the shared test clock. Two answers had to be chosen rather than read off. An operation asked to move a request out of a state it no longer holds answers ConcurrentModification: no modeled error says "wrong state", and AcceptDelegationRequest models only NoSuchEntity, ServiceFailure and ConcurrentModification, so the conflict is the closest of the three and is used on all four writers rather than a different code each. PermissionCheckResult answers UNSURE when the check is asked for, which the enum models, because a delegation request carries no permission to evaluate. A member that breaks the format or constraints it declares answers ValidationError. The reference publishes that as a common error, "the input doesn't meet the required format or constraints", for every IAM operation while listing it on no operation at all, which is why it appears in no error table and in none of these; the rest of IAM answers it in the same shape and wording, so these operations do too. The InvalidInput they do model is kept for a value that cannot be read as the member's type, which is where the shared pagination already puts a MaxItems that is not a number. A lifecycle call reads a request, checks its state and writes it back, so all of them take one lock, as the sibling IAM services do with theirs. Without it two callers could both claim the same unassigned request and the later write would decide the owner, and two creates could both pass the workflow-id uniqueness check. Each call also takes a single clock reading, threaded from the lookup into the transition, so a request cannot be expired on the way in and moved on anyway. Two shape details come from the pinned botocore model rather than the reference PDF, which omits both: GetDelegationRequest also takes DelegationPermissionCheck and answers PermissionCheckStatus and PermissionCheckResult, and ListDelegationRequests spells its flag isTruncated in lower case where every other IAM list spells it IsTruncated. The model names the member, so the wire follows the model. SessionDuration's 300 to 43200 range, PolicyParameter's shape and the 100-default, 1000-maximum page size come from there too. The CLI reference supplies the constraints the PDF leaves hard to read: the redirect URL's whole pattern, which the PDF breaks across a line, the character class the free-text members carry, and the printable-ASCII class on a policy parameter's name and values. Each is enforced. It also settles that the Permissions structure is required while both of its members are optional, marking neither. Reading it is what caught an empty required member being treated as an omission: Description is required and its pattern permits an empty string, so Description= is a value and only an absent member is missing, which is a distinction that exists on the wire and is tested there. Notes and RejectionReason both exist on the shape and each gets exactly one writer: an update carries notes for an administrator and a rejection carries the explanation the reference describes for it. An indexed member is read from the keys the request carries rather than counted up from one, so Parameters.member.2 without a member.1 keeps its entry instead of being dropped at the gap, and a boolean member has to carry true or false rather than being read as false for anything else. delegation-request leaves ResourceArnBuilder.UNRESOLVED_TYPES, since that entry claimed the type belongs only to actions nothing dispatches. The four by-id actions mint arn:<partition>:iam::<account>:delegation-request/<id> from the request, the same way the ARN-carrying actions pass an ARN through, one step earlier. CreateDelegationRequest stays at the wildcard because IAM assigns the id, and UpdateDelegationRequest stays there because AWS publishes no authorizable action for it at all. UnresolvedResourceTypesIntegrationTest would have failed until this was done, which is that test working as intended. The console deep link follows the partition too. CreateDelegationRequest answers the URL the partner redirects the customer to, and a caller in China or GovCloud was handed a console their account cannot reach. The host now comes from the region's partition, the way the CodePipeline approval links already resolve theirs, keeping the commercial console's path because that is the only path any partition publishes. The account-root stand-in behind an owner ARN is minted through RegionResolver for the same reason rather than concatenated, which is also the shape IamEnforcementFilter synthesizes. Nothing is enforced that AWS does not publish. LimitExceeded is modeled with no quota behind it, so none is invented. NotificationChannel is validated and stored and nothing reads it, there being no notification to send yet. PolicyTemplateArn is kept as given and resolved against nothing, templates being registered by email with no API. All four new model types are registered for reflection, the state enum included: it is reachable from a stored request, and a native image that cannot read it back loses every delegation request on restart, which is what the persistence guard checks. Twenty-seven unit tests drive the state machine, both expiry windows, the two races and the deep link in each partition, with a clock the test owns, and fifteen integration tests drive the lifecycle over the wire across two accounts, the access key id being the account id as the rest of the suite does it. Routing needs nothing added: #5879 has the Query router read each service's actions from its botocore model, which names all seven already, so the matrix row in docs/services/index.md moving 167 to 174 is the only count this changes. |
||
|
|
b0777a4020 |
fix(iam): check the actions an S3 operation needs besides its own (#5846)
Under IAM enforcement an S3 object operation was checked only as its own action. A PutObject, CopyObject or CreateMultipartUpload that set tags, an ACL, a retention period or a legal hold needed only s3:PutObject, GetObjectAttributes needed only the read, and a retention change or a delete asking to bypass governance retention needed no s3:BypassGovernanceRetention. No Object Lock condition key was offered. Each now also needs the actions the S3 user guide's permissions table and the API references require besides its own. An object creation needs the action of each setting it applies: s3:PutObjectTagging, s3:PutObjectAcl, s3:PutObjectRetention or s3:PutObjectLegalHold. A copy under the default COPY tagging directive keeps a tagged source's tags, so it needs s3:PutObjectTagging too, checked where the source is read against the request's credential, a presigned URL's included, and it offers no request tag keys from the x-amz-tagging header it ignores. GetObjectAttributes needs s3:GetObjectAttributes, or s3:GetObjectVersionAttributes for a version. A PutObjectRetention or DeleteObject that sends x-amz-bypass-governance-retention needs s3:BypassGovernanceRetention; an annotation delete does not, as the user guide says the permission does not apply to annotation operations. s3:PutObject, s3:PutObjectRetention and s3:PutObjectLegalHold are offered the Object Lock keys from the request's headers or body, and an object creation offers its tag and Object Lock keys to each extra action. A denial names the missing permission, and CloudTrail records the operation that was refused, PutObjectRetention and GetObjectAttributes included. Generated presigned URLs refuse all four creation settings, as they refused tags. Refs #5716 |
||
|
|
a611e9ea6f |
fix(iam): authorize Secrets Manager requests against the secret's ARN (#5781)
* fix(iam): authorize Secrets Manager requests against the secret's ARN IAM enforcement evaluated CreateSecret against secret:* because the builder read only SecretId, and a secret named by its name was evaluated as secret:<name>, without the random suffix every secret ARN carries. A secret:<name>-?????? policy, the pattern AWS documents for granting access to a secret that may not exist yet, matched neither. CreateSecret is now evaluated against secret:<Name>-??????, standing in for the suffix that is assigned at creation, and a name-based SecretId resolves to the stored secret's full ARN in the target account. Closes #5364 * fix(iam): pick the Secrets Manager target by the serving operation CreateSecret now reads only Name and other actions only SecretId, so a field the handler ignores cannot choose the resource. Minted ARNs take the request's partition, and a name lookup also reads a legacy unprefixed secret for the default account. Adds an SDK compatibility test. * fix(iam): resolve a partial-ARN SecretId to the stored secret's ARN A SecretId given as an ARN without the random suffix is now authorized against the stored secret's full ARN, resolved in the caller's account in the order the operations use: an exact ARN first, then the ARN read as a partial one. The enforcement tests share EnforcementFixtures' auth, a new assumeRole helper, and a new createRole helper that removes the role after the test. The Secrets Manager enforcement test also deletes the secrets it creates. |
||
|
|
92be67d2df |
fix(logs): enforce group permissions for lifecycle changes (#5840)
* fix(logs): enforce group permissions for lifecycle changes * fix(logs): accept bare group ARNs in lifecycle policies |
||
|
|
2f56c225dc |
docs(iam): note which resource policies are not evaluated (#4899)
The IAM page says S3 bucket, Lambda function and SNS topic policies take part in request authorization, but not that SQS queue and API Gateway REST API policies are stored without being evaluated. Add that next to the S3, Lambda and SNS bullets. No behaviour changes. |
||
|
|
49a3ff9a10 |
fix(logs): bind ARN tag operations to their owning group (#5810)
* fix(logs): bind ARN tag operations to their owning group * fix(logs): preserve literal names in tag requests * test(logs): share authorization fixtures |
||
|
|
7e98592761 |
fix(s3): act on the object version a tagging request names (#5775)
PutObjectTagging and DeleteObjectTagging ignored versionId and changed the current version. GetObjectTagging dropped it in the controller, so it read the current version too, and the service took versionId=null as the current version even on a key that has no null version. All three now act on the version named. "null" names only the null version, the object stored without a version id; on a key that has none the request answers NoSuchVersion. Each returns the version it acted on in x-amz-version-id. A request on a delete marker, named or current, answers 405 MethodNotAllowed with Method and ResourceType, and with x-amz-delete-marker: true, as S3 does. A put or delete runs under the bucket monitor that writes, deletes and the lifecycle sweep hold, so a version deleted between the lookup and the write is not written back. Since they act on the version named, a request naming one is now checked as s3:GetObjectVersionTagging, s3:PutObjectVersionTagging or s3:DeleteObjectVersionTagging, carrying s3:versionid, in place of the base tagging action. Part 1 kept these requests on the base actions because the operations changed the current version. The s3:ExistingObjectTag lookup already read the version named, so the tags a condition sees are now those of the version the request changes. The IAM condition context still reads s3:ExistingObjectTag for versionId=null from the current version, which GetObject still serves for it, so a deny on those tags keeps applying. Refs #5716 |
||
|
|
608a38bff3 |
fix(iam): read a role trust policy with the caller's principal keys (#5770)
A role's trust policy was the one context a request is evaluated against that did not say who was calling. AssumeRolePolicyEvaluator assembled its own map and put aws:PrincipalArn into it alone, so a trust policy keyed on aws:userid, aws:PrincipalType or aws:username could not match, where every other context a request is evaluated against carries all four through CallerArns.putPrincipalKeys. The user guide puts aws:PrincipalType and aws:userid in "the request context for all requests, including anonymous requests" and aws:username in it for every IAM user, and an sts:AssumeRole request is no exception: the guide's own example of a resource-based policy tells principals apart in a Condition on aws:userid. Raised by hectorvent on the review of #5568 and left to its own PR. The evaluator now takes the caller's CallerArns in place of its two ARN strings and writes the keys through that single writer, so no second context has to be kept in step. STS passes the caller it already resolves, and a credential that resolves to no identity is the account root stand-in it already names in its denial, now with the account's own keys: the guide gives the root user the account id as its aws:userid, the type Account and no aws:username, which is what S3 and the enforcement filter already build for it. That construction had three copies and is now one factory on the record. Step Functions passes the execution role as the session it is, carrying AssumedRole as its aws:PrincipalType: it assumes that role on the state machine's behalf, so a target role's trust policy may condition on the type. It mints no session name there, and a session's aws:userid is role-id:session-name, so that key and aws:username stay absent. AssumeRolePolicyEvaluatorTest builds its callers through the record, with three cases on the keys: a condition on aws:username matching the caller and not matching the same caller carrying no keys, aws:PrincipalType and aws:userid telling a user apart from a role session, and a value the caller carries winning over the request's own copy. AssumeRoleTrustConditionsIntegrationTest signs four more AssumeRole calls end to end, over a condition on the calling user's name, on the principal type, on the root stand-in's account id, and on a session's role-id:session-name. Reverting the evaluator to aws:PrincipalArn alone fails all seven; writing the keys with putIfAbsent instead fails the precedence case alone. LambdaTaskAuthorizerTest covers the Step Functions caller from both sides, a trust condition on the principal type matching it and one on the session's own id not matching. |
||
|
|
21184df828 |
fix(iam): authorize S3 object operations as the actions S3 documents (#5756)
Under IAM enforcement, CreateMultipartUpload, CompleteMultipartUpload, RestoreObject and SelectObjectContent were never checked against the caller's identity policies. They are POST requests, the registry had no S3 POST rule, and an action no rule maps is allowed. A user with no S3 permission could start and complete multipart uploads, restore objects and read them through Select. Many other S3 requests were checked as the wrong action: - ListParts and AbortMultipartUpload as s3:GetObject and s3:DeleteObject. - Object retention and legal hold as s3:GetObject and s3:PutObject, so a user allowed only to write objects could set a retention period or a legal hold. - Object annotations as the plain object actions. - A request naming a versionId as the current-version action. A deny on s3:DeleteObjectVersion, the usual guard against permanent deletes, did not stop one, and reading a version needed s3:GetObject rather than s3:GetObjectVersion. - Analytics, inventory and Intelligent-Tiering configurations as s3:ListBucket, s3:CreateBucket or s3:DeleteBucket. - DeleteBucketTagging as s3:DeleteBucketTagging, which is not an IAM action. A policy naming it granted the call, and one granting s3:PutBucketTagging, the action AWS checks, was refused. - A request naming two sub-resources as the first one the registry looked for. The controller runs a different one: GET ?acl&tagging returns the tags while needing only s3:GetObjectAcl. The object sub-resources are now resolved per method, in the order S3Controller dispatches them. A versionId selects the version action AWS checks for a read, head, delete, ACL or annotation request, and for Select, which S3Controller runs on the version named; the bucket configurations follow the controller's bucket chains. Tagging keeps the tagging actions: the tagging operations still act on the current version whatever versionId names, so a version tagging action would authorize one version and let the request change another. The actions come from the S3 user guide's "Required permissions for S3 API operations" and multipart permissions tables, the API reference and the Service Reference: - s3:PutObject for creating and completing an upload; - s3:RestoreObject, and s3:GetObject for Select; - s3:AbortMultipartUpload and s3:ListMultipartUploadParts; - the retention, legal-hold, version and configuration actions; - s3:PutBucketTagging for DeleteBucketTagging, and each configuration's Put action for its delete. A write carrying If-Match already needed s3:GetObject as well. The conditional-writes guide lists PutObject, CopyObject and CompleteMultipartUpload as the operations that take the header, so now that completing an upload is checked as s3:PutObject it gets that check too, while CreateMultipartUpload and UploadPart, which ignore the header, no longer do. A conditional delete with an If-Match ETag already needed s3:GetObject. A delete naming a version is now s3:DeleteObjectVersion, so that check covers it too, still as s3:GetObject: the conditional-deletes guide evaluates the condition against the current version only. Condition keys, per the Service Reference: - s3:versionid is given to the version actions. - s3:ExistingObjectTag is given to the version actions and the annotation actions, read from the version the request names. - DeleteBucketTagging, checked as s3:PutBucketTagging, keeps the bucket's tags in its context. CloudTrail denials name the version actions' operations, and give no name to a POST operation rather than a wrong one. The actions an operation needs besides its own, S3 behaviour behind these checks and S3's own bucket-policy check follow separately (#5716). Refs #5716 |
||
|
|
b58d181a30 |
feat(iam): authorize the account password policy's self-service flag (#5717)
The account password policy accepted AllowUsersToChangePassword, echoed it
back from GetAccountPasswordPolicy, and no authorization decision read it: the
six references in src/main were the field, its accessors, the setter call and
the XML element. So under enforcement a user needed a policy naming their own
user however the flag was set, and the option AWS describes as account-level
authorized nothing.
The user guide: the option "gives users access to the iam:ChangePassword
action for only their user and to the iam:GetAccountPasswordPolicy action",
and it "does not attach a permissions policy to each user. Rather, IAM applies
the permissions at the account-level for all users."
So it is one document for the whole account rather than a grant assembled per
user: iam:ChangePassword on user/${aws:username} and on
user/*/${aws:username}, the two patterns AWS's own IAMUserChangePassword
policy writes, the second for a user under a path, plus
iam:GetAccountPasswordPolicy. The resource ARNs are minted in the request's
partition, for the account whose password policy sets the flag.
Writing it with the variable rather than the caller's resolved ARN is what
makes it the grant the guide describes, and it carries two properties for
free. The scope to "only their user" is the variable's, so one stored document
serves every user in the account. And the grant belongs to IAM users without a
principal check of its own: a role session and the account root have no
aws:username, the variable resolves to nothing, and a resource holding a
variable with no value "will not match any resource". It therefore rests on the
substitution #5639 added, now on main; without it the statement is literal
text and matches nobody, which is what the probe below shows.
The grant reaches the caller wherever the principal is an IAM user: its own
access key, a session token it minted, and the simulate path. It is appended
to the identity policies the evaluator already reads, so nothing about
evaluation order changes: an explicit Deny still refuses the call and a
permissions boundary still caps it. collectUserPolicies stays the user's own
set, so ListUserPolicies, ListAttachedUserPolicies and
GetAccountAuthorizationDetails report nothing new, which is the "does not
attach a permissions policy" half of the guide.
That half holds for the answers AWS scopes to attached policies.
ListPoliciesGrantingServiceAccess reports policies by name and type and has
none to report here, and GetContextKeysForPrincipalPolicy returns "only
context keys referenced by the identity-based policies attached to the
specified entity, and any additional policies that you provide", so it reads
the attached set rather than the evaluated one: it had been naming the
${aws:username} of the grant's own resource, twice, once per pattern, out of
a document the user does not hold.
A last-accessed report answers the other question, "every AWS service that
the resource could access using permissions policies", and an account-level
permission is one the user can reach: GenerateServiceLastAccessedDetails
lists iam for a user carrying no policy of their own while the flag is set,
and nothing for that same user once it is cleared. The grant goes into the
documents the service list is read from rather than into the policies the
report names, since it is no policy of the user's and has no name or ARN to
report as one.
One thing the variable form exposed. SimulatePrincipalPolicy built its context
from the call's ContextEntries alone, so a policy scoped to ${aws:username}
simulated as if the key were absent and this grant answered implicitDeny for a
permission the account really gives. The guide lists what a simulation starts
with, "aws:PrincipalAccount, aws:PrincipalId, aws:PrincipalType, aws:Type,
aws:UserId, aws:UserName", adding that "because these keys are populated for
you ... You provide the values for all other condition keys". So the handler
now populates them for a user policy source, through the same CallerArns
writer the enforcement filter uses, which makes a simulation read what an
enforced request reads: aws:PrincipalArn, aws:PrincipalType, aws:username,
aws:userid and the account. The guide's aws:PrincipalId and aws:Type are in no
request context here, so a simulation does not invent them either, and iam.md
says so rather than leaving the list to imply all six. A value the call
supplied still wins, in whatever case it spelled the key, since the context is
keyed the way the evaluator compares key names: keyed by the raw spelling, a
supplied aws:principaltype and a populated aws:PrincipalType were two entries
and the later lowercasing kept whichever hashing happened to reach first. The
account comes from the identity that resolved rather than from the ARN the
call wrote, which need not be one this emulator can parse: a PolicySourceArn
is resolved by its trailing name, so arn:aws:iam:user/bob names a user while
parsing as nothing, and parsing the request's own text turned that call into a
500. A role named as the source is not a session: there is no session name for
an aws:userid and no documented aws:PrincipalType for it, so those keys stay
absent and a statement matching on one does not match.
The flag that answers for a user is their own account's. A PolicySourceArn is
the one way to name a user elsewhere, and the lookup already resolves them in
the account their ARN names, so the flag is read there as well and the grant's
resource ARNs are minted for that account. This account's grant therefore
never resolves ${aws:username} to a user its password policy does not cover,
and a user of another account is not refused a permission their own account
really gives: an allowed answer needs their account to set the flag and the
resource to be theirs.
Thirteen integration tests under enforcement: the flag letting a user with
no policies change its own password and read the policy, the grant appearing
in neither listing nor in GetAccountAuthorizationDetails, nor among the
context keys a simulation's caller is told to supply, while a policy the
user really carries appears in all three, a last-accessed report listing iam
for a user carrying nothing else while the flag is set and nothing once it
is cleared, an explicit Deny of iam:ChangePassword still refusing the call,
a permissions boundary still capping it, the grant reaching none of GetUser,
UpdateLoginProfile or CreateUser, the flag read both ways by one user whose
policies never change, the scope checked through SimulatePrincipalPolicy
against another user's ARN, a supplied context value surviving a key spelled
in another case, a PolicySourceArn that parses as nothing still simulating,
this account's flag not reaching a user of another account, and that user's
own account's flag reaching them over their own ARNs. Each of the
authorizing ones ends on something only the grant allows, which the first
round of them lacked: two asserted refusals alone and passed with the grant
withheld. Probed six ways, by withholding the grant, by disabling
substitution, by dropping the simulator's populated keys, and by reverting
each of three tests' fixes, failing all ten, all ten, the one simulation,
and one test apiece. The three added here were probed the same way, one
behaviour at a time: the other account's user went back to implicitDeny, the
context keys answered aws:username twice, and withholding the grant from the
report emptied it.
Verified on main: 6680 tests across the 342 IAM, core, enforcement and
resource-policy classes that reach the evaluator, 13 skipped and none
failing, with Checkstyle, docs-check and partition-check clean, the last
because the grant mints its resource ARNs rather than writing a partition
literal.
|
||
|
|
dbe7fdb92e |
fix(logs): enforce stream resource permissions (#5694)
* fix(logs): enforce stream resource permissions * fix(logs): retain request partitions for stream permissions |
||
|
|
425cd3167d |
feat(iam): resolve policy variables in Resource patterns and Condition values (#5639)
A ${...} in a Resource pattern or a Condition value was matched as the text it
is written as, so a statement scoped to arn:aws:iam::*:user/${aws:username}
matched no user at all. AWS's own IAMUserChangePassword policy is written that
way and floci vendors it verbatim, so under enforcement it authorized nothing,
and it is not alone: 244 of the 1586 vendored managed policy documents carry a
variable, and of the 1635 occurrences in them 1443 sit in a Condition value
and 192 in a Resource. The Condition share is where the loss bites hardest,
since a variable that cannot resolve quietly drops a Deny that AWS honours.
The keys a variable resolves against arrived with #5568, which put
aws:username, aws:userid and aws:PrincipalType into the request context. This
is the other half of that work: without substitution the keys answer nobody,
and without the keys substitution has nothing to find.
Variables now resolve wherever the evaluator matches a statement, which covers
every document it reads: identity policies, resource policies, session
policies, permissions boundaries, SCPs, and the Condition of a role trust
policy, whose own Version now reaches the condition check. A trust policy is
the narrow case, since sts:AssumeRole is authorized before there is a session
to describe: that context carries aws:PrincipalArn, the account and region
keys, sts:RoleSessionName and sts:ExternalId, so a variable naming
aws:username, aws:userid or aws:PrincipalType finds nothing there, which
iam.md now says.
Two of the rules are easy to miss. Substitution is gated on "Version":
"2012-10-17", because under the older 2008-10-17, which is also the default
when the element is absent, the user guide says variables "are instead treated
as literal strings in the policy"; the version therefore rides on each parsed
statement, since statements from many documents are evaluated as one list. And
a variable with no value is not an empty string: in Resource the pattern "will
not match any resource", in NotResource that same rule excludes nothing, and
in a Condition the positive operators do not match while the inverted ones do,
which is what makes the Deny AWS documents for an unset principal tag fire.
The rest, also from the user guide: a variable resolves only in the resource
portion of an ARN, after the fifth colon; only with the string and ARN
condition operators, never Numeric, Date, Bool, IpAddress or Null; only for a
single-valued key, a multivalued one having no one value to stand in, which a
default does not rescue, since a default answers a key with no value rather
than one with several; and case-insensitively by key name, a name that holds
no space, the guide allowing one inside a quoted default and nowhere else. A
spaced name, an empty ${}, a missing brace and an unquoted default are the
forms the guide's policy checks call errors, and each stays the text it is.
${*}, ${?} and ${$} stand for a literal character, so the glob gained an
escape marker, honoured only on a pattern that came back from substitution and
stripped from whatever arrived in the policy: a document can write the marker
as a JSON escape, and reading it as one would turn a wildcard of the
document's own into a literal character and narrow the statement it sits in. A
resolved value is not escaped, matching AWS, whose policy checks warn that
variables "can be evaluated as effective wildcards".
Verified at this commit: 7442 tests across the 439 IAM, core, enforcement and
resource-policy classes the evaluator is reached from, Checkstyle and
docs-check clean. AWS's own IAMUserChangePassword document is attached to a
user and called on the request path, both of its patterns included, the second
scoping a user under a path. Each rule was probed by reverting it alone, which
is how two weak tests were found: a valueless variable beside a wildcard and
the operator restriction both needed a case whose answer flips. The escape
marker is probed from both sides, by letting the resolver keep one that
arrived in a policy and by honouring markers on every pattern rather than only
a substituted one, and each side fails a different case of the same test.
|
||
|
|
29ead624f8 |
fix(iam): authorize a Smithy RPC v2 call as the operation its route runs (#5620)
A Smithy RPC v2 call names its operation in the path, /service/<service>/operation/<operation>, not in a Query Action or an X-Amz-Target header. Enforcement found no action for it, and an unknown action is allowed, so under enforcement any known key could run any operation of SQS, SNS, DynamoDB, Kinesis, Step Functions, CloudWatch or Marketplace over RPC v2, explicit denies included. Enforcement also took the call's shape from the protocol claim, which the claim filter reads before routing, while the CBOR endpoint dispatches whatever its route matched. The two disagree in several ways: - An unrecognised smithy-protocol value leaves the call unclaimed. With strict claiming off, the default, it is still served, so an unsigned call was not refused. - An X-Amz-Target header on the call named the operation it was checked as, while the path named the one that ran. - A path with a prefix before /service/ is claimed as RPC v2 while another route serves it. The filter now reads the service and operation from the route the call reached, the values the endpoint dispatches. It authorizes that operation as the action AWS checks for it, under the serving service's namespace, and records the call's claim, so the unsigned refusal and the CBOR error format apply whatever its smithy-protocol header says. A call on any other route is handled as before. The resources and condition keys a request names in its body were read only from JSON, and a CBOR body fell back to a wildcard resource: a deny on one queue, table or stream did not apply, a grant on one did not match, and a ForAllValues dynamodb:LeadingKeys condition granted every key. The body is now read as CBOR when its content type says so, on the RPC v2 path and on the x-amz-cbor-1.1 one, which had the same gap. |
||
|
|
46f4977b23 |
fix(ses): publish to an SNS topic only when its policy allows SES (#5650)
Under IAM enforcement, SES published event-destination events and identity notifications to
whatever SNS topic it was configured with, through an internal call nothing checked, so a caller
refused sns:Publish could still put messages on a topic by pointing a configuration set at it. On
AWS, SES publishes as ses.amazonaws.com and the topic's policy decides: it has to allow SES, under
an aws:SourceArn naming the configuration set or identity whose configuration names the topic.
- ServiceCallAuthorizer decides a call one AWS service makes to another's resource on its own
behalf from the target's resource policy alone, read through the same providers the request
filter uses and picked by the target ARN's service. A target with no policy refuses, and with
enforcement off every call is allowed. ResourcePolicyProviders collects what the providers
supply, for the filter and the authorizer alike.
- IamConditionContextResolver.serviceCallContext builds that call's request context from the IAM
User Guide's global keys: aws:PrincipalIsAWSService, aws:PrincipalServiceName and
aws:PrincipalServiceNamesList, aws:SourceArn and aws:SourceAccount, aws:ResourceAccount and
aws:RequestedRegion, and none of the keys that describe an IAM principal. A publish to an SNS
topic from SES also carries aws:SourceOwner, which the SNS Developer Guide lists SES among the
services setting, and which the default topic policy checks.
- SnsResourcePolicyProvider supplies a topic's policy and the account in its ARN, also when the
topic does not exist. A topic with no Policy attribute gets the default a new topic has, for the
topic's own account. Topic policies so also take part in a JSON-protocol request that names a
topic, as any resource policy does.
- SesEventPublisher asks before publishing to SNS: for an event destination with the configuration
set's ARN, for an identity notification with the ARN of the identity that names the topic, the
sender's own or its domain's, both with the sending account. A refused event is dropped. A
notification SES cannot publish, because the topic is gone from its own account or its policy
refuses SES, also takes the topic out of the identity's bounce and complaint settings and turns
email feedback forwarding back on, as the SES Developer Guide describes; a delivery setting
stays. The identity's notification settings are written under the identity lock, so that
write and an API call changing them cannot lose each other.
- CreateReceiptRule and UpdateReceiptRule ask the same question of an action's TopicArn, with the
rule's ARN as aws:SourceArn, and answer InvalidSnsTopic when the topic's policy does not let SES
publish, which the SES API Reference lists as "could not publish to the topic, possibly due to
permissions issues". The rules still route no mail.
- A resource policy statement that names the caller only through its account, by its id, root ARN
or S3 canonical user ID, delegates to that account (IAM User Guide, "AWS account principals"):
across accounts it is still the owner's half of the grant, but within the account it no longer
grants on its own, and the caller's identity policies have to allow the request. Floci let such
a statement grant on its own, for bucket and function policies already, so a topic policy naming
its own account would have let every user of the account publish.
- A Deny's NotPrincipal follows the IAM User Guide ("AWS JSON policy elements: NotPrincipal"): it
spares an IAM caller only when it names the caller's account as well as the caller, since without
the account AWS "might deny access to the entire account", and never spares one with a permissions
boundary attached, which it "will always deny". CallerArns says whether a boundary is attached to
the user or to the role a session assumed. An Allow's NotPrincipal still grants everyone it does
not name, as Access Analyzer warns it can.
|
||
|
|
4ea7e3da23 |
fix(dynamodb): authorize every requested item return mode (#5652)
* fix(dynamodb): authorize every requested item return mode * test(dynamodb): share authorization fixtures |
||
|
|
eba058266b |
fix(iam): authorize an operation as the action AWS checks for it (#5604)
Under enforcement a request naming its operation, in a Query Action or an X-Amz-Target header, was authorized as <namespace>:<Operation>, the operation's own name. AWS authorizes some operations as an action of another name: SQS SendMessageBatch, DeleteMessageBatch and ChangeMessageVisibilityBatch as sqs:SendMessage, sqs:DeleteMessage and sqs:ChangeMessageVisibility, and SNS PublishBatch as sns:Publish. None of the batch names is an IAM action, so a policy AWS honours for a batch call was denied, and a policy naming the batch operation granted something AWS does not check. AWS publishes the mapping in the Operations of each Service Reference file. tools/aws/regen_iam_authorized_actions.py vendors the operations authorized by exactly one action of their own namespace under another name, 235 over 33 namespaces, into src/main/resources/aws/iam-authorized-actions.json. Everything else keeps its own name. The generator leaves out operations that list: - several actions, whose extras apply only when tags or a role are passed; - no action, which is missing data; - an action of another namespace; - another action while one of the operation's own name exists; - a tagging action alone; - the same action for several SDK clients, which AWS can authorize differently, as S3 and S3 Control's GetPublicAccessBlock; or whose name is listed again with another answer. A record of the wrong shape fails the run instead of being skipped. make iam-authorized-actions-check gates the file's shape on pull requests that touch it, and iam-authorized-actions-verify, run by the IAM Data Drift workflow, checks every entry against AWS. IamAuthorizedActions reads the file through the new core.common VendoredResources, rather than adding one more copy of the read-or-fail block a dozen catalogs carry, and the Query and X-Amz-Target paths ask it for the action. DynamoDB TransactGetItems, which AWS authorizes as dynamodb:GetItem, keeps its own name: the transaction check recognizes the call by it and checks every Get as dynamodb:GetItem on its own table, with its own dynamodb:LeadingKeys. Renamed, the call would skip that check and be authorized as one GetItem whose body has no top-level Key, which a ForAllValues condition accepts, so a fine-grained policy would grant every key. The check for operations AWS serves without credentials reads the Query action directly, rather than through resolve with a placeholder scope, now that resolve returns the authorized action. A Query request naming no action is not one of them. An SDK compatibility test covers SendMessageBatch and PublishBatch, granted by the single-item action and refused under the batch name, with enforcement on. |
||
|
|
287d683da7 |
feat(iam): populate aws:username, aws:userid and aws:PrincipalType (#5568)
The request context carried seven aws: keys plus aws:PrincipalArn, and none of
the three that say who is calling. A Condition matching on any of them could
not match, which is also why an IAM policy variable has nothing to resolve:
AWS's own IAMUserChangePassword policy scopes itself to user/${aws:username},
and substituting that needs the key to exist before it needs a substituter.
The values come from the user guide's principal key values list, one shape per
principal: Account with the account id for the account-root principal and for a
session token it minted, User with the user's own id for an IAM user access key
and for a session token that user minted, FederatedUser with account:name for a
GetFederationToken session, and AssumedRole with role-id:session-name for a role
session, which for a role on an EC2 instance is role-id:instance-id.
aws:username is the exception and is only published for an IAM user. The guide
is explicit: "always included in the request context for IAM users" while
"anonymous requests and requests that are made using the AWS account root user
or IAM roles do not include this key". Leaving it absent is what makes a
statement matching on it fail to match, which is the documented behaviour for a
key with no value, so the absence is the enforcement rather than a gap in it.
One judgement. The principal key values list renders the role-session type both
as AssumedRole and, twice, as "Assumed role". The unspaced form is the one that
fits the vocabulary of every other value in that list, each a single word or
CamelCase, and it is the form AWS publishes machine-side, as CloudTrail's
userIdentity.type does.
aws:userid was already derived in full by resolveCallerUserId, for every
principal type including the EC2 and ECS session-name fallbacks, so that
derivation is now a shared sessionUserId rather than a second copy inside
resolveCallerArns: reporting one key two ways is how the two readers would
drift. CallerArns carries the three values so they come from the single lookup
its javadoc already required, two lookups being able to straddle a session's
expiry, and it writes them itself, so every context a request is evaluated
against describes the same principal and there is one place that decides which
keys a principal publishes. The enforcement filter builds one context per
resource the request names and, since #5576, one per transaction item, which is
what a policy scoped to dynamodb:LeadingKeys = ${aws:userid} will need. S3
builds one of its own when s3.enforce-auth has it evaluate a bucket policy
there and then, and that one carried aws:PrincipalArn alone, so an inverted
Condition on any of the three keys held against a caller that has them and
fired a Deny the policy meant to leave alone.
Three unit tests and four integration tests, one on the transaction-item path
and one in S3's own bucket-policy class, with the existing caller-ARN
assertions widened to pin the keys for the root, federated and user-minted
session principals they already covered. Each key probed by dropping it alone:
without aws:PrincipalType or aws:userid both enforcement tests fail, without
aws:username one does, and giving a role session a username it should not have
fails the test that asserts the absence. The two contexts outside the filter
are probed the same way, each reverted to aws:PrincipalArn alone, and each
fails its own test. 4489 tests pass at this commit, across all 277 IAM and
core/common classes, the shared enforcement fixtures, and the S3 policy,
enforcement, presigned and account-context ones, the shared filter and
CallerArns reaching all of them. Checkstyle and docs-check clean.
|
||
|
|
9ab820d7f7 |
fix(iam): preserve later policy writes during rollback (#5596)
* fix(iam): preserve later policy writes during rollback * fix(iam): explain rollback ownership conflicts |
||
|
|
1d8f65d231 | fix(iam): enforce user and group inline policy quotas (#5590) | ||
|
|
69bbd2242b |
fix(iam): check DynamoDB transaction item permissions (#5576)
* fix(iam): check DynamoDB transaction item permissions * test(iam): cover transaction attribute and item permissions * test(iam): cover transaction policy boundaries * fix(iam): bind transaction permissions to the accessed table * fix(dynamodb): preserve omitted transaction return values * docs(iam): clarify transaction return-value conditions |
||
|
|
367ae0b2db |
fix(iam): honor managed policy attachment conditions (#5578)
* fix(iam): honor managed policy attachment conditions * test(iam): keep managed policy group tests isolated |
||
|
|
1b7c79fd9e |
fix(signin): accept the cross-device redirect on each partition's sign-in host (#5557)
The cross-device redirect_uri was matched against the commercial <region>.signin.aws.amazon.com only, so a login that resolved another partition's Sign-In host was refused with invalid_request. regen_partitions.py now reads botocore's signin endpoint ruleset and vendors one signinHost per partition into aws/partitions.json. The redirect is accepted on the Sign-In host of a region in the deployment's partition, and another partition's host is refused. The device authorization client ids keep their literals: the Sign-In model spells them the same way in every partition. Signed-off-by: Hector Ventura <hectorvent@gmail.com> |
||
|
|
5ea632cc13 |
feat(iam): change the calling user's console password (#5546)
ChangePassword was the last IAM operation held back for a reason that turned out not to hold. It was tracked as blocked on disambiguating a shared Query action name by Version, because Cognito publishes the name too. In fact IAM sits second in inferServiceFromAction's chain and Cognito ninth, and Cognito's form path answers UnsupportedOperation to every request, so adding the name to IAM_ACTIONS routes it to IAM and costs Cognito nothing. A request carrying a credential scope never reaches that chain at all. The operation takes no UserName. The API reference says it changes the password of the IAM user who is calling, and the CLI reference adds that it "can be called by IAM users only. If this command is called using AWS account (root) credentials, the command returns an InvalidUserType error", so a signing key with no stored user behind it, which is Floci's stand-in for that caller, answers InvalidUserType rather than reporting the key as missing. The resource the request is evaluated against needed nothing new: ResourceArnBuilder already resolves the signing user for an action whose UserName is absent, and the vendored action map already authorizes ChangePassword against a user. OldPassword is checked against the stored login profile before the new password is held to the account password policy, so a caller who cannot prove the current password learns nothing about what that policy requires. A mismatch is the one refusal the reference leaves unnamed: every error it publishes for this operation describes something else, so this answers InvalidParameterValue, the common error type AWS publishes for a parameter value a service cannot accept. A successful change clears PasswordResetRequired, which is what lets a user whose password an administrator reset restore their own console access programmatically, and it moves the password_last_changed the credential report reads. The passwordType shape check is now shared and names the member that failed, because this operation has two password members and a caller told that 'password' failed would have to guess which. An absent member and an empty one stay different answers. Two things the login profile needed before a self-service change could be trusted. The comparison and the write are one step under a new loginProfileLock, which every login-profile writer takes: read apart from the write, two requests presenting the same valid old password both pass the comparison and both are told they set the password, while only the later write survives, and a guard one writer skipped would leave a racing UpdateLoginProfile free to overwrite a password a ChangePassword had just promised. And PasswordReusePrevention is now enforced, on UpdateLoginProfile as well, the two sharing one bounded history per profile: the reference defines the value as "the number of previous passwords that IAM users are prevented from reusing" and makes no window mean no prevention. The password the profile holds is refused alongside the superseded ones, which the reference leaves open; read the other way the smallest window the policy accepts would allow setting a password to the value it already has, and would not refuse the change away and straight back that the setting is for. Twelve unit tests, one concurrency test and six integration tests, with each guard probed by reverting it alone: dropping the old-password comparison, the reset-flag clear, the policy check or the check order is caught by the test written for it, and dropping the routing entry leaves the unsigned request answered by Cognito, which is what the routing parity test says too. Dropping the lock leaves five of twenty-four racing requests all told they succeeded with one password stored, neutering the reuse check leaves both refusals silent, and widening the window by one lets it reach a password that has left it. 1668 tests across all 98 IAM and query-routing classes pass at this commit. docs/services/iam.md documents the operation, the judgements, and the one thing Floci still does not model. AllowUsersToChangePassword is accepted and reported but grants nothing: the user guide says the option gives all users in the account access to iam:ChangePassword for only their user and to iam:GetAccountPasswordPolicy, applied at the account level rather than by attaching a policy, while Floci authorizes both from identity policies alone, so under enforcement a caller needs a policy naming their own user however the flag is set. The matrix row moves 166 to 167. |
||
|
|
bcda5958e0 |
fix(signin): complete aws login --remote against an endpoint override (#5552)
The AWS CLI builds the cross-device redirect from the Sign-In endpoint it resolved, so with --endpoint-url it sends Floci's own address plus /v1/sessions/confirmation. Floci accepted only an https AWS sign-in host there and served no confirmation page, so the authorize request was refused and the remote login could not finish. A cross-device redirect is now also accepted on the scheme, host and port the authorize request arrived on, and GET /v1/sessions/confirmation shows the verification code in the form the CLI decodes. Any other origin is still refused. Signed-off-by: Hector Ventura <hectorvent@gmail.com> |
||
|
|
72a4cc5515 |
fix(iam): page ListRoles and ListPolicies through MaxItems and Marker (#5515)
Both actions returned every match in one response with IsTruncated false. They now use the existing paginate helper, so an omitted MaxItems returns 100 items, a MaxItems outside 1 to 1000 is a ValidationError, and Marker appears only on a truncated page. PathPrefix and Scope filter first. Roles and customer managed policies are listed in name order so a marker keeps pointing at the same place between calls. |
||
|
|
ea8da22226 |
fix(iam): match absent context keys with ForAllValues (#5482)
* fix(iam): match absent context keys with ForAllValues * fix(iam): preserve condition guards for missing keys * fix(iam): reject unsupported condition shortcuts * docs(iam): clarify supported IfExists conditions * fix(iam): enforce requested keys in set conditions * docs(iam): clarify unresolved attribute conditions * fix(iam): enforce requested S3 object tag keys * fix(iam): scope object tag keys to the authorized action |
||
|
|
4e769484df |
feat(iam): generate and read the Organizations access report (#5467)
GenerateOrganizationsAccessReport and GetOrganizationsAccessReport answered
UnsupportedOperation, which is not a reply any SDK models. They are the Access
Advisor job shape over a different question, and everything the question needs
was already here: an Organizations tree with roots, OUs, accounts and SCPs, a
policy evaluator, and a job model whose report is fixed at generation time.
The report is the services the service control policies along an entity path
leave reachable. The path names the organization, its root, and the OUs or
account below it, and the SCPs attached to each of those are read from
Organizations and evaluated. Only SCP logic applies, which the reference is
explicit about: identity policies, resource policies, ACLs, permissions
boundaries and trust policies play no part in this data.
Attached SCPs are a union within one level and the levels are intersected, so a
service survives only where every level allows it. That cannot be answered a
namespace at a time, because a service is reachable only while some action in it
survives the whole chain: two levels allowing single disjoint actions,
s3:GetObject under s3:PutObject, leave no S3 action at all, and a Deny on the one
action a level allows leaves none either. What a namespace-wide reading got right
stays right. An SCP denying s3:DeleteBucket alone keeps S3 on the list, because
every other S3 action is still reachable, and a Deny carrying a Condition or
naming particular resources closes nothing: the region guardrail on * that most
organizations carry, and a deny scoped to one bucket, both leave the service
reachable by every request they do not cover, and reading them as total denials
would report an organization that reaches nothing.
This is still not the existing scpAllows asked once per namespace. That question
needs a concrete action, and a request action of s3:* would not match a statement
naming s3:GetObject, a pattern globbing against a request value and never the
other way round. The survivors are found by probing instead, with the actions the
policies themselves name and one stand-in action per wildcard, which decides the
patterns policies are written with exactly: a deny on s3:GetObject leaves the
service reachable where a deny on s3:Get* does not. A wildcard that is not a
trailing one is the limit of it, since the stand-in for s3:*Object misses the
s3:GetObject that s3:Get* would allow; such a pattern leaves the service on the
list rather than off it, which is the side the namespace reading was already on.
The management account is not limited by SCPs, so its report lists every service
and an OrganizationsPolicyId passed with it is ignored, both as documented.
Passing that ID otherwise narrows the report to the one SCP named, and it has to
name one: Organizations keeps tag, backup, chatbot and opt-out policies in the
same ID space, none of them carries statements, and evaluating one as a ceiling
would read as a level that constrains nothing and report every service there is.
The entity path has to be a path the organization actually has. The segments
below the root name a chain of parent and child, so the path is held to the one
Organizations reports for its last node rather than each segment being resolved
on its own. Resolving them one at a time accepts a path assembled from two
branches, or one that skips an OU, and reports the policies of a chain the
organization does not have; it also lets a path whose last segment is the
management account take the unlimited answer with an OU above it that does not
exist.
Floci records no service access, so every service in a report is one principals
are allowed but never reached. The reference's own example gives such a service
as a namespace and a zero count with no region, entity path or last-authenticated
time, so that is the shape here and NumberOfServicesNotAccessed equals
NumberOfServicesAccessible. ServiceName carries a display name Floci has no
mapping for, so the namespace stands in for it as it does on the last-accessed
reader. SortKey is validated against its four values: the namespace keys sort
the list and the time keys leave it in namespace order, since ordering on a
timestamp no entry carries would be ordering on nothing.
A caller who is not the management account gets AccessDenied 403. Neither
operation models a code for that, but a per-action error list is additive: the
reference's common error types "that this AWS service may return" apply to every
action and include the 403 permission denial, and the user guide names the code
for a denied IAM action outright in its AddRoleToInstanceProfile entry. That page
spells it AccessDeniedException where the user guide and the rest of this
service's surface spell it AccessDenied; the latter is used, so a caller sees one
spelling across IAM and STS.
Three things are inferences, and they are the same inference three times. The
docs say so. The generator models no error for an entity path that is well-formed
but resolves to nothing, nor for the prerequisite the reference states, that SCPs
be enabled for the organization root, nor for an OrganizationsPolicyId naming a
policy of some other type, so each produces a FAILED job carrying ErrorDetails:
InvalidEntityPath or the Organizations code for the entity in the first case,
PolicyTypeNotEnabled in the second, Organizations' InvalidInputException in the
third. That is read off the shape of the API rather than off a sentence: AWS
publishes both fields on this reader for failures the generator does not report
synchronously. The alternatives are worse. Letting Organizations' own error
escape unchanged puts another service's code on an IAM operation, a COMPLETED job
with an empty list cannot be told apart from an organization that reaches no
services, and ValidationError is for a shape violation, which a well-formed path,
a disabled policy type and an existing policy of the wrong type are not.
ReportGenerationLimitExceeded, the generator's only modeled error, reports
concurrent generations and stays unreachable: a job completes the moment it is
created, so two never overlap.
The generator also carries the access-report resource type, so it leaves
UNRESOLVED_TYPES and resolves from the request. The reference spells the type as
access-report/${EntityPath}, so the entity path goes into the ARN whole: its
slashes are the organization's tree, not an IAM path, which is why it does not
go through the minting the creates use.
Both actions join AwsQueryController.IAM_ACTIONS as well as the handler, without
which inferService would never route them. That list and the handler now hold
166 each, still exactly in step.
Validation runs before the lookup, as AWS rejects a request shape whether or not
the job exists: a SortKey outside the enum answers ValidationError even for a
job ID nothing holds, where validating it afterwards would answer NoSuchEntity.
A member the request carries is held to its shape whatever it carries, an empty
value included, since SortKey= and OrganizationsPolicyId= are a malformed enum
and a malformed id rather than a way of leaving an optional member out. The
entity path reports the constraint that failed rather than the regular
expression for every case, so a path over the maximum length reads as a length
violation, which is what every other validated IAM member does.
Only the one Organizations answer that means something about the caller becomes
AccessDenied. A read that fails for any other reason keeps its own error, rather
than reaching the caller as a permission problem they do not have.
Two things are shared rather than copied. The job registry both report
generators keep, an account-scoped store keyed by job ID that answers
NoSuchEntity for an ID it does not hold, moves into IamJobStore and
ServiceLastAccessedService reads it from there; the two had the same three
methods and the same message. The report's timestamps come from the injected
Clock, which IamService already takes, rather than from Instant.now(), so they
agree with every other time IAM decides. IamQueryHandlerTest builds the handler
itself rather than through injection, so it passes the new service along with
the dependencies it already does not use.
Fourteen unit tests cover the chain semantics, including the allow-list idiom of
allowing everything and denying all but one namespace, levels allowing disjoint
single actions, a deny on the only action allowed and on a pattern wider than it,
a conditional deny, a deny scoped to one bucket, a level with an unreadable
document, and a level with none. Twenty-one integration tests drive the pair over
an organization built through the Organizations API, on a management account of
their own so they never contend with the existing Organizations suites for one.
Two of them are the ones that hold the walk honest: the OU path, where the root
leaves S3 and DynamoDB and the OU leaves DynamoDB and IAM, so only a report
reading both levels answers DynamoDB alone, and the management account path,
which reports every service and ignores the policy ID passed with it even with a
ceiling attached to the root above it. With the tree read deliberately broken the
first SCP test returns all 456 namespaces instead of the one, and it is the only
test that notices. Two more tests mock the Organizations read, which is the one
failure a real organization cannot be made to produce.
|
||
|
|
6d7d85f0f8 |
fix(lambda): enforce function policies on cross-account calls (#5476)
Under IAM enforcement, a caller whose own policy allowed lambda:InvokeFunction could invoke another account's function by ARN even when that function's policy granted nothing, and RotateSecret could be pointed at another account's function the same way. Three things combined: there was no resource-policy provider for Lambda, so the call was judged as same-account; the function name was cut at its first colon, so an ARN was evaluated as function:arn in the caller's account, where no Allow or Deny written for the function could match; and the invoke followed the account in the ARN. - LambdaResourcePolicyProvider supplies a function's policy statements and the account its ARN names, also when the function has no policy, so a call to another account's function needs that function's policy to allow the caller as well as the caller's own policy. It is keyed on the ARN, so RotateSecret's check on its rotation function, made under the secretsmanager scope, sees it too. - ResourceArnBuilder evaluates each call against the function it acts on. An invoke runs in the account and Region a full or partial ARN names, as the version or alias it names in the function name or in Qualifier, since Lambda authorizes a qualified call against the qualified ARN. GetFunction, GetFunctionConfiguration and ListDurableExecutionsByFunction read a qualified full ARN in the account it names, so they are evaluated there too, and a read of another account's function needs its policy as on AWS. Every other route acts on the caller's own function of that name, so it is evaluated against that function, unqualified because not all of their handlers act on the qualifier. - An invoke by partial ARN runs in the account it names, as one by full ARN already did. - RotateSecret looks its function up where the rotation runs it: in the ARN's account, and as the version or alias the ARN names. |
||
|
|
d884d55c26 |
fix(iam): evaluate every IAM action against the resource it acts on (#5404)
Under enforcement, almost every IAM action reached the policy evaluator with
* as its resource, because ResourceArnBuilder named only the server-certificate
operations and everything else fell through to the wildcard. A statement naming
an IAM resource was therefore ignored, and wrongly in both directions, because
the evaluator globs the statement's pattern against the request's resource and
a resource of * is matched as that literal string. So a Deny on
arn:aws:iam::000000000000:user/bob did not stop DeleteUser for bob, while an
Allow scoped to that same user did not permit DeleteUser on anyone at all: a
least-privilege policy naming the resource it meant to grant refused the call.
Measured both ways by reverting this resolver to the wildcard, which turns the
permitted call in aResourceScopedAllowGrantsThatUserOnly into a 403 and the
refused call in aDenyNamingOneUserLeavesTheOthersAlone into a 200. Nothing
failed and nothing warned, which is the dangerous shape for an emulator people
test policies against.
The resource type each action is evaluated against now comes from AWS's own
authorization metadata for IAM, action by action. That is not the parameter an
action happens to take: AddUserToGroup and RemoveUserFromGroup are evaluated
against the group, AddRoleToInstanceProfile and RemoveRoleFromInstanceProfile
against the instance profile, and EnableMFADevice, DeactivateMFADevice and
ResyncMFADevice against the user rather than the device they name. Mapping those
from the request's parameters would have scoped them to the wrong resource and
let a deny on the right one pass.
An action acting on a resource that exists is checked against that resource's
stored ARN. The reference gives the formats as user/${UserNameWithPath},
group/${GroupNameWithPath} and so on, so the path is part of the ARN a policy
names, and only the store knows it; the stored ARN also carries the partition
the resource was created in, which re-minting from the caller's signing region
would get wrong. A create has nothing stored, so its ARN is minted from the
request's own Path: reading a stored path there would authorize a create into
/team/ against the root path.
A policy, MFA device, SAML provider, OIDC provider or principal is named by an
ARN the request already carries, so that is passed through rather than rebuilt
from parts. Only an ARN is: a hardware MFA device's SerialNumber is a bare
serial, and naming the request after it would produce a resource no policy could
be written against.
That table is read before the one keyed by resource type, so an action in both
would silently take its ARN parameter and the mistake would look like a resource
that never matches rather than like a bug. An attach is the case that makes it
worth pinning down: it carries both a user and a policy ARN, and the reference
gives it the user alone, so it stays out of that table and
iamNamesTheUserRatherThanThePolicyOnAnAttach is what holds it there.
UpdateUser and UpdateGroup join UpdateServerCertificate in naming both the old
resource and the one the request would produce. Both are documented, which the
certificate case was not: UpdateUser's reference says the requester "must have
appropriate permissions on both the source object and the target object", and
UpdateGroup's that a principal allowed to update the old group but not the new
one has the update fail.
Two actions name their role indirectly and are derived rather than looked up.
CreateServiceLinkedRole does not name the role it creates, so the check reads
the same ServiceLinkedRoles table the create reads and cannot name a different
role. GetServiceLinkedRoleDeletionStatus carries only a DeletionTaskId, and its
reference publishes that identifier's format as
task/aws-service-role/<service-principal-name>/<role-name>/<task-uuid>, which is
the role's own path and name with a prefix in front and a uuid behind; the role
is already deleted by the time the status is asked for, so there is no stored ARN
left to read either way. The /aws-service-role/ path moved to that class, so there is one copy of
it rather than a second in the builder. GetAccessKeyLastUsed names only a key,
and is evaluated against a user: the User Guide's own iam:*AccessKey* example
scopes exactly that set to user/${aws:username}, so the owner is resolved from
the key.
That covers all 130 of the IAM actions this emulator dispatches that AWS gives a
resource type, out of 164 in total. The remaining 34 have no resource type in the
reference, such as ListUsers, GetAccountSummary and SimulateCustomPolicy, so *
is the right answer for them. An action that names its target only by defaulting
to the calling user, such as GetUser or ChangePassword with no UserName, is
resolved from the credential instead, which the last paragraph here sets out.
Nine enforcement tests drive the whole path rather than the ARN the builder
returns, since the defect was invisible: a scoped statement was ignored, not
rejected. They cover a deny that must bind to one user and leave another alone,
the stored path being part of the ARN, the group and the instance profile being
the resource where two entities are named, a managed policy named by ARN, a
create authorized against the path it asks for, a rename refused on its
destination alone, and a scoped Allow granting one user only. Reverting the
mapping to the wildcard fails all nine.
The map is vendored rather than written out here, because a hand-written copy of
AWS's metadata is exactly what tools/aws exists to prevent.
regen_iam_action_resources.py generates src/main/resources/aws/iam-action-resources.json
from the same reference, 190 actions with the resource types each is authorized
against plus the ARN format of all 15 resource types, and it gates the file the
way regen_service_namespaces.py gates the namespace list: --check offline for
shape, --verify online against AWS. A type the file claims and AWS does not fails,
since that would authorize against a resource AWS does not use, which is the one
outcome worse than the wildcard. A type or an action AWS has added is reported
without failing, because being behind leaves that action on * and failing there
would break this build for someone else's launch. make
iam-action-resources-check runs per pull request beside the namespace check, and
make iam-action-resources-verify weekly in the drift workflow. Its unit tests need
no step of their own: make aws-data-test in that same job already runs every
generator's.
So no list of actions is written down here. What stays in code is the half that is
Floci's rather than AWS's: the parameter each resource type arrives in, the nine
creates and the name each spells, the actions whose request carries an ARN, the
three resolved from something other than a name, and the three resource types
that belong only to actions the handler does not dispatch. IamActionResourcesTest
checks the code against the data: every resource type AWS uses must be resolved
or declared unresolved, every create must have exactly one type to mint, and
every minted prefix must match the ARN format AWS publishes for that type. A
regeneration that brings in a new resource type then fails a test naming the
type, rather than quietly putting that action back on *, which is the permissive
answer and a silent one. The create check reads the resolver's own map rather
than restating it, so a create added there is checked too, and the minting falls
back to the wildcard instead of indexing an empty list: a create AWS authorizes
against no single type has no ARN to build, and a request should not fail on
what is a defect in this class.
The reason each declared-unresolved type gives is a claim about the handler, not
about the builder, so nothing inside the builder can check it, and getting it
wrong is silent and fail-open: dispatching such an action without teaching the
resolver its type leaves it evaluated against *, which is the gap this closes.
UnresolvedResourceTypesIntegrationTest therefore sends every action carrying one
of those types and holds it to answering UnsupportedOperation, naming the action
and what to do if it no longer does. No other vendored-data loader validates at class init
either, so the checks read the data the way AwsPartitions and
AwsServiceNamespaces do: parse, and let the gate and the tests have the opinion.
The nineteen user actions whose UserName the model marks optional act on the
user who signed the request, so that user is the resource they resolve to. The
access key id in the credential names the identity, which is the same lookup
GetAccessKeyLastUsed already makes on a key passed as a parameter, and the
stored ARN carries the path and partition as everywhere else here. The wildcard
still stands when the signer is not an IAM user, an account's root stand-in and
a session credential having no user record to name.
What stays at the wildcard is what AWS gives no resource type, 34 of the 164.
Closes #4979
The online gate verifies the ARN formats as well as the action mapping. A format
drifts invisibly otherwise: the offline check only asks whether it still looks
like an IAM ARN, and a changed one does, while the minting reads that string to
place the resource type. So a right-looking file could build a wrong ARN.
The resource types this class covers are worked out from its own tables rather
than restated in the test, so a type cannot be waved through by adding it to a
list in the test file. That is the check the earlier startup guard made.
The three actions whose resource the request carries in some other form hold
their own resolver, rather than being listed in one place and routed by name in
another. A list cannot then say an action is handled while the dispatch has
nothing for it, since adding a key means supplying the resolver that goes with
it.
The enforcement suite removes what it creates. The emulator is shared, so a user,
group, role, profile, policy or provider left behind turns up in the next class
to list one, and the shared fixture helper grew the prerequisites IAM enforces
before a delete: group memberships and attached policies for a user, inline and
managed policies for a role and a group. A rename leaves its destination name
behind rather than the name that was created, and the create test goes through
the enforced path, so both register their own removal.
The drift workflow stays one check, and make iam-data-verify is what keeps that
honest. Two sequential steps stop at the first failure: while the namespace list
was stale, the action resource check this change adds never ran at all, so the
gate arrived unexercised in CI. The target runs both regardless of the first
result and then fails, naming the file that drifted rather than leaving a reader
to guess from one message. The workflow file is renamed to match what it covers,
and the IAM targets it uses join .PHONY, which they should have done when they
were added.
That namespace check was red because AWS retired evidently and iotevents, and
the vendored list still claimed both. Regenerating it drops those two, picks up
end-user-messaging and startups, and leaves the count at 456. A retired
namespace only narrows wildcard expansion; a policy naming one literally is
still reported, since a namespace written out is kept whether or not the catalog
knows it.
|
||
|
|
b2b083ee91 |
fix(iam): validate RoleName in every role action (#5391)
Every action whose RoleName is roleNameType now answers a bad name with ValidationError instead of NoSuchEntity, as CreateRole does. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
c6068e8cf5 |
chore(iam): generate the managed-policy catalog from iam-dataset (#5403)
* chore(iam): generate the managed-policy catalog from iam-dataset The three managed-policy resources were hand-seeded in #2194, #3237 and #3275, so nothing noticed when AWS added or revised a policy. tools/aws/ regen_managed_policies.py now rebuilds them from the local/aws/iam-dataset checkout: names, paths, versions and update dates from aws/managed_policies.json, documents from aws/managedpolicies/. Deprecated policies leave the catalog except AWSLambdaFullAccess, which #2194 kept on purpose. createDate (from the AWS managed policy reference pages) and the curated descriptions are not in the dataset and are carried over. It joins make aws-data-sync and aws-data-check. CI has no iam-dataset, so there the check verifies the three files agree and keep their shape, the way regen_region_facts.py handles its missing corpus. This commit changes no data; only the catalog header gains a generated-by line. The files were taken from three dataset days, and the generator reproduces each from its own: the names from 2026-08-12 (f18cb038), the versions from 2026-09-08 (a52abe16), and the documents from 2026-09-08 too, except AWSCodeStarServiceRole, which matches 2026-09-07 (1c729479). * chore(iam): refresh the managed-policy catalog from iam-dataset 2026-09-19 make aws-data-sync against the local/aws/iam-dataset checkout (72d2a4f62, 2026-09-19). Catalog 1566 -> 1578 policies: - 12 added: AIDevOpsChannelAccessPolicy, AIDevOpsReleaseManagementVPCPolicy, AWSWellArchitectedAgentOrganizationsServiceRolePolicy, AmazonBioDiscoveryFullAccess, AmazonBioDiscoveryInAppFullAccess, AmazonODBAutonomousDatabaseAdmin, AmazonODBExadataVmClusterAdmin, AmazonODBExascaleStorageVaultAdmin, AmazonODBExascaleVmClusterAdmin, AmazonSageMakerHyperPodInferenceGatewayAccess, AssuranceServiceRolePolicy, NetworkSecurityManagerServiceRolePolicy. All are on v1, so their createDate is the dataset's date. - 0 removed. - 22 changed: 21 moved to a new default version with a new document and update date (among them ReadOnlyAccess and SecurityAudit), and AWSCodeStarServiceRole kept v12 but took the document and update date the dataset recorded on 2026-09-08. No path or description changed, and the service-linked role table still matches the documents (make slr-check). * chore(iam): make the managed-policy generator's date fetch and offline check stricter --fetch-create-dates now reads the reference page of every policy past v1 that has no creation date, not only of policies new to the catalog, so a policy first vendored without the flag can be dated by a later run. A page that cannot be read leaves that one policy undated with a warning instead of ending the run with nothing written. The offline check compares the catalog with a re-render of its parsed entries, so content outside the generated header and policy entries fails it instead of passing unnoticed. * chore(iam): refresh the managed-policy catalog from iam-dataset 2026-10-09 The dataset moved after the first refresh. Regenerated against 2244bd78a (2026-10-09) with --fetch-create-dates. Catalog 1578 -> 1586 policies: - 11 added. Ten are on v1 and take the dataset's date; AWSCloudWatchOmniServiceRolePolicy is on v2 and takes its creation date from its reference page. - 3 removed: the CloudWatch Evidently policies, which the dataset now marks deprecated. - 45 moved to a new default version, among them SecurityAudit (v94) and ReadOnlyAccess (v190). The generated header said createDate falls back to the dataset's date for a policy with no reference page. It does so only for a policy that entered the catalog on v1; one past v1 stays undated, and the header now says so. AWSConfigRole is still the only policy without a creation date. |
||
|
|
cb673802e0 |
fix(iam): validate RoleName in CreateRole (#5374)
Follow-up to #5289. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
477e3ef813 |
fix(iam): make the server certificate reference check atomic with the write (#5368)
DeleteServerCertificate checked the reference providers under its own lock, while a referring service validated the certificate and then saved the resource naming it. Nothing tied the two together, so a delete running between the check and the write saw no reference, removed the certificate, and left a live distribution or listener holding one that was gone. It reproduced in 233 of 400 trials. CloudFront and ELB Classic now perform that check and the write while holding the lock the delete takes, so only the two sensible orders remain: the delete loses and answers DeleteConflict, or it wins and the create is refused. The ordering runs one way only. deleteServerCertificate holds the lock while calling serverCertificateReferences() on each provider, and those are plain reads over the provider's own store that take no provider monitor, so IAM never waits on a provider while a provider waits on IAM. ELBv2 is untouched: it never validates certificate references, so a listener there can name a certificate that was never present, which is a separate gap. Removing a listener needs a lock too, for a different reason than adding one. deleteLoadBalancerListeners removed from the listener list with no lock at all, while the certificate delete walked that same ArrayList, and a structural change to a list being walked ends the walk in ConcurrentModificationException. No mapper covers that, so DeleteServerCertificate answered an unmapped 500 rather than 200 or DeleteConflict. A probe calling the scan exactly as the delete does, against a loop of listener removals, hit it within two seconds. That one is the list's problem rather than the lock's, so the listeners are held in a CopyOnWriteArrayList, as Stack.events and IamUser.groupNames already are, and the walk reads a snapshot of it. Removal then takes only this service's own monitor, which the add shares so that a removal cannot land between the add's look at the port and its decision, and a certificate delete no longer waits on either. A unit test runs the scan against a loop of listener writes: with a plain list it ends in ConcurrentModificationException inside a second, which is how the probe became a test. The two race tests keep their own fixtures and read their own failures. Each trial's certificate, and its load balancer or distribution, now come back out in a finally, so a trial that fails part way through leaves nothing behind in the application the other test classes share, which matters against a 20 certificate quota. The racing tasks' futures are read as well: each catches the AwsException its order expects, and anything else used to stay in the future, leaving the trial looking like the other order had won and the test passing green without the race ever having run. The load balancer name check moves inside the guard too. It was made before the write and nowhere else, so two creates of one name both passed it and both committed, and the first caller was told it had succeeded while holding a load balancer that had been replaced. The check above the guard stays as the fail-fast that keeps AWS's error precedence. Reverting the inner one has the new test report two winners where there should be one. That also showed the guard was not always a lock. Built without IAM, which is how this service's unit tests build it, it ran the action with nothing held, so a re-check there would have been worth no more than the first check. The name is settled by putIfAbsent instead, which holds whether or not IAM is present and needs no lock to carry it. Neither service takes the lock for a write that cannot record an IAM certificate. A distribution that names none, a listener with no certificate or one served by ACM, and a listener removal cannot leave a resource holding a deleted certificate, and the delete reads a copy of the distribution store and a snapshot of each listener list, so an unguarded write cannot disturb its walk either. Holding it for every write would instead have an unrelated load balancer, zone or health check write delay a certificate delete, and the other way round. The race tests stop accepting any AwsException as an order. Each task swallows only the code its own order produces, InvalidViewerCertificate for the create and DeleteConflict for the delete, and rethrows the rest into the future the trial now reads. The load balancer trials record both statuses, and the run asserts every one resolved as one order winning with the other told why, since two failures would otherwise pass as a clean trial with the race untested. The doc paragraph for this behaviour claimed the DeleteConflict refusal was what AWS does, and nothing sources that. DeleteConflict is modeled on the operation, but the API Reference describes it only as attached subordinate entities without saying what counts as one for a certificate, and the operation's own page warns that if Elastic Load Balancing does not detect the deletion of a bound certificate it may continue to use it, which reads as the delete going through. The refusal stays, being the more useful answer to a caller than a dangling reference, and is now recorded as the intentional deviation it is. The ELBv2 note carries its evidence too: CertificateNotFound is modeled on CreateListener, ModifyListener and AddListenerCertificates, and none of the three checks anything. Closes #5087 |
||
|
|
46f9c23c8b |
fix(iam): refuse inactive keys and unreadable credentials in enforcement (#5346)
With enforcement on, three kinds of request got past the filter's
credential checks, and an expired session was answered as a key that
exists nowhere.
A deactivated access key could still be used. Account routing skips an
inactive key, so its requests landed in the default account. A key of a
user there kept that user's permissions, since resolveCallerContext
reads the user's policies whatever the key's status. A key of another
account matched no user in the default account, and isKnownAccessKey,
which counts every key in every account, let the request through as a
credential the filter could not map, with no policy check at all.
Deactivating a key of a user allowed nothing let it create IAM users
and mint session tokens. The IAM User Guide ("Manage access keys for
IAM users") says that once deactivated a key "can no longer be used by
API calls" until it is activated again.
An Authorization header the filter could not read a credential from made
it return before any check. That covered a header naming no access key
at all (a Bearer token, SigV2, a Credential without the SigV4 scheme or
with the key left out) and a SigV4 scope missing a part, such as its
aws4_request terminator. Any caller could make any call that way,
including the management calls an unsigned request is refused. Such a
request is now refused as AWS refuses a header it cannot read:
IncompleteSignature for Query services and IncompleteSignatureException
for JSON and CBOR ones (the common errors, and the IAM User Guide's
SigV4 troubleshooting section), and S3's AuthorizationHeaderMalformed
with the wording S3HeaderSignatureFilter already uses, all 400. A
presigned S3 URL sends no header, and S3 answers a mal-formed
X-Amz-Credential with AuthorizationQueryParametersError, so that is
what it gets. Otherwise the request is treated as an unsigned one is: an
operation AWS serves without credentials is left alone, and a REST
request is refused only when the header claims SigV4 and its route maps
to an action, since AppSync, CodeArtifact's package endpoints, Identity
Store's SCIM endpoint and API Gateway's authorizers take Bearer and
Basic tokens of their own. An empty header with nothing else to read is
refused the same way, not as a missing one; next to a presigned URL's
X-Amz-Credential it still defers to that credential. Where the guide
gives the message, the refusal uses it: "Authorization header cannot be
empty." and, for a SigV4 header with no Credential, "Authorization
header requires 'Credential' parameter.". The other shapes get the
common errors' "The request signature does not conform to AWS
standards.".
sts:GetCallerIdentity answered a key that exists nowhere, as the
default account's root, because its exemption ran before the
unknown-key check. The exemption is about permissions only, so the key
checks now run first.
An expired session was refused with InvalidClientTokenId or
UnrecognizedClientException, because resolveCallerContext deletes it and
the known-key check then finds nothing. The common errors of the IAM,
STS, EC2, SNS, CloudFormation, Lambda and Step Functions API references
give ExpiredTokenException, 403, "The security token included in the
request has expired", and S3's error list gives ExpiredToken, 400. The
filter now asks isExpiredSession before resolving the caller, so it no
longer deletes the session, and later uses get the same answer. Both
lookups are asked about one moment: read apart, a session expiring
between them would be deleted and answered as unknown, or on the
presigned POST path below allowed with no policy check. Once Floci's own
sweep has removed the session (the first presigned URL it generates in a
process runs one), the key reads as unknown again, as
docs/services/iam.md says.
The inactive-key, expired-session and unknown-key checks run before the
action is used, on every Query, JSON and CBOR call and on every REST
request whose route maps to an action. A REST request no rule maps is
left alone, as an unsigned one already is: the filter cannot tell it
from the API Gateway execute path, Lambda function URLs and the other
paths it sees that are unsigned by design, and the execute path answers
a bad AWS_IAM signature in its own shape. Every refusal to a CBOR call,
AccessDenied included, now arrives CBOR-encoded, where only the
unsigned-call refusal did before; the others were JSON bodies the client
could not read. AccessDenied keeps its 403, the status the Kinesis and
CloudWatch common errors give it. The filter's JSON errors are now
written from AwsErrorResponse, as AwsExceptionMapper writes every other
JSON error, rather than built as strings. That gives a REST JSON
refusal, such as Lambda's, the X-Amzn-Errortype header the rest of
Floci's REST JSON errors carry.
A presigned POST carries its credential in the form body, which the
filter never sees, so authorizeAdditionalResource is the only IAM check
it gets. That evaluated an inactive key with its user's policies, and
resolved an expired session, which deleted it. Both are now refused
there as the filter refuses them, before the caller is resolved:
InvalidAccessKeyId, 403, and ExpiredToken, 400. A key that exists
nowhere, or a credential that cannot be read, is still left to S3's own
presigned-POST check, and uploads as an unsigned request would when that
check is off. docs/services/iam.md now says so.
isKnownAccessKey keeps counting inactive keys: GetSessionToken relies
on it, so a session minted with an inactive key has no issuer rather
than acting as the account root. resolveCallerContext keeps returning
an inactive key's user policies rather than null, which AppSync and RDS
read as allowed; both verify the signature first, which an inactive key
fails. isInactiveAccessKey looks in the request's account before
scanning the others, since routing sends an active key to its own
account.
Integration tests cover a same-account and another account's inactive
key (including GetCallerIdentity, GetSessionToken, S3, a JSON service,
a presigned POST, and reactivation); an expired session on Query (asked
twice), JSON (with its X-Amzn-Errortype header), S3 and presigned POST
calls; an unreadable credential on Query (eight header shapes, none of
which creates the user), JSON, CBOR and S3 calls, on a presigned S3 URL,
and with the guide's two messages; the cases left alone (a Cognito flow
AWS serves without credentials, a Bearer token on S3, a REST route no
rule maps); an unknown key on GetCallerIdentity and on a CBOR call; and
AccessDenied on a CBOR call. Every refusal fails without this change.
IamServiceTest and IamEnforcementFilterTest check that the expiry check
and the caller lookup are asked about one moment. The SDK compatibility
suite's IamEnforcementTest adds a deactivated key, refused by STS and S3
with the codes the SDK reads and accepted again once activated.
docs/services/iam.md lists the cases in both enforcement tables and
under unsigned requests.
|
||
|
|
88d429a968 |
fix(iam): open every ValidationError with the count AWS puts on it (#5280)
hectorvent asked on #5240 whether the account-property constraint messages should carry the "1 validation error detected: " prefix that #5239's two recorded messages have, noting there is no recording for PutAccountProperties itself. There is evidence, just not on that operation. Across the AWS-validated snapshots for IAM, CloudWatch and SNS, every recorded constraint message opens with the count: six of six. The prefix is the envelope the front end puts on a validation report, not a property of the member being validated, and SNS settles the part the question turned on, because two of its recordings are map members and both carry it: 1 validation error detected: Value null at 'attributes' failed to satisfy constraint: Member must not be null 1 validation error detected: Value null at 'messageAttributes.attr1.member.dataType' failed to satisfy constraint: Member must not be null The first of those is this change's absent-map case almost verbatim, down to "Value null at '<map>'". Looking for that turned up something wider than the question. IamQueryHandler's requireParam, which every required member in the service is read through, emitted its message without the prefix, while StsQueryHandler's validateRequired in the same package and TagDispatcher in core.common both already carry it on the identical sentence. IAM was the outlier, so one line fixes all 28 call sites. The five messages here are the four on the account-properties path and that one. Each was probed by reverting it on its own, and each fails only the tests that cover it. Three more constraint reports were still opening without the count, so the title did not hold when it was written: the ListPolicies scope enum, the GenerateServiceLastAccessedDetails granularity enum, and optionalInt. No test pinned any of their text, which is how they survived a change that touched every other one. A fourth, the CredentialAgeDays range check, survived a sweep for that phrase because its message builds "failed to " and "satisfy constraint" as separate literals, so the phrase never appears contiguously in the source. The sweep now joins adjacent literals before matching, which finds that one and no others. optionalInt is reachable only through CredentialAgeDays on CreateServiceSpecificCredential, so its case sits beside the test that already exercises that path and asserted only the error code. Two things deliberately left as they are. No snapshot in any service records a map *key* constraint, so the "Map keys must satisfy constraint: [...]" tail is a reasonable shape rather than an attested one, and the same goes for how a string-valued map spells its value path. The prefix is the attested part and the only part this changes. Not touched either: CloudWatch's recorded enum message names both the offending value and the permitted set, where IAM's omits both. That they differ is the point, and it is why #5239 changed only IAM's rendering. Refs #5240 |
||
|
|
df4fa58ea1 |
fix(iam): take service-linked role names and suffix support from AWS evidence (#5293)
CreateServiceLinkedRole guessed both things it cannot derive. The role name came from capitalising the principal, which is wrong for 141 of the 162 services the table covers: acm.amazonaws.com is AWSServiceRoleForCertificateManager on AWS and was AWSServiceRoleForAcm here. And a CustomSuffix was accepted for every service, where AWS refuses one for 68 of the 71 it has been recorded against, so the emulator minted roles AWS would have rejected outright. Both now come from iam/service-linked-roles.tsv, generated by tools/slr/service_linked_roles.py and gated by make slr-check. One table, because both facts come out of one pass over the same AWS-validated snapshot: the name from a recorded create response, the suffix verdict from the test's own parameterisation. Writing either by hand only captures what someone noticed, and every finding behind this change came from grepping. Sources, each row recording its own: recording, actual create responses and the only source that can establish suffix support; policy-documents, role ARNs in the vendored AWS managed policies, names only; and docs, from AWS's own service-linked role pages, quoted and linked in the generator. Counts live in the table's header, where this script keeps them right. Two shapes in the policy documents have to be refused rather than read, and both were being read. A name followed by `*` is a prefix pattern: the policy writes AWSServiceRoleForAmazonCognitoIdpEmail* where the recorded create returns AWSServiceRoleForAmazonCognitoIdpEmailService, so reading the prefix invents a role AWS never mints. Twenty-one principals rested on nothing but such a prefix. And a role name is unique per account, which these documents ignore: they point maintenance.elasticbeanstalk at the parent's AWSServiceRoleForElasticBeanstalk, so taking that at face value made the sibling's create fail as a duplicate of a role it does not own. A collision guard drops the weaker row back to the derived fallback and says so; an unresolvable collision is an error for a human. KNOWN_SOURCE_CONFLICTS is empty as a result. Its one entry was never a disagreement between sources, only that truncated prefix read as a name. The mechanism stays for a real one. make slr-check runs offline: policy-documents rows must still match the vendored JSON, every vendored service must be in the table, it must be sorted, and a suffix verdict on a non-recording row is an error because nothing but a recording can establish one. Three extraction traps have a test each, all three being ones the real data walked into: an underscore can be part of a name, so splitting on the CustomSuffix separator truncates ApplicationAutoScaling_CassandraTable; a policy matching suffixed roles writes the prefix with a trailing separator; and a wildcard ARN names a role without saying which principal mints it, which is how an earlier pass handed plain GuardDuty the MalwareProtection role's name. The name was not only wrong against AWS, it was inconsistent within the tree. ConnectService built an ARN for AWSServiceRoleForAmazonConnect while CreateServiceLinkedRole minted AWSServiceRoleForConnect for the same principal: two roles for one purpose. GuardDutyService, MacieController and RamController each hard-coded their own name too, and all four were right where IamService was wrong. They read the table now, and a test fails if a principal any of them builds an ARN for loses its row, since the fallback would quietly derive a name again. ApplicationAutoScalingService was wrong a different way. It maps a namespace to a dimension itself, and had no arm for appstream, cassandra, ec2 or sagemaker, so all four fell to CustomResource where AWS names them AppStreamFleet, CassandraTable, EC2SpotFleetRequest and SageMakerEndpoint. It prefers the table now and keeps its switch for the namespaces nothing records, where the shape is right even when the dimension is a guess. Its dynamodb arm is gone with the rest: the table covers that namespace, so the arm was unreachable and a second copy of a fact the table owns, free to disagree with it while never running. A test pins dynamodb resolving through the table, since removing the arm is what left nothing else covering it. Two behaviour changes worth calling out. rds.amazonaws.com is AWSServiceRoleForRDS rather than the derived Rds, which flipped one existing expectation. And two table names are long enough that a suffix alone breaches the 64-character RoleName limit, ApplicationDiscoveryService's ContinuousExport role leaving three characters and SageMakerEndpoint six, so that check now reports "The role name" rather than "The derived role name", which stopped being true. cloud9 is in the table because deleting IamService's three-entry override map dropped it: autoscaling and ram were covered, cloud9 was not, and it regressed to the derived AWSServiceRoleForCloud9. Two tests caught it. Rather than restore the literal, which is the circular sourcing this work exists to remove, its User Guide settles it and the row carries that citation. The table is registered in quarkus.native.resources.includes rather than exempted from it. AwsManagedPolicies is exempt because parsing its 3.5 MB at image build time and keeping the result in the heap beats shipping the source twice; at 13 KB that saving is not worth depending on the static initialiser running at build time, and NativeImageResourceIncludesTest is the thing that says so. The header records the sha256 of the snapshot the recording rows came from, because that half cannot be rechecked offline and --check can only say so rather than fix it. A digest makes the next --refresh a diff against a known source: an unchanged digest means any difference in the table came from the vendored policy documents, and a changed one says the recordings moved with it. --check cannot verify the digest without the snapshot, but it does reject a table that has quietly lost the line, or one claiming no snapshot while carrying recording rows. Refs #5084 |
||
|
|
da53fc1c05 |
docs(partition): document deployment, test coverage and known gaps (#5292)
* docs(partition): document deployment, test coverage and known gaps partitions.md said every partition-dependent rule had integration tests over all eight partitions and that the China compat allowlist only shrinks. Neither is accurate now: most services are tested in China alone, and the allowlist is empty. The page now states the coverage as it is (unit tests over every partition, IAM, Step Functions and the cross-service smoke test through the emulator, China end to end), gives a recipe for running a China, GovCloud, ISO or EUSC deployment, and lists the known gaps: global state shared across partitions in one process (now naming the Identity Center instance, which the smoke test's inventory exempts for that reason), the commercial managed-policy catalog, and client tooling untested outside the commercial partition. API Gateway, IAM and Step Functions gain a Partitions section, and the WAFv2 scope note names the partition's CloudFront region and where the CLOUDFRONT scope exists. * docs(partition): say only custom domains refuse EDGE, and when FLOCI_HOSTNAME is enough The API Gateway Partitions section said EDGE was refused outside the commercial partition and that REGIONAL and PRIVATE worked everywhere. Only custom domains are checked: createRestApi and the REST API update path accept EDGE in any partition, and createDomainName refuses PRIVATE in all of them. The section now says so. The deployment recipe offered FLOCI_HOSTNAME for a different port, but it replaces only the host and keeps FLOCI_BASE_URL's port, so a different port needs FLOCI_BASE_URL. |
||
|
|
5fc8b0418c |
fix(iam): separate a constraint failure from an invalid value in PutAccountProperties (#5240)
The key pattern and length checks answered InvalidInput while carrying the "failed to satisfy constraint" wording that every other constraint check in IamService pairs with ValidationError. The model declares InvalidInputException on the operation and says nothing about which code a pattern miss produces, so the two had drifted apart with nothing to settle them. The API Reference settles it in Common Error Types rather than the operation's own error table. ValidationError is a common error for every action, defined as "The input doesn't meet the required format or constraints", 400. InvalidInput, the one the operation declares, is "an invalid or out-of-range value was supplied for an input parameter". PutAccountProperties publishes a Key Pattern of ^[A-Za-z][A-Za-z0-9/_-]*$, a key length of 1 to 50 and a value length of 1 to 1024, and the model declares all three on accountPropertyKeyType and accountPropertyValueType. Violating a published pattern or length is a format failure; a value that satisfies them and is still wrong is not. So it is a split rather than a rename. The key pattern and length, and the value length, are now ValidationError and keep the constraint wording, which was already right for them. The Namespace/PropertyName rule stays InvalidInput: the published pattern admits a key with no slash, with several, and with a trailing one, so that rule only applies once the format is already good. Its message drops the constraint wording and reads as prose, since that wording is what made the pair look inconsistent. The same-namespace rule is unchanged. aMalformedKeyIsRejected asserted one code for seven keys that fall on both sides of that line, so it splits in two, each asserting its own code and the absence of the other. As written it could not tell a pattern failure from the slash rule. Not touched, though the same reading would question it: createServiceLinkedRole answers InvalidInput for a check that is exactly the declared constraint on AWSServiceName. Its message is prose rather than the front-end format, there is no recording either way, and CreateServiceLinkedRole's error table is structured identically to this one, so it proves nothing. Left alone rather than changed on inference. Refs #5177 |
||
|
|
3a8f974554 |
fix(iam): answer AWS's own errors for a malformed service-credential id, and for DeleteUser (#5239)
Three answers on the service-specific credential operations did not match what AWS sends. All three are recorded against real AWS in LocalStack's IAM snapshots, under @markers.aws.validated. A ServiceSpecificCredentialId that does not match the model's [\w]+ was looked up regardless, so it came back NoSuchEntity 404. AWS checks the format first and answers ValidationError 400 quoting the pattern, on UpdateServiceSpecificCredential, ResetServiceSpecificCredential and DeleteServiceSpecificCredential alike. A malformed id and an unknown one are different mistakes, and they now get different answers. An id that does satisfy the pattern and names no credential of that user was "The Service Specific Credential with id <id> cannot be found." AWS says "No such credential <id> exists", still NoSuchEntity 404. DeleteUser named the credential in its refusal: "must delete service-specific credentials first." This case gets no message of its own on AWS, unlike the access-key and policy cases beside it, and falls back to the generic "Cannot delete entity, must remove referenced objects first.", DeleteConflict 409. The API Reference publishes a length of 20 to 128 on the id as well as the pattern, so both are now enforced, and an id breaking both is reported as two validation errors rather than one, which is what the counted prefix is for. Only the pattern message is recorded; the length wording is the form AWS uses for a member carrying both bounds, which validateLoginProfilePassword already spells the same way. The same snapshots show an invalid Status answered with "1 validation error detected: Value at 'status' failed to satisfy constraint: Member must satisfy enum value set", naming neither the offending value nor the permitted set, where the code named both. statusType is one shape, validated by one front end, and UpdateSigningCertificate, UpdateSSHPublicKey and UpdateServiceSpecificCredential all take it, so the recording of one is the rendering of all three. They had the same message copied three times and now share a helper, placed ahead of all three rather than inside one family's section. Elsewhere in the tree this message does carry the permitted set, and those are other services with their own renderings, so they are left alone. UpdateSSHPublicKey had no test for a status outside the enum at all, and the two that did have one asserted only the code, so the message none of them pinned could have been reverted with the suite still green. All three now assert the counted prefix and the absence of both the value and the set. UpdateAccessKey takes the same shape and is further off: "Status must be Active or Inactive." is not AWS's format at all, it refuses the Expired that statusType allows, and it validates the status only after looking the key up, so a bad key and a bad status answer NoSuchEntity where the front end would answer ValidationError first. That is a behavioural change with its own tests to write, so it is not folded in here. Refs #5084 |
||
|
|
04a3b97346 |
feat(iam): model account properties and outbound web identity federation (#5177)
Adds GetAccountProperties, PutAccountProperties, SetSecurityTokenServicePreferences, EnableOutboundWebIdentityFederation, DisableOutboundWebIdentityFederation and GetOutboundWebIdentityFederationInfo, which completes step 9f of the IAM gap plan. A property key is Namespace/PropertyName with exactly one forward slash and neither a leading nor a trailing one, and every key in one request must share a namespace, which AWS states directly. A request mixing namespaces is rejected whole rather than partly applied. Enabling federation twice is FeatureEnabled 409 and disabling it twice is FeatureDisabled 404, an asymmetry AWS documents. The getter answers FeatureDisabled too when the feature is off, reusing the disable operation's own wording, which is matched rather than improved. The issuer URL is derived from the request's partition rather than the literal in the API Reference's example: api.aws is only the commercial partition's dual-stack suffix. It is minted once per account and survives a disable, since a relying party verifying tokens will have pinned it. AWS documents neither that nor JwtVendingEnabled's source, so both are recorded in the docs as choices. The OIDC discovery endpoints the issuer is documented to host, and the GetWebIdentityToken API the feature references, are not modelled: these six are the management operations only. |
||
|
|
9c0102559d |
feat(iam): model service-specific credentials (#5084)
Adds CreateServiceSpecificCredential, ListServiceSpecificCredentials, UpdateServiceSpecificCredential, ResetServiceSpecificCredential and DeleteServiceSpecificCredential, the five the wire model defines. A credential takes one of two shapes, decided by the service: CodeCommit and Keyspaces get a ServiceUserName and a ServicePassword, while the long-term API key services get a ServiceCredentialAlias and a ServiceCredentialSecret and accept CredentialAgeDays. The quota is two per service rather than two per user, and the version behind a service user name's +n suffix is the lowest one free rather than a count, so deleting out of order cannot mint a name already in use. A credential blocks DeleteUser until it is removed, the last item on AWS's list of what to delete first, and follows the user across an UpdateUser rename. |
||
|
|
a84a8a0435 |
fix(iam): resolve server certificate references in ELB and CloudFront (#5075)
Resolve certificate ids on the way in and refuse deleting one in use. * Fix #4875 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
fe296fda69 |
feat(iam): model SSH public keys (#5051)
UploadSSHPublicKey, GetSSHPublicKey, ListSSHPublicKeys, UpdateSSHPublicKey and DeleteSSHPublicKey, stored per user with the documented quota of five. AWS accepts the body in ssh-rsa form or as PEM, so both are read, and the body is kept exactly as it arrived: a caller that uploaded PEM gets that PEM back rather than a re-encoding. GetSSHPublicKey converts, because Encoding is required and decides the form of the response. Fingerprint is the MD5 of the OpenSSH blob, confirmed by reproducing the worked example in the IAM API Reference rather than assumed. It is not the digest EC2 reports for the same key, which is taken over the DER: both are sixteen bytes of colon hex, so the wrong one would look right. The two rejection errors are kept apart the way the model separates them. A body in neither accepted encoding is UnrecognizedPublicKeyEncoding; one in a recognised encoding that will not parse, or that carries a key type other than ssh-rsa, is InvalidPublicKey. An OpenSSH line is recognised by its key-type token rather than by whether part of it base64-decodes, since a short word often does. DuplicateSSHPublicKey is per user, unlike the account-wide rule for signing certificates, and compares fingerprints so the same key in the other encoding still counts. A key blocks DeleteUser until removed and follows the user across an UpdateUser rename, both under a lock taken in the same order DeleteUser takes it. |
||
|
|
290f952cb1 |
feat(iam): model signing certificates (#5024)
UploadSigningCertificate, ListSigningCertificates, UpdateSigningCertificate and DeleteSigningCertificate, stored per user with the documented quota of two and account-wide duplicate detection compared on the encoded form. The body is parsed on upload, because MalformedCertificate cannot be answered without reading it. Status accepts Active, Inactive and Expired: the API Reference gives all three as valid values even though the parameter's prose explains only the first two. UserName is optional on every operation and resolves from the access key that signed the request. A certificate blocks DeleteUser until it is removed, which AWS lists as a prerequisite, and follows the user across an UpdateUser rename rather than being stranded on a name that no longer exists. The credential report's cert_1 and cert_2 columns are backed by the store instead of always reporting FALSE, reporting N/A for the rotation date unless the certificate is Active, as the User Guide defines them. |
||
|
|
cd57deac18 |
fix(iam): authorize a server-certificate rename against both names (#5016)
AWS requires the principal to hold permission on the old name and the new one, so that a rename into a name they may not write fails. ResourceArnBuilder named only the stored certificate, so a Deny on the destination did not match and the rename went through. UpdateServerCertificate now names both the current ARN and the one the request would produce, which the filter authorizes once per resource. The destination is built beside the stored ARN so it keeps the certificate's partition and account, and an update that renames and moves nothing still names a single resource. |
||
|
|
d0c7c23f6b |
feat(iam): model server certificates (#4975)
Replace the ListServerCertificates stub with the server-certificate lifecycle: UploadServerCertificate, GetServerCertificate, UpdateServerCertificate, DeleteServerCertificate, ListServerCertificates and the tag operations. The uploaded material is really parsed, because two of the upload's modeled errors cannot be answered otherwise. CertificateBody, and every certificate in CertificateChain rather than only its first block, must be readable PEM or the upload is MalformedCertificate; the private key must match the certificate's public key or it is KeyPairMismatch. The match is a sign-then-verify check, so it holds for RSA and EC alike. All of it goes through core.common.Pem rather than a second copy of the parsing. Expiration is read from the certificate's own notAfter rather than stored separately, so it cannot drift from what it describes. ServerCertificateId uses AWS's ASCA prefix. The private key is stored and never returned: AWS marks privateKeyType sensitive and models it only on the upload, so neither reader echoes it back, and ListServerCertificates returns metadata only as AWS documents. Request shapes are enforced from the wire model: the 16384-character caps on the body and key, the much larger 2097152 cap on the chain, and the per-account quota of 20 that the User Guide's table publishes, counted under the same lock as the write. A rename that only changes case is allowed, excluding the certificate from its own duplicate check by id the way updateUser does. GetAccountSummary's ServerCertificates count is now backed by the store instead of a hardcoded zero. ResourceArnBuilder gains an iam case naming the certificate an operation targets, so a policy statement scoped to one certificate constrains it under enforcement. Every other IAM action still resolves to *, which is long-standing behaviour rather than something this adds; documented in docs/services/iam.md and tracked in #4979. DeleteServerCertificate does not raise the in-use DeleteConflict AWS returns when a load balancer still references the certificate. Floci cannot determine that yet, because ELB Classic and CloudFront store certificate identifiers without resolving them against IAM. Documented, and tracked in #4875. |
||
|
|
b679fe2312 |
fix(s3): match a bucket policy's Principal the way IAM does in S3's own checks (#4961)
Follow-up from the reviews of #4838 and #4839. S3 checks a bucket policy itself in two places, and neither matched its Principal the way the IAM evaluator does since #4839: - The signed-request check (s3.enforce-auth) passed the caller to the IAM evaluator as a bare ARN, so a role session was matched through a role ARN rebuilt from the session ARN, which drops the role's path. A bucket policy naming role/team/App never reached that role's sessions. - The CopyObject/UploadPartCopy source check used S3's own matcher, which compared each AWS entry with the caller's ARN as a string. A grant to the caller's account, by id or root ARN, or to its role, never matched, so a cross-account caller allowed to read an object could not copy it. Both now pass the typed caller to the IAM evaluator, a role session with the ARN of the role it assumed, through a RequestPrincipal.caller factory the enforcement filter now uses too. The copy check's own matcher is gone: its direct-grant rules (an exact user ARN, or "*" with aws:PrincipalArn pinned to it) are the IAM evaluator's, and the unit tests that pinned them there move to IamPolicyEvaluatorTest. S3PublicAccessEvaluator keeps its principal matching for CloudFront's origin access identity check. A CanonicalUser entry matched nothing since #4839, and docs/services/iam.md described that as AWS behaviour. The IAM User Guide ("AWS account principals") lets an S3 bucket policy name an account by its canonical user ID, which the S3 User Guide describes as an obfuscated form of the account ID. It now matches the IAM identities of that account, as an account principal does. Floci's canonical ID for an account is its account id, the owner ID its S3 ACL responses report. Integration tests (IAM and S3 enforcement, real SigV4) read and copy across accounts under bucket policies naming the caller's account, a role under a path, and the account's canonical ID; each fails on main. docs/services/iam.md and docs/services/s3.md describe the matching. |
||
|
|
2bdfe45207 |
fix(iam): match a resource policy's Principal by the kind of caller it names (#4839)
IamPolicyEvaluator matched a resource policy's Principal against one string,
the caller's ARN, and compared every principal type other than AWS and "*"
with it by glob. So {"Service": "*"} and {"Federated": "*"} matched every IAM
caller: under enforcement a bucket policy granting {"Service": "*"}, a form AWS
does not accept at all, let an IAM user from any account read the bucket.
Services could not be passed as a caller at all, so {"AWS": "*"}, which AWS
itself relies on to cover services (an FIS Deny pausing DynamoDB replication
names the replication service that way), could not match one. And a role
session matched a Principal naming its role only through a role ARN rebuilt
from the session ARN, which drops the role's path, so a policy naming
role/team/App never matched that role's sessions.
A new RequestPrincipal carries the kind of caller (IAM, service, anonymous),
and for a role session the ARN of the role it assumed. Each principal type now
matches only the callers it can name (IAM User Guide, "AWS JSON policy
elements: Principal"): "*" anyone; {"AWS": "*"} IAM identities and services;
any other AWS entry IAM identities only, a role session matching through its
role's own ARN; {"Service": "<name>"} that service exactly; {"Service": "*"}
nothing; Federated and CanonicalUser never an IAM caller. NotPrincipal is typed
the same way. The direct-IAM-user branch and the aws:PrincipalArn stand-in for
a missing caller stay IAM-only.
A new evaluateResourcePolicyFor takes a RequestPrincipal; the existing String
evaluateResourcePolicy reads its argument as an IAM caller and delegates to it.
The typed method has its own name rather than being an overload of the same
arity, so a call passing a literal null caller to the String form still
compiles. A new
evaluateServicePrincipal decides a call a service makes on its own behalf from
the resource policy alone, since a service principal has no identity policy,
boundary or session policy and SCPs do not apply to it: Deny denies, Allow
allows, silence denies. Nothing calls it yet; the shared service-call
authorizer will.
The enforcement filter now passes the typed principal, with a role session's
role ARN from IamService.resolveCallerArns, to both resource-policy
evaluations. S3's own bucket-policy checks still go through the String
overload; giving them the role ARN follows the change that splits the two ARNs
there.
docs/services/iam.md describes the matching rules.
|