diff --git a/docs/services/iam.md b/docs/services/iam.md index 92cc9ac523..90e5f51033 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3099,8 +3099,40 @@ floci populates: `GenerateOrganizationsAccessReport`. - `iam:DelegationRequestOwner` from `OwnerId` on `ListDelegationRequests`, which is how the owner grant scopes a holder's listing to its own requests. The seven other delegation - actions the Service Reference lists the key on read it from the stored request rather than - from a parameter, so they stay in `notRead`. + actions take the key from the request they name rather than from a parameter, which the + `fromResource` entries below do. + + The table's `fromResource` entries read a key the Service Reference publishes on a resource + type rather than on an action, which makes its value the stored resource's rather than the + request's. One key is published that way: `iam:DelegationRequestOwner`, on + `delegation-request`, for `AcceptDelegationRequest`, `AssociateDelegationRequest`, + `CreateDelegationRequest`, `GetDelegationRequest`, `GetHumanReadableSummary`, + `RejectDelegationRequest` and `SendDelegationToken`. Each entry carries the type, the member + of its record the value is read from and the type's ARN format, so the enforcement filter + asks the service holding the resource an ARN names for what its record keeps there, the same + per-resource read that gives a resource its tags. Which member carries the owner is the one + thing neither botocore nor the Service Reference says, so the generator states it under the + rules it states anything by hand: AWS's own word, quoted and linked. The + [IAM guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html) + says the key "Filters access based on the AWS identity or principal that owns the delegation + request" and that "The owner of a delegation request is the AWS identity or principal in the + customer account that initiated or received the delegation request", which is the `OwnerId` + botocore's record of the type holds, and writes the example as `"ArnEquals": + {"iam:DelegationRequestOwner": "${aws:PrincipalArn}"}` so that "you allow users to manage only + delegation requests that they own". + + A request that names no delegation request carries no value for the key, so a conditioned + allow does not match and a conditioned deny does not apply. That covers + `CreateDelegationRequest`, whose request does not exist yet while it is authorized, and any + request still unclaimed, which records no owner until it is. The owner is answered to the + account that owns the request and to no other, the line the service itself draws when it + reads one request by id. + + Floci differs from AWS on one action here: the same guide page lists + `UpdateDelegationRequest` among the operations the key supports, and the Service Reference + does not publish it on that action or on a resource type it acts on. The generated reading is + what Floci follows, so a policy conditioning `UpdateDelegationRequest` on the key matches + nothing here while AWS evaluates it. The table's `fromTarget` entries read `iam:PermissionsBoundary` from the role or user the request names in `RoleName` or `UserName`: its stored boundary, on the 15 actions on an diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index 5b8da68d91..31cff0ed17 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -208,7 +208,34 @@ public class IamConditionContextResolver { } /** - * {@code context} with the condition keys {@link #resourceTags} read from a resource's stored tags, each in place of + * The condition keys the table reads from the record of the resource {@code resource} names for + * {@code action}: what the service holding that resource keeps in the member the table asks for + * ({@link StoredResourceArns#recorded}), by key. Null when the action takes none, the ARN is of no type the + * table gives such a key, or the record holds nothing there, which is every resource a request names before + * the value is set on it. Read for each ARN on its own, as the stored tags are, and + * {@link #withResourceTags} puts them in that ARN's context. + */ + public Map> resourceKeys(String action, String resource) { + Map keys = IamConditionKeys.resources(action); + if (keys.isEmpty() || !AwsArnUtils.isArn(resource)) { + return null; + } + StoredResourceArns stored = storedResourceArns(AwsArnUtils.parse(resource).service()); + if (stored == null) { + return null; + } + Map> conditions = new LinkedHashMap<>(); + keys.forEach((key, held) -> { + if (held.arn().matcher(resource).matches()) { + stored.recorded(resource, held.member()).ifPresent(value -> conditions.put(key, List.of(value))); + } + }); + return conditions.isEmpty() ? null : conditions; + } + + /** + * {@code context} with the condition keys read from a resource itself, its stored tags through + * {@link #resourceTags} or its record through {@link #resourceKeys}, each in place of * any key of the same name, case aside, the context held; {@code context} itself when there are none. */ public static Map> withResourceTags(Map> context, diff --git a/src/main/java/io/floci/aws/core/common/IamConditionKeys.java b/src/main/java/io/floci/aws/core/common/IamConditionKeys.java index 3f8b31853e..21ae27043a 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionKeys.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionKeys.java @@ -6,17 +6,25 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; +import java.util.regex.Pattern; /** - * The {@code iam:} condition keys an IAM request carries in its own members, and those read from the - * role or user it names, generated from the AWS Service Reference and pinned botocore by - * {@code tools/aws/regen_iam_condition_keys.py}. + * The {@code iam:} condition keys an IAM request carries in its own members, those read from the + * role or user it names, and those read from the record of the resource it names, generated from the + * AWS Service Reference and pinned botocore by {@code tools/aws/regen_iam_condition_keys.py}. */ final class IamConditionKeys { record RequestTags(String member, String keyMember, String valueMember) {} + /** + * A key the reference publishes on a resource type: the type, the member of its record the value is read + * from, and the pattern the type's ARN format makes, which says whether an ARN is one of that type. + */ + record Resource(String type, String member, Pattern arn) {} + private record Table(Map> members, Map> targets, + Map> resources, Map> requestTags) {} private static final Table TABLE = VendoredResources.read( @@ -24,6 +32,9 @@ final class IamConditionKeys { JsonNode document = new ObjectMapper().readTree(input); return new Table(section(document.path("read"), entry -> text(entry, "member")), section(document.path("fromTarget"), entry -> text(entry, "target")), + section(document.path("fromResource"), entry -> new Resource(text(entry, "type"), + text(entry, "member"), + RequestResourceMembers.pattern(text(entry, "arn")))), section(document.path("requestTags"), entry -> new RequestTags(text(entry, "member"), entry.has("keyMember") ? text(entry, "keyMember") : null, entry.has("keyMember") ? text(entry, "valueMember") : null))); @@ -64,6 +75,14 @@ final class IamConditionKeys { return TABLE.targets().getOrDefault(action, Map.of()); } + /** + * Each condition key a request for {@code action} takes from the resource it names, to the type of that + * resource and the member of its record holding the value; empty when none. + */ + static Map resources(String action) { + return TABLE.resources().getOrDefault(action, Map.of()); + } + static Map requestTags(String action) { return TABLE.requestTags().getOrDefault(action, Map.of()); } diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index eb96ec8439..069b457e63 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -1383,6 +1383,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } taggedContext = IamConditionContextResolver.withResourceTags(taggedContext, conditionContextResolver.resourceTags(resource)); + taggedContext = IamConditionContextResolver.withResourceTags(taggedContext, + conditionContextResolver.resourceKeys(action, resource)); Map> effectiveContext = IamConditionContextResolver.withGlobalContext( taggedContext, resource, region, accountId, resourceOwnerAccountId, action); ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicyFor( diff --git a/src/main/java/io/floci/aws/services/iam/DelegationRequestOwnership.java b/src/main/java/io/floci/aws/services/iam/DelegationRequestOwnership.java index 5fa88f6cc2..578fd618de 100644 --- a/src/main/java/io/floci/aws/services/iam/DelegationRequestOwnership.java +++ b/src/main/java/io/floci/aws/services/iam/DelegationRequestOwnership.java @@ -1,6 +1,7 @@ package io.floci.aws.services.iam; import java.util.List; +import java.util.Optional; /** * Which delegation requests an identity owns, asked by the policy set rather than by a handler. @@ -24,4 +25,16 @@ public interface DelegationRequestOwnership { * none, which is every caller who has claimed no request. */ List requestIdsOwnedBy(String accountId, String ownerArn); + + /** + * The ARN the request {@code requestId} records as its owner, where {@code accountId} is the account that + * owns it; empty when no request carries that id, when the account owning it is another, and when it + * records no owner at all, which is every request until it is claimed. + * + *

Asked for by the condition key the Service Reference publishes on the delegation request type, which + * AWS describes as filtering "based on the AWS identity or principal that owns the delegation request". The + * lookup is of what the store holds under that id and nothing more: which requests an operation acts on is + * the generated table's to say. + */ + Optional ownerArnOf(String accountId, String requestId); } diff --git a/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java b/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java index ea216aad02..ad1145abfa 100644 --- a/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java +++ b/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java @@ -553,7 +553,7 @@ public class DelegationRequestService implements DelegationRequestOwnership, Res private record Owner(String accountId, String arn) {} /** Every owner's request ids as one scan found them, with the version that scan read. */ - private record OwnedRequests(long version, Map> ids) {} + private record OwnedRequests(long version, Map> ids, Map owners) {} /** * The requests an identity owns, for the grant the policy set writes from them. It reads the @@ -581,30 +581,60 @@ public class DelegationRequestService implements DelegationRequestOwnership, Res return ownership().getOrDefault(new Owner(accountId, ownerArn), List.of()); } + /** + * {@inheritDoc} + * + *

Answered from the same scan the owner listing reads, by request id rather than by owner, so an + * authorization costs a lookup rather than a pass over the store: this runs on every request for the + * actions the condition key is published on, which the listing does not. The owner is answered to the + * account that owns the request and to no other, which is the same line {@code visible} draws, and a + * request still unclaimed has no owner to answer with. + */ + @Override + public Optional ownerArnOf(String accountId, String requestId) { + if (accountId == null || requestId == null || requests.isEmptyInAllAccounts()) { + return Optional.empty(); + } + Owner owner = scanned().owners().get(requestId); + return owner == null || !accountId.equals(owner.accountId()) + ? Optional.empty() : Optional.of(owner.arn()); + } + /** * Who owns what, from the last scan still current, or from a fresh one. A scan that a write * overtook answers this caller and is not kept, so the next caller reads the store again * rather than a view of the moment before that write. */ private Map> ownership() { + return scanned().ids(); + } + + /** + * The scan both views are read from: which identity owns what, and which identity owns one request. One + * pass fills both, so the second reader costs nothing the first does not already pay, and the whole of it + * is dropped by the same version bump a write makes. + */ + private OwnedRequests scanned() { long version = ownershipVersion.get(); OwnedRequests cached = ownedRequests.get(); if (cached != null && cached.version() == version) { - return cached.ids(); + return cached; } Map> owned = new HashMap<>(); + Map byId = new HashMap<>(); for (DelegationRequest request : requests.scanAllAccounts()) { if (request.getOwnerAccountId() == null || request.getOwnerId() == null || request.getDelegationRequestId() == null) { continue; } - owned.computeIfAbsent(new Owner(request.getOwnerAccountId(), request.getOwnerId()), - owner -> new ArrayList<>()).add(request.getDelegationRequestId()); + Owner owner = new Owner(request.getOwnerAccountId(), request.getOwnerId()); + owned.computeIfAbsent(owner, held -> new ArrayList<>()).add(request.getDelegationRequestId()); + byId.put(request.getDelegationRequestId(), owner); } owned.replaceAll((owner, ids) -> List.copyOf(ids)); - Map> view = Map.copyOf(owned); + OwnedRequests view = new OwnedRequests(version, Map.copyOf(owned), Map.copyOf(byId)); if (ownershipVersion.get() == version) { - ownedRequests.compareAndSet(cached, new OwnedRequests(version, view)); + ownedRequests.compareAndSet(cached, view); } return view; } diff --git a/src/main/java/io/floci/aws/services/iam/IamStoredResourceArns.java b/src/main/java/io/floci/aws/services/iam/IamStoredResourceArns.java new file mode 100644 index 0000000000..c862fbdc5f --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/IamStoredResourceArns.java @@ -0,0 +1,66 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.StoredResourceArns; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Optional; + +/** + * What IAM asks of its own resources a request names: what a delegation request records, which is the owner + * the condition key the Service Reference publishes on that type is evaluated against. + * + *

The delegation store is reached through {@link DelegationRequestOwnership} rather than directly, as + * {@code IamService} reaches it, so the lookup does not tie IAM's enforcement to the service that holds + * the requests. + */ +@ApplicationScoped +public class IamStoredResourceArns implements StoredResourceArns { + + private static final String DELEGATION_REQUEST = "delegation-request/"; + private static final String OWNER = "OwnerId"; + + private final Instance delegationRequests; + + @Inject + public IamStoredResourceArns(Instance delegationRequests) { + this.delegationRequests = delegationRequests; + } + + @Override + public String namespace() { + return "iam"; + } + + /** IAM's own ARNs carry the names a request gives, so there is no stored ARN to find behind one. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + /** + * {@inheritDoc} + * + *

Only a delegation request records anything a condition key is read from, and only its owner, so an ARN + * of any other type and any other member are answered with nothing. The id is what resolves a request, and + * the account the ARN names is the one the owner is answered to. + */ + @Override + public Optional recorded(String arn, String member) { + if (!OWNER.equals(member) || !AwsArnUtils.isArn(arn) || delegationRequests.isUnsatisfied()) { + return Optional.empty(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith(DELEGATION_REQUEST)) { + return Optional.empty(); + } + String id = parsed.resource().substring(DELEGATION_REQUEST.length()); + if (id.isBlank()) { + return Optional.empty(); + } + return delegationRequests.get().ownerArnOf(parsed.accountId(), id); + } +} diff --git a/src/main/resources/aws/iam-condition-keys.json b/src/main/resources/aws/iam-condition-keys.json index f64fbf5c63..ffe1a06f53 100644 --- a/src/main/resources/aws/iam-condition-keys.json +++ b/src/main/resources/aws/iam-condition-keys.json @@ -163,15 +163,21 @@ {"action": "iam:UploadSigningCertificate", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, {"action": "iam:UploadSigningCertificate", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]} ], + "fromResource": [ + {"action": "iam:AcceptDelegationRequest", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"}, + {"action": "iam:AssociateDelegationRequest", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"}, + {"action": "iam:CreateDelegationRequest", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"}, + {"action": "iam:GetDelegationRequest", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"}, + {"action": "iam:GetHumanReadableSummary", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"}, + {"action": "iam:RejectDelegationRequest", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"}, + {"action": "iam:SendDelegationToken", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"} + ], "notRead": [ - {"action": "iam:AcceptDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:AddClientIDToOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, {"action": "iam:AddRoleToInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, - {"action": "iam:AssociateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:AttachRolePolicy", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, {"action": "iam:ChangePassword", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["user"]}, {"action": "iam:ChangePassword", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["user"]}, - {"action": "iam:CreateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:CreateInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, {"action": "iam:CreateOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, {"action": "iam:CreatePolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, @@ -204,8 +210,6 @@ {"action": "iam:GetAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "the value is the namespaces of the properties read or written"}, {"action": "iam:GetContextKeysForPrincipalPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, {"action": "iam:GetContextKeysForPrincipalPolicy", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, - {"action": "iam:GetDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, - {"action": "iam:GetHumanReadableSummary", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:GetInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, {"action": "iam:GetOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, {"action": "iam:GetPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, @@ -232,11 +236,9 @@ {"action": "iam:PutAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "the value is the namespaces of the properties read or written"}, {"action": "iam:PutRolePermissionsBoundary", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, {"action": "iam:PutRolePolicy", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, - {"action": "iam:RejectDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:RemoveClientIDFromOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, {"action": "iam:RemoveRoleFromInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, {"action": "iam:ResetServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"}, - {"action": "iam:SendDelegationToken", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:SetDefaultPolicyVersion", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, {"action": "iam:SimulatePrincipalPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, {"action": "iam:SimulatePrincipalPolicy", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, diff --git a/src/test/java/io/floci/aws/services/iam/DelegationRequestOwnerConditionIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/DelegationRequestOwnerConditionIntegrationTest.java new file mode 100644 index 0000000000..f63c9337f4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/DelegationRequestOwnerConditionIntegrationTest.java @@ -0,0 +1,229 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.DelegationRequests; +import io.floci.aws.testing.S3IamEnforcementProfile; +import io.floci.aws.testutil.S3RequestSigner; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * Policies scoped by the owner of the delegation request a call names. + * + *

The Service Reference publishes {@code iam:DelegationRequestOwner} on the {@code delegation-request} + * resource type rather than on the actions that act on one, so its value is not in the request: it is what the + * stored request records. AWS describes the key as filtering "based on the AWS identity or principal that owns + * the delegation request", the owner being "the AWS identity or principal in the customer account that + * initiated or received the delegation request", and writes the example as + * {@code "ArnEquals": {"iam:DelegationRequestOwner": "${aws:PrincipalArn}"}} so that "you allow users to manage + * only delegation requests that they own". + * + *

So each case here turns on the value being the owner on the request, not merely present: an allow holds a + * caller to its own requests, a deny reaches one request and leaves the next alone, and a call that names no + * request carries no value at all. + */ +@QuarkusTest +@TestProfile(S3IamEnforcementProfile.class) +class DelegationRequestOwnerConditionIntegrationTest { + + private static final String CUSTOMER = "222233334444"; + private static final String PARTNER = "000000000001"; + private static final String TOPIC = "arn:aws:sns:us-east-1:000000000001:partner-notifications"; + private static final String TEMPLATE = "arn:aws:iam::partner:policy/template/example"; + private static final String STRANGER = "arn:aws:iam::222233334444:user/someone-else"; + + /** Claiming, plus approving only the requests the caller owns, which is the guide's own example shape. */ + private static final String MAY_CLAIM_AND_ACCEPT_ITS_OWN = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:AssociateDelegationRequest","Resource":"*"}, + {"Effect":"Allow","Action":"iam:AcceptDelegationRequest","Resource":"*", + "Condition":{"ArnEquals":{"iam:DelegationRequestOwner":"%s"}}}]}"""; + private static final String MAY_CLAIM = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"iam:AssociateDelegationRequest","Resource":"*"}]}"""; + /** Claiming, with one action the owner grant would otherwise give taken back for its own requests. */ + private static final String MAY_CLAIM_DENIED_ON_ITS_OWN = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:AssociateDelegationRequest","Resource":"*"}, + {"Effect":"Deny","Action":"%s","Resource":"*", + "Condition":{"ArnEquals":{"iam:DelegationRequestOwner":"%s"}}}]}"""; + private static final String MAY_CREATE_ITS_OWN = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"iam:CreateDelegationRequest","Resource":"*", + "Condition":{"ArnEquals":{"iam:DelegationRequestOwner":"%s"}}}]}"""; + private static final String MAY_CREATE = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"iam:CreateDelegationRequest","Resource":"*"}]}"""; + + @Test + void anAllowHeldToTheOwnerReachesTheRequestThatCallerOwns() { + String name = unique("owner-accept"); + S3RequestSigner owner = userWithPolicy(name, MAY_CLAIM_AND_ACCEPT_ITS_OWN.formatted(userArn(name))); + String id = partnerCreate(); + byUser(owner, "AssociateDelegationRequest", id).statusCode(200); + + // Approving is not part of the grant an owner carries, so this allow is the only thing that can + // reach it, and it only matches where the stored request names this caller as its owner. + byUser(owner, "AcceptDelegationRequest", id).statusCode(200); + } + + @Test + void theSameAllowDoesNotReachARequestAnotherIdentityOwns() { + String name = unique("owner-other"); + S3RequestSigner caller = userWithPolicy(name, MAY_CLAIM_AND_ACCEPT_ITS_OWN.formatted(userArn(name))); + S3RequestSigner neighbour = userWithPolicy(unique("owner-neighbour"), MAY_CLAIM); + String theirs = partnerCreate(); + byUser(neighbour, "AssociateDelegationRequest", theirs).statusCode(200); + + byUser(caller, "AcceptDelegationRequest", theirs).statusCode(403); + } + + @Test + void theSameAllowDoesNotReachARequestNobodyOwnsYet() { + String name = unique("owner-unclaimed"); + S3RequestSigner caller = userWithPolicy(name, MAY_CLAIM_AND_ACCEPT_ITS_OWN.formatted(userArn(name))); + + // A request records no owner until it is claimed, so there is no value for the key to match and the + // conditioned allow does not apply. + byUser(caller, "AcceptDelegationRequest", partnerCreate()).statusCode(403); + } + + @Test + void aDenyHeldToTheOwnerTakesBackWhatOwningWouldGive() { + String name = unique("deny-own"); + S3RequestSigner owner = userWithPolicy(name, + MAY_CLAIM_DENIED_ON_ITS_OWN.formatted("iam:GetDelegationRequest", userArn(name))); + String id = partnerCreate(); + byUser(owner, "AssociateDelegationRequest", id).statusCode(200); + + // Reading its own request is what an owner may do with no policy at all, so a deny that lands here + // can only have matched on the owner the stored request records. + byUser(owner, "GetDelegationRequest", id).statusCode(403); + } + + @Test + void aDenyHeldToAnotherOwnerLeavesTheCallersOwnRequestAlone() { + String name = unique("deny-other"); + S3RequestSigner owner = userWithPolicy(name, + MAY_CLAIM_DENIED_ON_ITS_OWN.formatted("iam:GetDelegationRequest", STRANGER)); + String id = partnerCreate(); + byUser(owner, "AssociateDelegationRequest", id).statusCode(200); + + // The value is this caller's ARN rather than any owner at all, so a deny written for someone else + // does not match it. + byUser(owner, "GetDelegationRequest", id).statusCode(200) + .body("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest" + + ".DelegationRequestId", equalTo(id)); + } + + @Test + void theSummaryCarriesTheOwnerOfTheRequestItsEntityArnNames() { + String name = unique("deny-summary"); + S3RequestSigner owner = userWithPolicy(name, + MAY_CLAIM_DENIED_ON_ITS_OWN.formatted("iam:GetHumanReadableSummary", userArn(name))); + String id = partnerCreate(); + byUser(owner, "AssociateDelegationRequest", id).statusCode(200); + + // This is the one action of the family that names its request by an ARN rather than by an id, and + // the owner is read for it all the same. + summaryBy(owner, id).statusCode(403); + } + + @Test + void creatingNamesNoRequestSoAnAllowHeldToTheOwnerNeverMatches() { + String conditioned = unique("create-conditioned"); + S3RequestSigner held = userWithPolicy(conditioned, MAY_CREATE_ITS_OWN.formatted(userArn(conditioned))); + S3RequestSigner plain = userWithPolicy(unique("create-plain"), MAY_CREATE); + + // The request a create makes does not exist while it is authorized, so the key carries nothing and + // a conditioned allow cannot match, while the same allow without the condition does. + createBy(held).statusCode(403); + createBy(plain).statusCode(200); + } + + private static ValidatableResponse byUser(S3RequestSigner caller, String action, String id) { + return given().filter(caller) + .formParam("Action", action) + .formParam("Version", "2010-05-08") + .formParam("DelegationRequestId", id) + .when().post("/").then(); + } + + private static ValidatableResponse summaryBy(S3RequestSigner caller, String id) { + return given().filter(caller) + .formParam("Action", "GetHumanReadableSummary") + .formParam("Version", "2010-05-08") + .formParam("EntityArn", DelegationRequests.entityArn(CUSTOMER, id)) + .when().post("/").then(); + } + + private static ValidatableResponse createBy(S3RequestSigner caller) { + return creation(given().filter(caller), null).when().post("/").then(); + } + + /** + * A well formed {@code CreateDelegationRequest}, named for the owner account where one is given, so that + * the shape a create has to take is written once however the call is signed. + */ + private static RequestSpecification creation(RequestSpecification request, String ownerAccountId) { + request = request + .formParam("Action", "CreateDelegationRequest") + .formParam("Version", "2010-05-08") + .formParam("Description", "Set up the integration") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", "workflow-" + Long.toString(System.nanoTime(), 36)) + .formParam("SessionDuration", "3600") + .formParam("Permissions.PolicyTemplateArn", TEMPLATE); + return ownerAccountId == null ? request : request.formParam("OwnerAccountId", ownerAccountId); + } + + private static String userArn(String userName) { + return "arn:aws:iam::" + CUSTOMER + ":user/" + userName; + } + + private static String partnerCreate() { + return creation(given().header("Authorization", auth(PARTNER, "iam")), CUSTOMER) + .when().post("/").then().statusCode(200) + .extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult" + + ".DelegationRequestId"); + } + + private static S3RequestSigner userWithPolicy(String userName, String policy) { + iam("CreateUser", "UserName", userName); + iam("PutUserPolicy", "UserName", userName, "PolicyName", "inline", "PolicyDocument", policy); + ExtractableResponse key = given().formParam("Action", "CreateAccessKey") + .formParam("UserName", userName) + .header("Authorization", auth(CUSTOMER, "iam")).when().post("/") + .then().statusCode(200).extract(); + return S3RequestSigner.signedAs( + key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"), + key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey")); + } + + private static void iam(String action, String... params) { + RequestSpecification request = given().formParam("Action", action) + .header("Authorization", auth(CUSTOMER, "iam")); + for (int i = 0; i < params.length; i += 2) { + request = request.formParam(params[i], params[i + 1]); + } + request.when().post("/").then().statusCode(200); + } + + private static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + private static String auth(String accessKeyId, String service) { + return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261002/us-east-1/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } +} diff --git a/src/test/java/io/floci/aws/services/iam/DelegationRequestServiceTest.java b/src/test/java/io/floci/aws/services/iam/DelegationRequestServiceTest.java index 10891f2419..c80fd88c07 100644 --- a/src/test/java/io/floci/aws/services/iam/DelegationRequestServiceTest.java +++ b/src/test/java/io/floci/aws/services/iam/DelegationRequestServiceTest.java @@ -113,6 +113,24 @@ class DelegationRequestServiceTest { null, null, null, null)).request(); } + @Test + void theOwnerIsAnsweredOnlyOnceARequestIsClaimedAndOnlyToItsOwner() { + String unclaimed = created("workflow-1", null).getDelegationRequestId(); + + // Nothing owns a request until it is claimed, so there is no value for the condition key to + // match and the caller is told so rather than given a stand-in. + assertTrue(service.ownerArnOf(CUSTOMER, unclaimed).isEmpty()); + assertTrue(service.ownerArnOf(CUSTOMER, "delegation-request-that-is-not-held").isEmpty()); + + String claimed = assigned("workflow-2").getDelegationRequestId(); + + // The claim is a write, so an answer read before it must not survive it. + assertEquals(CUSTOMER_ARN, service.ownerArnOf(CUSTOMER, claimed).orElse(null)); + // And it is the owner's own account that is answered, never another reading the same id. + assertTrue(service.ownerArnOf(PARTNER, claimed).isEmpty()); + assertTrue(service.ownerArnOf(CUSTOMER, unclaimed).isEmpty()); + } + private DelegationRequest created(String workflowId, String ownerAccountId) { return createdIn(REGION, workflowId, ownerAccountId).request(); } diff --git a/tools/aws/regen_iam_condition_keys.py b/tools/aws/regen_iam_condition_keys.py index 51c686e6e7..55a5996b4b 100644 --- a/tools/aws/regen_iam_condition_keys.py +++ b/tools/aws/regen_iam_condition_keys.py @@ -17,6 +17,11 @@ file does not list. --verify compares every pair and key type with the live refe fails on any difference, added pairs included: a key missing from the context stops a conditioned Allow matching and a conditioned Deny applying. --source reads a saved reference. +A key the reference publishes on a resource type rather than on the action is the stored resource's +value, and MEASURED names the member of that type's record it is read from, which neither botocore nor +the reference says; its pairs go in fromResource with the type, that member and the type's ARN format, +and the reader asks the type's service for what the record holds there. + Resource tag keys use the same fromTarget route as permissions boundaries for existing roles and users. Unsupported targets and exceptions are recorded in notRead with a reason. requestTags lists the request tag keys of actions marked IsTaggingOnly in the reference, with their list @@ -63,7 +68,6 @@ TARGET_MEMBERS = ("RoleName", "UserName") # Keys whose value, on an action without the member, does not come from the request. NOT_IN_REQUEST = { "iam:AccountPropertyNamespaces": "the value is the namespaces of the properties read or written", - "iam:DelegationRequestOwner": "the value is the delegation request's owner", "iam:FIDO-FIPS-140-2-certification": "the value comes from the FIDO Alliance Metadata Service", "iam:FIDO-FIPS-140-3-certification": "the value comes from the FIDO Alliance Metadata Service", "iam:FIDO-certification": "the value comes from the FIDO Alliance Metadata Service", @@ -72,6 +76,34 @@ NOT_IN_REQUEST = { "iam:ServiceSpecificCredentialServiceName": "the value is the named credential's service", } +# MEASURED: the member of a resource's record a key's value is read from, where neither botocore nor the +# Service Reference says it. +# +# This is the only place in this generator that states where a value comes from rather than deriving it, and it +# is closed to everything but AWS's own word. An entry is admitted only when ALL of these hold: +# +# 1. From AWS. Its evidence is AWS itself: a policy probe run against real AWS published with its cases and +# results in a Floci pull request, an AWS response recorded verbatim, or AWS's documentation saying it in +# so many words, the sentence quoted. An analogy with another key, the request's shape and what a Floci +# handler does are NOT evidence. +# 2. Absent from the metadata. The reference publishes the key on a resource type rather than on the action, +# so no action list names it, and botocore names no request member after it. +# 3. Named by botocore. The type's record holds the member, as a string, so the value the reader asks for is +# one botocore says the record carries. +# 4. Linked. The evidence carries an https link to itself. +# +# The generator refuses an entry that breaks 3 or 4, and the reference decides 2; review enforces 1. +MEASURED: dict[str, tuple[str, str]] = { + "iam:DelegationRequestOwner": ( + "OwnerId", + 'AWS\'s IAM User Guide says the key "Filters access based on the AWS identity or principal that owns ' + 'the delegation request", and that "The owner of a delegation request is the AWS identity or principal ' + 'in the customer account that initiated or received the delegation request", which is what botocore\'s ' + "record of the type holds in OwnerId; the Service Reference publishes the key on the delegation-request " + "type without saying which member carries it " + "(https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html)"), +} + def action_keys(reference): """Every IAM-specific or resource-tag (action, key) pair, with each key's types.""" @@ -107,10 +139,50 @@ def member_type(model, operation, path): shape = model["shapes"][member["shape"]] return shape["type"] -def classify(pairs, types, model, resource_types=None): - """The read, fromTarget and notRead entries for the reference's pairs.""" +def measured_resources(reference): + """For each pair a resource type carries a MEASURED key on, that type and its ARN format.""" + resources = {r["Name"]: (set(r.get("ConditionKeys") or []), (r.get("ARNFormats") or [None])[0]) + for r in reference["Resources"]} + found = {} + for action in reference["Actions"]: + listed = set(action.get("ActionConditionKeys") or []) + for named in action.get("Resources", []): + keys, arn = resources.get(named["Name"], (set(), None)) + for key in set(named.get("ConditionKeys", keys)) & set(MEASURED) - listed: + found[("iam:" + action["Name"], key)] = (named["Name"], arn) + return dict(sorted(found.items())) + +def record_shape(model, resource_type): + """The botocore shape holding a resource type's record, named after the type (delegation-request + is DelegationRequest), or None when the model has none.""" + name = "".join(part[:1].upper() + part[1:] for part in resource_type.split("-")) + return model["shapes"].get(name) + +def require_measured_admitted(model, measured): + """A MEASURED entry is refused unless botocore names its member on the type's record as a string and + its evidence links to itself.""" + for (action, key), (resource_type, arn) in sorted(measured.items()): + member, evidence = MEASURED[key] + if "https://" not in evidence: + raise ValueError(f"MEASURED gives {key} with no link to the evidence of AWS it rests on") + if arn is None: + raise ValueError(f"MEASURED gives {key} on {resource_type}, which has no ARN format") + record = record_shape(model, resource_type) + if record is None: + raise ValueError(f"MEASURED gives {key} on {resource_type}, whose record botocore does not hold") + held = record.get("members", {}).get(member) + if held is None: + raise ValueError(f"MEASURED reads {key} from {member}, which botocore's {resource_type} record " + f"does not hold") + if model["shapes"][held["shape"]]["type"] != "string": + raise ValueError(f"MEASURED reads {key} from {member}, which is not a string member") + del action + +def classify(pairs, types, model, resource_types=None, measured=None): + """The read, fromTarget, fromResource and notRead entries for the reference's pairs.""" resource_types = resource_types or {} - read, from_target, not_read = [], [], [] + measured = measured or {} + read, from_target, from_resource, not_read = [], [], [], [] for action, key in sorted(pairs): operation = model["operations"].get(action.split(":", 1)[1]) if (action, key) in BY_HAND: @@ -147,6 +219,11 @@ def classify(pairs, types, model, resource_types=None): if key not in RESOURCE_TAG_KEYS: raise ValueError(f"{action}: no member names the role or user {key} is read from") reason = "no member names a stored role or user whose resource tags can be read" + elif member is None and (action, key) in measured: + resource_type, arn = measured[(action, key)] + from_resource.append({"action": action, "key": key, "type": resource_type, + "member": MEASURED[key][0], "arn": arn}) + continue elif member is None: reason = NOT_IN_REQUEST.get(key, "no member named after the key") elif not set(types.get(key, [])) <= READ_TYPES: @@ -160,7 +237,8 @@ def classify(pairs, types, model, resource_types=None): for entry in from_target + not_read: if entry["key"] in RESOURCE_TAG_KEYS: entry["resources"] = resource_types.get((entry["action"], entry["key"]), []) - return read, from_target, not_read + require_measured_admitted(model, measured) + return read, from_target, from_resource, not_read def require_by_hand_listed(pairs): stale = sorted(set(BY_HAND) - set(pairs)) @@ -208,14 +286,15 @@ def validate_request_tags(entries, model): def pairs_of(document): return sorted((e["action"], e["key"]) - for e in document["read"] + document["fromTarget"] + document["notRead"]) + for e in document["read"] + document["fromTarget"] + document["fromResource"] + + document["notRead"]) def render(document): """The document with one entry to a line.""" lines = ["{"] for key in ("source", "botocore", "types"): lines.append(f' "{key}": {json.dumps(document[key])},') - for section, tail in (("read", ","), ("fromTarget", ","), ("notRead", ","), + for section, tail in (("read", ","), ("fromTarget", ","), ("fromResource", ","), ("notRead", ","), ("requestTags", "")): entries = document[section] lines.append(f' "{section}": [') @@ -240,8 +319,9 @@ def main(argv=None): model = load_model(latest_model_dir(resolve_botocore_data(args.botocore_data)[0], "iam")) resource_types = {(e["action"], e["key"]): e["resources"] for e in document["fromTarget"] + document["notRead"] if e["key"] in RESOURCE_TAG_KEYS} - if classify(pairs, document["types"], model, resource_types) != ( - document["read"], document["fromTarget"], document["notRead"]): + measured = {(e["action"], e["key"]): (e["type"], e["arn"]) for e in document["fromResource"]} + if classify(pairs, document["types"], model, resource_types, measured) != ( + document["read"], document["fromTarget"], document["fromResource"], document["notRead"]): raise ValueError("IAM condition key members differ from pinned botocore") validate_request_tags(document["requestTags"], model) return 0 @@ -265,8 +345,8 @@ def main(argv=None): if set(pairs) != vendored or document["types"] != types: raise ValueError("IAM condition keys differ from AWS Service Reference") model = load_model(latest_model_dir(resolve_botocore_data(args.botocore_data)[0], "iam")) - if classify(pairs, types, model, resource_tag_types(reference)) != ( - document["read"], document["fromTarget"], document["notRead"]): + if classify(pairs, types, model, resource_tag_types(reference), measured_resources(reference)) != ( + document["read"], document["fromTarget"], document["fromResource"], document["notRead"]): raise ValueError("IAM condition key targets differ from AWS Service Reference") if request_tag_context(reference, model) != document["requestTags"]: raise ValueError("IAM tag condition keys differ from AWS Service Reference") @@ -274,11 +354,12 @@ def main(argv=None): require_by_hand_listed(pairs) data, provenance = resolve_botocore_data(args.botocore_data) model = load_model(latest_model_dir(data, "iam")) - read, from_target, not_read = classify(pairs, types, model, resource_tag_types(reference)) + read, from_target, from_resource, not_read = classify( + pairs, types, model, resource_tag_types(reference), measured_resources(reference)) request_tags = request_tag_context(reference, model) OUTPUT.write_text(render({"source": URL, "botocore": provenance, "types": types, - "read": read, "fromTarget": from_target, "notRead": not_read, - "requestTags": request_tags})) + "read": read, "fromTarget": from_target, "fromResource": from_resource, + "notRead": not_read, "requestTags": request_tags})) return 0 diff --git a/tools/aws/test_regen_iam_condition_keys.py b/tools/aws/test_regen_iam_condition_keys.py index 953b195fd8..d447117944 100644 --- a/tools/aws/test_regen_iam_condition_keys.py +++ b/tools/aws/test_regen_iam_condition_keys.py @@ -28,6 +28,8 @@ MODEL = {"operations": { "SessionDuration": {"shape": "Days"}}}, "Permission": {"type": "structure", "members": {"PolicyTemplateArn": {"shape": "Arn"}}}, "ListDelegationInput": {"type": "structure", "members": {"OwnerId": {"shape": "Arn"}}}, + "DelegationRequest": {"type": "structure", "members": {"OwnerId": {"shape": "Arn"}, + "Permissions": {"shape": "Permission"}}}, "Arn": {"type": "string"}, "Name": {"type": "string"}, "Days": {"type": "integer"}, }} @@ -46,7 +48,7 @@ def test_resource_and_action_keys_are_combined_and_unrelated_global_keys_dropped def test_member_is_matched_ignoring_case_only_on_actions_listing_the_key(): - read, from_target, not_read = classify([("iam:AttachRolePolicy", "iam:PolicyARN")], + read, from_target, _, not_read = classify([("iam:AttachRolePolicy", "iam:PolicyARN")], {"iam:PolicyARN": ["ARN"]}, MODEL) assert read == [{"action": "iam:AttachRolePolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}] assert from_target == not_read == [] @@ -54,7 +56,7 @@ def test_member_is_matched_ignoring_case_only_on_actions_listing_the_key(): def test_permissions_boundary_without_a_request_member_is_read_from_the_named_role_or_user(): pairs = [("iam:GetRole", "iam:PermissionsBoundary"), ("iam:DeleteUserPolicy", "iam:PermissionsBoundary")] - read, from_target, not_read = classify(pairs, {"iam:PermissionsBoundary": ["ARN"]}, MODEL) + read, from_target, _, not_read = classify(pairs, {"iam:PermissionsBoundary": ["ARN"]}, MODEL) assert read == not_read == [] assert from_target == [ {"action": "iam:DeleteUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"}, @@ -71,7 +73,7 @@ def test_unread_pairs_name_their_reason(): ("iam:CreateServiceSpecificCredential", "iam:CredentialAgeDays")] types = {"iam:RoleTemplateARN": ["ARN"], "iam:PassedToService": ["String"], "iam:CredentialAgeDays": ["Numeric"]} - read, from_target, not_read = classify(pairs, types, MODEL) + read, from_target, _, not_read = classify(pairs, types, MODEL) assert read == from_target == [] assert {(e["action"], e["key"]): e["reason"] for e in not_read} == { ("iam:CreateServiceSpecificCredential", "iam:CredentialAgeDays"): "the key's type is Numeric", @@ -86,7 +88,7 @@ BY_HAND_TYPES = {"iam:DelegationDuration": ["String"], "iam:TemplateArn": ["ARN" def test_by_hand_pairs_read_their_member_including_a_nested_one(): - read, from_target, not_read = classify(sorted(regen_iam_condition_keys.BY_HAND), BY_HAND_TYPES, MODEL) + read, from_target, _, not_read = classify(sorted(regen_iam_condition_keys.BY_HAND), BY_HAND_TYPES, MODEL) assert from_target == not_read == [] assert {(e["action"], e["key"]): e["member"] for e in read} == regen_iam_condition_keys.BY_HAND @@ -157,6 +159,12 @@ def test_check_fails_on_a_hand_edited_member(tmp_path, monkeypatch): def reference_from_document(document): actions = {} + formats = {} + for entry in document["fromResource"]: + name = entry["action"].removeprefix("iam:") + action = actions.setdefault(name, {"Name": name, "ActionConditionKeys": [], "Resources": []}) + action["Resources"].append({"Name": entry["type"], "ConditionKeys": [entry["key"]]}) + formats[entry["type"]] = entry["arn"] for entry in document["read"] + document["fromTarget"] + document["notRead"]: name = entry["action"].removeprefix("iam:") action = actions.setdefault(name, {"Name": name, "ActionConditionKeys": [], "Resources": []}) @@ -170,7 +178,9 @@ def reference_from_document(document): action = actions.setdefault(name, {"Name": name, "ActionConditionKeys": [], "Resources": []}) action["Annotations"] = {"Properties": {"IsTaggingOnly": True}} action["ActionConditionKeys"].append(entry["key"]) - return {"Resources": [], "Actions": list(actions.values()), + return {"Resources": [{"Name": name, "ARNFormats": [arn], "ConditionKeys": []} + for name, arn in sorted(formats.items())], + "Actions": list(actions.values()), "ConditionKeys": [{"Name": key, "Types": types} for key, types in document["types"].items()]} @@ -255,7 +265,7 @@ def test_resource_tags_use_the_same_target_route_and_keep_reasoned_exceptions(): ("GetUser", "user"), ("CreateUser", "user"), ("CreateAccessKey", "user"), ("AddRoleToInstanceProfile", "instance-profile"))]} pairs, types = action_keys(reference) - read, targets, not_read = classify(pairs, types, model, regen_iam_condition_keys.resource_tag_types(reference)) + read, targets, _, not_read = classify(pairs, types, model, regen_iam_condition_keys.resource_tag_types(reference)) assert read == [] assert {(e["action"], e["target"]) for e in targets} == { ("iam:GetRole", "RoleName"), ("iam:GetUser", "UserName"), ("iam:CreateAccessKey", "UserName")} @@ -328,3 +338,45 @@ def test_check_rejects_hand_edited_tag_fields(tmp_path, monkeypatch): monkeypatch.setattr(regen_iam_condition_keys, "OUTPUT", edited) with pytest.raises(ValueError, match="request tag members differ"): regen_iam_condition_keys.main(["--check"]) + + +def test_a_key_published_on_a_resource_type_is_read_from_that_resources_record(): + """The seven delegation actions the reference gives the key through delegation-request read it from the + stored request, at the member MEASURED names, rather than being left unread.""" + document = json.loads(OUTPUT.read_text()) + rows = {entry["action"]: entry for entry in document["fromResource"]} + assert set(rows) == {f"iam:{name}" for name in ( + "AcceptDelegationRequest", "AssociateDelegationRequest", "CreateDelegationRequest", + "GetDelegationRequest", "GetHumanReadableSummary", "RejectDelegationRequest", "SendDelegationToken")} + for entry in rows.values(): + assert entry["key"] == "iam:DelegationRequestOwner" + assert entry["type"] == "delegation-request" + assert entry["member"] == "OwnerId" + assert entry["arn"] == "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}" + unread = {(e["action"], e["key"]) for e in document["notRead"]} + assert not [pair for pair in unread if pair[1] == "iam:DelegationRequestOwner"] + assert ("iam:ListDelegationRequests", "iam:DelegationRequestOwner") in { + (e["action"], e["key"]) for e in document["read"]} + + +def test_a_measured_entry_is_refused_without_a_link_or_a_member_botocore_holds(monkeypatch): + """MEASURED is admitted on AWS's own word: the evidence links to itself and botocore's record of the + type holds the member it names, as a string.""" + reference = reference_from_document(json.loads(OUTPUT.read_text())) + measured = regen_iam_condition_keys.measured_resources(reference) + assert measured, "the reference publishes the key on a resource type" + + monkeypatch.setitem(regen_iam_condition_keys.MEASURED, "iam:DelegationRequestOwner", + ("OwnerId", "a sentence with no link to AWS")) + with pytest.raises(ValueError, match="no link to the evidence"): + regen_iam_condition_keys.require_measured_admitted(MODEL, measured) + + monkeypatch.setitem(regen_iam_condition_keys.MEASURED, "iam:DelegationRequestOwner", + ("OwnedBy", "https://docs.aws.amazon.com/IAM/latest/UserGuide/")) + with pytest.raises(ValueError, match="which botocore's delegation-request record does not hold"): + regen_iam_condition_keys.require_measured_admitted(MODEL, measured) + + monkeypatch.setitem(regen_iam_condition_keys.MEASURED, "iam:DelegationRequestOwner", + ("Permissions", "https://docs.aws.amazon.com/IAM/latest/UserGuide/")) + with pytest.raises(ValueError, match="not a string member"): + regen_iam_condition_keys.require_measured_admitted(MODEL, measured)