mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 07:11:11 -05:00
4afa7d8e9f5c716c4bf16af2eb0291f495ebc708
71
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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.
|
||
|
|
c7bb03ace3 |
feat(iam): model virtual MFA devices with real TOTP verification (#4820)
Replace the ListMFADevices stub with the virtual MFA device lifecycle: CreateVirtualMFADevice, ListVirtualMFADevices, DeleteVirtualMFADevice, EnableMFADevice, DeactivateMFADevice, ResyncMFADevice, ListMFADevices, and the device tag readers/writers. The seed is real rather than a placeholder. CreateVirtualMFADevice generates a 160-bit secret from SecureRandom and returns it as an RFC 4648 base32 string, and EnableMFADevice/ResyncMFADevice verify codes against it as RFC 6238 TOTP, so a caller that does not hold the seed cannot enable a device. The codes must be consecutive, as AWS asks for. Implemented on the JDK's own javax.crypto, with no new dependency. The TOTP arithmetic is the shared core.common.Totp primitive (#4814): CognitoTotp keeps its single-code window and attempt budget, and VirtualMfaCodes holds the consecutive-pair rule that is specific to IAM. Request shapes are validated against the wire model before the device is resolved, so a malformed SerialNumber is a ValidationError rather than a NoSuchEntity, and UserName is enforced as required on Enable and Resync. VirtualMFADeviceName gets its own validator because it is the one IAM name type with no documented maximum length, so borrowing the usual 1-to-128 name check would have rejected names AWS accepts. Device state also reaches the places that report on it: DeleteUser now returns DeleteConflict while a user still holds a device, GetAccountSummary counts devices and their assignments, and the credential report's mfa_active column is backed by real state instead of a constant. Documented as out of scope: QRCodePNG is not returned (it needs a QR encoder, and the otpauth URI it encodes is derivable from the seed that is returned), GetMFADevice takes only FIDO security key ARNs, hardware and FIDO devices are not modeled, MFA still has no effect on authorization because the aws:MultiFactorAuth* keys are never populated, and STS does not accept SerialNumber/TokenCode. |
||
|
|
cf04f433b6 |
fix(iam): give a role session's aws:PrincipalArn as its role's ARN under enforcement (#4810)
Follow-up from the review of #4716. The enforcement filter put the assumed-role session ARN (arn:aws:sts::<account>:assumed-role/<role>/<session>) in aws:PrincipalArn for a caller using role-session credentials. AWS puts the ARN of the role that was assumed there, path included ("For IAM roles, the request context returns the ARN of the role, not the ARN of the user that assumed the role", IAM User Guide, global condition keys). So an identity or resource policy keyed on the role's ARN never matched its sessions: an Allow scoped that way refused them and a Deny written that way never fired, while a condition naming the session ARN, which AWS says not to use for this key, matched. The filter now reads both values from one lookup of the key, through a new IamService.resolveCallerArns: the caller ARN, still the session ARN for a role session, and the principal ARN, the role ARN the session recorded when it was issued (#4716). A user's key and the account-root principal give the same value for both. One lookup matters: two could straddle the session's expiry, answer the first and not the second, and leave a fallback to fill aws:PrincipalArn with the session ARN, so a Deny keyed on the role's ARN would miss. resolveCallerArn and resolvePrincipalArn now read through it, and the STS trust check, which made the same two lookups, uses it too. Both places the filter fills the key (the request's own authorization and authorizeAdditionalResource) take it from there. The session ARN stays the caller's principal for matching a resource policy's Principal, which is a separate change. docs/services/iam.md describes the key for role sessions and drops the caveat about the session name, which no longer applies to it. The integration test covers both paths: IAM calls whose policy is keyed on the role's ARN, and an SSM GetParameter on a Secrets Manager reference, whose secretsmanager:GetSecretValue check goes through authorizeAdditionalResource. The SDK compatibility suite's IamEnforcementTest gets the same IAM checks with AWS SDK clients; like the rest of that class it runs only against a Floci with IAM enforcement on. |
||
|
|
275d874fed |
fix(ses): authorize SES v2 calls against their IAM actions under enforcement (#4775)
SES v1 is a Query API, so IAM enforcement resolves its action from the request's Action like any other. SES v2 is REST-JSON under /v2/email and IamActionRegistry had no rules for it, so every v2 call resolved to no action, which the enforcement filter lets through: with enforcement on, the whole v2 API was unguarded, CreateConfigurationSetEventDestination included. IamActionRegistry now has one rule per operation in the SES v2 model (botocore sesv2/2019-09-27, 112 operations), each mapped to the IAM action AWS's service reference lists for it (servicereference.us-east-1.amazonaws.com/v1/ses/ses.json). That is always ses:<Operation>, in the ses namespace v1 and v2 share. SendEmail has no entry there; the Service Authorization Reference's SES v2 page defines ses:SendEmail as v2's only send action whatever the content (ses:SendRawEmail is a v1 action), so it takes its name too. No two rules can match the same path, so their order does not matter. The 20 operations Floci does not serve yet are mapped too, so a route added later is guarded from the start. Two ways round a rule are closed for every REST service, not only SES v2. IamActionRegistry.resolve read X-Amz-Target before the path rules, so a REST request carrying one was checked as whatever operation the header named: a POST /v2/email/outbound-emails with X-Amz-Target: SES.GetAccount went through for a caller denied ses:SendEmail. REST-claimed requests now resolve through a new resolveRoute, from method and path alone. And the rules matched the decoded path while the router matches the encoded one, so a%2Fb@example.com reached the suppressed-destination endpoint while its decoded path matched no rule and passed as an unknown action. resolveRoute matches the path still percent-encoded, read from the request URI since RESTEasy Reactive does not serve UriInfo.getPath(false). A denied call answers AccessDeniedException with HTTP 403, as the SES v2 API Reference lists among its common errors. Like v1, v2 is evaluated with resource "*"; resource ARNs for SES, and the extra actions the service reference lists for some operations (ses:TagResource on the create operations, iam:PassRole for event destinations), are left for later and documented in docs/services/ses.md. IamActionRegistryTest checks every operation against a table generated from the model and the service reference, not from the rule table. SesV2IamEnforcementIntegrationTest shows a caller without SES permissions refused, a single allowed action granting only that operation, a target header not changing the checked action, and an encoded slash still authorized. |
||
|
|
4e2c1d11ff |
fix(sts): evaluate AssumeRole trust-policy conditions against the real caller (#4716)
With IAM enforcement on, AssumeRole matched a trust policy on its Action and Principal only. The Condition block was never read and the ExternalId request parameter was ignored, so a role guarded by sts:ExternalId, the documented confused-deputy guard, could be assumed without it, and a conditional Deny applied whether or not its condition held. Trust-policy conditions now go through IamPolicyEvaluator's condition engine, through a new package-private conditionMatches, so they get the same operators as identity and resource policies. The request context holds sts:RoleSessionName, sts:ExternalId when the caller sends one, the global keys the enforcement filter already provides, and aws:PrincipalArn. A role session is now matched as the role that issued it, through that role's own ARN, path included. AssumeRole records it on the session when it issues one, and a new IamService.resolvePrincipalArn reads it back as is, so an old session keeps naming its role even after a same-named role replaces it. The evaluator used to rebuild the role ARN from the assumed-role session ARN, which names the role without its path, so a session of role/team/App was compared as role/App: a Principal naming the role refused it, and a condition on aws:PrincipalArn saw the wrong value. IAM stores a Principal naming a role as the role's unique ID, and aws:PrincipalArn is the ARN of the role that was assumed, so both are the full role ARN. A negated operator on an absent key now holds, as the IAM User Guide says for every condition operator but the IfExists forms and Null: "If the policy condition requires that the key is not matched, such as StringNotLike or ArnNotLike, and the right key is not present, the condition is true." evaluateConditionBlock failed every operator on an absent key, so once trust conditions were evaluated a Deny with StringNotEquals on sts:ExternalId stopped refusing a call that omits ExternalId. The change is in the shared engine, so identity, resource and SCP conditions get the same rule; the set operators keep their own rule for an absent key. The AppSync service-trust path from #4555 had its own small condition evaluator for aws:SourceArn and aws:SourceAccount. It now uses the same engine with those two keys as its context, which also makes negated operators such as StringNotEquals work there instead of refusing the document. A Condition that is not an object of non-empty operator objects still invalidates the whole trust document, now on every path. The trust check also resolved the caller's account from the Authorization header alone, where only a 12-digit key names an account. An IAM user's or a role session's key, and any presigned request, therefore counted as the default account and could assume a role that trusts only that account. The check now uses the account the request was resolved to, and reads a presigned caller's key from X-Amz-Credential. |
||
|
|
055c411b9a |
fix(iam): share case-sensitive condition matching (#4725)
* fix(iam): share case-sensitive condition matching * fix(iam): use iterative glob matching for conditions * fix(iam): match wildcard before literal asterisk |
||
|
|
33617e340d |
fix(iam): match condition values case-sensitively (#4672)
* fix(iam): match condition values case-sensitively * chore(ci): retry transient registry pull failure |
||
|
|
970bdf2e54 |
fix(iam): return protocol-correct access-denied statuses (#4673)
* fix(iam): return protocol-correct access-denied statuses * chore(test): alphabetize IAM enforcement imports |
||
|
|
26146a3f94 |
feat(iam): expand wildcard service grants against a vendored namespace catalog (#4544)
GetServiceLastAccessedDetails reports the services an entity can reach, but a grant that names no namespace could not be expanded: "Action": "*", a globbed prefix such as s3*, and any NotAction all denote a set no policy document spells out. A user holding only AdministratorAccess came back with an empty report. Closes #4487. The list of namespaces is vendored in aws/iam-service-namespaces.json and generated by tools/aws/regen_service_namespaces.py from AWS's Service Reference Information index, whose per-service "service" field is the IAM namespace itself. botocore is deliberately not the source, even though every other vendored file here comes from it: a namespace is not any botocore field, since CloudWatch's endpointPrefix is monitoring and its serviceId is CloudWatch against an IAM namespace of cloudwatch. A rule over botocore metadata is wrong for some service, and a wrong namespace is worse than a missing one because it names something IAM does not have. That index is a live endpoint rather than a pinned dependency, so unlike regen_partitions.py a fresh generation is not byte-identical and byte equality is the wrong gate. What must be guaranteed is that nothing in the file is invented, which is checked directly: make iam-namespaces-check validates the file's shape offline, and make iam-namespaces-verify checks online that every namespace in it still exists upstream, failing on one that does not. Services AWS has added since the last sync are reported without failing, since the file being behind makes the report incomplete rather than wrong. A namespace a policy names outright is kept whether or not the catalog knows it, so a catalog trailing an AWS launch still reports an explicitly named service; only wildcard expansion depends on it being current. A globbed prefix now expands to the namespaces it matches rather than being treated as every service and then dropped. |
||
|
|
c26f782ea8 |
fix(iam): refuse an unsigned management call under enforcement (#4489)
A request carrying no Authorization header returned before any policy check, so with enforcement on an unauthenticated caller reached every emulated API by simply omitting the header. Refuse one whose wire shape names a management operation: a JSON, CBOR or Query claim exists only for a request carrying X-Amz-Target, an rpcv2 path or an Action parameter. AWS answers a credential-less request with MissingAuthenticationToken at 403, returned here in the encoding the request used. Operations AWS itself serves without credentials stay allowed, taken from the authtype: none trait in its service models: the Cognito user-pool and identity flows and the two web-identity and SAML AssumeRole calls. The list is keyed by service because GetUser needs no credentials on cognito-idp and requires them on iam. REST is left alone. This filter also sees the API Gateway execute path, Lambda function URLs, CloudFront serving and the Cognito OIDC endpoints, which are unsigned by design, and a REST claim does not say which service will serve the request. The CBOR error shape moves into CborErrorResponses, shared with the rpcv2 controller so the two cannot drift into answering the same failure differently. EksIrsaDockerIntegrationTest set up its IAM fixtures over unsigned Query calls and so began failing: CreateRole is not an operation AWS serves without credentials. Its fixture calls now carry the root stand-in credential, which is what every other test does under enforcement. The AssumeRoleWithWebIdentity calls it actually tests stay unsigned, as AWS serves those without credentials. |
||
|
|
67437115c5 |
feat(iam): add last-accessed reporting actions (#4488)
Add GenerateServiceLastAccessedDetails, GetServiceLastAccessedDetails, GetServiceLastAccessedDetailsWithEntities and ListPoliciesGrantingServiceAccess. Floci records no service-access history, but AWS's "never used" shape keeps the report and nulls the usage fields rather than emptying the report, so that is what these reproduce. GetServiceLastAccessedDetails lists every service the entity could reach through its permissions policies and leaves LastAuthenticated and TotalAuthenticatedEntities absent for the ones never used. GetServiceLastAccessedDetailsWithEntities lists the entities that could have used the reported permissions: a group report yields the group's users, a policy report the users and roles it is attached to, and a user or role report that entity. Both lists come from permissions-policy logic, which Floci can evaluate, so both are computed rather than stubbed; the usage timestamps are the only part left out. A report is produced when the job is created and stored with it, matching AWS, where the Get operations retrieve a report that Generate produced. So editing the policies afterwards does not change what a completed job answers, and deleting the entity does not stop a valid JobId resolving. Generate resolves the whole ARN first, rejecting one whose account is not the caller's or whose path is not the resolved entity's, so it cannot fall back to a same-named local identity; AWS-managed policy ARNs carry the literal "aws" account and are allowed through to the global catalog. An unknown JobId is NoSuchEntity, Granularity is validated and echoed back as JobType, and both readers honour MaxItems and Marker. ListPoliciesGrantingServiceAccess needs no job and no usage history, since AWS defines it purely over permissions-policy logic. A user contributes its own managed and inline policies plus those of every group it belongs to, while a group or role contributes only its own; permissions boundaries are excluded. Only Allow grants, and Allow with NotAction grants every service the list does not carve out. It models a Marker but no MaxItems, so only the former is applied. Services reachable only through a wildcard or NotAction cannot be enumerated without a catalog of IAM service namespaces, which is tracked separately in #4487 and documented. |
||
|
|
3d35eabf51 |
feat(iam): finish the SAML provider lifecycle (#4360)
Adds UpdateSAMLProvider, DeleteSAMLProvider, TagSAMLProvider, UntagSAMLProvider and ListSAMLProviderTags, and adds tags to GetSAMLProvider. UpdateSAMLProvider re-parses a new SAMLMetadataDocument the same way CreateSAMLProvider does and replaces the stored entity ID and certificate. The document is optional on the request: omitting it (metadata == null) is a no-op, but an explicitly empty one is invalid input, the same as CreateSAMLProvider already rejects it as; the two are distinguishable at the wire level and were previously treated the same. The update replaces the stored provider with a newly built one rather than mutating the existing, already-published object's fields one at a time: assertion verification (StsQueryHandler) reads a provider via find() / findForAccount() without taking providerLock, so setting entityId and certificate as two separate writes on the live object could let it observe one field updated and the other not. Publishing a fully-built replacement through the same ConcurrentHashMap-backed store means any reader, synchronized or not, sees either the old provider intact or the new one intact, never a mix. DeleteSAMLProvider's existence check now runs inside the same lock as the delete itself, not before it: two concurrent deletes could otherwise both pass the check before either removed the provider, so the second returned success instead of NoSuchEntity, and a delete racing a recreate of the same ARN could remove the newly created provider instead of the deleted one. DeleteSAMLProvider itself does not check or update any role whose trust policy still references the provider's ARN. This corrects an assumption from the original gap-report plan (which expected a delete-blocked-while- referenced check, by analogy with DeletePolicy's attachment guard): AWS's own docs say the opposite, that deletion always succeeds and it is a later AssumeRoleWithSAML against the now-dangling ARN that fails, not this call. GetSAMLProvider and ListSAMLProviderTags both sort their tags by key, matching AWS's own documented behavior for both, which the same wording in ListInstanceProfileTags's docs already established the precedent for. Also completes AwsQueryController's IAM_ACTIONS fallback set for every SAML provider action, including the three pre-existing ones (ListSAMLProviders, CreateSAMLProvider, GetSAMLProvider), none of which were there before, and adds SDK-client coverage for the whole SAML provider lifecycle to compatibility-tests/sdk-test-java/IamTest.java, which (like the three pre-existing SAML actions) had none. |
||
|
|
910f0922c9 |
feat(iam): add GenerateCredentialReport and GetCredentialReport (#4298)
Generates and downloads the account's credential report, the 23 columns AWS documents for it, in CSV, Base64-encoded per the wire model. The report is a single value per account, stored the same way accountAliases and passwordPolicies already are, and regenerated only once the previous one is older than 4 hours, matching AWS's documented caching window. CSV content: every IAM user gets real password_enabled, password_last_used, password_last_changed and access_key_1/2_active/last_rotated where Floci already tracks that state, plus the documented placeholder values for what it does not model (MFA devices, X.509 signing certificates, access-key last-used date/region/service, and password_last_used itself, since nothing in the codebase ever sets IamUser's passwordLastUsed field). The root account row is present, as AWS always includes it, but is placeholder throughout: Floci does not model root account credentials at all, the same reason GetAccountSummary's AccountPasswordPresent and AccountAccessKeysPresent are always zero. password_last_changed needed a new LoginProfile field: UpdateLoginProfile changes the password without touching LoginProfile's own createDate (its meaning stays 'profile created'), so reading createDate for this column would have kept reporting the original creation time after a password change. passwordLastChanged is set alongside createDate initially and updated whenever UpdateLoginProfile actually changes the password, falling back to createDate for a profile persisted before this field existed. additional_credentials_info is Floci's own wording, since AWS does not document the exact text; in practice it is unreachable, since CreateAccessKey already enforces the real 2-key-per-user quota. Generating a report is effectively instant here, so GenerateCredentialReport never actually returns INPROGRESS; a GetCredentialReport call right after it always finds the report ready. The STARTED state and its description for the no-report-exists case match AWS's own documented example response verbatim; the report-expired case's wording is Floci's own, since AWS does not document it. |
||
|
|
1fa5534e6c |
feat(iam): add GetAccountAuthorizationDetails (#4208)
Returns every user, group and role in the account, plus every local (customer-managed) policy and every AWS-managed policy actually attached to or used as a permissions boundary by something in the account: the entity lists themselves, their inline and attached policies, group membership, instance profiles, permissions boundaries, and each managed policy's version list. AttachmentCount and PermissionsBoundaryUsageCount are computed by scanning the account's own users, groups and roles rather than read off IamPolicy.getAttachmentCount(): for an AWS-managed policy that field is a single object shared process-wide across every account (attachUserPolicy et al. mutate the same catalog entry every account resolves), so trusting it would leak one account's attachments into another's response. Filed separately as #4205, since fixing it properly means changing the attach/detach methods themselves, well beyond this action. Also fixes two related, smaller gaps found while building this: - CreateInstanceProfile silently dropped a Tags parameter at creation, unlike every other Create* action. - GetInstanceProfile, CreateInstanceProfile and ListInstanceProfilesForRole never serialized an instance profile's own tags into the response. ListInstanceProfiles keeps omitting them: its own operation documentation, like ListRoles's, says it returns a subset of attributes and does not return tags, even though the InstanceProfile shape itself carries no such exclusion note. Policy documents are returned as plain JSON, not URL-encoded as AWS documents them for this action: matches every other IAM action that returns a policy document, none of which URL-encode either. Filter, MaxItems and Marker are not honored; the response always includes everything. |
||
|
|
d30a744b66 |
fix(iam): reject an access key that exists nowhere under enforcement (#4182)
With enforcement enabled, a signed request whose access key resolved to no caller context was allowed through, so any access key id authorized any call. Reject it with InvalidAccessKeyId for S3 and UnrecognizedClientException elsewhere, matching what the S3 signature filter and the API Gateway execute path already return. resolveCallerContext returns null for a key that does not exist and for a real credential it cannot map to policies, such as a session carrying no role ARN. Only the first is unauthenticated, so isKnownAccessKey searches sessions and long-term keys across every account and only a key found nowhere is rejected. The test credential, the bare account-id root principal, unresolvable actions and unsigned requests are unchanged. |
||
|
|
04b75fd1f5 |
feat(iam): add SimulateCustomPolicy and GetContextKeysFor*Policy (#4185)
SimulateCustomPolicy evaluates requested actions and resources against a
standalone set of policy documents plus an optional permissions boundary,
reusing the same identity/boundary evaluation as SimulatePrincipalPolicy.
GetContextKeysForCustomPolicy and GetContextKeysForPrincipalPolicy list the
context keys referenced across a set of documents, or a resolved principal's
policies plus any extra documents supplied.
contextKeysReferencedIn collects every Condition operator's key, every
${...} policy variable named in a Resource pattern, and every one named in
a Condition value, in statement order, without sorting or de-duplicating:
AWS's own documented example response for GetContextKeysForPrincipalPolicy
repeats a key referenced by more than one statement. A variable's default
value (${key, 'default'}) is stripped to just the key name, and the three
single-character escapes (${*}, ${?}, ${$}) are excluded, since AWS
defines those as literal-character substitutions, not context-key
references. NotResource is not scanned: AWS documents policy variables as
usable only in Resource and in Condition values, never in NotResource,
Action or Principal.
Also completes AwsQueryController's IAM_ACTIONS fallback set for the three
new actions, matching SimulatePrincipalPolicy's existing entry there.
Known limitations, documented in iam.md: PolicySourceArn resolves a user or
role only, not a group (inherited from SimulatePrincipalPolicy); only one
PermissionsBoundaryPolicyInputList document is honored, matching AWS's own
stated limit; ResourcePolicy, ResourceOwner, ResourceHandlingOption and
OrderedOrganizationPolicyInputList are not evaluated; MatchedStatements,
ResourceSpecificResults and PermissionsBoundaryDecisionDetail are never
populated; ContextKeyType is accepted but not read, since the comparison is
driven by the policy's own condition operator.
|
||
|
|
2f5aa99701 |
feat(iam): add ListInstanceProfileTags (#4140)
TagInstanceProfile and UntagInstanceProfile already existed; the read side was missing. Mirrors ListUserTags's response shape, and sorts the result by tag key to match the documented AWS behavior. Also adds the instance-profile tag actions to AwsQueryController's IAM_ACTIONS fallback set, completing the Tag/Untag/List triple already present there for users, roles and policies. Covers the trio in the SDK compatibility suite (compatibility-tests), which previously had no instance-profile tagging coverage. |
||
|
|
7f5336e2dc |
docs(iam): document dispatched actions missing from the service page (#4074)
CreateSAMLProvider, GetSAMLProvider, ListSAMLProviders, TagInstanceProfile, UntagInstanceProfile, the Organizations root-access actions, and the ListMFADevices/ListServerCertificates stubs are dispatched by IamQueryHandler but were not listed. Also correct the GetAccountSummary note: Providers counts OIDC providers only, so it is no longer described as zero for OIDC. |
||
|
|
09b1dc0803 |
fix(iam): resolve s3:ExistingObjectTag and s3:RequestObjectTag under enforcement (#3946)
* fix(iam): resolve s3:ExistingObjectTag and s3:RequestObjectTag under enforcement The S3 condition context was built for s3:ListBucket and the bucket-tagging actions only, so a statement conditioned on an object tag never matched and a tag-conditioned allow denied everything, including what AWS allows. Object reads are now given s3:ExistingObjectTag/<key> from the object's tags, PutObject is given s3:RequestObjectTag/<key> from x-amz-tagging, and PutObjectTagging both. Which action gets which key follows what real AWS was measured to do rather than what reads naturally: s3:DeleteObject is given neither, and s3:PutObject never sees the tags of an object it is about to overwrite. A PutObject carrying If-Match is additionally authorized as s3:GetObject with the object tags stripped from the context, as measured: under a tag-conditioned GetObject allow the conditional write is denied, under a prefix-scoped one it succeeds, and If-None-Match needs no such permission. The per-resource evaluation loop is extracted into abortIfDenied so the second authorization reuses it rather than duplicating it. The class comment named floci.iam.enforcement-enabled; the key that works is floci.services.iam.enforcement-enabled. Closes #209 (cherry picked from commit 402920cf137c98f45283ad093f3df97807bb1dc7) * fix(iam): authorize an object-tag condition against the version the request names Review follow-ups on #3946. s3:ExistingObjectTag was read from the current version whatever the request asked for, so an allow conditioned on a tag decided a versioned read against tags the older version does not carry, letting it through. The lookup now passes the versionId query parameter, via a new S3Service.getObjectTagging overload that takes one. A malformed x-amz-tagging value such as "a=%zz" threw IllegalArgumentException out of URLDecoder inside the filter, answering 500 where S3 returns 400 InvalidTag. An undecodable pair is now dropped, so the policy decides. Documents both condition keys under "Condition keys floci populates" in docs/services/iam.md, including which actions receive them, the If-Match coupling, and that s3:RequestObjectTagKeys is not populated. Replaces the two var declarations in the new test with explicit types, and drops the downstream project's name from the comments and test fixtures. |
||
|
|
eef69445cc |
feat(iam): enforce DeleteUser prerequisites and carry access keys and group membership through a rename (#3918)
DeleteUser now returns DeleteConflict while the user still has inline policies or access keys, matching AWS. UpdateUser rename moves the user's access keys and group membership to the new name, so a renamed user keeps them and a user recreated under the old name does not inherit them. |
||
|
|
5ac07733e9 |
chore(iam): report enforcement state at startup and cover IAM management actions (#3935)
* chore(iam): report enforcement state at startup and cover IAM management actions Issue #3931 reported that an IAM user with an S3-only policy could call CreateUser, CreateGroup, AttachUserPolicy and DeleteUser. The reporter had set FLOCI_IAM_STRICT_VALIDATION, which is not a Floci flag, so enforcement was never on; with FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true those calls already return AccessDenied, including under an explicit Deny on iam:*. Make that state visible: the startup banner now prints whether IAM policy enforcement is enabled and names the correct variable when it is off. The IAM docs state that management actions are enforced too and that any other flag spelling is silently ignored. A regression test pins the issue's scenario (group-attached S3-only policy, plus a direct explicit-deny policy) against the four actions over HTTP with enforcement enabled. * chore(iam): use explicit types and imports in the enforcement regression test * chore(iam): stub the IAM config in EmulatorLifecycleTest and cover the enforcement banner line |
||
|
|
e190f7d340 |
feat(iam): implement CreateLoginProfile, UpdateLoginProfile, DeleteLoginProfile (#3865)
* feat(iam): implement CreateLoginProfile, UpdateLoginProfile, DeleteLoginProfile GetLoginProfile previously existed as a permanent stub always returning NoSuchEntity, and the docs claimed the other three actions were supported even though the query handler had no case for them at all. Adds a LoginProfile model and the full lifecycle on IamService: a user holds at most one login profile, Create/Get/Delete default UserName to the caller's resolved identity (matching AWS), Update requires it explicitly, and Update leaves an omitted field (Password or PasswordResetRequired) unchanged rather than resetting it. The password is validated against AWS's wire character-class/length rule and, when the account has one, against the existing account password policy (PasswordPolicyViolation). Verified against the real AWS IAM API reference for all four actions' request/response shapes and error lists. * fix(iam): block DeleteUser on a login profile and carry it through UpdateUser rename Login profiles now persist, so deleteUser left an orphaned profile that a recreated user of the same name would inherit, and a rename dropped the profile. DeleteUser now returns DeleteConflict while a login profile exists, as AWS does, and UpdateUser moves the profile to the new name. |
||
|
|
3c23784ca7 | feat(s3): evaluate bucket policies for authenticated callers (#3632) | ||
|
|
43a0d737e9 |
perf(iam): cache parsed policy and lowercase patterns once (#3635)
* perf(iam): cache parsed policy documents in IamPolicyEvaluator Every evaluate call parsed each policy document with Jackson again. A caller with a large managed policy such as ReadOnlyAccess (94 KB) paid that parse on every request under IAM enforcement. The evaluator now keeps the parsed statements per document text in a ConcurrentHashMap. Parsing is a pure function of the text, so entries never go stale. The map is bounded at 2048 entries and cleared when the bound is reached, which only matters for many distinct session policies. A document that fails to parse is cached as failed, so the warning is logged once instead of on every request. AWS managed policy catalog has 1566 documents. All 1566 parsed take about 9.5 MB of heap, and AWS caps a customer managed policy at 6144 characters and a session policy at 2048, so 2048 entries stay within tens of MBs in the worst case. * perf(iam): store policy patterns lowercased in the parsed statement cache Action and Resource matching is case-insensitive. globMatches lowercased both the pattern and the request value on every comparison, which for a policy like ReadOnlyAccess meant about 5800 new strings per request. The patterns are now lowercased once when the document is parsed and cached, and the request action and resource are lowercased once per evaluation. The public globMatches helper used by the trust policy and S3 public access evaluators is unchanged. * fix(iam): compare resource ARNs case-sensitively AWS documents the Action element as case-insensitive, but the Resource element is not: the IAM user name in a Resource ARN is case sensitive, and so are S3 object keys. The evaluator lowercased both sides of every Resource and NotResource comparison, so a grant on user/Bob also matched user/bob and a grant on bucket/Private/* also matched bucket/private/*. Resource and NotResource patterns are now kept as written in the parsed statement cache and the request resource is compared as is. Action and NotAction patterns stay lowercased once at parse time. |
||
|
|
abfa8e949e |
fix(iam): report the real default version of AWS-managed policies (#3275)
Signed-off-by: Matheus André <matheusandr2@gmail.com> |