mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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.
This commit is contained in:
1 parent
9a7ec1c9d0
commit
d884d55c26
19 files changed
+2947
-173
No files matched your search
@@ -0,0 +1,68 @@
|
||||
name: IAM Data Drift
|
||||
|
||||
# Checks the two vendored files that come from AWS's live service reference rather than from a
|
||||
# pinned dependency: the IAM service namespace list, and the map of which resource each IAM action
|
||||
# is authorized against. That needs the live service reference index, so unlike every other check here it can
|
||||
# fail without anything in the repository having changed: an AWS outage, or a namespace AWS has
|
||||
# retired. It therefore runs on its own, never as part of a job that ordinary changes trigger.
|
||||
#
|
||||
# Two triggers, for two different failures:
|
||||
#
|
||||
# - On a pull request that touches either vendored file or its generator, which is where a
|
||||
# hand-typed or mistyped entry would enter the repository. A pull request that does not touch
|
||||
# them cannot introduce one, so it does not run and cannot be failed by an outage.
|
||||
# - Weekly, because both files also go stale without anyone touching them: AWS ships services
|
||||
# and actions, and occasionally retires them. Tying the only upstream check to pull request
|
||||
# activity would mean a quiet month is a month with no drift detection at all.
|
||||
#
|
||||
# An entry AWS has *added* since the last sync is reported without failing: a new namespace makes
|
||||
# the service-last-accessed report incomplete rather than wrong, and a new action or resource type
|
||||
# leaves that action evaluated against `*`, which is where it was before any of this existed. The
|
||||
# fix for a real failure is to run the matching sync target and commit the result.
|
||||
#
|
||||
# The offline shape check is hermetic and runs per pull request inside the "Vendored AWS data in
|
||||
# sync" job in partition-literals.yml instead.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'src/main/resources/aws/iam-service-namespaces.json'
|
||||
- 'src/main/resources/aws/iam-action-resources.json'
|
||||
- 'tools/aws/regen_service_namespaces.py'
|
||||
- 'tools/aws/test_regen_service_namespaces.py'
|
||||
- 'tools/aws/regen_iam_action_resources.py'
|
||||
- 'tools/aws/test_regen_iam_action_resources.py'
|
||||
- '.github/workflows/iam-data-drift.yml'
|
||||
schedule:
|
||||
# Mondays at 06:00 UTC, before the working week rather than during it.
|
||||
- cron: '0 6 * * 1'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# One job, and one step that runs both verifies. They are kept in a single Makefile target rather
|
||||
# than two steps because sequential steps stop at the first failure: while the namespace list was
|
||||
# stale, the action resource check never ran at all, so the half that was still fine went
|
||||
# unreported. The target runs both regardless and fails afterwards, naming which file drifted.
|
||||
jobs:
|
||||
iam-data-drift:
|
||||
name: Vendored IAM data still matches upstream
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
# No dependency install: the generators are deliberately stdlib-only, and this job runs no
|
||||
# tests. The pinned botocore the sibling workflow needs is for the partition generator.
|
||||
- name: Check every vendored IAM file still matches upstream
|
||||
run: make iam-data-verify
|
||||
@@ -1,59 +0,0 @@
|
||||
name: IAM Namespace Drift
|
||||
|
||||
# Checks that every namespace in the vendored IAM service namespace list is one AWS actually
|
||||
# publishes. That needs the live service reference index, so unlike every other check here it can
|
||||
# fail without anything in the repository having changed: an AWS outage, or a namespace AWS has
|
||||
# retired. It therefore runs on its own, never as part of a job that ordinary changes trigger.
|
||||
#
|
||||
# Two triggers, for two different failures:
|
||||
#
|
||||
# - On a pull request that touches the vendored file or its generator, which is where a
|
||||
# hand-typed or mistyped namespace would enter the repository. A pull request that does not
|
||||
# touch them cannot introduce one, so it does not run and cannot be failed by an outage.
|
||||
# - Weekly, because the list also goes stale without anyone touching it: AWS ships services and
|
||||
# occasionally retires them. Tying the only upstream check to pull request activity would mean
|
||||
# a quiet month is a month with no drift detection at all.
|
||||
#
|
||||
# A namespace AWS has *added* since the last `make iam-namespaces-sync` is reported without
|
||||
# failing, because being behind makes the service-last-accessed report incomplete rather than
|
||||
# wrong. The fix for a real failure is to run that target and commit the result.
|
||||
#
|
||||
# The offline shape check is hermetic and runs per pull request inside the "Vendored AWS data in
|
||||
# sync" job in partition-literals.yml instead.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'src/main/resources/aws/iam-service-namespaces.json'
|
||||
- 'tools/aws/regen_service_namespaces.py'
|
||||
- 'tools/aws/test_regen_service_namespaces.py'
|
||||
- '.github/workflows/iam-namespace-drift.yml'
|
||||
schedule:
|
||||
# Mondays at 06:00 UTC, before the working week rather than during it.
|
||||
- cron: '0 6 * * 1'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
iam-namespaces-drift:
|
||||
name: Vendored IAM namespaces still exist upstream
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
# No dependency install: the generator is deliberately stdlib-only, and this job runs no
|
||||
# tests. The pinned botocore the sibling workflow needs is for the partition generator.
|
||||
- name: Check every vendored IAM namespace still exists upstream
|
||||
run: make iam-namespaces-verify
|
||||
@@ -97,11 +97,17 @@ jobs:
|
||||
run: make aws-data-check
|
||||
|
||||
# Offline and hermetic, so it is safe on a job this broadly triggered. The online check
|
||||
# that needs AWS lives in iam-namespace-drift.yml, which only runs when the vendored file
|
||||
# that needs AWS lives in iam-data-drift.yml, which only runs when the vendored file
|
||||
# or its generator changes, so an outage cannot fail an unrelated Java pull request.
|
||||
- name: Check the vendored IAM namespace list is well-formed
|
||||
run: make iam-namespaces-check
|
||||
|
||||
# Same split for the IAM action resource map: shape here, the online check against AWS in
|
||||
# iam-data-drift.yml. A malformed or hand-edited map would authorize IAM requests
|
||||
# against the wrong resource, which is why its shape is gated on every pull request.
|
||||
- name: Check the vendored IAM action resource map is well-formed
|
||||
run: make iam-action-resources-check
|
||||
|
||||
# Also offline: the service-linked role table is checked against the vendored managed
|
||||
# policy documents in the repository, never against AWS. The half that comes from a
|
||||
# recorded create cannot be re-derived without the snapshot, which is why every row in
|
||||
|
||||
@@ -46,7 +46,9 @@ PREFIX ?= $(HOME)/.local
|
||||
docs-sync docs-check docs-test partition-check partition-baseline partition-audit partition-test \
|
||||
slr-check slr-table slr-audit slr-test \
|
||||
aws-data-sync aws-data-check aws-data-test \
|
||||
iam-namespaces-sync iam-namespaces-check iam-namespaces-verify iam-namespaces-test
|
||||
iam-namespaces-sync iam-namespaces-check iam-namespaces-verify iam-namespaces-test \
|
||||
iam-action-resources-sync iam-action-resources-check iam-action-resources-verify \
|
||||
iam-action-resources-test iam-data-verify
|
||||
|
||||
help: ## List the targets below
|
||||
@grep -hE '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}'
|
||||
@@ -258,3 +260,50 @@ iam-namespaces-verify: ## CI gate (online): every vendored IAM namespace must st
|
||||
|
||||
iam-namespaces-test: ## Run the IAM namespace generator's unit tests
|
||||
$(PYTHON) -m pytest tools/aws/test_regen_service_namespaces.py -q
|
||||
|
||||
iam-action-resources-sync: ## Regenerate src/main/resources/aws/iam-action-resources.json from AWS (commit the result)
|
||||
$(PYTHON) tools/aws/regen_iam_action_resources.py
|
||||
|
||||
iam-action-resources-check: ## CI gate (offline): the vendored IAM action resource map must be well-formed
|
||||
@$(PYTHON) tools/aws/regen_iam_action_resources.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/iam-action-resources.json is malformed."; \
|
||||
echo " Run 'make iam-action-resources-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
|
||||
iam-action-resources-verify: ## CI gate (online): every vendored IAM action resource must match AWS
|
||||
@$(PYTHON) tools/aws/regen_iam_action_resources.py --verify; status=$$?; \
|
||||
if [ $$status -eq 2 ]; then \
|
||||
echo ""; \
|
||||
echo "error: could not reach AWS's IAM service reference, so nothing was verified."; \
|
||||
exit 1; \
|
||||
elif [ $$status -ne 0 ]; then \
|
||||
echo ""; \
|
||||
echo "error: the vendored IAM action resource map claims a resource AWS does not use,"; \
|
||||
echo " so enforcement would authorize against the wrong thing."; \
|
||||
echo " Run 'make iam-action-resources-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
iam-data-verify: ## CI gate (online): every vendored IAM file must still match AWS
|
||||
@# Both halves run even when the first fails, so one file's drift cannot hide the other's
|
||||
@# state. Sequential steps in CI stop at the first failure, which once left the action
|
||||
@# resource gate unexercised while the namespace list was stale.
|
||||
@namespaces=0; actions=0; \
|
||||
$(MAKE) --no-print-directory iam-namespaces-verify || namespaces=$$?; \
|
||||
$(MAKE) --no-print-directory iam-action-resources-verify || actions=$$?; \
|
||||
if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ]; then \
|
||||
echo ""; \
|
||||
echo "error: vendored IAM data does not match upstream:"; \
|
||||
if [ $$namespaces -ne 0 ]; then \
|
||||
echo " the service namespace list, see its message above"; \
|
||||
fi; \
|
||||
if [ $$actions -ne 0 ]; then \
|
||||
echo " the action resource map, see its message above"; \
|
||||
fi; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
iam-action-resources-test: ## Run the IAM action resource generator's unit tests
|
||||
$(PYTHON) -m pytest tools/aws/test_regen_iam_action_resources.py -q
|
||||
+67
-32
@@ -714,9 +714,12 @@ because listing goes through the user.
|
||||
marks it optional and it resolves from the access key that signed the request. That is the opposite
|
||||
of the signing-certificate operations, where it is optional throughout.
|
||||
|
||||
Under [enforcement](#iam-enforcement-mode) these actions are evaluated against `*` rather than the
|
||||
owning user's ARN, along with every other IAM action except the server-certificate operations, which
|
||||
is the general gap tracked in [#4979](https://github.com/floci-io/floci/issues/4979).
|
||||
Under [enforcement](#iam-enforcement-mode) these actions are evaluated against the owning user's
|
||||
ARN, which is the resource type the Service Authorization Reference gives them, so a statement
|
||||
naming one user binds to that user. `ListSSHPublicKeys` with `UserName` omitted names the user who
|
||||
signed the request, resolved from the access key in the credential, so a statement naming that user
|
||||
binds to it as well. The wildcard stands only when the signer is not an IAM user, an account's root
|
||||
stand-in and a session credential having no user record to name.
|
||||
|
||||
### Signing Certificates
|
||||
|
||||
@@ -759,10 +762,10 @@ date, and `N/A` when the certificate is not `Active`, which is how the User Guid
|
||||
`GetAccountSummary`'s `AccountSigningCertificatesPresent` is unaffected: it reports the account root
|
||||
user's certificates, and Floci does not model root credentials.
|
||||
|
||||
Under [enforcement](#iam-enforcement-mode) these actions are evaluated against `*` rather than the
|
||||
owning user's ARN, along with every other IAM action except the server-certificate operations. That
|
||||
is the general gap tracked in [#4979](https://github.com/floci-io/floci/issues/4979), not something
|
||||
specific to signing certificates.
|
||||
Under [enforcement](#iam-enforcement-mode) these actions are evaluated against the owning user's
|
||||
ARN. `UserName` is optional throughout, and a request that omits it names the user who signed the
|
||||
request, resolved from the access key in the credential, so those bind to that user rather than to
|
||||
`*`.
|
||||
|
||||
### Service-Specific Credentials
|
||||
|
||||
@@ -881,9 +884,9 @@ was minted rather than re-derived from the new name, because it is what the call
|
||||
with and rewriting it would break a working credential; AWS does not document which way it goes, so
|
||||
this is a choice rather than a sourced behaviour.
|
||||
|
||||
Under [enforcement](#iam-enforcement-mode) these actions are evaluated against `*` rather than the
|
||||
owning user's ARN, as the general gap in
|
||||
[#4979](https://github.com/floci-io/floci/issues/4979) describes.
|
||||
Under [enforcement](#iam-enforcement-mode) these actions are evaluated against the owning user's
|
||||
ARN, which when `UserName` is omitted is the ARN of the user who signed the request, resolved from
|
||||
the access key in the credential.
|
||||
|
||||
## AWS Managed Policies
|
||||
|
||||
@@ -1037,30 +1040,62 @@ These identities always bypass enforcement (backward-compatible defaults):
|
||||
| No `Authorization` header | **Rejected** for a JSON, CBOR or Query management call, unless AWS serves the operation without credentials. Allowed for a REST request such as a health check (see [Unsigned requests](#unsigned-requests)) |
|
||||
| Unresolvable IAM action for the request | Allowed — unknown mappings are permissive |
|
||||
|
||||
**IAM's own resources are mostly not named.** When enforcement evaluates a request, the target
|
||||
resource comes from `ResourceArnBuilder`, which builds an ARN for S3, Lambda, SQS, SNS, DynamoDB,
|
||||
Kinesis, Secrets Manager, SSM, KMS, and, within IAM, only the server-certificate operations. Every
|
||||
other IAM action is evaluated against `*`, so a statement naming a specific user, role, policy,
|
||||
instance profile, MFA device or identity provider does not constrain it: a `Deny` on
|
||||
`arn:aws:iam::123456789012:user/bob` does not stop `DeleteUser` from running, and an `Allow`
|
||||
scoped to one role does not limit `DeleteRole` to it. Action-level matching works normally, so
|
||||
denying `iam:DeleteUser` outright does take effect; it is only the resource half that is missing.
|
||||
**IAM's own resources are named.** When enforcement evaluates a request, the target resource comes
|
||||
from `ResourceArnBuilder`, which builds an ARN for S3, Lambda, SQS, SNS, DynamoDB, Kinesis, Secrets
|
||||
Manager, SSM, KMS and IAM. Within IAM the resource type each action is evaluated against is the one
|
||||
the Service Authorization Reference gives it, so a statement naming a specific user, role, group,
|
||||
instance profile, managed policy, MFA device, identity provider or server certificate constrains
|
||||
it: a `Deny` on `arn:aws:iam::123456789012:user/bob` stops `DeleteUser` for Bob and leaves other
|
||||
users alone, and an `Allow` scoped to one role limits `DeleteRole` to it.
|
||||
|
||||
This is the behaviour IAM has always had here rather than a recent change, and it errs toward
|
||||
permissive, which is the direction worth knowing about. Closing it means mapping the resource of
|
||||
every dispatched IAM action, which is tracked in
|
||||
[#4979](https://github.com/floci-io/floci/issues/4979) rather than bundled into the
|
||||
server-certificate work that mapped the first few.
|
||||
The resource type is not the parameter the 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. An action
|
||||
acting on something that already exists is checked against that resource's stored ARN, path and
|
||||
partition included; a create is checked against an ARN minted from the request's own `Path`, since
|
||||
reading a stored path would authorize a create into a path the policy does not name.
|
||||
|
||||
**A certificate rename names two resources.** `UpdateServerCertificate` is evaluated against both
|
||||
the certificate's current ARN and the ARN that `NewServerCertificateName` or `NewPath` would
|
||||
produce, because AWS requires the principal to hold permission on the old name and the new one: a
|
||||
principal allowed to update `ProductionCert` but not `ProdCert` cannot rename the first into the
|
||||
second. A request naming several resources is authorized once per resource, so a `Deny` on either
|
||||
name refuses the rename, and the certificate keeps its original name and path. An update that
|
||||
changes neither the name nor the path names a single resource. The destination ARN is built beside
|
||||
the stored one, keeping the certificate's own partition and account, since a rename moves a
|
||||
certificate within an account rather than between partitions.
|
||||
Which type each action takes is vendored, not written out in Java:
|
||||
`src/main/resources/aws/iam-action-resources.json` is generated by
|
||||
`tools/aws/regen_iam_action_resources.py` from AWS's Service Reference Information for IAM, and
|
||||
carries every published action with the resource types it is authorized against, plus the ARN
|
||||
format of each type. `make iam-action-resources-check` gates its shape offline on every pull
|
||||
request and `make iam-action-resources-verify` checks every claim in it against AWS weekly, so a
|
||||
type that drifts from what AWS publishes fails in CI rather than authorizing against the wrong
|
||||
resource. What stays in Java is the half that is Floci's: the request parameter each type's name
|
||||
arrives in, the creates, the actions whose request carries an ARN, and the resource types that
|
||||
belong only to actions Floci does not dispatch. `IamActionResourcesTest` checks the one against
|
||||
the other, so a regeneration that introduces a resource type nothing resolves fails a test naming
|
||||
it rather than quietly putting that action back on `*`.
|
||||
|
||||
The nineteen user actions whose `UserName` the model marks optional, `GetUser`, `ListAccessKeys` and
|
||||
`CreateAccessKey` among them, resolve to the user who signed the request when it is omitted, which
|
||||
is the user AWS acts on. The access key id in the credential names that identity, the same lookup
|
||||
`GetAccessKeyLastUsed` makes on a key passed as a parameter, and the user's stored ARN is then the
|
||||
resource. The wildcard still stands when the signer is not an IAM user: an account's root stand-in
|
||||
and a session credential have no user record to name.
|
||||
|
||||
What resolves to `*` is what the reference gives no resource type, such as `ListUsers`,
|
||||
`GetAccountSummary` and `SimulateCustomPolicy`. Every other mapped action takes its parameter as a
|
||||
required member, so it always resolves.
|
||||
|
||||
A resource of `*` is matched as that literal string, because the evaluator globs the statement's
|
||||
pattern against the request's resource and not the other way round. So a statement whose `Resource`
|
||||
names an ARN applies to such a request in neither direction: a `Deny` on one of those actions does
|
||||
not refuse it, and an `Allow` does not permit it either.
|
||||
|
||||
**A rename names two resources.** `UpdateUser`, `UpdateGroup` and `UpdateServerCertificate` are
|
||||
evaluated against both the resource's current ARN and the ARN the new name or `NewPath` would
|
||||
produce, because AWS requires the principal to hold permission on the old name and the new one.
|
||||
`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. So a principal allowed to update `ProductionCert` but not
|
||||
`ProdCert` cannot rename the first into the second. A request naming several resources is
|
||||
authorized once per resource, so a `Deny` on either name refuses the rename and the resource keeps
|
||||
its original name and path. An update that changes neither the name nor the path names a single
|
||||
resource. The destination ARN is built beside the stored one, keeping the resource's own partition
|
||||
and account, since a rename moves a resource within an account rather than between partitions.
|
||||
|
||||
**Exception:** a bare 12-digit account-id key that equals its own account and sits under
|
||||
an effective SCP ceiling is **not** treated as an unknown key — it is evaluated against
|
||||
|
||||
@@ -6,12 +6,14 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Extracts the SigV4 signing service name from an Authorization header's
|
||||
* credential scope ({@code Credential=<key>/<date>/<region>/<service>/aws4_request}).
|
||||
* Extracts the parts of an Authorization header's SigV4 credential scope
|
||||
* ({@code Credential=<key>/<date>/<region>/<service>/aws4_request}): the signing service name,
|
||||
* and the access key id the request signed with.
|
||||
*/
|
||||
public final class SigV4CredentialScope {
|
||||
|
||||
private static final Pattern SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
|
||||
private static final Pattern ACCESS_KEY_PATTERN = Pattern.compile("Credential=([^/\\s,]+)/");
|
||||
|
||||
private SigV4CredentialScope() {
|
||||
}
|
||||
@@ -27,6 +29,19 @@ public final class SigV4CredentialScope {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The access key id the request signed with, which is the credential scope's first segment.
|
||||
* Not lower-cased, unlike the service name: an access key id is case sensitive, and in Floci
|
||||
* that segment may also carry an account id used for routing.
|
||||
*/
|
||||
public static Optional<String> accessKeyId(String authorization) {
|
||||
if (authorization == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Matcher matcher = ACCESS_KEY_PATTERN.matcher(authorization);
|
||||
return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty();
|
||||
}
|
||||
|
||||
public static Optional<String> serviceNameFromCredential(String credential) {
|
||||
if (credential == null) {
|
||||
return Optional.empty();
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Which of IAM's own resources each IAM action is authorized against, read once from the vendored
|
||||
* {@code aws/iam-action-resources.json}.
|
||||
*
|
||||
* <p>The file is generated by {@code tools/aws/regen_iam_action_resources.py} from AWS's Service
|
||||
* Reference Information for IAM
|
||||
* (https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json). It is vendored rather than
|
||||
* derived because the resource an IAM action acts on is not in the request:
|
||||
* {@code AddUserToGroup} carries a {@code UserName} and a {@code GroupName} and is authorized
|
||||
* against the group, {@code AddRoleToInstanceProfile} carries a {@code RoleName} and is authorized
|
||||
* against the instance profile, and {@code EnableMFADevice} carries a {@code SerialNumber} and is
|
||||
* authorized against the user rather than the device. Reading the type off the parameters would
|
||||
* scope those to the wrong resource and let a deny on the right one pass.
|
||||
*
|
||||
* <p>{@code make iam-action-resources-check} gates its shape offline and
|
||||
* {@code make iam-action-resources-verify} checks every claim in it against AWS, so a type that
|
||||
* drifts from what AWS publishes fails in CI rather than quietly authorizing against the wrong
|
||||
* resource. {@link ResourceArnBuilder} is the only consumer.
|
||||
*
|
||||
* <p>An action absent from the file is one AWS does not publish, which is different from an action
|
||||
* published with no resource type: the first is a gap, the second is a wildcard on purpose. Both
|
||||
* read as {@link #typesOf} returning an empty list, and the caller treats both as {@code *}, but
|
||||
* the distinction is why resource-less actions are still listed with an empty list rather than
|
||||
* left out.
|
||||
*
|
||||
* <p>A missing or malformed resource is a build defect, not a runtime condition, so loading fails
|
||||
* with {@link IllegalStateException} rather than degrading to an empty map, which would silently
|
||||
* put every IAM action back on the wildcard.
|
||||
*/
|
||||
public final class IamActionResources {
|
||||
|
||||
static final String RESOURCE_NAME = "aws/iam-action-resources.json";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private static final class Holder {
|
||||
static final Catalog CATALOG = load();
|
||||
}
|
||||
|
||||
/** The two halves of the vendored file: what each action names, and how each type is spelled. */
|
||||
record Catalog(Map<String, List<String>> actionResources,
|
||||
Map<String, List<String>> resourceArnFormats) {
|
||||
}
|
||||
|
||||
private IamActionResources() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource types AWS authorizes {@code action} against, or an empty list when it
|
||||
* authorizes against none and when the action is one AWS does not publish.
|
||||
*/
|
||||
public static List<String> typesOf(String action) {
|
||||
if (action == null) {
|
||||
return List.of();
|
||||
}
|
||||
return Holder.CATALOG.actionResources().getOrDefault(action, List.of());
|
||||
}
|
||||
|
||||
/** Every resource type AWS publishes an ARN format for, with those formats. */
|
||||
public static Map<String, List<String>> arnFormats() {
|
||||
return Holder.CATALOG.resourceArnFormats();
|
||||
}
|
||||
|
||||
/** Every action the file carries, which is every action AWS publishes for IAM. */
|
||||
public static Map<String, List<String>> all() {
|
||||
return Holder.CATALOG.actionResources();
|
||||
}
|
||||
|
||||
private static Catalog load() {
|
||||
try (InputStream in = Thread.currentThread().getContextClassLoader()
|
||||
.getResourceAsStream(RESOURCE_NAME)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("IAM action resource catalog resource not found: "
|
||||
+ RESOURCE_NAME);
|
||||
}
|
||||
return parse(in);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Failed to read the IAM action resource catalog "
|
||||
+ RESOURCE_NAME, e);
|
||||
}
|
||||
}
|
||||
|
||||
static Catalog parse(InputStream in) throws IOException {
|
||||
JsonNode root = MAPPER.readTree(in);
|
||||
Map<String, List<String>> actions = readLists(root.path("actionResources"),
|
||||
"actionResources");
|
||||
Map<String, List<String>> formats = readLists(root.path("resourceArnFormats"),
|
||||
"resourceArnFormats");
|
||||
for (Map.Entry<String, List<String>> entry : actions.entrySet()) {
|
||||
for (String type : entry.getValue()) {
|
||||
if (!formats.containsKey(type)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has " + entry.getKey()
|
||||
+ " naming the resource type " + type + ", which has no ARN format");
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Catalog(actions, formats);
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> readLists(JsonNode node, String field) {
|
||||
if (!node.isObject() || node.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no " + field);
|
||||
}
|
||||
Map<String, List<String>> parsed = new LinkedHashMap<>();
|
||||
node.properties().forEach(entry -> {
|
||||
JsonNode values = entry.getValue();
|
||||
if (!values.isArray()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has " + field + "."
|
||||
+ entry.getKey() + " as something other than a list");
|
||||
}
|
||||
List<String> read = new ArrayList<>(values.size());
|
||||
for (JsonNode value : values) {
|
||||
String text = value.asText("");
|
||||
if (text.isBlank()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has a blank entry under "
|
||||
+ field + "." + entry.getKey());
|
||||
}
|
||||
read.add(text);
|
||||
}
|
||||
parsed.put(entry.getKey(), List.copyOf(read));
|
||||
});
|
||||
return Map.copyOf(parsed);
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
/** CSPRNG for long-term secret access keys; ordinary resource IDs keep using {@link ThreadLocalRandom}. */
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
private static final String SERVICE_LINKED_ROLE_PATH = "/aws-service-role/";
|
||||
/** AWSServiceName as AWS constrains it: 1-128 characters of {@code [\w+=,.@-]}. */
|
||||
private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}");
|
||||
/** CustomSuffix as AWS constrains it: 1-64 characters of {@code [\w+=,.@-]}. */
|
||||
@@ -961,6 +960,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
"The group with name " + groupName + " cannot be found.", 404));
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up a group by name in a specific account's namespace, without throwing when absent.
|
||||
* Mirrors {@link #findUser(String, String)}, and exists for the same reason: a caller
|
||||
* resolving a group's ARN has only the name, and the path that completes that ARN is held by
|
||||
* the stored group.
|
||||
*/
|
||||
public Optional<IamGroup> findGroup(String accountId, String groupName) {
|
||||
if (groups instanceof AccountAwareStorageBackend<IamGroup> aware) {
|
||||
return aware.getForAccount(accountId, groupName);
|
||||
}
|
||||
return groups.get(groupName);
|
||||
}
|
||||
|
||||
public void updateGroup(String groupName, String newGroupName, String newPath) {
|
||||
validateIamResourceName(groupName, "GroupName");
|
||||
if (newGroupName != null) {
|
||||
@@ -1181,7 +1193,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
/** The linked service, recovered from the {@code /aws-service-role/<principal>/} path. */
|
||||
private static String linkedServicePrincipal(IamRole role) {
|
||||
String path = role.getPath();
|
||||
return path.substring(SERVICE_LINKED_ROLE_PATH.length(), path.length() - 1);
|
||||
return path.substring(ServiceLinkedRoles.PATH.length(), path.length() - 1);
|
||||
}
|
||||
|
||||
public void deleteRole(String roleName) {
|
||||
@@ -1258,7 +1270,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
String principal = ServicePrincipals.canonical(awsServiceName);
|
||||
String trustPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"Service\":\"" + principal + "\"},\"Action\":\"sts:AssumeRole\"}]}";
|
||||
IamRole role = createRole(roleName, SERVICE_LINKED_ROLE_PATH + principal + "/",
|
||||
IamRole role = createRole(roleName, ServiceLinkedRoles.PATH + principal + "/",
|
||||
trustPolicy, description, 0, Map.of());
|
||||
role.setServiceLinkedRole(true);
|
||||
roles.put(roleName, role);
|
||||
@@ -1289,7 +1301,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
roles.delete(roleName);
|
||||
LOG.infov("Deleted service-linked IAM role: {0}", roleName);
|
||||
|
||||
String deletionTaskId = "task" + SERVICE_LINKED_ROLE_PATH + servicePrincipal + "/"
|
||||
String deletionTaskId = "task" + ServiceLinkedRoles.PATH + servicePrincipal + "/"
|
||||
+ roleName + "/" + UUID.randomUUID();
|
||||
serviceLinkedRoleDeletions.put(deletionTaskId, roleName);
|
||||
return deletionTaskId;
|
||||
|
||||
@@ -5,7 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableTokens;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -18,8 +19,10 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -34,14 +37,11 @@ import java.util.regex.Matcher;
|
||||
@ApplicationScoped
|
||||
public class ResourceArnBuilder {
|
||||
|
||||
/**
|
||||
* The IAM actions whose resource this builder can name. Deliberately only the
|
||||
* server-certificate operations; see {@link #buildIamArn}.
|
||||
*/
|
||||
private static final Set<String> SERVER_CERTIFICATE_ACTIONS = Set.of(
|
||||
"UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",
|
||||
"DeleteServerCertificate", "TagServerCertificate", "UntagServerCertificate",
|
||||
"ListServerCertificateTags");
|
||||
/** The only scheme IAM accepts on an OIDC provider URL, and the part its ARN drops. */
|
||||
private static final String OIDC_URL_SCHEME = "https://";
|
||||
|
||||
/** What a service-linked role deletion task identifier starts with; see its resolver. */
|
||||
private static final String DELETION_TASK_PREFIX = "task" + ServiceLinkedRoles.PATH;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
/**
|
||||
@@ -93,87 +93,376 @@ public class ResourceArnBuilder {
|
||||
|
||||
// ── IAM ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** A stored entity's ARN and path, the two things a target ARN is built from. */
|
||||
private record StoredEntity(String arn, String path) {}
|
||||
|
||||
/**
|
||||
* IAM resource ARNs are only built for the server-certificate operations. Every other IAM
|
||||
* action still resolves to {@code *}, so a policy naming a specific user, role, policy or MFA
|
||||
* device does not constrain it. That is how IAM behaved before server certificates existed,
|
||||
* and closing it for the rest means mapping the resource of every dispatched IAM action, which
|
||||
* is its own change rather than a side effect of this one: tracked in issue 4979, and
|
||||
* described in docs/services/iam.md.
|
||||
* The request parameter carrying the name of the target, per resource type, for an action on a
|
||||
* resource that already exists.
|
||||
*
|
||||
* <p>Which type an action is authorized against is not decided here: it comes per action from
|
||||
* {@link IamActionResources}, which vendors AWS's own authorization metadata, because the
|
||||
* resource an IAM action acts on is not in the request. {@code AddUserToGroup} carries a
|
||||
* {@code UserName} and a {@code GroupName} and is authorized against the group,
|
||||
* {@code AddRoleToInstanceProfile} carries a {@code RoleName} and is authorized against the
|
||||
* instance profile, and the MFA actions that take a {@code SerialNumber} are authorized
|
||||
* against the user that device belongs to. Keeping the type in vendored data and only the
|
||||
* parameter here is what lets {@code make iam-action-resources-verify} check the half that is
|
||||
* AWS's against AWS.
|
||||
*
|
||||
* <p>An action whose type is not in here, and which is not a create or one of the ARN-carrying
|
||||
* actions, is evaluated against {@code *}. That is right for the types the reference gives
|
||||
* actions Floci does not dispatch, which {@link #UNRESOLVED_TYPES} names.
|
||||
*/
|
||||
static final Map<String, String> NAME_PARAMETERS = Map.of(
|
||||
"user", "UserName",
|
||||
"role", "RoleName",
|
||||
"group", "GroupName",
|
||||
"instance-profile", "InstanceProfileName",
|
||||
"server-certificate", "ServerCertificateName");
|
||||
|
||||
/**
|
||||
* The actions that create their target, with the parameter naming it. Their ARN is minted from
|
||||
* the request rather than read back, since there is no stored record yet, and a create is
|
||||
* checked against the {@code Path} it asks for, because reading a stored path would authorize
|
||||
* a create into a path the policy does not name.
|
||||
*
|
||||
* <p>Keyed by action rather than by type because a create spells the name its own way:
|
||||
* {@code CreateSAMLProvider} takes {@code Name} and {@code CreateOpenIDConnectProvider} takes
|
||||
* {@code Url}, where the others take the type's usual parameter. The type itself still comes
|
||||
* from the vendored metadata.
|
||||
*
|
||||
* <p>Package-private, as the other tables here are, so {@code IamActionResourcesTest} can
|
||||
* work out which resource types this class covers instead of restating them, which is what
|
||||
* catches both a create AWS gives no single type to mint and a type nothing resolves.
|
||||
*/
|
||||
static final Map<String, String> CREATE_PARAMETERS = Map.of(
|
||||
"CreateUser", "UserName",
|
||||
"CreateRole", "RoleName",
|
||||
"CreateGroup", "GroupName",
|
||||
"CreateInstanceProfile", "InstanceProfileName",
|
||||
"UploadServerCertificate", "ServerCertificateName",
|
||||
"CreatePolicy", "PolicyName",
|
||||
"CreateVirtualMFADevice", "VirtualMFADeviceName",
|
||||
"CreateSAMLProvider", "Name",
|
||||
"CreateOpenIDConnectProvider", "Url");
|
||||
|
||||
/**
|
||||
* The resource types AWS gives IAM actions that Floci does not resolve, with why. Every one
|
||||
* belongs to an action the handler does not dispatch, so there is no request to name a
|
||||
* resource for.
|
||||
*
|
||||
* <p>Declared rather than implied so that a type which is neither resolved nor listed here
|
||||
* fails a test naming it, instead of quietly putting that action back on {@code *}. The
|
||||
* resolver's fallback for a type it does not know is the permissive answer, so a regeneration
|
||||
* that introduces one is only visible if something asserts the set.
|
||||
*
|
||||
* <p>Package-private because the reason each entry gives is a claim about the handler, not
|
||||
* about this class: {@code UnresolvedResourceTypesIntegrationTest} sends each of these actions
|
||||
* and holds it to answering {@code UnsupportedOperation}. Dispatching one without resolving
|
||||
* its type would leave it evaluated against {@code *}, which is the fail-open this class
|
||||
* exists to close.
|
||||
*/
|
||||
static final Map<String, String> UNRESOLVED_TYPES = Map.of(
|
||||
"access-report", "GenerateOrganizationsAccessReport is not dispatched",
|
||||
"delegation-request", "the delegation request family is not dispatched",
|
||||
"role-template", "GetRoleTemplateVersion is not dispatched");
|
||||
|
||||
/**
|
||||
* The IAM actions whose target the request carries as an ARN, and the parameter holding it.
|
||||
* Passed through rather than rebuilt: the ARN is the caller's own naming of the resource, and
|
||||
* an action naming one that does not exist fails as {@code NoSuchEntity} regardless of what a
|
||||
* policy says.
|
||||
*
|
||||
* <p>This is also the answer for every action AWS gives more than one resource type. The four
|
||||
* that take a principal ARN are authorized against whichever of user, role or group that ARN
|
||||
* names, and {@code DeleteVirtualMFADevice} against either {@code mfa} or {@code sms-mfa}, so
|
||||
* the parameter is the resource and there is nothing to choose.
|
||||
*/
|
||||
static final Map<String, String> IAM_ARN_PARAMETERS = iamArnParameters();
|
||||
|
||||
/**
|
||||
* The actions resolved by a branch of their own in {@link #buildIamArns}, because the request
|
||||
* identifies the resource without naming it: a service principal for
|
||||
* {@code CreateServiceLinkedRole}, an access key id for {@code GetAccessKeyLastUsed}, and a
|
||||
* deletion task id for {@code GetServiceLinkedRoleDeletionStatus}.
|
||||
*
|
||||
* <p>The resolver is the value rather than a branch elsewhere, so this cannot become a list
|
||||
* that says an action is handled while the dispatch has nothing for it. The keys are also what
|
||||
* {@code IamActionResourcesTest} reads to tell a type one of these covers from a type nothing
|
||||
* resolves.
|
||||
*/
|
||||
static final Map<String, DerivedResolver> DERIVED_RESOLVERS = Map.of(
|
||||
"CreateServiceLinkedRole", ResourceArnBuilder::serviceLinkedRoleArn,
|
||||
"GetAccessKeyLastUsed",
|
||||
(self, ctx, region, accountId) -> self.accessKeyOwnerArn(ctx, accountId),
|
||||
"GetServiceLinkedRoleDeletionStatus", ResourceArnBuilder::deletionTaskRoleArn);
|
||||
|
||||
/** How one of {@link #DERIVED_RESOLVERS} reads its resource out of the request. */
|
||||
interface DerivedResolver {
|
||||
List<String> resolve(ResourceArnBuilder self, ContainerRequestContext ctx, String region,
|
||||
String accountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The actions that rename or move their target, and the parameter carrying the new name. These
|
||||
* name two resources, because AWS requires the principal to be allowed on both: 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. The filter authorizes a request once per resource,
|
||||
* so naming both is what enforces it.
|
||||
*/
|
||||
private static final Map<String, String> IAM_RENAME_PARAMETERS = Map.of(
|
||||
"UpdateUser", "NewUserName",
|
||||
"UpdateGroup", "NewGroupName",
|
||||
"UpdateServerCertificate", "NewServerCertificateName");
|
||||
|
||||
private static Map<String, String> iamArnParameters() {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
arnParameter(parameters, "PolicyArn",
|
||||
"CreatePolicyVersion", "DeletePolicy", "DeletePolicyVersion", "GetPolicy",
|
||||
"GetPolicyVersion", "ListEntitiesForPolicy", "ListPolicyTags", "ListPolicyVersions",
|
||||
"SetDefaultPolicyVersion", "TagPolicy", "UntagPolicy");
|
||||
arnParameter(parameters, "SerialNumber",
|
||||
"DeleteVirtualMFADevice", "ListMFADeviceTags", "TagMFADevice", "UntagMFADevice");
|
||||
arnParameter(parameters, "SAMLProviderArn",
|
||||
"DeleteSAMLProvider", "GetSAMLProvider", "ListSAMLProviderTags", "TagSAMLProvider",
|
||||
"UntagSAMLProvider", "UpdateSAMLProvider");
|
||||
arnParameter(parameters, "OpenIDConnectProviderArn",
|
||||
"AddClientIDToOpenIDConnectProvider", "DeleteOpenIDConnectProvider",
|
||||
"GetOpenIDConnectProvider", "ListOpenIDConnectProviderTags",
|
||||
"RemoveClientIDFromOpenIDConnectProvider", "TagOpenIDConnectProvider",
|
||||
"UntagOpenIDConnectProvider", "UpdateOpenIDConnectProviderThumbprint");
|
||||
arnParameter(parameters, "Arn",
|
||||
"GenerateServiceLastAccessedDetails", "ListPoliciesGrantingServiceAccess");
|
||||
arnParameter(parameters, "PolicySourceArn",
|
||||
"GetContextKeysForPrincipalPolicy", "SimulatePrincipalPolicy");
|
||||
return Map.copyOf(parameters);
|
||||
}
|
||||
|
||||
private static void arnParameter(Map<String, String> parameters, String parameter,
|
||||
String... actions) {
|
||||
for (String action : actions) {
|
||||
parameters.put(action, parameter);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource ARN an IAM action is evaluated against, so a policy statement naming one user,
|
||||
* role, group, profile, policy, provider, MFA device or certificate binds to it and to nothing
|
||||
* else. Everything this cannot name resolves to {@code *}, which is the permissive answer and
|
||||
* the one AWS gives for the actions that take no resource.
|
||||
*
|
||||
* <p>The operation is resolved through {@link AwsQueryServiceResolver#action(String, String)},
|
||||
* so the legacy {@code Operation} parameter names the resource exactly as {@code Action} does.
|
||||
* Reading {@code Action} alone would let a caller spell the operation the other way and have
|
||||
* the request evaluated against {@code *}, skipping a deny that names the certificate.
|
||||
* the request evaluated against {@code *}, skipping a deny that names the resource.
|
||||
*
|
||||
* <p>The path is taken from the stored certificate when one exists: a policy names the full
|
||||
* ARN, path included, and only the store knows the path.
|
||||
*
|
||||
* <p>A rename names two resources rather than one; see {@link #renameTargetArn}.
|
||||
* <p>An action that defaults to the calling user when its {@code UserName} is omitted, as
|
||||
* {@code GetUser} and {@code ChangePassword} do, resolves to that user: the access key id in
|
||||
* the credential names the identity, and the stored ARN carries its path and partition. The
|
||||
* wildcard stands only when the signer is not an IAM user, an account's root stand-in and a
|
||||
* session credential having no user record to name.
|
||||
*/
|
||||
private List<String> buildIamArns(ContainerRequestContext ctx, String region,
|
||||
String accountId) {
|
||||
String action = AwsQueryServiceResolver.action(
|
||||
RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
if (action == null || !SERVER_CERTIFICATE_ACTIONS.contains(action)) {
|
||||
if (action == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
String name = RequestBodyReader.formField(ctx, "ServerCertificateName");
|
||||
String arnParameter = IAM_ARN_PARAMETERS.get(action);
|
||||
if (arnParameter != null) {
|
||||
// Only an ARN is passed through. A hardware MFA device's SerialNumber is a bare serial
|
||||
// rather than an ARN, and naming the request after it would produce a resource no
|
||||
// policy can be written against.
|
||||
String arn = RequestBodyReader.formField(ctx, arnParameter);
|
||||
return arn == null || !AwsArnUtils.isArn(arn) ? List.of("*") : List.of(arn);
|
||||
}
|
||||
DerivedResolver derived = DERIVED_RESOLVERS.get(action);
|
||||
if (derived != null) {
|
||||
return derived.resolve(this, ctx, region, accountId);
|
||||
}
|
||||
String createParameter = CREATE_PARAMETERS.get(action);
|
||||
if (createParameter != null) {
|
||||
// A create names a resource that does not exist yet, so its ARN is minted from the
|
||||
// request: the path it asks for, in the partition it is being created in. Reading a
|
||||
// stored path here would authorize a create under /team/ against the root path.
|
||||
String created = RequestBodyReader.formField(ctx, createParameter);
|
||||
List<String> createdTypes = IamActionResources.typesOf(action);
|
||||
// One type is what there is to mint. A create AWS authorizes against none, or against
|
||||
// several, has no single ARN to build, so the wildcard stands rather than the request
|
||||
// failing on it; IamActionResourcesTest is what says so out loud.
|
||||
if (created == null || created.isBlank() || createdTypes.size() != 1) {
|
||||
return List.of("*");
|
||||
}
|
||||
return List.of(mintedIamArn(createdTypes.get(0), created, ctx, region, accountId));
|
||||
}
|
||||
// Everything else is an action on a resource that exists, named by name. Which type that
|
||||
// is comes from AWS's own metadata, and the parameter the name arrives in comes from the
|
||||
// type: an action AWS gives a type this resolver has no parameter for, or more than one
|
||||
// type, is left at the wildcard rather than guessed at.
|
||||
String resourceType = nameableType(action);
|
||||
if (resourceType == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
String name = RequestBodyReader.formField(ctx, NAME_PARAMETERS.get(resourceType));
|
||||
if (name == null || name.isBlank()) {
|
||||
return List.of("*");
|
||||
// Nineteen user actions make UserName optional, and AWS then acts on the user who
|
||||
// signed the request, so that user is the resource the request names. Resolving it
|
||||
// here is what lets a statement scoped to one user reach GetUser, ListAccessKeys and
|
||||
// the rest when they are called the way the console calls them, with no UserName.
|
||||
return "user".equals(resourceType) ? signingUserArn(ctx, accountId) : List.of("*");
|
||||
}
|
||||
if ("UploadServerCertificate".equals(action)) {
|
||||
// An upload names a certificate that does not exist yet, so its ARN is minted from
|
||||
// the request: the path it asks for, in the partition it is being created in. Reading
|
||||
// a stored path here would authorize an upload to /team/ against the root path.
|
||||
// IAM is global, so the ARN carries no region. Minted in the request's partition
|
||||
// rather than through a blank-region Arn.of, which would silently mean the
|
||||
// commercial one.
|
||||
String path = normalizeArnPath(RequestBodyReader.formField(ctx, "Path"));
|
||||
return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam",
|
||||
accountId, "server-certificate" + path + name).toString());
|
||||
}
|
||||
// Every other operation acts on a certificate that already exists, so the check uses that
|
||||
// certificate's own stored ARN instead of deriving one again. The stored ARN carries the
|
||||
// path and, more to the point, the partition the certificate was created in: a resource
|
||||
// stays in its partition, so re-minting from the caller's signing region would name an
|
||||
// ARN that no resource has and leave a deny on the real one unmatched.
|
||||
Optional<ServerCertificate> stored = storedServerCertificate(name);
|
||||
// Every other action acts on a resource that already exists, so the check uses that
|
||||
// resource's own stored ARN instead of deriving one again. The stored ARN carries the path
|
||||
// and, more to the point, the partition the resource was created in: a resource stays in
|
||||
// its partition, so re-minting from the caller's signing region would name an ARN that no
|
||||
// resource has and leave a deny on the real one unmatched.
|
||||
Optional<StoredEntity> stored = storedIamEntity(resourceType, name, accountId);
|
||||
if (stored.isEmpty()) {
|
||||
return List.of("*");
|
||||
}
|
||||
String storedArn = stored.get().getArn();
|
||||
if (!"UpdateServerCertificate".equals(action)) {
|
||||
String storedArn = stored.get().arn();
|
||||
String renameParameter = IAM_RENAME_PARAMETERS.get(action);
|
||||
if (renameParameter == null) {
|
||||
return List.of(storedArn);
|
||||
}
|
||||
String target = renameTargetArn(ctx, stored.get(), name, region, accountId);
|
||||
return storedArn.equals(target) ? List.of(storedArn) : List.of(storedArn, target);
|
||||
String renamed = renameTargetArn(ctx, stored.get(), resourceType, name,
|
||||
renameParameter, region, accountId);
|
||||
return storedArn.equals(renamed) ? List.of(storedArn) : List.of(storedArn, renamed);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN a rename or a move would produce. AWS requires the principal to be allowed on both
|
||||
* the old and the new name, so that a rename into a name they cannot write fails: naming both
|
||||
* resources is what enforces it, because the filter authorizes a request once per resource.
|
||||
*
|
||||
* <p>Built beside the stored ARN so it keeps the certificate's partition and account. Only
|
||||
* the path and the name change, and taking the partition from the caller's signing region
|
||||
* instead would name a resource in a partition the certificate does not live in. Returns the
|
||||
* stored ARN unchanged when the request renames and moves nothing.
|
||||
* The ARN a rename or a move would produce, built beside the stored ARN so it keeps the
|
||||
* resource's partition and account. Only the path and the name change, and taking the
|
||||
* partition from the caller's signing region instead would name a resource in a partition the
|
||||
* original does not live in. Returns the stored ARN unchanged when the request renames and
|
||||
* moves nothing.
|
||||
*/
|
||||
private String renameTargetArn(ContainerRequestContext ctx, ServerCertificate stored,
|
||||
String name, String region, String accountId) {
|
||||
String newName = RequestBodyReader.formField(ctx, "NewServerCertificateName");
|
||||
private String renameTargetArn(ContainerRequestContext ctx, StoredEntity stored,
|
||||
String resourceType, String name, String renameParameter,
|
||||
String region, String accountId) {
|
||||
String newName = RequestBodyReader.formField(ctx, renameParameter);
|
||||
String newPath = RequestBodyReader.formField(ctx, "NewPath");
|
||||
String targetName = newName == null || newName.isBlank() ? name : newName;
|
||||
String targetPath = newPath == null || newPath.isBlank()
|
||||
? normalizeArnPath(stored.getPath())
|
||||
? normalizeArnPath(stored.path())
|
||||
: normalizeArnPath(newPath);
|
||||
String partition = AwsArnUtils.partitionOrDefault(stored.getArn(),
|
||||
String partition = AwsArnUtils.partitionOrDefault(stored.arn(),
|
||||
AwsRegions.partitionFor(region));
|
||||
String account = AwsArnUtils.accountOrDefault(stored.getArn(), accountId);
|
||||
String account = AwsArnUtils.accountOrDefault(stored.arn(), accountId);
|
||||
return AwsArnUtils.Arn.global(partition, "iam", account,
|
||||
"server-certificate" + targetPath + targetName).toString();
|
||||
resourceType + targetPath + targetName).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of a resource the request is creating. IAM is global, so it carries no region, and
|
||||
* it is minted in the request's partition rather than through a blank-region {@code Arn.of},
|
||||
* which would silently mean the commercial one.
|
||||
*/
|
||||
private String mintedIamArn(String resourceType, String name, ContainerRequestContext ctx,
|
||||
String region, String accountId) {
|
||||
String resource = switch (resourceType) {
|
||||
// A SAML provider's ARN is its bare name and an OIDC provider's is its URL without
|
||||
// the scheme, as IAM stores it. Neither format has a path, so Path is not read here.
|
||||
case "saml-provider" -> "saml-provider/" + name;
|
||||
case "oidc-provider" -> "oidc-provider/" + oidcProviderName(name);
|
||||
default -> resourceType
|
||||
+ normalizeArnPath(RequestBodyReader.formField(ctx, "Path")) + name;
|
||||
};
|
||||
return AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId, resource)
|
||||
.toString();
|
||||
}
|
||||
|
||||
/** An OIDC provider URL as its ARN carries it, which is the URL without its scheme. */
|
||||
private static String oidcProviderName(String url) {
|
||||
return url.startsWith(OIDC_URL_SCHEME) ? url.substring(OIDC_URL_SCHEME.length()) : url;
|
||||
}
|
||||
|
||||
/**
|
||||
* The role {@code CreateServiceLinkedRole} would create. Its name is not in the request: AWS
|
||||
* derives it from {@code AWSServiceName}, so the table the create itself reads is read here
|
||||
* too, and the path is the service-role path carrying the canonical principal. A service with
|
||||
* no entry names no role, leaving nothing to authorize against but {@code *}.
|
||||
*/
|
||||
private List<String> serviceLinkedRoleArn(ContainerRequestContext ctx, String region,
|
||||
String accountId) {
|
||||
String serviceName = RequestBodyReader.formField(ctx, "AWSServiceName");
|
||||
if (serviceName == null || serviceName.isBlank()) {
|
||||
return List.of("*");
|
||||
}
|
||||
Optional<String> baseName = ServiceLinkedRoles.roleName(serviceName);
|
||||
if (baseName.isEmpty()) {
|
||||
return List.of("*");
|
||||
}
|
||||
String suffix = RequestBodyReader.formField(ctx, "CustomSuffix");
|
||||
String roleName = baseName.get()
|
||||
+ (suffix == null || suffix.isBlank() ? "" : "_" + suffix);
|
||||
String path = ServiceLinkedRoles.PATH + ServicePrincipals.canonical(serviceName) + "/";
|
||||
return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
|
||||
"role" + path + roleName).toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The role {@code GetServiceLinkedRoleDeletionStatus} asks about. The request names no role,
|
||||
* but the deletion task does: the action's own reference gives the identifier's format as
|
||||
* {@code task/aws-service-role/<service-principal-name>/<role-name>/<task-uuid>}, which is the
|
||||
* role's path and name with a prefix in front and a uuid behind, and that is the shape
|
||||
* {@code DeleteServiceLinkedRole} mints. Derived rather than looked up because by the time
|
||||
* this action is called the role is gone, so there is no stored ARN left to read.
|
||||
*/
|
||||
private List<String> deletionTaskRoleArn(ContainerRequestContext ctx, String region,
|
||||
String accountId) {
|
||||
String taskId = RequestBodyReader.formField(ctx, "DeletionTaskId");
|
||||
if (taskId == null || !taskId.startsWith(DELETION_TASK_PREFIX)) {
|
||||
return List.of("*");
|
||||
}
|
||||
int uuidSeparator = taskId.lastIndexOf('/');
|
||||
if (uuidSeparator <= DELETION_TASK_PREFIX.length()) {
|
||||
return List.of("*");
|
||||
}
|
||||
String pathAndName = taskId.substring("task".length(), uuidSeparator);
|
||||
return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
|
||||
"role" + pathAndName).toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The user who owns the access key {@code GetAccessKeyLastUsed} asks about. The action is
|
||||
* evaluated against a user, which is what the IAM User Guide's own {@code iam:*AccessKey*}
|
||||
* example scopes to {@code user/${aws:username}}, but the request names only the key, so the
|
||||
* owner is resolved from it.
|
||||
*/
|
||||
private List<String> accessKeyOwnerArn(ContainerRequestContext ctx, String accountId) {
|
||||
String accessKeyId = RequestBodyReader.formField(ctx, "AccessKeyId");
|
||||
if (accessKeyId == null || accessKeyId.isBlank() || iamService == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
return iamService.get().findUserNameByAccessKeyId(accessKeyId)
|
||||
.flatMap(userName -> storedIamEntity("user", userName, accountId))
|
||||
.map(stored -> List.of(stored.arn()))
|
||||
.orElse(List.of("*"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The user who signed the request, for the actions whose {@code UserName} is optional. The
|
||||
* credential's own key names the identity, which is the same lookup
|
||||
* {@code GetAccessKeyLastUsed} makes on a key the request carries as a parameter.
|
||||
*
|
||||
* <p>The wildcard stands when the signer is not an IAM user: an account's root stand-in and a
|
||||
* session credential have no user record, and AWS evaluates those against the identity they
|
||||
* belong to rather than against a user ARN this resolver could mint.
|
||||
*/
|
||||
private List<String> signingUserArn(ContainerRequestContext ctx, String accountId) {
|
||||
if (iamService == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
return SigV4CredentialScope.accessKeyId(ctx.getHeaderString("Authorization"))
|
||||
.flatMap(accessKeyId -> iamService.get().findUserNameByAccessKeyId(accessKeyId))
|
||||
.flatMap(userName -> storedIamEntity("user", userName, accountId))
|
||||
.map(stored -> List.of(stored.arn()))
|
||||
.orElse(List.of("*"));
|
||||
}
|
||||
|
||||
/** A request's Path as it appears in an ARN: slash-delimited, defaulting to a bare slash. */
|
||||
@@ -186,18 +475,47 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored certificate of that name in this account, carrying its own ARN. Empty when the
|
||||
* account has none, or when the stored record has no ARN to read: the operation fails as
|
||||
* NoSuchEntity either way, and minting an ARN for a resource that is not there would only
|
||||
* offer a policy something to match.
|
||||
* The resource type an action names by name, or null when there is none to use: AWS gives the
|
||||
* action no type, gives it more than one, or gives it a type this resolver has no name
|
||||
* parameter for. More than one type always means the request carries an ARN, which the caller
|
||||
* handles before reaching here.
|
||||
*/
|
||||
private Optional<ServerCertificate> storedServerCertificate(String name) {
|
||||
private static String nameableType(String action) {
|
||||
List<String> types = IamActionResources.typesOf(action);
|
||||
if (types.size() != 1) {
|
||||
return null;
|
||||
}
|
||||
String resourceType = types.get(0);
|
||||
return NAME_PARAMETERS.containsKey(resourceType) ? resourceType : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored resource of that name in this account, carrying its own ARN and path. Empty when
|
||||
* the account holds none, or when the stored record has no ARN to read: the operation fails as
|
||||
* {@code NoSuchEntity} either way, and minting an ARN for a resource that is not there would
|
||||
* only offer a policy something to match.
|
||||
*/
|
||||
private Optional<StoredEntity> storedIamEntity(String resourceType, String name,
|
||||
String accountId) {
|
||||
if (iamService == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return iamService.get().findServerCertificate(name)
|
||||
.filter(certificate -> certificate.getArn() != null
|
||||
&& !certificate.getArn().isBlank());
|
||||
IamService iam = iamService.get();
|
||||
Optional<StoredEntity> stored = switch (resourceType) {
|
||||
case "user" -> iam.findUser(accountId, name)
|
||||
.map(user -> new StoredEntity(user.getArn(), user.getPath()));
|
||||
case "role" -> iam.findRole(accountId, name)
|
||||
.map(role -> new StoredEntity(role.getArn(), role.getPath()));
|
||||
case "group" -> iam.findGroup(accountId, name)
|
||||
.map(group -> new StoredEntity(group.getArn(), group.getPath()));
|
||||
case "instance-profile" -> iam.findInstanceProfile(accountId, name)
|
||||
.map(profile -> new StoredEntity(profile.getArn(), profile.getPath()));
|
||||
case "server-certificate" -> iam.findServerCertificate(name)
|
||||
.map(certificate -> new StoredEntity(certificate.getArn(),
|
||||
certificate.getPath()));
|
||||
default -> Optional.empty();
|
||||
};
|
||||
return stored.filter(entity -> entity.arn() != null && !entity.arn().isBlank());
|
||||
}
|
||||
|
||||
// ── S3 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -34,6 +34,12 @@ import java.util.Optional;
|
||||
*/
|
||||
public final class ServiceLinkedRoles {
|
||||
|
||||
/**
|
||||
* The path every service-linked role sits under, with the canonical service principal and a
|
||||
* trailing slash after it. Part of the role's ARN, so a policy naming one carries it.
|
||||
*/
|
||||
public static final String PATH = "/aws-service-role/";
|
||||
|
||||
/** Whether AWS accepts a {@code CustomSuffix} for a service, as far as anything records it. */
|
||||
public enum CustomSuffixSupport {
|
||||
/** A recorded create accepted a suffix. */
|
||||
|
||||
@@ -0,0 +1,543 @@
|
||||
{
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_iam_action_resources.py",
|
||||
"reference": "https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json",
|
||||
"retrieved": "2026-10-10",
|
||||
"note": "make iam-action-resources-verify checks every entry against AWS."
|
||||
},
|
||||
"actionResources": {
|
||||
"AcceptDelegationRequest": [
|
||||
"delegation-request"
|
||||
],
|
||||
"AddClientIDToOpenIDConnectProvider": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"AddRoleToInstanceProfile": [
|
||||
"instance-profile"
|
||||
],
|
||||
"AddUserToGroup": [
|
||||
"group"
|
||||
],
|
||||
"AssociateDelegationRequest": [
|
||||
"delegation-request"
|
||||
],
|
||||
"AttachGroupPolicy": [
|
||||
"group"
|
||||
],
|
||||
"AttachRolePolicy": [
|
||||
"role"
|
||||
],
|
||||
"AttachUserPolicy": [
|
||||
"user"
|
||||
],
|
||||
"ChangePassword": [
|
||||
"user"
|
||||
],
|
||||
"CreateAccessKey": [
|
||||
"user"
|
||||
],
|
||||
"CreateAccountAlias": [],
|
||||
"CreateDelegationRequest": [
|
||||
"delegation-request"
|
||||
],
|
||||
"CreateGroup": [
|
||||
"group"
|
||||
],
|
||||
"CreateInstanceProfile": [
|
||||
"instance-profile"
|
||||
],
|
||||
"CreateLoginProfile": [
|
||||
"user"
|
||||
],
|
||||
"CreateOpenIDConnectProvider": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"CreatePolicy": [
|
||||
"policy"
|
||||
],
|
||||
"CreatePolicyVersion": [
|
||||
"policy"
|
||||
],
|
||||
"CreateRole": [
|
||||
"role"
|
||||
],
|
||||
"CreateSAMLProvider": [
|
||||
"saml-provider"
|
||||
],
|
||||
"CreateServiceLinkedRole": [
|
||||
"role"
|
||||
],
|
||||
"CreateServiceSpecificCredential": [
|
||||
"user"
|
||||
],
|
||||
"CreateUser": [
|
||||
"user"
|
||||
],
|
||||
"CreateVirtualMFADevice": [
|
||||
"mfa"
|
||||
],
|
||||
"DeactivateMFADevice": [
|
||||
"user"
|
||||
],
|
||||
"DeleteAccessKey": [
|
||||
"user"
|
||||
],
|
||||
"DeleteAccountAlias": [],
|
||||
"DeleteAccountPasswordPolicy": [],
|
||||
"DeleteCloudFrontPublicKey": [],
|
||||
"DeleteGroup": [
|
||||
"group"
|
||||
],
|
||||
"DeleteGroupPolicy": [
|
||||
"group"
|
||||
],
|
||||
"DeleteInstanceProfile": [
|
||||
"instance-profile"
|
||||
],
|
||||
"DeleteLoginProfile": [
|
||||
"user"
|
||||
],
|
||||
"DeleteOpenIDConnectProvider": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"DeletePolicy": [
|
||||
"policy"
|
||||
],
|
||||
"DeletePolicyVersion": [
|
||||
"policy"
|
||||
],
|
||||
"DeleteRole": [
|
||||
"role"
|
||||
],
|
||||
"DeleteRolePermissionsBoundary": [
|
||||
"role"
|
||||
],
|
||||
"DeleteRolePolicy": [
|
||||
"role"
|
||||
],
|
||||
"DeleteSAMLProvider": [
|
||||
"saml-provider"
|
||||
],
|
||||
"DeleteSSHPublicKey": [
|
||||
"user"
|
||||
],
|
||||
"DeleteServerCertificate": [
|
||||
"server-certificate"
|
||||
],
|
||||
"DeleteServiceLinkedRole": [
|
||||
"role"
|
||||
],
|
||||
"DeleteServiceSpecificCredential": [
|
||||
"user"
|
||||
],
|
||||
"DeleteSigningCertificate": [
|
||||
"user"
|
||||
],
|
||||
"DeleteUser": [
|
||||
"user"
|
||||
],
|
||||
"DeleteUserPermissionsBoundary": [
|
||||
"user"
|
||||
],
|
||||
"DeleteUserPolicy": [
|
||||
"user"
|
||||
],
|
||||
"DeleteVirtualMFADevice": [
|
||||
"mfa",
|
||||
"sms-mfa"
|
||||
],
|
||||
"DetachGroupPolicy": [
|
||||
"group"
|
||||
],
|
||||
"DetachRolePolicy": [
|
||||
"role"
|
||||
],
|
||||
"DetachUserPolicy": [
|
||||
"user"
|
||||
],
|
||||
"DisableOrganizationsRootCredentialsManagement": [],
|
||||
"DisableOrganizationsRootSessions": [],
|
||||
"DisableOutboundWebIdentityFederation": [],
|
||||
"EnableMFADevice": [
|
||||
"user"
|
||||
],
|
||||
"EnableOrganizationsRootCredentialsManagement": [],
|
||||
"EnableOrganizationsRootSessions": [],
|
||||
"EnableOutboundWebIdentityFederation": [],
|
||||
"GenerateCredentialReport": [],
|
||||
"GenerateOrganizationsAccessReport": [
|
||||
"access-report"
|
||||
],
|
||||
"GenerateServiceLastAccessedDetails": [
|
||||
"group",
|
||||
"policy",
|
||||
"role",
|
||||
"user"
|
||||
],
|
||||
"GetAccessKeyLastUsed": [
|
||||
"user"
|
||||
],
|
||||
"GetAccountAuthorizationDetails": [],
|
||||
"GetAccountEmailAddress": [],
|
||||
"GetAccountName": [],
|
||||
"GetAccountPasswordPolicy": [],
|
||||
"GetAccountProperties": [],
|
||||
"GetAccountSummary": [],
|
||||
"GetCloudFrontPublicKey": [],
|
||||
"GetContextKeysForCustomPolicy": [],
|
||||
"GetContextKeysForPrincipalPolicy": [
|
||||
"group",
|
||||
"role",
|
||||
"user"
|
||||
],
|
||||
"GetCredentialReport": [],
|
||||
"GetDelegationRequest": [
|
||||
"delegation-request"
|
||||
],
|
||||
"GetGroup": [
|
||||
"group"
|
||||
],
|
||||
"GetGroupPolicy": [
|
||||
"group"
|
||||
],
|
||||
"GetHumanReadableSummary": [
|
||||
"delegation-request"
|
||||
],
|
||||
"GetInstanceProfile": [
|
||||
"instance-profile"
|
||||
],
|
||||
"GetLoginProfile": [
|
||||
"user"
|
||||
],
|
||||
"GetMFADevice": [
|
||||
"user"
|
||||
],
|
||||
"GetOpenIDConnectProvider": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"GetOrganizationsAccessReport": [],
|
||||
"GetOutboundWebIdentityFederationInfo": [],
|
||||
"GetPolicy": [
|
||||
"policy"
|
||||
],
|
||||
"GetPolicyVersion": [
|
||||
"policy"
|
||||
],
|
||||
"GetRole": [
|
||||
"role"
|
||||
],
|
||||
"GetRolePolicy": [
|
||||
"role"
|
||||
],
|
||||
"GetRoleTemplateVersion": [
|
||||
"role-template"
|
||||
],
|
||||
"GetSAMLProvider": [
|
||||
"saml-provider"
|
||||
],
|
||||
"GetSSHPublicKey": [
|
||||
"user"
|
||||
],
|
||||
"GetServerCertificate": [
|
||||
"server-certificate"
|
||||
],
|
||||
"GetServiceLastAccessedDetails": [],
|
||||
"GetServiceLastAccessedDetailsWithEntities": [],
|
||||
"GetServiceLinkedRoleDeletionStatus": [
|
||||
"role"
|
||||
],
|
||||
"GetUser": [
|
||||
"user"
|
||||
],
|
||||
"GetUserPolicy": [
|
||||
"user"
|
||||
],
|
||||
"ListAccessKeys": [
|
||||
"user"
|
||||
],
|
||||
"ListAccountAliases": [],
|
||||
"ListAttachedGroupPolicies": [
|
||||
"group"
|
||||
],
|
||||
"ListAttachedRolePolicies": [
|
||||
"role"
|
||||
],
|
||||
"ListAttachedUserPolicies": [
|
||||
"user"
|
||||
],
|
||||
"ListCloudFrontPublicKeys": [],
|
||||
"ListDelegationRequests": [],
|
||||
"ListEntitiesForPolicy": [
|
||||
"policy"
|
||||
],
|
||||
"ListGroupPolicies": [
|
||||
"group"
|
||||
],
|
||||
"ListGroups": [],
|
||||
"ListGroupsForUser": [
|
||||
"user"
|
||||
],
|
||||
"ListInstanceProfileTags": [
|
||||
"instance-profile"
|
||||
],
|
||||
"ListInstanceProfiles": [],
|
||||
"ListInstanceProfilesForRole": [
|
||||
"role"
|
||||
],
|
||||
"ListMFADeviceTags": [
|
||||
"mfa"
|
||||
],
|
||||
"ListMFADevices": [
|
||||
"user"
|
||||
],
|
||||
"ListOpenIDConnectProviderTags": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"ListOpenIDConnectProviders": [],
|
||||
"ListOrganizationsFeatures": [],
|
||||
"ListPolicies": [],
|
||||
"ListPoliciesGrantingServiceAccess": [
|
||||
"group",
|
||||
"role",
|
||||
"user"
|
||||
],
|
||||
"ListPolicyTags": [
|
||||
"policy"
|
||||
],
|
||||
"ListPolicyVersions": [
|
||||
"policy"
|
||||
],
|
||||
"ListRolePolicies": [
|
||||
"role"
|
||||
],
|
||||
"ListRoleTags": [
|
||||
"role"
|
||||
],
|
||||
"ListRoles": [],
|
||||
"ListSAMLProviderTags": [
|
||||
"saml-provider"
|
||||
],
|
||||
"ListSAMLProviders": [],
|
||||
"ListSSHPublicKeys": [
|
||||
"user"
|
||||
],
|
||||
"ListSTSRegionalEndpointsStatus": [],
|
||||
"ListServerCertificateTags": [
|
||||
"server-certificate"
|
||||
],
|
||||
"ListServerCertificates": [],
|
||||
"ListServiceSpecificCredentials": [
|
||||
"user"
|
||||
],
|
||||
"ListSigningCertificates": [
|
||||
"user"
|
||||
],
|
||||
"ListUserPolicies": [
|
||||
"user"
|
||||
],
|
||||
"ListUserTags": [
|
||||
"user"
|
||||
],
|
||||
"ListUsers": [],
|
||||
"ListVirtualMFADevices": [],
|
||||
"PassRole": [
|
||||
"role"
|
||||
],
|
||||
"PutAccountProperties": [],
|
||||
"PutGroupPolicy": [
|
||||
"group"
|
||||
],
|
||||
"PutRolePermissionsBoundary": [
|
||||
"role"
|
||||
],
|
||||
"PutRolePolicy": [
|
||||
"role"
|
||||
],
|
||||
"PutUserPermissionsBoundary": [
|
||||
"user"
|
||||
],
|
||||
"PutUserPolicy": [
|
||||
"user"
|
||||
],
|
||||
"RejectDelegationRequest": [
|
||||
"delegation-request"
|
||||
],
|
||||
"RemoveClientIDFromOpenIDConnectProvider": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"RemoveRoleFromInstanceProfile": [
|
||||
"instance-profile"
|
||||
],
|
||||
"RemoveUserFromGroup": [
|
||||
"group"
|
||||
],
|
||||
"ResetServiceSpecificCredential": [
|
||||
"user"
|
||||
],
|
||||
"ResyncMFADevice": [
|
||||
"user"
|
||||
],
|
||||
"SendDelegationToken": [
|
||||
"delegation-request"
|
||||
],
|
||||
"SetDefaultPolicyVersion": [
|
||||
"policy"
|
||||
],
|
||||
"SetSTSRegionalEndpointStatus": [],
|
||||
"SetSecurityTokenServicePreferences": [],
|
||||
"SimulateCustomPolicy": [],
|
||||
"SimulatePrincipalPolicy": [
|
||||
"group",
|
||||
"role",
|
||||
"user"
|
||||
],
|
||||
"TagInstanceProfile": [
|
||||
"instance-profile"
|
||||
],
|
||||
"TagMFADevice": [
|
||||
"mfa"
|
||||
],
|
||||
"TagOpenIDConnectProvider": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"TagPolicy": [
|
||||
"policy"
|
||||
],
|
||||
"TagRole": [
|
||||
"role"
|
||||
],
|
||||
"TagSAMLProvider": [
|
||||
"saml-provider"
|
||||
],
|
||||
"TagServerCertificate": [
|
||||
"server-certificate"
|
||||
],
|
||||
"TagUser": [
|
||||
"user"
|
||||
],
|
||||
"UntagInstanceProfile": [
|
||||
"instance-profile"
|
||||
],
|
||||
"UntagMFADevice": [
|
||||
"mfa"
|
||||
],
|
||||
"UntagOpenIDConnectProvider": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"UntagPolicy": [
|
||||
"policy"
|
||||
],
|
||||
"UntagRole": [
|
||||
"role"
|
||||
],
|
||||
"UntagSAMLProvider": [
|
||||
"saml-provider"
|
||||
],
|
||||
"UntagServerCertificate": [
|
||||
"server-certificate"
|
||||
],
|
||||
"UntagUser": [
|
||||
"user"
|
||||
],
|
||||
"UpdateAccessKey": [
|
||||
"user"
|
||||
],
|
||||
"UpdateAccountEmailAddress": [],
|
||||
"UpdateAccountName": [],
|
||||
"UpdateAccountPasswordPolicy": [],
|
||||
"UpdateAssumeRolePolicy": [
|
||||
"role"
|
||||
],
|
||||
"UpdateCloudFrontPublicKey": [],
|
||||
"UpdateGroup": [
|
||||
"group"
|
||||
],
|
||||
"UpdateLoginProfile": [
|
||||
"user"
|
||||
],
|
||||
"UpdateOpenIDConnectProviderThumbprint": [
|
||||
"oidc-provider"
|
||||
],
|
||||
"UpdateRole": [
|
||||
"role"
|
||||
],
|
||||
"UpdateRoleDescription": [
|
||||
"role"
|
||||
],
|
||||
"UpdateSAMLProvider": [
|
||||
"saml-provider"
|
||||
],
|
||||
"UpdateSSHPublicKey": [
|
||||
"user"
|
||||
],
|
||||
"UpdateServerCertificate": [
|
||||
"server-certificate"
|
||||
],
|
||||
"UpdateServiceSpecificCredential": [
|
||||
"user"
|
||||
],
|
||||
"UpdateSigningCertificate": [
|
||||
"user"
|
||||
],
|
||||
"UpdateUser": [
|
||||
"user"
|
||||
],
|
||||
"UploadCloudFrontPublicKey": [],
|
||||
"UploadSSHPublicKey": [
|
||||
"user"
|
||||
],
|
||||
"UploadServerCertificate": [
|
||||
"server-certificate"
|
||||
],
|
||||
"UploadSigningCertificate": [
|
||||
"user"
|
||||
]
|
||||
},
|
||||
"resourceArnFormats": {
|
||||
"access-report": [
|
||||
"arn:${Partition}:iam::${Account}:access-report/${EntityPath}"
|
||||
],
|
||||
"assumed-role": [
|
||||
"arn:${Partition}:iam::${Account}:assumed-role/${RoleName}/${RoleSessionName}"
|
||||
],
|
||||
"delegation-request": [
|
||||
"arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"
|
||||
],
|
||||
"federated-user": [
|
||||
"arn:${Partition}:iam::${Account}:federated-user/${UserName}"
|
||||
],
|
||||
"group": [
|
||||
"arn:${Partition}:iam::${Account}:group/${GroupNameWithPath}"
|
||||
],
|
||||
"instance-profile": [
|
||||
"arn:${Partition}:iam::${Account}:instance-profile/${InstanceProfileNameWithPath}"
|
||||
],
|
||||
"mfa": [
|
||||
"arn:${Partition}:iam::${Account}:mfa/${MfaTokenIdWithPath}"
|
||||
],
|
||||
"oidc-provider": [
|
||||
"arn:${Partition}:iam::${Account}:oidc-provider/${OidcProviderName}"
|
||||
],
|
||||
"policy": [
|
||||
"arn:${Partition}:iam::${Account}:policy/${PolicyNameWithPath}"
|
||||
],
|
||||
"role": [
|
||||
"arn:${Partition}:iam::${Account}:role/${RoleNameWithPath}"
|
||||
],
|
||||
"role-template": [
|
||||
"arn:${Partition}:iam::aws:role-template/${AWSServicePrincipal}/${RoleTemplateName}:${RoleTemplateMajorVersion}"
|
||||
],
|
||||
"saml-provider": [
|
||||
"arn:${Partition}:iam::${Account}:saml-provider/${SamlProviderName}"
|
||||
],
|
||||
"server-certificate": [
|
||||
"arn:${Partition}:iam::${Account}:server-certificate/${CertificateNameWithPath}"
|
||||
],
|
||||
"sms-mfa": [
|
||||
"arn:${Partition}:iam::${Account}:sms-mfa/${MfaTokenIdWithPath}"
|
||||
],
|
||||
"user": [
|
||||
"arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_service_namespaces.py",
|
||||
"index": "https://servicereference.us-east-1.amazonaws.com/",
|
||||
"retrieved": "2026-09-27",
|
||||
"retrieved": "2026-10-10",
|
||||
"note": "make iam-namespaces-verify checks every entry still exists upstream."
|
||||
},
|
||||
"serviceNamespaces": [
|
||||
@@ -171,11 +171,11 @@
|
||||
"elemental-support-content",
|
||||
"emr-containers",
|
||||
"emr-serverless",
|
||||
"end-user-messaging",
|
||||
"entityresolution",
|
||||
"es",
|
||||
"events",
|
||||
"eventsbilltoaws",
|
||||
"evidently",
|
||||
"evs",
|
||||
"execute-api",
|
||||
"finops-agent",
|
||||
@@ -224,7 +224,6 @@
|
||||
"iot-device-tester",
|
||||
"iotanalytics",
|
||||
"iotdeviceadvisor",
|
||||
"iotevents",
|
||||
"iotfleethub",
|
||||
"iotfleetwise",
|
||||
"iotjobsdata",
|
||||
@@ -412,6 +411,7 @@
|
||||
"sso",
|
||||
"sso-directory",
|
||||
"sso-oauth",
|
||||
"startups",
|
||||
"states",
|
||||
"storagegateway",
|
||||
"sts",
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The vendored IAM action resource map, and the cases that justify vendoring it rather than
|
||||
* reading the resource off the request.
|
||||
*/
|
||||
class IamActionResourcesTest {
|
||||
|
||||
@Test
|
||||
void theResourceTypeIsNotTheParameterTheActionTakes() {
|
||||
// The whole reason this is AWS's data and not a rule over the request. Each of these
|
||||
// carries a parameter naming something other than what it is authorized against.
|
||||
assertEquals(List.of("group"), IamActionResources.typesOf("AddUserToGroup"));
|
||||
assertEquals(List.of("group"), IamActionResources.typesOf("RemoveUserFromGroup"));
|
||||
assertEquals(List.of("instance-profile"),
|
||||
IamActionResources.typesOf("AddRoleToInstanceProfile"));
|
||||
assertEquals(List.of("instance-profile"),
|
||||
IamActionResources.typesOf("RemoveRoleFromInstanceProfile"));
|
||||
assertEquals(List.of("user"), IamActionResources.typesOf("EnableMFADevice"));
|
||||
assertEquals(List.of("user"), IamActionResources.typesOf("DeactivateMFADevice"));
|
||||
assertEquals(List.of("user"), IamActionResources.typesOf("ResyncMFADevice"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionAwsAuthorizesAgainstNothingCarriesNoType() {
|
||||
assertEquals(List.of(), IamActionResources.typesOf("ListUsers"));
|
||||
assertEquals(List.of(), IamActionResources.typesOf("GetAccountSummary"));
|
||||
assertEquals(List.of(), IamActionResources.typesOf("SimulateCustomPolicy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionNobodyPublishesReadsTheSameWayAsOneWithNoResource() {
|
||||
assertEquals(List.of(), IamActionResources.typesOf("MakeBelieve"));
|
||||
assertEquals(List.of(), IamActionResources.typesOf(null));
|
||||
// Which is why the resource-less ones are still listed: absence is a gap, an empty list
|
||||
// is a wildcard on purpose, and only the map itself can tell them apart.
|
||||
assertTrue(IamActionResources.all().containsKey("ListUsers"));
|
||||
assertFalse(IamActionResources.all().containsKey("MakeBelieve"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionCanBeAuthorizedAgainstSeveralTypes() {
|
||||
// These take a principal ARN, so the request names whichever type it is.
|
||||
assertEquals(List.of("group", "role", "user"),
|
||||
IamActionResources.typesOf("SimulatePrincipalPolicy"));
|
||||
assertEquals(List.of("group", "policy", "role", "user"),
|
||||
IamActionResources.typesOf("GenerateServiceLastAccessedDetails"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyTypeNamedByAnActionCarriesTheArnFormatAwsMintsItIn() {
|
||||
Map<String, List<String>> formats = IamActionResources.arnFormats();
|
||||
for (Map.Entry<String, List<String>> entry : IamActionResources.all().entrySet()) {
|
||||
for (String resourceType : entry.getValue()) {
|
||||
assertTrue(formats.containsKey(resourceType),
|
||||
entry.getKey() + " names " + resourceType + ", which has no ARN format");
|
||||
}
|
||||
}
|
||||
assertEquals(List.of("arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"),
|
||||
formats.get("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyCreateIsAuthorizedAgainstExactlyOneResourceType() {
|
||||
// A create has nothing to read the resource off, so ResourceArnBuilder mints the ARN from
|
||||
// the type AWS gives the action. One type is what lets it mint without being told which,
|
||||
// and two would leave it picking. Iterated rather than restated: a create added to the
|
||||
// resolver that AWS gives no single type falls back to the wildcard, which is the
|
||||
// permissive answer and a silent one, so this is what says it out loud.
|
||||
for (String create : ResourceArnBuilder.CREATE_PARAMETERS.keySet()) {
|
||||
assertEquals(1, IamActionResources.typesOf(create).size(),
|
||||
create + " is no longer authorized against exactly one resource type, so "
|
||||
+ "there is no single ARN for it to mint: "
|
||||
+ IamActionResources.typesOf(create));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArnSpellsTheResourceTypeInFrontOfTheName() {
|
||||
// What minting assumes. ResourceArnBuilder builds `:<type>/<name>`, which holds only
|
||||
// while AWS spells that type's ARN the same way, and the reference publishes the format,
|
||||
// so the assumption is checked rather than carried.
|
||||
for (Map.Entry<String, List<String>> entry : IamActionResources.arnFormats().entrySet()) {
|
||||
for (String arnFormat : entry.getValue()) {
|
||||
assertTrue(arnFormat.contains(":" + entry.getKey() + "/"),
|
||||
"AWS spells a " + entry.getKey() + " ARN as " + arnFormat
|
||||
+ ", which this resolver's minting does not match");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyResourceTypeInUseIsOneTheResolverCoversOrDeclaresUnresolved() {
|
||||
// Read off the resolver's own tables rather than restated, so a type cannot be waved
|
||||
// through by adding it to a list in this file. The resolver answers `*` for a type it
|
||||
// does not know, which is the permissive answer and a silent one.
|
||||
Set<String> covered = new TreeSet<>(ResourceArnBuilder.NAME_PARAMETERS.keySet());
|
||||
covered.addAll(ResourceArnBuilder.UNRESOLVED_TYPES.keySet());
|
||||
for (String action : ResourceArnBuilder.IAM_ARN_PARAMETERS.keySet()) {
|
||||
covered.addAll(IamActionResources.typesOf(action));
|
||||
}
|
||||
for (String action : ResourceArnBuilder.CREATE_PARAMETERS.keySet()) {
|
||||
covered.addAll(IamActionResources.typesOf(action));
|
||||
}
|
||||
for (String action : ResourceArnBuilder.DERIVED_RESOLVERS.keySet()) {
|
||||
covered.addAll(IamActionResources.typesOf(action));
|
||||
}
|
||||
for (Map.Entry<String, List<String>> entry : IamActionResources.all().entrySet()) {
|
||||
for (String resourceType : entry.getValue()) {
|
||||
assertTrue(covered.contains(resourceType), "AWS authorizes " + entry.getKey()
|
||||
+ " against '" + resourceType + "', which ResourceArnBuilder neither "
|
||||
+ "resolves nor lists as unresolved, so the action falls back to *");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theResourceTypesInUseAreTheOnesTheResolverKnowsAbout() {
|
||||
// The upstream half of the same question: which types AWS uses at all. The test above
|
||||
// catches a type nothing resolves; this one catches AWS changing the set, including a
|
||||
// type disappearing, which leaves a dead entry behind rather than a gap.
|
||||
Set<String> inUse = new TreeSet<>();
|
||||
IamActionResources.all().values().forEach(inUse::addAll);
|
||||
assertEquals(Set.of(
|
||||
// Named by a parameter the resolver reads.
|
||||
"user", "role", "group", "instance-profile", "server-certificate",
|
||||
// Named by an ARN the request carries, or minted by a create.
|
||||
"policy", "mfa", "sms-mfa", "saml-provider", "oidc-provider",
|
||||
// Only on actions the handler does not dispatch.
|
||||
"access-report", "delegation-request", "role-template"),
|
||||
inUse,
|
||||
"AWS has changed which resource types IAM actions are authorized against; "
|
||||
+ "teach ResourceArnBuilder the new one or list it as unresolved");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMapMissingItsActionsIsABuildDefect() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"resourceArnFormats\":{}}"));
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"actionResources\":{}}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeWithNoArnFormatIsABuildDefect() {
|
||||
// The two halves have to agree, because the minting reads the format to check itself.
|
||||
assertThrows(IllegalStateException.class, () -> parse("""
|
||||
{"actionResources":{"GetUser":["user"]},
|
||||
"resourceArnFormats":{"role":["arn:${Partition}:iam::${Account}:role/${Name}"]}}"""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankEntryIsABuildDefect() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("""
|
||||
{"actionResources":{"GetUser":[""]},
|
||||
"resourceArnFormats":{"user":["arn:${Partition}:iam::${Account}:user/${Name}"]}}"""));
|
||||
}
|
||||
|
||||
private static IamActionResources.Catalog parse(String json) throws IOException {
|
||||
return IamActionResources.parse(
|
||||
new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
}
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* A policy statement naming one IAM resource has to bind to that resource and no other. Issue
|
||||
* #4979 was that almost every IAM action reached the evaluator with {@code *} as its resource, so
|
||||
* a statement naming a user, role, group, profile or policy was silently inert: nothing failed,
|
||||
* the statement was simply ignored, which is why these drive the whole path rather than the ARN
|
||||
* the builder returns.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class IamResourceScopedPolicyEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
/**
|
||||
* The emulator is shared with every other test class, so each fixture here is removed again:
|
||||
* a user, group, role, profile, policy or provider left behind shows up in the next class to
|
||||
* list one unscoped.
|
||||
*/
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI baseUri;
|
||||
|
||||
private static String arn(String resource) {
|
||||
return "arn:aws:iam::" + ACCOUNT_ID + ":" + resource;
|
||||
}
|
||||
|
||||
private static String denying(String action, String resource) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"iam:%s","Resource":"%s"}]}"""
|
||||
.formatted(action, resource);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyNamingOneUserLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-" + suffix;
|
||||
String allowed = "keep-" + suffix;
|
||||
createUser(denied);
|
||||
createUser(allowed);
|
||||
|
||||
String akid = userWith(denying("DeleteUser", arn("user/" + denied)));
|
||||
|
||||
userIam(akid, "DeleteUser", Map.of("UserName", denied))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "DeleteUser", Map.of("UserName", allowed)).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference gives the resource as {@code user/${UserNameWithPath}}, so a user at
|
||||
* {@code /eng/} is only named by an ARN carrying that path. The second half is what makes this
|
||||
* discriminating: the same ARN without the path must not match.
|
||||
*/
|
||||
@Test
|
||||
void theStoredPathIsPartOfTheArn() {
|
||||
String name = "pathed-" + suffix();
|
||||
createUser(name, "Path", "/eng/");
|
||||
|
||||
String withPath = userWith(denying("GetUser", arn("user/eng/" + name)));
|
||||
userIam(withPath, "GetUser", Map.of("UserName", name))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
String withoutPath = userWith(denying("GetUser", arn("user/" + name)));
|
||||
userIam(withoutPath, "GetUser", Map.of("UserName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code AddUserToGroup} names two entities and is authorized against one. The reference gives
|
||||
* it the group as its only resource type, so a deny on the group binds and a deny on the user
|
||||
* it adds does not.
|
||||
*/
|
||||
@Test
|
||||
void aGroupMembershipChangeIsAuthorizedAgainstTheGroup() {
|
||||
String suffix = suffix();
|
||||
String group = "Group-" + suffix;
|
||||
String member = "member-" + suffix;
|
||||
createGroup(group);
|
||||
createUser(member);
|
||||
|
||||
String groupDenied = userWith(denying("AddUserToGroup", arn("group/" + group)));
|
||||
userIam(groupDenied, "AddUserToGroup", Map.of("GroupName", group, "UserName", member))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
String userDenied = userWith(denying("AddUserToGroup", arn("user/" + member)));
|
||||
userIam(userDenied, "AddUserToGroup", Map.of("GroupName", group, "UserName", member))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyNamingOneRoleLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-role-" + suffix;
|
||||
String allowed = "keep-role-" + suffix;
|
||||
String trust = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
|
||||
createRole(denied, trust);
|
||||
createRole(allowed, trust);
|
||||
|
||||
String akid = userWith(denying("PutRolePolicy", arn("role/" + denied)));
|
||||
String inline = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"*"}]}""";
|
||||
|
||||
userIam(akid, "PutRolePolicy", Map.of("RoleName", denied, "PolicyName", "p",
|
||||
"PolicyDocument", inline)).statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "PutRolePolicy", Map.of("RoleName", allowed, "PolicyName", "p",
|
||||
"PolicyDocument", inline)).statusCode(200);
|
||||
}
|
||||
|
||||
/** The instance-profile half of the same shape: the profile is the resource, not the role. */
|
||||
@Test
|
||||
void aProfileRoleChangeIsAuthorizedAgainstTheProfile() {
|
||||
String suffix = suffix();
|
||||
String profile = "profile-" + suffix;
|
||||
String role = "profile-role-" + suffix;
|
||||
createInstanceProfile(profile);
|
||||
createRole(role, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}""");
|
||||
|
||||
String akid = userWith(denying("AddRoleToInstanceProfile", arn("instance-profile/" + profile)));
|
||||
userIam(akid, "AddRoleToInstanceProfile",
|
||||
Map.of("InstanceProfileName", profile, "RoleName", role))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
/** A managed policy is named by the ARN the request already carries. */
|
||||
@Test
|
||||
void aDenyNamingOneManagedPolicyLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-policy-" + suffix;
|
||||
String allowed = "keep-policy-" + suffix;
|
||||
String document = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"*"}]}""";
|
||||
createManagedPolicy(denied, document);
|
||||
createManagedPolicy(allowed, document);
|
||||
|
||||
String akid = userWith(denying("DeletePolicy", arn("policy/" + denied)));
|
||||
userIam(akid, "DeletePolicy", Map.of("PolicyArn", arn("policy/" + denied)))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "DeletePolicy", Map.of("PolicyArn", arn("policy/" + allowed)))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A create has no stored resource to read, so its ARN comes from the request's own
|
||||
* {@code Path}. The same name at a different path is a different resource and stays allowed.
|
||||
*/
|
||||
@Test
|
||||
void aCreateIsAuthorizedAgainstThePathItAsksFor() {
|
||||
String name = "created-" + suffix();
|
||||
// Created through the enforced path rather than by the admin helper, so register it here.
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(port(), adminAuth(), name));
|
||||
String akid = userWith(denying("CreateUser", arn("user/eng/" + name)));
|
||||
|
||||
userIam(akid, "CreateUser", Map.of("UserName", name, "Path", "/eng/"))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "CreateUser", Map.of("UserName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A rename is authorized against both names, which UpdateUser's own reference requires: the
|
||||
* requester must have permissions "on both the source object and the target object". A deny on
|
||||
* the destination alone is enough to refuse it.
|
||||
*/
|
||||
@Test
|
||||
void aRenameIsRefusedWhenOnlyTheDestinationIsDenied() {
|
||||
String suffix = suffix();
|
||||
String from = "rename-from-" + suffix;
|
||||
String to = "rename-to-" + suffix;
|
||||
createUser(from);
|
||||
// A rename moves the user, so the name that survives is the destination's.
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(port(), adminAuth(), to));
|
||||
|
||||
String akid = userWith(denying("UpdateUser", arn("user/" + to)));
|
||||
userIam(akid, "UpdateUser", Map.of("UserName", from, "NewUserName", to))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
// With both names allowed it goes through, so the extra resource is not a blanket no.
|
||||
String allowed = userWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:*","Resource":"*"}]}""");
|
||||
userIam(allowed, "UpdateUser", Map.of("UserName", from, "NewUserName", to)).statusCode(200);
|
||||
}
|
||||
|
||||
/** A resource-scoped Allow grants that resource only, which is the other direction. */
|
||||
@Test
|
||||
void aResourceScopedAllowGrantsThatUserOnly() {
|
||||
String suffix = suffix();
|
||||
String granted = "allow-" + suffix;
|
||||
String other = "other-" + suffix;
|
||||
createUser(granted);
|
||||
createUser(other);
|
||||
|
||||
String akid = userWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:GetUser","Resource":"%s"}]}"""
|
||||
.formatted(arn("user/" + granted)));
|
||||
|
||||
userIam(akid, "GetUser", Map.of("UserName", granted)).statusCode(200);
|
||||
userIam(akid, "GetUser", Map.of("UserName", other))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The actions whose {@code UserName} is optional act on the user who signed the request, so a
|
||||
* statement scoped to that user has to reach them. Before this, such a call arrived with
|
||||
* {@code *} as its resource and the statement was ignored.
|
||||
*/
|
||||
@Test
|
||||
void anOmittedUserNameNamesTheSigningUser() {
|
||||
String user = "self-" + suffix();
|
||||
createUser(user);
|
||||
adminIam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "p",
|
||||
"PolicyDocument", denying("GetUser", arn("user/" + user)))).statusCode(200);
|
||||
String akid = adminIam("CreateAccessKey", Map.of("UserName", user)).statusCode(200)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey"
|
||||
+ ".AccessKeyId");
|
||||
|
||||
// No UserName: the request is about the signer, and the deny names exactly that user.
|
||||
userIam(akid, "GetUser", Map.of()).statusCode(403).body(containsString("AccessDenied"));
|
||||
// Naming someone else still goes through, so the deny bound to the signer and not to all.
|
||||
String other = "other-" + suffix();
|
||||
createUser(other);
|
||||
userIam(akid, "GetUser", Map.of("UserName", other)).statusCode(200);
|
||||
}
|
||||
|
||||
/** A virtual MFA device is named by the serial number the request carries. */
|
||||
@Test
|
||||
void aDenyNamingOneVirtualMfaDeviceLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-mfa-" + suffix;
|
||||
String allowed = "keep-mfa-" + suffix;
|
||||
createVirtualMfaDevice(denied);
|
||||
createVirtualMfaDevice(allowed);
|
||||
|
||||
String akid = userWith(denying("DeleteVirtualMFADevice", arn("mfa/" + denied)));
|
||||
userIam(akid, "DeleteVirtualMFADevice", Map.of("SerialNumber", arn("mfa/" + denied)))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "DeleteVirtualMFADevice", Map.of("SerialNumber", arn("mfa/" + allowed)))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** A SAML provider is named by the ARN the request carries. */
|
||||
@Test
|
||||
void aDenyNamingOneSamlProviderLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-saml-" + suffix;
|
||||
String allowed = "keep-saml-" + suffix;
|
||||
createSamlProvider(denied);
|
||||
createSamlProvider(allowed);
|
||||
|
||||
String akid = userWith(denying("GetSAMLProvider", arn("saml-provider/" + denied)));
|
||||
userIam(akid, "GetSAMLProvider",
|
||||
Map.of("SAMLProviderArn", arn("saml-provider/" + denied)))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "GetSAMLProvider",
|
||||
Map.of("SAMLProviderArn", arn("saml-provider/" + allowed))).statusCode(200);
|
||||
}
|
||||
|
||||
/** An OIDC provider's ARN carries its URL without the scheme, which is how IAM stores it. */
|
||||
@Test
|
||||
void aDenyNamingOneOidcProviderLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-oidc-" + suffix + ".example.com";
|
||||
String allowed = "keep-oidc-" + suffix + ".example.com";
|
||||
createOidcProvider(denied);
|
||||
createOidcProvider(allowed);
|
||||
|
||||
String akid = userWith(denying("GetOpenIDConnectProvider", arn("oidc-provider/" + denied)));
|
||||
userIam(akid, "GetOpenIDConnectProvider",
|
||||
Map.of("OpenIDConnectProviderArn", arn("oidc-provider/" + denied)))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "GetOpenIDConnectProvider",
|
||||
Map.of("OpenIDConnectProviderArn", arn("oidc-provider/" + allowed)))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** The shape {@code SAMLProviderLifecycleIntegrationTest} already establishes as acceptable. */
|
||||
private static String samlMetadata(String entityId) {
|
||||
return "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\""
|
||||
+ entityId + "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\">"
|
||||
+ "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data>"
|
||||
+ "<ds:X509Certificate>c2NvcGVk</ds:X509Certificate></ds:X509Data></ds:KeyInfo>"
|
||||
+ "</md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
|
||||
}
|
||||
|
||||
private String createUser(String name, String... extraParams) {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("UserName", name);
|
||||
for (int i = 0; i < extraParams.length; i += 2) {
|
||||
params.put(extraParams[i], extraParams[i + 1]);
|
||||
}
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(port(), adminAuth(), name));
|
||||
return adminIam("CreateUser", params).statusCode(200).extract().path(
|
||||
"CreateUserResponse.CreateUserResult.User.Arn");
|
||||
}
|
||||
|
||||
private void createGroup(String name) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeGroup(port(), adminAuth(), name));
|
||||
adminIam("CreateGroup", Map.of("GroupName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
private void createRole(String name, String trustPolicy) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeRole(port(), adminAuth(), name));
|
||||
adminIam("CreateRole", Map.of("RoleName", name,
|
||||
"AssumeRolePolicyDocument", trustPolicy)).statusCode(200);
|
||||
}
|
||||
|
||||
private void createInstanceProfile(String name) {
|
||||
cleanup.register(() ->
|
||||
EnforcementFixtures.removeInstanceProfile(port(), adminAuth(), name));
|
||||
adminIam("CreateInstanceProfile", Map.of("InstanceProfileName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
private void createManagedPolicy(String name, String document) {
|
||||
cleanup.register(() ->
|
||||
EnforcementFixtures.removePolicy(port(), adminAuth(), arn("policy/" + name)));
|
||||
adminIam("CreatePolicy", Map.of("PolicyName", name, "PolicyDocument", document))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void createVirtualMfaDevice(String name) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeByArn(port(), adminAuth(),
|
||||
"DeleteVirtualMFADevice", "SerialNumber", arn("mfa/" + name)));
|
||||
adminIam("CreateVirtualMFADevice", Map.of("VirtualMFADeviceName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
private void createSamlProvider(String name) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeByArn(port(), adminAuth(),
|
||||
"DeleteSAMLProvider", "SAMLProviderArn", arn("saml-provider/" + name)));
|
||||
adminIam("CreateSAMLProvider", Map.of("Name", name, "SAMLMetadataDocument",
|
||||
samlMetadata("https://idp.example.test/" + name))).statusCode(200);
|
||||
}
|
||||
|
||||
private void createOidcProvider(String host) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeByArn(port(), adminAuth(),
|
||||
"DeleteOpenIDConnectProvider", "OpenIDConnectProviderArn",
|
||||
arn("oidc-provider/" + host)));
|
||||
adminIam("CreateOpenIDConnectProvider", Map.of("Url", "https://" + host,
|
||||
"ClientIDList.member.1", "sts.amazonaws.com")).statusCode(200);
|
||||
}
|
||||
|
||||
private int port() {
|
||||
return baseUri.getPort();
|
||||
}
|
||||
|
||||
private static String adminAuth() {
|
||||
return auth(ACCOUNT_ID);
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
/** An IAM user in {@link #ACCOUNT_ID} carrying {@code policy} inline. */
|
||||
private String userWith(String policy) {
|
||||
String user = "scoped-" + suffix();
|
||||
createUser(user);
|
||||
adminIam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "p",
|
||||
"PolicyDocument", policy)).statusCode(200);
|
||||
return adminIam("CreateAccessKey", Map.of("UserName", user)).statusCode(200)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
}
|
||||
|
||||
private static ValidatableResponse adminIam(String action, Map<String, String> params) {
|
||||
return iamCall(ACCOUNT_ID, action, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse userIam(String akid, String action,
|
||||
Map<String, String> params) {
|
||||
return iamCall(akid, action, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse iamCall(String akid, String action,
|
||||
Map<String, String> params) {
|
||||
RequestSpecification spec = given()
|
||||
.header("Authorization", auth(akid))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2010-05-08");
|
||||
params.forEach(spec::formParam);
|
||||
return spec.when().post("/").then();
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260919/" + REGION + "/iam"
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamGroup;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
@@ -30,6 +34,8 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class ResourceArnBuilderTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private ResourceArnBuilder builder;
|
||||
private ContainerRequestContext ctx;
|
||||
private UriInfo uriInfo;
|
||||
@@ -87,6 +93,306 @@ class ResourceArnBuilderTest {
|
||||
return new ResourceArnBuilder(new ObjectMapper(), instance);
|
||||
}
|
||||
|
||||
/** A builder reading {@code service}, for the actions that name a resource that exists. */
|
||||
private static ResourceArnBuilder backedBy(IamService service) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<IamService> instance = mock(Instance.class);
|
||||
when(instance.get()).thenReturn(service);
|
||||
return new ResourceArnBuilder(new ObjectMapper(), instance);
|
||||
}
|
||||
|
||||
private static IamService storeHolding(String userName, String path, String arn) {
|
||||
IamUser user = new IamUser();
|
||||
user.setUserName(userName);
|
||||
user.setPath(path);
|
||||
user.setArn(arn);
|
||||
IamService service = mock(IamService.class);
|
||||
when(service.findUser(ACCOUNT, userName)).thenReturn(Optional.of(user));
|
||||
return service;
|
||||
}
|
||||
|
||||
/** The ARN the builder gives for the request in {@code form}, with one resource expected. */
|
||||
private String resourceOf(ResourceArnBuilder resourceArnBuilder, String form) {
|
||||
setFormBody(form);
|
||||
return resourceArnBuilder.build("iam", ctx, "us-east-1", ACCOUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* The gap issue 4979 describes, for the type most of IAM's actions take. A deny naming one
|
||||
* user has to bind to that user, which it cannot do while the action is evaluated against
|
||||
* {@code *}.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheUserBeingActedOn() {
|
||||
String arn = "arn:aws:iam::000000000000:user/eng/bob";
|
||||
IamService store = storeHolding("bob", "/eng/", arn);
|
||||
for (String action : List.of("DeleteUser", "GetUser", "CreateAccessKey", "PutUserPolicy",
|
||||
"AttachUserPolicy", "TagUser", "EnableMFADevice", "UpdateAccessKey")) {
|
||||
assertEquals(arn, resourceOf(backedBy(store), "Action=" + action + "&UserName=bob"),
|
||||
action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored path is part of the ARN, as {@code user/${UserNameWithPath}} in the reference's
|
||||
* ARN format says. A user at {@code /eng/} is not named by the ARN without it, so reading the
|
||||
* path from the store rather than deriving a root-path ARN is what makes a scoped deny bind.
|
||||
*/
|
||||
@Test
|
||||
void iamReadsThePathOfTheStoredUser() {
|
||||
String arn = "arn:aws:iam::000000000000:user/eng/deep/bob";
|
||||
assertEquals(arn,
|
||||
resourceOf(backedBy(storeHolding("bob", "/eng/deep/", arn)),
|
||||
"Action=GetUser&UserName=bob"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Two entities named, one authorized. The reference gives {@code AddUserToGroup} the group as
|
||||
* its only resource type, so taking the user from the request would scope it to the wrong one
|
||||
* and have a deny on the group pass.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheGroupRatherThanTheUserOnAGroupMembershipChange() {
|
||||
String groupArn = "arn:aws:iam::000000000000:group/admins";
|
||||
IamGroup group = new IamGroup();
|
||||
group.setGroupName("admins");
|
||||
group.setPath("/");
|
||||
group.setArn(groupArn);
|
||||
IamService store = mock(IamService.class);
|
||||
when(store.findGroup(ACCOUNT, "admins")).thenReturn(Optional.of(group));
|
||||
|
||||
for (String action : List.of("AddUserToGroup", "RemoveUserFromGroup")) {
|
||||
assertEquals(groupArn,
|
||||
resourceOf(backedBy(store),
|
||||
"Action=" + action + "&GroupName=admins&UserName=bob"),
|
||||
action);
|
||||
}
|
||||
}
|
||||
|
||||
/** The same shape for instance profiles, whose role actions name the profile only. */
|
||||
@Test
|
||||
void iamNamesTheInstanceProfileRatherThanTheRoleOnAProfileChange() {
|
||||
String profileArn = "arn:aws:iam::000000000000:instance-profile/app";
|
||||
InstanceProfile profile = new InstanceProfile();
|
||||
profile.setInstanceProfileName("app");
|
||||
profile.setPath("/");
|
||||
profile.setArn(profileArn);
|
||||
IamService store = mock(IamService.class);
|
||||
when(store.findInstanceProfile(ACCOUNT, "app")).thenReturn(Optional.of(profile));
|
||||
|
||||
for (String action : List.of("AddRoleToInstanceProfile", "RemoveRoleFromInstanceProfile")) {
|
||||
assertEquals(profileArn,
|
||||
resourceOf(backedBy(store),
|
||||
"Action=" + action + "&InstanceProfileName=app&RoleName=app-role"),
|
||||
action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamNamesTheRoleBeingActedOn() {
|
||||
String arn = "arn:aws:iam::000000000000:role/service-role/app";
|
||||
IamRole role = new IamRole();
|
||||
role.setRoleName("app");
|
||||
role.setPath("/service-role/");
|
||||
role.setArn(arn);
|
||||
IamService store = mock(IamService.class);
|
||||
when(store.findRole(ACCOUNT, "app")).thenReturn(Optional.of(role));
|
||||
|
||||
assertEquals(arn, resourceOf(backedBy(store), "Action=PutRolePolicy&RoleName=app"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A create names a resource that does not exist, so its ARN comes from the request's own
|
||||
* {@code Path}. Reading a stored path would resolve to the root and let a policy scoped to one
|
||||
* path authorize a create into another.
|
||||
*/
|
||||
@Test
|
||||
void iamMintsTheArnOfAResourceBeingCreated() {
|
||||
assertEquals("arn:aws:iam::000000000000:user/eng/bob",
|
||||
resourceOf(builder, "Action=CreateUser&UserName=bob&Path=/eng/"));
|
||||
assertEquals("arn:aws:iam::000000000000:role/app",
|
||||
resourceOf(builder, "Action=CreateRole&RoleName=app"));
|
||||
assertEquals("arn:aws:iam::000000000000:group/admins",
|
||||
resourceOf(builder, "Action=CreateGroup&GroupName=admins"));
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/ops/app",
|
||||
resourceOf(builder,
|
||||
"Action=CreateInstanceProfile&InstanceProfileName=app&Path=/ops/"));
|
||||
assertEquals("arn:aws:iam::000000000000:policy/team/p",
|
||||
resourceOf(builder, "Action=CreatePolicy&PolicyName=p&Path=/team/"));
|
||||
assertEquals("arn:aws:iam::000000000000:mfa/bob-key",
|
||||
resourceOf(builder,
|
||||
"Action=CreateVirtualMFADevice&VirtualMFADeviceName=bob-key"));
|
||||
}
|
||||
|
||||
/** A create is minted in the partition it is being created in, not the commercial one. */
|
||||
@Test
|
||||
void iamMintsACreateInTheRequestsPartition() {
|
||||
setFormBody("Action=CreateUser&UserName=bob");
|
||||
assertEquals("arn:aws-cn:iam::000000000000:user/bob",
|
||||
builder.build("iam", ctx, "cn-north-1", ACCOUNT));
|
||||
}
|
||||
|
||||
/**
|
||||
* A policy, MFA device, SAML provider or OIDC provider is named by an ARN the request already
|
||||
* carries, so it is passed through. Rebuilding it from parts would only invent a second
|
||||
* spelling of the resource the caller already named.
|
||||
*/
|
||||
@Test
|
||||
void iamPassesThroughAnArnTheRequestAlreadyCarries() {
|
||||
assertEquals("arn:aws:iam::000000000000:policy/team/p",
|
||||
resourceOf(builder, "Action=DeletePolicy"
|
||||
+ "&PolicyArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Apolicy%2Fteam%2Fp"));
|
||||
assertEquals("arn:aws:iam::000000000000:mfa/bob-key",
|
||||
resourceOf(builder, "Action=DeleteVirtualMFADevice"
|
||||
+ "&SerialNumber=arn%3Aaws%3Aiam%3A%3A000000000000%3Amfa%2Fbob-key"));
|
||||
assertEquals("arn:aws:iam::000000000000:saml-provider/corp",
|
||||
resourceOf(builder, "Action=GetSAMLProvider"
|
||||
+ "&SAMLProviderArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Asaml-provider%2Fcorp"));
|
||||
assertEquals("arn:aws:iam::000000000000:oidc-provider/example.com",
|
||||
resourceOf(builder, "Action=DeleteOpenIDConnectProvider"
|
||||
+ "&OpenIDConnectProviderArn="
|
||||
+ "arn%3Aaws%3Aiam%3A%3A000000000000%3Aoidc-provider%2Fexample.com"));
|
||||
assertEquals("arn:aws:iam::000000000000:user/bob",
|
||||
resourceOf(builder, "Action=SimulatePrincipalPolicy"
|
||||
+ "&PolicySourceArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Auser%2Fbob"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A SAML provider's ARN is its bare name and an OIDC provider's is its URL without the
|
||||
* scheme, neither of which carries a path. Minting them the way the pathed types are minted
|
||||
* would name resources that do not exist.
|
||||
*/
|
||||
@Test
|
||||
void iamMintsProviderArnsWithoutAPath() {
|
||||
assertEquals("arn:aws:iam::000000000000:saml-provider/corp",
|
||||
resourceOf(builder, "Action=CreateSAMLProvider&Name=corp"));
|
||||
assertEquals("arn:aws:iam::000000000000:oidc-provider/example.com/app",
|
||||
resourceOf(builder, "Action=CreateOpenIDConnectProvider"
|
||||
+ "&Url=https%3A%2F%2Fexample.com%2Fapp"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A user rename names both the old user and the new one, for the reason the API reference
|
||||
* gives: the requester "must have appropriate permissions on both the source object and the
|
||||
* target object". A group rename says the same in its own words.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesBothNamesOfAUserOrGroupRename() {
|
||||
String userArn = "arn:aws:iam::000000000000:user/bob";
|
||||
setFormBody("Action=UpdateUser&UserName=bob&NewUserName=robert");
|
||||
assertEquals(List.of(userArn, "arn:aws:iam::000000000000:user/robert"),
|
||||
backedBy(storeHolding("bob", "/", userArn))
|
||||
.buildResources("iam", ctx, "us-east-1", ACCOUNT));
|
||||
|
||||
String groupArn = "arn:aws:iam::000000000000:group/managers";
|
||||
IamGroup group = new IamGroup();
|
||||
group.setGroupName("managers");
|
||||
group.setPath("/");
|
||||
group.setArn(groupArn);
|
||||
IamService store = mock(IamService.class);
|
||||
when(store.findGroup(ACCOUNT, "managers")).thenReturn(Optional.of(group));
|
||||
setFormBody("Action=UpdateGroup&GroupName=managers&NewGroupName=mgrs");
|
||||
assertEquals(List.of(groupArn, "arn:aws:iam::000000000000:group/mgrs"),
|
||||
backedBy(store).buildResources("iam", ctx, "us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code CreateServiceLinkedRole} does not name the role it creates. AWS derives it from
|
||||
* {@code AWSServiceName}, so the same table the create reads gives the name, and the role
|
||||
* sits under the service-role path carrying the canonical principal.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheRoleAServiceLinkedCreateWouldMint() {
|
||||
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/autoscaling.amazonaws.com/"
|
||||
+ "AWSServiceRoleForAutoScaling",
|
||||
resourceOf(builder, "Action=CreateServiceLinkedRole"
|
||||
+ "&AWSServiceName=autoscaling.amazonaws.com"));
|
||||
// A suffix is part of the name AWS mints, so it is part of the resource too.
|
||||
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/autoscaling.amazonaws.com/"
|
||||
+ "AWSServiceRoleForAutoScaling_fleet",
|
||||
resourceOf(builder, "Action=CreateServiceLinkedRole"
|
||||
+ "&AWSServiceName=autoscaling.amazonaws.com&CustomSuffix=fleet"));
|
||||
// A principal the table does not carry keeps the derived name, which is what the create
|
||||
// mints for it: the two read the same table, so the check cannot name a different role.
|
||||
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/es.amazonaws.com/"
|
||||
+ "AWSServiceRoleForEs",
|
||||
resourceOf(builder,
|
||||
"Action=CreateServiceLinkedRole&AWSServiceName=es.amazonaws.com"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code GetAccessKeyLastUsed} is evaluated against a user, which is what the User Guide's own
|
||||
* {@code iam:*AccessKey*} example scopes to {@code user/${aws:username}}, but the request
|
||||
* names only the key, so the owner is resolved from it.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheUserOwningAnAccessKey() {
|
||||
String arn = "arn:aws:iam::000000000000:user/bob";
|
||||
IamService store = storeHolding("bob", "/", arn);
|
||||
when(store.findUserNameByAccessKeyId("AKIAEXAMPLE")).thenReturn(Optional.of("bob"));
|
||||
assertEquals(arn, resourceOf(backedBy(store),
|
||||
"Action=GetAccessKeyLastUsed&AccessKeyId=AKIAEXAMPLE"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A hardware MFA device's {@code SerialNumber} is a bare serial rather than an ARN, so there
|
||||
* is nothing to pass through and nothing a policy could be written against.
|
||||
*/
|
||||
@Test
|
||||
void iamFallsBackToTheWildcardForASerialThatIsNotAnArn() {
|
||||
assertEquals("*", resourceOf(builder,
|
||||
"Action=TagMFADevice&SerialNumber=GAHT12345678"));
|
||||
}
|
||||
|
||||
/**
|
||||
* An action whose resource the request does not name stays at {@code *}: the ones the
|
||||
* reference gives no resource type, and the ones that default to the calling user, whose
|
||||
* identity is the filter's to supply rather than this builder's.
|
||||
*/
|
||||
@Test
|
||||
void iamFallsBackToTheWildcardWhenTheRequestNamesNoResource() {
|
||||
for (String form : List.of("Action=ListUsers", "Action=GetAccountSummary",
|
||||
"Action=CreateAccountAlias&AccountAlias=corp", "Action=GetUser",
|
||||
"Action=ChangePassword", "Action=SimulateCustomPolicy")) {
|
||||
assertEquals("*", resourceOf(builder, form), form);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The deletion task identifier carries the role's path and name, in the format the action's
|
||||
* reference publishes, which is the only thing left to name: the role itself is already gone
|
||||
* by the time the status is asked for.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheRoleADeletionTaskIdentifies() {
|
||||
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/lex.amazonaws.com/"
|
||||
+ "AWSServiceRoleForLexBots",
|
||||
resourceOf(builder, "Action=GetServiceLinkedRoleDeletionStatus&DeletionTaskId="
|
||||
+ "task%2Faws-service-role%2Flex.amazonaws.com"
|
||||
+ "%2FAWSServiceRoleForLexBots%2F12345678-1234-1234-1234-123456789012"));
|
||||
// A malformed identifier names nothing rather than half a resource.
|
||||
for (String taskId : List.of("task%2Faws-service-role%2F", "nonsense", "task%2Fother%2Fx")) {
|
||||
assertEquals("*", resourceOf(builder,
|
||||
"Action=GetServiceLinkedRoleDeletionStatus&DeletionTaskId=" + taskId), taskId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An attach carries both a user and a policy ARN, and the reference gives it the user alone.
|
||||
* Taking the ARN the request happens to carry would scope it to the policy and let a deny on
|
||||
* the user pass, so the attaches stay out of the ARN-parameter table and this is what holds
|
||||
* them there: that table is read first, and an action in it never reaches the type the
|
||||
* vendored metadata gives.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheUserRatherThanThePolicyOnAnAttach() {
|
||||
String userArn = "arn:aws:iam::000000000000:user/bob";
|
||||
assertEquals(userArn,
|
||||
resourceOf(backedBy(storeHolding("bob", "/", userArn)),
|
||||
"Action=AttachUserPolicy&UserName=bob"
|
||||
+ "&PolicyArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Apolicy%2Fp"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource a certificate-specific policy statement has to match. Without this the action
|
||||
* is evaluated against {@code *}, so a deny naming the certificate never applies.
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
/**
|
||||
* Holds {@link ResourceArnBuilder}'s declared-unresolved resource types to the reason each one
|
||||
* gives. Every entry claims its type belongs only to actions the handler does not dispatch, and
|
||||
* that is a claim about the handler rather than about the builder, so nothing inside the builder
|
||||
* can check it.
|
||||
*
|
||||
* <p>It matters because the failure is silent and fail-open. Dispatching such an action without
|
||||
* teaching the resolver its type leaves the action evaluated against {@code *}, so a policy
|
||||
* statement naming the resource never applies, which is the gap this builder exists to close.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class UnresolvedResourceTypesIntegrationTest {
|
||||
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261010/us-east-1/iam/aws4_request";
|
||||
|
||||
@Test
|
||||
void everyTypeDeclaredUnresolvedIsCarriedOnlyByActionsNobodyDispatches() {
|
||||
assertFalse(ResourceArnBuilder.UNRESOLVED_TYPES.isEmpty(),
|
||||
"nothing is declared unresolved any more, so this test has nothing to hold");
|
||||
for (Map.Entry<String, String> declared : ResourceArnBuilder.UNRESOLVED_TYPES.entrySet()) {
|
||||
Set<String> actions = actionsCarrying(declared.getKey());
|
||||
assertFalse(actions.isEmpty(), declared.getKey()
|
||||
+ " is declared unresolved but AWS no longer gives it to any action, so the "
|
||||
+ "entry is dead and should go");
|
||||
for (String action : actions) {
|
||||
// The credential scope resolves the service, so this reaches the IAM handler
|
||||
// whether or not the action is routable by name, and an action the handler does
|
||||
// not dispatch falls to its default branch.
|
||||
Response response = given().header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", action)
|
||||
.when().post("/");
|
||||
// The status is read before the body: a dispatched action may answer with no
|
||||
// parseable body at all, and the reason for failing is the same either way.
|
||||
assertEquals(400, response.statusCode(), reason(declared, action));
|
||||
assertEquals("UnsupportedOperation",
|
||||
response.xmlPath().getString("ErrorResponse.Error.Code"),
|
||||
reason(declared, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String reason(Map.Entry<String, String> declared, String action) {
|
||||
return action + " is dispatched now, so '" + declared.getKey() + "' is no longer a type "
|
||||
+ "only undispatched actions carry (" + declared.getValue() + "). Resolve it in "
|
||||
+ "ResourceArnBuilder rather than leaving it declared, or the action is evaluated "
|
||||
+ "against * and a policy naming the resource never applies";
|
||||
}
|
||||
|
||||
private static Set<String> actionsCarrying(String resourceType) {
|
||||
Set<String> actions = new TreeSet<>();
|
||||
for (Map.Entry<String, List<String>> entry : IamActionResources.all().entrySet()) {
|
||||
if (entry.getValue().contains(resourceType)) {
|
||||
actions.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
return actions;
|
||||
}
|
||||
}
|
||||
@@ -28,10 +28,10 @@ public final class EnforcementFixtures {
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an IAM user, and first the inline policies and access keys that IAM wants gone
|
||||
* before it will. The IAM API reference lists "Access keys (DeleteAccessKey)" and "Inline
|
||||
* policies (DeleteUserPolicy)" among the items to remove "before attempting to delete a
|
||||
* user", and Floci answers {@code DeleteConflict} for each of them.
|
||||
* Deletes an IAM user, and first everything IAM wants gone before it will: inline policies,
|
||||
* access keys, group memberships and attached managed policies. The IAM API reference lists
|
||||
* all four among the items to remove "before attempting to delete a user", and Floci answers
|
||||
* {@code DeleteConflict} for each of them.
|
||||
*
|
||||
* @param authorization an IAM-scoped header. Signing with an account id reaches that
|
||||
* account's namespace as its root stand-in, which is how a user outside
|
||||
@@ -55,6 +55,20 @@ public final class EnforcementFixtures {
|
||||
iam(port, authorization, "DeleteAccessKey", "UserName", userName,
|
||||
"AccessKeyId", accessKeyId).statusCode(200);
|
||||
}
|
||||
for (String groupName : iam(port, authorization, "ListGroupsForUser",
|
||||
"UserName", userName).statusCode(200).extract().xmlPath()
|
||||
.getList("ListGroupsForUserResponse.ListGroupsForUserResult.Groups.member"
|
||||
+ ".GroupName", String.class)) {
|
||||
iam(port, authorization, "RemoveUserFromGroup", "GroupName", groupName,
|
||||
"UserName", userName).statusCode(200);
|
||||
}
|
||||
for (String policyArn : iam(port, authorization, "ListAttachedUserPolicies",
|
||||
"UserName", userName).statusCode(200).extract().xmlPath()
|
||||
.getList("ListAttachedUserPoliciesResponse.ListAttachedUserPoliciesResult"
|
||||
+ ".AttachedPolicies.member.PolicyArn", String.class)) {
|
||||
iam(port, authorization, "DetachUserPolicy", "UserName", userName,
|
||||
"PolicyArn", policyArn).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteUser", "UserName", userName).statusCode(200);
|
||||
}
|
||||
|
||||
@@ -66,6 +80,98 @@ public final class EnforcementFixtures {
|
||||
*
|
||||
* @param authorization an S3-scoped header for an identity allowed to read and delete here
|
||||
*/
|
||||
/**
|
||||
* Deletes a managed policy, and first the versions and attachments IAM wants gone before it
|
||||
* will. Returns quietly when the policy is already absent, so a caller can register the
|
||||
* removal before creating it.
|
||||
*/
|
||||
public static void removePolicy(int port, String authorization, String policyArn) {
|
||||
if (iam(port, authorization, "GetPolicy", "PolicyArn", policyArn)
|
||||
.extract().statusCode() == 404) {
|
||||
return;
|
||||
}
|
||||
iam(port, authorization, "DeletePolicy", "PolicyArn", policyArn).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a role, and first the policies it carries: Floci answers {@code DeleteConflict},
|
||||
* "must detach all policies first", for a role holding either an inline or a managed one.
|
||||
*/
|
||||
public static void removeRole(int port, String authorization, String roleName) {
|
||||
if (iam(port, authorization, "GetRole", "RoleName", roleName)
|
||||
.extract().statusCode() == 404) {
|
||||
return;
|
||||
}
|
||||
for (String policyName : iam(port, authorization, "ListRolePolicies", "RoleName", roleName)
|
||||
.statusCode(200).extract().xmlPath()
|
||||
.getList("ListRolePoliciesResponse.ListRolePoliciesResult.PolicyNames.member",
|
||||
String.class)) {
|
||||
iam(port, authorization, "DeleteRolePolicy", "RoleName", roleName,
|
||||
"PolicyName", policyName).statusCode(200);
|
||||
}
|
||||
for (String policyArn : iam(port, authorization, "ListAttachedRolePolicies",
|
||||
"RoleName", roleName).statusCode(200).extract().xmlPath()
|
||||
.getList("ListAttachedRolePoliciesResponse.ListAttachedRolePoliciesResult"
|
||||
+ ".AttachedPolicies.member.PolicyArn", String.class)) {
|
||||
iam(port, authorization, "DetachRolePolicy", "RoleName", roleName,
|
||||
"PolicyArn", policyArn).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteRole", "RoleName", roleName).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an instance profile, taking any role out of it first: AWS requires the profile to
|
||||
* hold no role before it can go, and the role is a separate resource with its own removal.
|
||||
*/
|
||||
public static void removeInstanceProfile(int port, String authorization, String profileName) {
|
||||
if (iam(port, authorization, "GetInstanceProfile", "InstanceProfileName", profileName)
|
||||
.extract().statusCode() == 404) {
|
||||
return;
|
||||
}
|
||||
for (String roleName : iam(port, authorization, "GetInstanceProfile",
|
||||
"InstanceProfileName", profileName).statusCode(200).extract().xmlPath()
|
||||
.getList("GetInstanceProfileResponse.GetInstanceProfileResult.InstanceProfile"
|
||||
+ ".Roles.member.RoleName", String.class)) {
|
||||
iam(port, authorization, "RemoveRoleFromInstanceProfile",
|
||||
"InstanceProfileName", profileName, "RoleName", roleName).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteInstanceProfile",
|
||||
"InstanceProfileName", profileName).statusCode(200);
|
||||
}
|
||||
|
||||
/** Deletes a group, and first the users in it, which IAM wants gone before it will. */
|
||||
public static void removeGroup(int port, String authorization, String groupName) {
|
||||
if (iam(port, authorization, "GetGroup", "GroupName", groupName)
|
||||
.extract().statusCode() == 404) {
|
||||
return;
|
||||
}
|
||||
for (String userName : iam(port, authorization, "GetGroup", "GroupName", groupName)
|
||||
.statusCode(200).extract().xmlPath()
|
||||
.getList("GetGroupResponse.GetGroupResult.Users.member.UserName", String.class)) {
|
||||
iam(port, authorization, "RemoveUserFromGroup",
|
||||
"GroupName", groupName, "UserName", userName).statusCode(200);
|
||||
}
|
||||
for (String policyName : iam(port, authorization, "ListGroupPolicies",
|
||||
"GroupName", groupName).statusCode(200).extract().xmlPath()
|
||||
.getList("ListGroupPoliciesResponse.ListGroupPoliciesResult.PolicyNames.member",
|
||||
String.class)) {
|
||||
iam(port, authorization, "DeleteGroupPolicy", "GroupName", groupName,
|
||||
"PolicyName", policyName).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteGroup", "GroupName", groupName).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a virtual MFA device, a SAML provider or an OIDC provider, each named by the ARN it
|
||||
* was created with. One method because the three take the same shape: an ARN parameter, a
|
||||
* delete that needs nothing removed first, and no read that distinguishes absent from denied,
|
||||
* so a delete of something already gone is accepted rather than asserted on.
|
||||
*/
|
||||
public static void removeByArn(int port, String authorization, String action,
|
||||
String parameter, String arn) {
|
||||
iam(port, authorization, action, parameter, arn);
|
||||
}
|
||||
|
||||
public static void removeBucket(int port, String authorization, String bucket) {
|
||||
if (s3(port, authorization).when().head("/" + bucket)
|
||||
.then().extract().statusCode() == 404) {
|
||||
|
||||
Executable
+342
@@ -0,0 +1,342 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate src/main/resources/aws/iam-action-resources.json from AWS's own IAM metadata.
|
||||
|
||||
Under IAM enforcement every request is authorized against a resource, and for an IAM action the
|
||||
resource is whichever of IAM's own entities the action acts on. That is not derivable from the
|
||||
request: `AddUserToGroup` takes a `UserName` and a `GroupName` and is authorized against the
|
||||
group, `AddRoleToInstanceProfile` takes a `RoleName` and is authorized against the instance
|
||||
profile, and `EnableMFADevice` takes a `SerialNumber` and is authorized against the user rather
|
||||
than the device. Reading the type off the parameters would scope those to the wrong resource and
|
||||
let a deny on the right one pass, so it has to come from AWS.
|
||||
|
||||
botocore is not the source here, as in `regen_service_namespaces.py` and for the same kind of
|
||||
reason: a botocore operation model describes the wire shape and says nothing about what IAM
|
||||
authorizes the operation against. AWS publishes that separately, per action, in the Service
|
||||
Reference Information for IAM:
|
||||
|
||||
https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json
|
||||
|
||||
Each action there carries the resource types it can be authorized against, and each type carries
|
||||
the ARN formats AWS mints it in. Both halves are vendored: the types decide which entity a request
|
||||
names, and the formats are what `ResourceArnBuilder` checks its own minting against, so a prefix
|
||||
that drifts from AWS fails at startup rather than producing an ARN no policy matches.
|
||||
|
||||
That endpoint is live rather than a pinned dependency, so a fresh generation is not byte-identical:
|
||||
AWS adds actions whenever it ships them. Byte-equality is therefore the wrong gate. What must be
|
||||
guaranteed is that nothing here is invented, which is checkable directly:
|
||||
|
||||
- `--check` is offline and structural. Sorted, duplicate-free, every action name usable, every
|
||||
resource type usable, and it must still carry the cases that justify not deriving this from the
|
||||
request (`AddUserToGroup` against the group, `EnableMFADevice` against the user, `ListUsers`
|
||||
against nothing). This catches corruption and hand-editing.
|
||||
- `--verify` is the real gate and needs the network. Every resource type the vendored file claims
|
||||
for an action must still be one AWS gives that action. A hand-typed type fails, and so does a
|
||||
type AWS has taken away, because the file then authorizes against something AWS does not. An
|
||||
action or a type AWS has *added* is reported without failing: being behind means Floci evaluates
|
||||
that action against `*`, which is where it was before any of this existed, so it is incomplete
|
||||
rather than wrong, and failing on it would break this repo's build for someone else's launch.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_iam_action_resources.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_iam_action_resources.py --check # offline: shape of the vendored file
|
||||
python3 tools/aws/regen_iam_action_resources.py --verify # online: nothing in it is invented
|
||||
python3 tools/aws/regen_iam_action_resources.py --source <file> # read a saved copy instead
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-action-resources.json"
|
||||
REFERENCE_URL = "https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json"
|
||||
FETCH_TIMEOUT_SECONDS = 30
|
||||
|
||||
# An IAM action name as it arrives in the Query `Action` field.
|
||||
ACTION_RE = re.compile(r"^[A-Z][A-Za-z0-9]{0,127}$")
|
||||
# A resource type as the reference names it, which is also the ARN's resource prefix.
|
||||
RESOURCE_TYPE_RE = re.compile(r"^[a-z][a-z0-9-]{0,63}$")
|
||||
# An ARN format with the reference's own ${Placeholder} segments left in. The region is always
|
||||
# empty for IAM and the account is usually ${Account}, but role-template publishes a literal `aws`
|
||||
# there and carries a colon inside its resource part, so neither segment is pinned to one spelling.
|
||||
ARN_FORMAT_RE = re.compile(r"^arn:\$\{Partition}:iam:[^:]*:[^:]*:\S+$")
|
||||
|
||||
# Cases whose value is the whole point of vendoring this rather than reading the request. Each is
|
||||
# an action whose resource is not the thing its parameters most obviously name, plus one action
|
||||
# that is authorized against nothing at all.
|
||||
ANCHORS = {
|
||||
"AddUserToGroup": ["group"],
|
||||
"RemoveUserFromGroup": ["group"],
|
||||
"AddRoleToInstanceProfile": ["instance-profile"],
|
||||
"EnableMFADevice": ["user"],
|
||||
"DeactivateMFADevice": ["user"],
|
||||
"CreateUser": ["user"],
|
||||
"ListUsers": [],
|
||||
}
|
||||
|
||||
|
||||
def fetch_reference(source: Path | None) -> tuple[dict, str]:
|
||||
"""AWS's IAM service reference and a provenance label for where it came from."""
|
||||
if source is not None:
|
||||
return json.loads(source.read_text(encoding="utf-8")), f"--source {source}"
|
||||
request = urllib.request.Request(REFERENCE_URL, headers={"Accept": "application/json"})
|
||||
with urllib.request.urlopen(request, timeout=FETCH_TIMEOUT_SECONDS) as response:
|
||||
payload = response.read().decode("utf-8")
|
||||
return json.loads(payload), REFERENCE_URL
|
||||
|
||||
|
||||
def action_resources_from(reference: dict) -> dict[str, list[str]]:
|
||||
"""Every action the reference publishes, mapped to the resource types it names, sorted.
|
||||
|
||||
An action with no resource type keeps an empty list rather than being left out, so the Java
|
||||
side can tell "AWS authorizes this against nothing" from "AWS has an action we have not
|
||||
vendored yet". The first is a wildcard on purpose; the second is a gap to close.
|
||||
"""
|
||||
actions = reference.get("Actions")
|
||||
if not isinstance(actions, list) or not actions:
|
||||
raise ValueError("the IAM service reference must carry a non-empty Actions list")
|
||||
found: dict[str, list[str]] = {}
|
||||
for action in actions:
|
||||
if not isinstance(action, dict) or "Name" not in action:
|
||||
raise ValueError(f"action entry without a 'Name' field: {action!r}")
|
||||
name = action["Name"]
|
||||
if not ACTION_RE.match(name):
|
||||
raise ValueError(f"{name!r} is not usable as an IAM action name")
|
||||
types = sorted({resource["Name"] for resource in action.get("Resources", [])})
|
||||
for resource_type in types:
|
||||
if not RESOURCE_TYPE_RE.match(resource_type):
|
||||
raise ValueError(f"{resource_type!r} is not usable as an IAM resource type")
|
||||
found[name] = types
|
||||
return dict(sorted(found.items()))
|
||||
|
||||
|
||||
def arn_formats_from(reference: dict) -> dict[str, list[str]]:
|
||||
"""Every resource type the reference publishes, mapped to its ARN formats, sorted."""
|
||||
resources = reference.get("Resources")
|
||||
if not isinstance(resources, list) or not resources:
|
||||
raise ValueError("the IAM service reference must carry a non-empty Resources list")
|
||||
found: dict[str, list[str]] = {}
|
||||
for resource in resources:
|
||||
if not isinstance(resource, dict) or "Name" not in resource:
|
||||
raise ValueError(f"resource entry without a 'Name' field: {resource!r}")
|
||||
name = resource["Name"]
|
||||
if not RESOURCE_TYPE_RE.match(name):
|
||||
raise ValueError(f"{name!r} is not usable as an IAM resource type")
|
||||
formats = sorted(resource.get("ARNFormats", []))
|
||||
for arn_format in formats:
|
||||
if not ARN_FORMAT_RE.match(arn_format):
|
||||
raise ValueError(f"{arn_format!r} is not an IAM ARN format")
|
||||
found[name] = formats
|
||||
return dict(sorted(found.items()))
|
||||
|
||||
|
||||
def build(reference: dict, provenance: str) -> dict:
|
||||
return {
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_iam_action_resources.py",
|
||||
"reference": provenance,
|
||||
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||
"note": "make iam-action-resources-verify checks every entry against AWS.",
|
||||
},
|
||||
"actionResources": action_resources_from(reference),
|
||||
"resourceArnFormats": arn_formats_from(reference),
|
||||
}
|
||||
|
||||
|
||||
def render(document: dict) -> str:
|
||||
return json.dumps(document, indent=2) + "\n"
|
||||
|
||||
|
||||
def validate(document: dict) -> list[str]:
|
||||
"""Problems that make the vendored file unusable, rather than merely out of date."""
|
||||
problems: list[str] = []
|
||||
actions = document.get("actionResources")
|
||||
formats = document.get("resourceArnFormats")
|
||||
if not isinstance(actions, dict) or not actions:
|
||||
return ["actionResources is missing or empty"]
|
||||
if not isinstance(formats, dict) or not formats:
|
||||
problems.append("resourceArnFormats is missing or empty")
|
||||
formats = {}
|
||||
if list(actions) != sorted(actions):
|
||||
problems.append("actionResources is not sorted by action name")
|
||||
if list(formats) != sorted(formats):
|
||||
problems.append("resourceArnFormats is not sorted by resource type")
|
||||
for action, types in actions.items():
|
||||
if not ACTION_RE.match(action):
|
||||
problems.append(f"{action!r} is not usable as an IAM action name")
|
||||
if not isinstance(types, list):
|
||||
problems.append(f"{action!r} does not carry a list of resource types")
|
||||
continue
|
||||
if types != sorted(types):
|
||||
problems.append(f"{action!r} lists its resource types out of order")
|
||||
if len(types) != len(set(types)):
|
||||
problems.append(f"{action!r} lists a resource type twice")
|
||||
for resource_type in types:
|
||||
if not isinstance(resource_type, str) or not RESOURCE_TYPE_RE.match(resource_type):
|
||||
problems.append(f"{action!r} names {resource_type!r}, which is not a resource type")
|
||||
elif resource_type not in formats:
|
||||
problems.append(f"{action!r} names {resource_type!r}, which has no ARN format")
|
||||
for resource_type, arn_formats in formats.items():
|
||||
if not isinstance(arn_formats, list) or not arn_formats:
|
||||
problems.append(f"{resource_type!r} carries no ARN format")
|
||||
continue
|
||||
for arn_format in arn_formats:
|
||||
if not isinstance(arn_format, str) or not ARN_FORMAT_RE.match(arn_format):
|
||||
problems.append(f"{resource_type!r} carries {arn_format!r}, not an ARN format")
|
||||
for action, expected in ANCHORS.items():
|
||||
if action not in actions:
|
||||
problems.append(f"expected {action!r} to be present")
|
||||
elif actions[action] != expected:
|
||||
problems.append(f"{action!r} should be authorized against {expected}, "
|
||||
f"not {actions[action]}")
|
||||
return problems
|
||||
|
||||
|
||||
def verify_against(vendored: dict[str, list[str]],
|
||||
upstream: dict[str, list[str]]) -> tuple[list[str], list[str]]:
|
||||
"""What the vendored file claims and AWS does not, and what AWS has since added.
|
||||
|
||||
A type the file claims for an action AWS does not give it is a failure: the request would be
|
||||
authorized 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 only a file that is behind.
|
||||
"""
|
||||
untrue: list[str] = []
|
||||
added: list[str] = []
|
||||
for action, types in vendored.items():
|
||||
if action not in upstream:
|
||||
untrue.append(f"{action!r} is not an action AWS publishes")
|
||||
continue
|
||||
for resource_type in types:
|
||||
if resource_type not in upstream[action]:
|
||||
untrue.append(f"{action!r} is not authorized against {resource_type!r} by AWS")
|
||||
for action, types in upstream.items():
|
||||
if action not in vendored:
|
||||
added.append(f"{action} (new action)")
|
||||
continue
|
||||
for resource_type in types:
|
||||
if resource_type not in vendored[action]:
|
||||
added.append(f"{action} -> {resource_type}")
|
||||
return untrue, sorted(added)
|
||||
|
||||
|
||||
def verify_formats_against(vendored: dict[str, list[str]],
|
||||
upstream: dict[str, list[str]]) -> tuple[list[str], list[str]]:
|
||||
"""What the vendored ARN formats claim and AWS does not, and what AWS has since added.
|
||||
|
||||
Checked separately from the action mapping because a format drifts invisibly: the shape check
|
||||
only asks whether it looks like an IAM ARN, and a changed one still does. The minting reads
|
||||
the type's format to place the resource type, so a vendored format AWS no longer publishes
|
||||
means a right-looking file building a wrong ARN.
|
||||
"""
|
||||
untrue: list[str] = []
|
||||
added: list[str] = []
|
||||
for resource_type, formats in vendored.items():
|
||||
if resource_type not in upstream:
|
||||
untrue.append(f"{resource_type!r} is not a resource type AWS publishes")
|
||||
continue
|
||||
for arn_format in formats:
|
||||
if arn_format not in upstream[resource_type]:
|
||||
untrue.append(f"AWS does not spell a {resource_type} ARN as {arn_format!r}")
|
||||
for resource_type, formats in upstream.items():
|
||||
if resource_type not in vendored:
|
||||
added.append(f"{resource_type} (new resource type)")
|
||||
continue
|
||||
for arn_format in formats:
|
||||
if arn_format not in vendored[resource_type]:
|
||||
added.append(f"{resource_type} -> {arn_format}")
|
||||
return untrue, sorted(added)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--check", action="store_true",
|
||||
help="offline: validate the shape of the vendored file")
|
||||
parser.add_argument("--verify", action="store_true",
|
||||
help="online: nothing in the vendored file is invented")
|
||||
parser.add_argument("--source", type=Path, default=None,
|
||||
help="read a saved copy of the reference instead of fetching it")
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.check:
|
||||
if not args.output.exists():
|
||||
print(f"error: {args.output} does not exist", file=sys.stderr)
|
||||
return 1
|
||||
document = json.loads(args.output.read_text(encoding="utf-8"))
|
||||
problems = validate(document)
|
||||
for problem in problems:
|
||||
print(f"error: {problem}", file=sys.stderr)
|
||||
if problems:
|
||||
return 1
|
||||
scoped = sum(1 for types in document["actionResources"].values() if types)
|
||||
print(f"{args.output.relative_to(REPO_ROOT)} is well-formed "
|
||||
f"({len(document['actionResources'])} actions, {scoped} with a resource type, "
|
||||
f"{len(document['resourceArnFormats'])} resource types)")
|
||||
return 0
|
||||
|
||||
if args.verify:
|
||||
if not args.output.exists():
|
||||
print(f"error: {args.output} does not exist", file=sys.stderr)
|
||||
return 1
|
||||
document = json.loads(args.output.read_text(encoding="utf-8"))
|
||||
vendored = document["actionResources"]
|
||||
vendored_formats = document.get("resourceArnFormats", {})
|
||||
try:
|
||||
reference, provenance = fetch_reference(args.source)
|
||||
upstream = action_resources_from(reference)
|
||||
upstream_formats = arn_formats_from(reference)
|
||||
except (OSError, ValueError) as e:
|
||||
# Distinct from a data problem: the gate could not run, rather than having found
|
||||
# something invented. Separate exit code so CI can tell the two apart. ValueError
|
||||
# covers a malformed reference, including the JSONDecodeError a truncated or non-JSON
|
||||
# response raises, which is just as much "could not verify" as an unreachable host.
|
||||
print(f"error: could not read the IAM service reference ({e})", file=sys.stderr)
|
||||
return 2
|
||||
untrue, added = verify_against(vendored, upstream)
|
||||
format_untrue, format_added = verify_formats_against(vendored_formats, upstream_formats)
|
||||
untrue += format_untrue
|
||||
added += format_added
|
||||
for claim in untrue:
|
||||
print(f"error: {claim}", file=sys.stderr)
|
||||
if untrue:
|
||||
print(f"error: {len(untrue)} vendored claim(s) do not hold upstream; the file would "
|
||||
f"authorize against a resource AWS does not use.", file=sys.stderr)
|
||||
return 1
|
||||
if added:
|
||||
print(f"{args.output.relative_to(REPO_ROOT)}: all {len(vendored)} actions verified. "
|
||||
f"AWS has since added {len(added)}, so the mapping is incomplete but not wrong "
|
||||
f"(run without --verify to refresh): {', '.join(added[:10])}"
|
||||
f"{'...' if len(added) > 10 else ''}")
|
||||
else:
|
||||
print(f"{args.output.relative_to(REPO_ROOT)}: all {len(vendored)} actions and "
|
||||
f"{len(vendored_formats)} ARN formats verified against {provenance}, nothing "
|
||||
f"added upstream.")
|
||||
return 0
|
||||
|
||||
try:
|
||||
reference, provenance = fetch_reference(args.source)
|
||||
document = build(reference, provenance)
|
||||
except (OSError, ValueError) as e:
|
||||
print(f"error: could not read the IAM service reference ({e})", file=sys.stderr)
|
||||
return 2
|
||||
problems = validate(document)
|
||||
for problem in problems:
|
||||
print(f"error: {problem}", file=sys.stderr)
|
||||
if problems:
|
||||
return 1
|
||||
args.output.write_text(render(document), encoding="utf-8")
|
||||
scoped = sum(1 for types in document["actionResources"].values() if types)
|
||||
print(f"wrote {args.output.relative_to(REPO_ROOT)} "
|
||||
f"({len(document['actionResources'])} actions, {scoped} with a resource type, "
|
||||
f"from {provenance})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Tests for regen_iam_action_resources.
|
||||
|
||||
Run with: pytest tools/aws -q (or: make iam-action-resources-test)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import regen_iam_action_resources as r
|
||||
|
||||
|
||||
def reference(actions: dict[str, list[str]], types: list[str] | None = None) -> dict:
|
||||
"""A reference payload shaped like AWS's, with an ARN format for every type mentioned."""
|
||||
if types is None:
|
||||
types = sorted({t for names in actions.values() for t in names})
|
||||
return {
|
||||
"Name": "iam",
|
||||
"Actions": [{"Name": name, "Resources": [{"Name": t} for t in resource_types]}
|
||||
for name, resource_types in actions.items()],
|
||||
"Resources": [{"Name": t,
|
||||
"ARNFormats": ["arn:${Partition}:iam::${Account}:" + t + "/${Name}"]}
|
||||
for t in types],
|
||||
}
|
||||
|
||||
|
||||
def document(actions: dict[str, list[str]], types: list[str] | None = None) -> dict:
|
||||
return r.build(reference(actions, types), "a test")
|
||||
|
||||
|
||||
ANCHORED = {
|
||||
"AddUserToGroup": ["group"],
|
||||
"RemoveUserFromGroup": ["group"],
|
||||
"AddRoleToInstanceProfile": ["instance-profile"],
|
||||
"EnableMFADevice": ["user"],
|
||||
"DeactivateMFADevice": ["user"],
|
||||
"CreateUser": ["user"],
|
||||
"ListUsers": [],
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# action_resources_from: what the reference is allowed to contain
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_actions_are_sorted_and_their_types_deduplicated():
|
||||
parsed = r.action_resources_from(reference({
|
||||
"GetUser": ["user"],
|
||||
"AddUserToGroup": ["group", "group"],
|
||||
}))
|
||||
assert list(parsed) == ["AddUserToGroup", "GetUser"]
|
||||
assert parsed["AddUserToGroup"] == ["group"]
|
||||
|
||||
|
||||
def test_an_action_with_no_resource_keeps_an_empty_list():
|
||||
# Kept rather than dropped so the Java side can tell "authorized against nothing" from
|
||||
# "an action we have not vendored yet". Both read as the wildcard; only one is a gap.
|
||||
assert r.action_resources_from(reference({"ListUsers": []}))["ListUsers"] == []
|
||||
|
||||
|
||||
def test_several_resource_types_are_all_kept():
|
||||
parsed = r.action_resources_from(reference({"SimulatePrincipalPolicy": ["user", "role", "group"]}))
|
||||
assert parsed["SimulatePrincipalPolicy"] == ["group", "role", "user"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
{"Name": "iam"},
|
||||
{"Name": "iam", "Actions": []},
|
||||
{"Name": "iam", "Actions": [{"Resources": []}]},
|
||||
])
|
||||
def test_malformed_reference_is_rejected(payload):
|
||||
with pytest.raises(ValueError):
|
||||
r.action_resources_from(payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["getUser", "Get User", "", "Get-User"])
|
||||
def test_an_unusable_action_name_is_rejected(action):
|
||||
with pytest.raises(ValueError):
|
||||
r.action_resources_from(reference({action: ["user"]}))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("resource_type", ["User", "my_type", "", "user/name"])
|
||||
def test_an_unusable_resource_type_is_rejected(resource_type):
|
||||
with pytest.raises(ValueError):
|
||||
r.action_resources_from(reference({"GetUser": [resource_type]}))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# arn_formats_from: the other half, which is what the minting is checked against
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_arn_formats_are_kept_per_type():
|
||||
formats = r.arn_formats_from(reference({"GetUser": ["user"]}))
|
||||
assert formats["user"] == ["arn:${Partition}:iam::${Account}:user/${Name}"]
|
||||
|
||||
|
||||
def test_the_role_template_format_aws_actually_publishes_is_accepted():
|
||||
# Its account segment is a literal `aws` and its resource part carries a colon, so a pattern
|
||||
# pinned to ${Account} and a colon-free resource would reject real AWS data.
|
||||
payload = {
|
||||
"Name": "iam",
|
||||
"Actions": [{"Name": "AcquireRole", "Resources": [{"Name": "role-template"}]}],
|
||||
"Resources": [{"Name": "role-template", "ARNFormats": [
|
||||
"arn:${Partition}:iam::aws:role-template/${AWSServicePrincipal}"
|
||||
"/${RoleTemplateName}:${RoleTemplateMajorVersion}"]}],
|
||||
}
|
||||
assert "role-template" in r.arn_formats_from(payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arn_format", [
|
||||
"arn:aws:iam::123456789012:user/bob",
|
||||
"arn:${Partition}:s3:::${Account}:bucket",
|
||||
"user/${Name}",
|
||||
])
|
||||
def test_something_that_is_not_an_iam_arn_format_is_rejected(arn_format):
|
||||
payload = {
|
||||
"Name": "iam",
|
||||
"Actions": [{"Name": "GetUser", "Resources": [{"Name": "user"}]}],
|
||||
"Resources": [{"Name": "user", "ARNFormats": [arn_format]}],
|
||||
}
|
||||
with pytest.raises(ValueError):
|
||||
r.arn_formats_from(payload)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# validate: what makes the vendored file unusable rather than merely behind
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_a_freshly_built_document_validates():
|
||||
assert r.validate(document(ANCHORED)) == []
|
||||
|
||||
|
||||
def test_an_anchor_authorized_against_the_wrong_resource_is_rejected():
|
||||
# The case the whole file exists for: AddUserToGroup is authorized against the group, not the
|
||||
# user its UserName names. A map that said otherwise would let a deny on the group pass.
|
||||
wrong = dict(ANCHORED)
|
||||
wrong["AddUserToGroup"] = ["user"]
|
||||
problems = r.validate(document(wrong))
|
||||
assert any("AddUserToGroup" in problem for problem in problems)
|
||||
|
||||
|
||||
def test_a_missing_anchor_is_rejected():
|
||||
missing = {name: types for name, types in ANCHORED.items() if name != "EnableMFADevice"}
|
||||
assert any("EnableMFADevice" in problem for problem in r.validate(document(missing)))
|
||||
|
||||
|
||||
def test_an_unsorted_map_is_rejected():
|
||||
doc = document(ANCHORED)
|
||||
doc["actionResources"] = {"ListUsers": [], "AddUserToGroup": ["group"]}
|
||||
assert any("not sorted" in problem for problem in r.validate(doc))
|
||||
|
||||
|
||||
def test_a_resource_type_with_no_arn_format_is_rejected():
|
||||
doc = document(ANCHORED)
|
||||
doc["actionResources"]["GetRole"] = ["role"]
|
||||
assert any("no ARN format" in problem for problem in r.validate(doc))
|
||||
|
||||
|
||||
def test_an_empty_map_is_rejected():
|
||||
assert r.validate({"actionResources": {}, "resourceArnFormats": {}}) == [
|
||||
"actionResources is missing or empty"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# verify_against: the online gate's judgement
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_a_claim_aws_does_not_make_fails():
|
||||
# A swapped type reads as both at once: the vendored `user` is untrue, and the `group` AWS
|
||||
# gives is missing. The untrue half is what fails the gate.
|
||||
untrue, added = r.verify_against({"AddUserToGroup": ["user"]}, {"AddUserToGroup": ["group"]})
|
||||
assert untrue == ["'AddUserToGroup' is not authorized against 'user' by AWS"]
|
||||
assert added == ["AddUserToGroup -> group"]
|
||||
|
||||
|
||||
def test_an_action_aws_no_longer_publishes_fails():
|
||||
untrue, _ = r.verify_against({"RetiredAction": ["user"]}, {"GetUser": ["user"]})
|
||||
assert any("RetiredAction" in claim for claim in untrue)
|
||||
|
||||
|
||||
def test_a_new_action_upstream_is_reported_without_failing():
|
||||
untrue, added = r.verify_against({"GetUser": ["user"]},
|
||||
{"GetUser": ["user"], "NewAction": ["role"]})
|
||||
assert not untrue
|
||||
assert added == ["NewAction (new action)"]
|
||||
|
||||
|
||||
def test_a_type_aws_has_added_to_a_known_action_is_reported_without_failing():
|
||||
# Being behind leaves that action on the wildcard, which is where it started. Wrong is worse
|
||||
# than incomplete, so only the first direction fails.
|
||||
untrue, added = r.verify_against({"GetUser": ["user"]}, {"GetUser": ["user", "role"]})
|
||||
assert not untrue
|
||||
assert added == ["GetUser -> role"]
|
||||
|
||||
|
||||
def test_an_identical_map_verifies_clean():
|
||||
assert r.verify_against({"GetUser": ["user"]}, {"GetUser": ["user"]}) == ([], [])
|
||||
|
||||
def test_a_drifted_arn_format_fails():
|
||||
# The gap the shape check cannot see: a changed format is still a well-formed one, so only a
|
||||
# comparison with AWS catches it, and the minting places the resource type from this string.
|
||||
untrue, added = r.verify_formats_against(
|
||||
{"user": ["arn:${Partition}:iam::${Account}:user/${UserName}"]},
|
||||
{"user": ["arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"]})
|
||||
assert untrue == ["AWS does not spell a user ARN as "
|
||||
"'arn:${Partition}:iam::${Account}:user/${UserName}'"]
|
||||
assert added == ["user -> arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"]
|
||||
|
||||
|
||||
def test_a_resource_type_aws_does_not_publish_fails():
|
||||
untrue, added = r.verify_formats_against(
|
||||
{"make-believe": ["arn:${Partition}:iam::${Account}:make-believe/${Name}"]},
|
||||
{"user": ["arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"]})
|
||||
assert untrue == ["'make-believe' is not a resource type AWS publishes"]
|
||||
assert added == ["user (new resource type)"]
|
||||
|
||||
|
||||
def test_an_arn_format_aws_added_is_reported_without_failing():
|
||||
untrue, added = r.verify_formats_against(
|
||||
{"user": ["arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"]},
|
||||
{"user": ["arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"],
|
||||
"role": ["arn:${Partition}:iam::${Account}:role/${RoleNameWithPath}"]})
|
||||
assert not untrue
|
||||
assert added == ["role (new resource type)"]
|
||||
|
||||
|
||||
def test_matching_formats_verify_clean():
|
||||
formats = {"user": ["arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"]}
|
||||
assert r.verify_formats_against(formats, dict(formats)) == ([], [])
|
||||
Reference in new issue
Block a user