diff --git a/docs/services/iam.md b/docs/services/iam.md index 80c1a8f887..8e47894ddb 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -222,6 +222,29 @@ no members is how an absent list arrives, so a required one reads as null rather breaking a minimum of 1. A structure member arrives as `TaskPolicyArn.Arn` and is named `taskPolicyArn.arn`. +The operations read their own lists the same way, off the indices the request numbers rather than +off a run from 1 that stops at the first gap: tags and tag keys, a provider's client IDs and +thumbprints, the namespaces `ListPoliciesGrantingServiceAccess` is asked for, each simulator's +actions, resources and policy documents, and the context entries and delegation policy parameters +with the values inside them. A request numbering tags 1 and 3 carries two tags, so the constraints +held such a request to both and the operation then stored the first alone. The count a tag list +and a tag key list are each held to is taken over the indices sent, a violation names the index +the request spelled, and the bare `Tags.1.Key` spelling is read where only `Tags.member.1.Key` +was. A member numbered only under a deeper key carries no value of its own and is no member of a +list of values. A tag numbered with a value and no key, or with a key and no value, never reaches +the operation at all: both members are required, so the constraints answer +`Value at 'tags.1.member.key' failed to satisfy constraint: Member must not be null` under the index +the request spelled. The reader skips such a member behind that gate, which is what a context entry +numbered with values and no name meets, nothing in the model requiring a name of one. An action +list whose first member is numbered 2 is a list with a member in it, where +`At least one ActionNames member is required.` was the answer a list that never arrived got. A +delegation request's policy parameters had a reader of their own that already read their indices, +and it is gone: they are read through the shared one, which takes the bare spelling with the +generic form, so this handler reads a list in one place rather than three. The tags a create is +authorized with are read the same way, so a tag numbered only at 2, or spelled bare, meets a policy +that requires that tag, and tags split across the two spellings are checked as the one list the +resource gets rather than as a set each. + A map is read the same way, from the entries the protocol numbers under its name: `ReplacementValues.entry.1.key` and `.entry.1.value`, which is the form `AcquireRole`'s own sample publishes, or the bare `ReplacementValues.1.key`. An entry's value is named under the key that @@ -1062,6 +1085,15 @@ such message recorded against AWS carries it, including on map members: SNS's re prefixed. What is not recorded anywhere is how AWS spells a map *key* constraint, so the "Map keys must satisfy constraint" tail is a reasonable shape rather than an attested one. +**The entries are read off the indices the request carries**, not off a run from 1. The Query +protocol numbers a map's entries rather than listing them, and the constraints read every index the +request names, so a request numbering entries 1 and 3 stores both: reading them as a run held such a +request to both entries and then stored only the first. The three spellings are read alike, +`Properties.entry.1.key`, the generic `Properties.member.1.key` and the bare `Properties.1.key`, +which is what the shared reader every other list and map here goes through already takes. An entry +numbered with a value and no key is no entry the map could hold, so it is neither counted nor +stored, and a request carrying only that one is a map that never arrived. + **Enabling federation twice is an error, and so is disabling it twice**, which is the asymmetry worth noticing: `EnableOutboundWebIdentityFederation` answers `FeatureEnabled` with status 409, while `DisableOutboundWebIdentityFederation` answers `FeatureDisabled` with status **404**. AWS diff --git a/src/main/java/io/github/hectorvent/floci/core/common/TagOnCreate.java b/src/main/java/io/github/hectorvent/floci/core/common/TagOnCreate.java index 0438fa0c23..325da407d8 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/TagOnCreate.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/TagOnCreate.java @@ -71,9 +71,10 @@ final class TagOnCreate { /** * How a Floci Query handler numbers a tag list: from 1 to the first number with no key, every number there - * is, or from 1 to the first number at which none of the prefixes has a key or a value. + * is, by {@link AwsQueryLists}'s own rule for a handler that reads one through it, or from 1 to the first + * number at which none of the prefixes has a key or a value. */ - private enum Numbering { TO_FIRST_GAP, EVERY, EITHER_AT_EACH } + private enum Numbering { TO_FIRST_GAP, EVERY, AS_THE_SHARED_READER, EITHER_AT_EACH } /** The prefixes a handler numbers a tag list under, in the order it reads them, and its tags' key and value. */ private record Reading(List prefixes, Numbering numbering, String key, String value) { @@ -303,6 +304,11 @@ final class TagOnCreate { */ private static List readings(String operation, TagOnCreateMembers.Member member, boolean ec2) { PassedRoleMembers.Step first = member.querySteps().getFirst(); + // IamQueryHandler reads every list it serves through AwsQueryLists, so this reads the member the table + // names by that same rule rather than restating it: nothing here to keep in step with that handler. + if (operation.startsWith("iam:")) { + return List.of(sharedReader(member, first.name())); + } return switch (operation.substring(0, operation.indexOf(':') + 1) + first.name()) { // Ec2QueryHandler.parseTagsForResource case "ec2:TagSpecification", "ec2:TagSpecifications" -> @@ -330,6 +336,12 @@ final class TagOnCreate { member.key() == null ? "key" : member.key(), member.value() == null ? "value" : member.value()); } + /** As {@link #gap} but by {@link AwsQueryLists}'s rule, for a handler that reads its lists through it. */ + private static Reading sharedReader(TagOnCreateMembers.Member member, String... prefixes) { + return new Reading(List.of(prefixes), Numbering.AS_THE_SHARED_READER, + member.key() == null ? "key" : member.key(), member.value() == null ? "value" : member.value()); + } + /** * The prefix an SDK numbers a list or a map under: EC2 numbers a list under its name, the Query protocol * under the name its shape gives elements, or {@code member}, and a map's entries under {@code entry}. @@ -370,6 +382,23 @@ final class TagOnCreate { }); } } + // The members AwsQueryLists reads, so a handler that reads a list through it needs nothing modelled + // here: the spellings it accepts and the indices it takes are read from the one rule both follow. + case AS_THE_SHARED_READER -> { + for (String prefix : reading.prefixes()) { + Pattern members = AwsQueryLists.memberKeys(prefix, null); + String suffix = "." + reading.key(); + form.forEach((parameter, key) -> { + if (key == null || !parameter.endsWith(suffix)) { + return; + } + String numbered = parameter.substring(0, parameter.length() - suffix.length()); + if (members.matcher(numbered).matches()) { + tags.put(key, form.getOrDefault(numbered + "." + reading.value(), "")); + } + }); + } + } case EITHER_AT_EACH -> { for (int i = 1; ; i++) { String key = null; diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index e84ff55f55..38408a6671 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.core.common.*; +import io.github.hectorvent.floci.core.common.AwsQueryLists; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.SmithyValidationErrors; import io.github.hectorvent.floci.services.iam.model.AccessKey; @@ -1559,16 +1560,25 @@ public class IamQueryHandler { /** * The Properties map arrives as {@code Properties.entry.N.key} and - * {@code Properties.entry.N.value}, which is how the API Reference spells the member. + * {@code Properties.entry.N.value}, which is how the API Reference spells the member, bare as + * {@code Properties.N.key}, or under the generic {@code Properties.member.N}. All three are + * read through the shared reader, off the indices the request carries rather than off a run + * from 1, which is what the protocol's numbering means and what the constraints ahead of this + * already read: a request numbering 1 and 3 was held to both entries and stored the first, and + * one sending the bare form was held to its entries and stored none, reaching the + * required-member refusal on an empty map. + * + *

An entry numbered with no key is not an entry the map could hold, the same reading the + * constraint walk takes, so it is skipped rather than stored under a null key. */ private Response handlePutAccountProperties(MultivaluedMap params) { Map properties = new LinkedHashMap<>(); - for (int i = 1; ; i++) { - String key = getParam(params, "Properties.entry." + i + ".key"); - if (key == null) { - break; + for (AwsQueryLists.IndexedMember entry + : AwsQueryLists.members(params, "Properties", "entry")) { + String key = getParam(params, entry.prefix() + ".key"); + if (key != null) { + properties.put(key, getParam(params, entry.prefix() + ".value")); } - properties.put(key, getParam(params, "Properties.entry." + i + ".value")); } iamService.putAccountProperties(properties); return Response.ok(AwsQueryResponse.envelopeNoResult("PutAccountProperties", @@ -2165,14 +2175,14 @@ public class IamQueryHandler { Map> context = extractContextEntries(params); // AWS accepts only one permissions boundary document per simulation; a request that // provides more than one is not modeled and only the first is applied. - List boundaryInputList = extractIndexedValues(params, "PermissionsBoundaryPolicyInputList.member"); + List boundaryInputList = getMemberList(params, "PermissionsBoundaryPolicyInputList"); String boundaryDocument = boundaryInputList.isEmpty() ? null : boundaryInputList.get(0); CallerContext caller = new CallerContext(policyInputList, null, boundaryDocument); return simulationResults("SimulateCustomPolicy", params, caller, actionNames, resourceArns, context); } private List requireActionNames(MultivaluedMap params) { - List actionNames = extractIndexedValues(params, "ActionNames.member"); + List actionNames = getMemberList(params, "ActionNames"); if (actionNames.isEmpty()) { throw new AwsException("ValidationError", "At least one ActionNames member is required.", 400); } @@ -2180,7 +2190,7 @@ public class IamQueryHandler { } private List requirePolicyInputList(MultivaluedMap params) { - List policyInputList = extractIndexedValues(params, "PolicyInputList.member"); + List policyInputList = getMemberList(params, "PolicyInputList"); if (policyInputList.isEmpty()) { throw new AwsException("ValidationError", "At least one PolicyInputList member is required.", 400); } @@ -2188,7 +2198,7 @@ public class IamQueryHandler { } private List extractResourceArnsOrWildcard(MultivaluedMap params) { - List resourceArns = extractIndexedValues(params, "ResourceArns.member"); + List resourceArns = getMemberList(params, "ResourceArns"); return resourceArns.isEmpty() ? List.of("*") : resourceArns; } @@ -2234,7 +2244,7 @@ public class IamQueryHandler { // with it. CallerContext caller = iamService.resolveAttachedPrincipalContext(policySourceArn); List allDocuments = new ArrayList<>(caller.identityPolicies()); - allDocuments.addAll(extractIndexedValues(params, "PolicyInputList.member")); + allDocuments.addAll(getMemberList(params, "PolicyInputList")); List keys = policyEvaluator.contextKeysReferencedIn(allDocuments); return Response.ok(AwsQueryResponse.envelope("GetContextKeysForPrincipalPolicy", AwsNamespaces.IAM, contextKeyNamesXml(keys))).build(); @@ -2765,20 +2775,14 @@ public class IamQueryHandler { private DelegationPermission parseDelegationPermissions(MultivaluedMap params) { String templateArn = getParam(params, "Permissions.PolicyTemplateArn"); List parameters = new ArrayList<>(); - for (int index : memberIndices(params, "Permissions.Parameters.member.")) { - String prefix = "Permissions.Parameters.member." + index; - List values = new ArrayList<>(); - for (int valueIndex : memberIndices(params, prefix + ".Values.member.")) { - // An index is read off the keys, so one can be present through a key of its own - // that carries no value, as a dotted sub-member does. That is no value to store: - // AWS reads the member it knows and nothing from the key it does not. - String value = getParam(params, prefix + ".Values.member." + valueIndex); - if (value != null) { - values.add(value); - } - } - parameters.add(new PolicyParameter(getParam(params, prefix + ".Name"), - getParam(params, prefix + ".Type"), values)); + for (AwsQueryLists.IndexedMember parameter + : AwsQueryLists.members(params, "Permissions.Parameters", null)) { + // The values are read through the same reader, which skips an index present through a + // key of its own that carries no value, as a dotted sub-member is: AWS reads the + // member it knows and nothing from the key it does not. + List values = getMemberList(params, parameter.prefix() + ".Values"); + parameters.add(new PolicyParameter(getParam(params, parameter.prefix() + ".Name"), + getParam(params, parameter.prefix() + ".Type"), values)); } if (templateArn == null && parameters.isEmpty() && params.getFirst("Permissions") == null) { @@ -2789,22 +2793,6 @@ public class IamQueryHandler { return new DelegationPermission(templateArn, parameters); } - /** - * The indices a request supplied under an indexed member prefix, in order. Read from the keys - * the request carries rather than counted up from one, so a list numbered from two, or one - * with a gap in it, keeps every entry instead of being cut short at the first index missing. - */ - private static List memberIndices(MultivaluedMap params, String prefix) { - return params.keySet().stream() - .filter(key -> key.startsWith(prefix)) - .map(key -> key.substring(prefix.length()).split("\\.")[0]) - .filter(segment -> segment.matches("\\d+")) - .map(Integer::valueOf) - .distinct() - .sorted() - .toList(); - } - /** * The caller's principal ARN, or the account-root stand-in when the access key maps to no IAM * user, which is the same synthesized principal {@code IamEnforcementFilter} uses. An owner has @@ -3453,24 +3441,27 @@ public class IamQueryHandler { * binds the members as sent, so the count is taken here, before the map collapses repeated keys. * Duplicate keys in the request are rejected with InvalidInput (case-insensitively for users and * roles, and case-sensitively for other IAM resource types). + * + *

The members are read off the indices the request numbers them with rather than off a run + * from 1, which is what the protocol's numbering means and what the constraints ahead of this + * already read: a request numbering tags 1 and 3 is counted as two and stores both, where + * stopping at the gap held such a caller to a tag it was then not given and left the tag past + * the gap unchecked. A member numbered with a value and no key is no tag a map could hold, so + * nothing is stored for it, and the index a violation names is the one the request spelled. */ private Map extractTags(MultivaluedMap params, boolean caseInsensitiveKeys) { - List> members = new ArrayList<>(); - for (int i = 1; ; i++) { - String key = params.getFirst("Tags.member." + i + ".Key"); - String value = params.getFirst("Tags.member." + i + ".Value"); - if (key == null) { - break; - } - members.add(Map.entry(key, value != null ? value : "")); - } + List members = AwsQueryLists.members(params, "Tags", null); checkListLength(members.size(), "tags"); Set seenKeys = new HashSet<>(); Map tags = new LinkedHashMap<>(); - for (int i = 0; i < members.size(); i++) { - String key = members.get(i).getKey(); - String value = members.get(i).getValue(); - String at = "tags." + (i + 1) + ".member"; + for (AwsQueryLists.IndexedMember member : members) { + String key = params.getFirst(member.prefix() + ".Key"); + if (key == null) { + continue; + } + String sent = params.getFirst(member.prefix() + ".Value"); + String value = sent != null ? sent : ""; + String at = "tags." + member.index() + ".member"; String keyViolation = tagKeyViolation(key); if (keyViolation != null) { throw validationError(key, at + ".key", keyViolation); @@ -3544,23 +3535,36 @@ public class IamQueryHandler { return IamValidationErrors.validationError(at, value, constraint); } + /** + * The values a list's members carry, off the indices the request numbers them with rather than + * off a run from 1: {@code .member.N} and the bare {@code .N} alike, as the shared + * reader takes them and as the constraints ahead of this already read them. A request numbering + * members 1 and 3 therefore carries both, where stopping at the gap carried the first alone. + * + *

An index numbered only under a deeper key carries no value of its own and is no member of + * a list of values, which is the reading the constraint walk takes for one. A member sent empty + * is a value the request carries, as it is to the constraints, so it is kept rather than left + * out to leave the list one member short. + */ private List getMemberList(MultivaluedMap params, String name) { List values = new ArrayList<>(); - for (int i = 1; ; i++) { - String value = params.getFirst(name + ".member." + i); - if (value == null) break; - values.add(value); + for (AwsQueryLists.IndexedMember member : AwsQueryLists.members(params, name, null)) { + String value = params.getFirst(member.prefix()); + if (value != null) { + values.add(value); + } } return values; } + /** + * {@code tagKeyListType} binds the keys as sent, the same as the tag list, so the count is + * taken over the indices the request numbers rather than over a run from 1: a request numbering + * keys 1 and 3 removes both and is held to both, where stopping at the gap removed the first + * alone and left the second neither counted nor checked. + */ private List extractTagKeys(MultivaluedMap params) { - List keys = new ArrayList<>(); - for (int i = 1; ; i++) { - String key = params.getFirst("TagKeys.member." + i); - if (key == null) break; - keys.add(key); - } + List keys = getMemberList(params, "TagKeys"); checkListLength(keys.size(), "tagKeys"); for (String key : keys) { String violation = tagKeyViolation(key); @@ -3572,29 +3576,24 @@ public class IamQueryHandler { return keys; } - private List extractIndexedValues(MultivaluedMap params, String prefix) { - List values = new ArrayList<>(); - for (int i = 1; ; i++) { - String value = params.getFirst(prefix + "." + i); - if (value == null) break; - values.add(value); - } - return values; - } - /** * Reads every {@code ContextEntries.member.N.ContextKeyValues.member.M}. AWS context keys * are set-typed, and the evaluator's set operators quantify over the whole set, so reading * only {@code member.1} silently dropped the values a ForAnyValue:/ForAllValues: condition * has to see. An entry that names a key but supplies no value is skipped. + * + *

Both levels are read off the indices the request numbers them with, so an entry past a gap + * is read with every value it carries: dropping it took its key and all of its values with it, + * which is the same class of loss one level up. */ private Map> extractContextEntries(MultivaluedMap params) { Map> context = new HashMap<>(); - for (int i = 1; ; i++) { - String name = params.getFirst("ContextEntries.member." + i + ".ContextKeyName"); - if (name == null) break; - List values = extractIndexedValues( - params, "ContextEntries.member." + i + ".ContextKeyValues.member"); + for (AwsQueryLists.IndexedMember entry : AwsQueryLists.members(params, "ContextEntries", null)) { + String name = params.getFirst(entry.prefix() + ".ContextKeyName"); + if (name == null) { + continue; + } + List values = getMemberList(params, entry.prefix() + ".ContextKeyValues"); if (!values.isEmpty()) { context.put(name, values); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesIntegrationTest.java index 76f2dd2c41..37cf65ad53 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesIntegrationTest.java @@ -146,6 +146,71 @@ class AccountPropertiesIntegrationTest { .when().post("/").then().statusCode(200); } + /** + * The protocol numbers a map's entries, it does not run them from 1 without a gap, and the + * constraints read every index the request carries. So a request numbering 1 and 3 is held to + * both entries and has to store both: stopping at the gap held a caller to an entry it was + * then not given. + */ + @Test + void entriesTheRequestNumbersWithAGapAreAllStored() { + String ns = namespace(); + + iam("PutAccountProperties") + .formParam("Properties.entry.1.key", ns + "/First") + .formParam("Properties.entry.1.value", "one") + .formParam("Properties.entry.3.key", ns + "/Third") + .formParam("Properties.entry.3.value", "three") + .when().post("/").then().statusCode(200); + + iam("GetAccountProperties").when().post("/").then().statusCode(200) + .body(containsString(ns + "/First")) + .body(containsString("one")) + .body(containsString(ns + "/Third")) + .body(containsString("three")); + } + + /** + * The bare {@code Properties.N} spelling, which the shared reader takes alongside + * {@code Properties.entry.N} and {@code Properties.member.N}. The constraints read it, so a + * request sending it carries a map: reading only the one spelling left it an empty map and the + * refusal for a member that never arrived. + */ + @Test + void theBareAndMemberSpellingsOfAnEntryAreRead() { + String bare = namespace(); + + iam("PutAccountProperties") + .formParam("Properties.1.key", bare + "/Bare") + .formParam("Properties.1.value", "read") + .when().post("/").then().statusCode(200); + + String member = namespace(); + + iam("PutAccountProperties") + .formParam("Properties.member.1.key", member + "/Member") + .formParam("Properties.member.1.value", "read") + .when().post("/").then().statusCode(200); + + iam("GetAccountProperties").when().post("/").then().statusCode(200) + .body(containsString(bare + "/Bare")) + .body(containsString(member + "/Member")); + } + + /** + * An entry numbered with a value and no key, which is no entry the map could hold: the + * constraint walk neither counts nor answers it, and nothing is stored under a null key. The + * request carries that one entry alone, so what is left is an empty map. + */ + @Test + void anEntryNumberedWithNoKeyIsNoEntry() { + iam("PutAccountProperties") + .formParam("Properties.entry.1.value", "orphan") + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("Member must not be null")); + } + @Test void anAbsentPropertiesMapIsRejected() { iam("PutAccountProperties").when().post("/").then().statusCode(400) diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java index fbad8ef629..b9d48317a4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java @@ -383,6 +383,34 @@ class DelegationRequestIntegrationTest { equalTo("reports")); } + @Test + void aPolicyParameterListSentBareKeepsItsEntries() { + // The bare List.N spelling, which the constraints ahead of this operation read alongside + // the generic one: reading only the generic form left the parameters it carried unread. + String id = iam(PARTNER_AUTH) + .formParam("Action", "CreateDelegationRequest") + .formParam("Description", "d") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", workflowId()) + .formParam("SessionDuration", "3600") + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .formParam("Permissions.Parameters.2.Name", "BucketName") + .formParam("Permissions.Parameters.2.Type", "string") + .formParam("Permissions.Parameters.2.Values.4", "reports") + .when().post("/").then().statusCode(200) + .extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult" + + ".DelegationRequestId"); + + byId(PARTNER_AUTH, "GetDelegationRequest", id) + .statusCode(200) + .body("GetDelegationRequestResponse.GetDelegationRequestResult" + + ".DelegationRequest.Permissions.Parameters.member.Name", + equalTo("BucketName")) + .body("GetDelegationRequestResponse.GetDelegationRequestResult" + + ".DelegationRequest.Permissions.Parameters.member.Values.member", + equalTo("reports")); + } + @Test void theCustomerReleasesTheTokenAndTheRequestFinalizes() { String id = createdId(); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryListIndicesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryListIndicesIntegrationTest.java new file mode 100644 index 0000000000..64b189e2af --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryListIndicesIntegrationTest.java @@ -0,0 +1,258 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.not; + +/** + * Every list these operations read is read off the indices the request numbers its members with, + * not off a run from 1 that stops at the first gap. The Query protocol numbers a list's members, + * and the constraints ahead of each operation read every index the request names, so a request + * numbering 1 and 3 was held to both members and then given one. The bare {@code List.N} spelling + * the constraints read is read here too. + */ +@QuarkusTest +class IamQueryListIndicesIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261103/us-east-1/iam/aws4_request"; + + private static final String CODE = "ErrorResponse.Error.Code"; + private static final String MESSAGE = "ErrorResponse.Error.Message"; + + private static final String TAGS = "ListUserTagsResponse.ListUserTagsResult.Tags.member.Key"; + + /** 40 characters, the only length `thumbprintType` accepts. */ + private static final String THUMBPRINT = "9e99a48a9960b14926bb7f3b02e22da2b0ab7280"; + private static final String OTHER_THUMBPRINT = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; + + private static final String ALLOW_GET_OBJECT = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + + /** The provider below outlives this class otherwise, and the next class to list providers reads it. */ + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private static RequestSpecification iam(String action) { + return given().header("Authorization", IAM_AUTH).formParam("Action", action); + } + + private static String unique(String prefix) { + return prefix + "-" + System.nanoTime(); + } + + private static String createUser(String prefix) { + String name = unique(prefix); + iam("CreateUser").formParam("UserName", name).when().post("/").then().statusCode(200); + return name; + } + + private static RequestSpecification listTags(String user) { + return iam("ListUserTags").formParam("UserName", user); + } + + /** + * A request numbering tags 1 and 3 carries two tags: the constraints hold it to both, so + * storing the first alone left the caller a tag short of what it was answered for. + */ + @Test + void tagsTheRequestNumbersWithAGapAreAllStored() { + String user = createUser("gap-tags"); + + iam("TagUser").formParam("UserName", user) + .formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "platform") + .formParam("Tags.member.3.Key", "owner").formParam("Tags.member.3.Value", "ops") + .when().post("/").then().statusCode(200); + + listTags(user).when().post("/").then().statusCode(200) + .body(TAGS, hasItems("team", "owner")); + } + + /** + * A tag numbered with a value and no key never reaches the operation: {@code Key} is required, so the + * constraints ahead of it answer under the index the request spelled, and nothing is attached. The skip + * inside the reader sits behind that gate, for a member the model requires nothing of. + */ + @Test + void aTagNumberedWithAValueAndNoKeyIsRefusedBeforeTheOperation() { + String user = createUser("no-key-tags"); + + iam("TagUser").formParam("UserName", user) + .formParam("Tags.member.1.Value", "blue") + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("ValidationError")) + .body(MESSAGE, containsString("Value at 'tags.1.member.key' failed to satisfy constraint: " + + "Member must not be null")); + + listTags(user).when().post("/").then().statusCode(200) + .body(not(containsString("blue"))); + } + + /** The duplicate check reads every tag the request carries, so a repeat past a gap is one. */ + @Test + void aDuplicateTagKeyPastAGapIsStillRefused() { + String user = createUser("gap-dup-tags"); + + iam("TagUser").formParam("UserName", user) + .formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "platform") + .formParam("Tags.member.3.Key", "Team").formParam("Tags.member.3.Value", "payments") + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("InvalidInput")) + .body(MESSAGE, equalTo("Duplicate tag keys found. Please note that Tag keys are case insensitive.")); + + listTags(user).when().post("/").then().statusCode(200) + .body(not(containsString("platform"))); + } + + /** The bare spelling of a tag, which the constraints read and the operation now reads with them. */ + @Test + void theBareSpellingOfATagIsRead() { + String user = createUser("bare-tags"); + + iam("TagUser").formParam("UserName", user) + .formParam("Tags.1.Key", "bare").formParam("Tags.1.Value", "read") + .when().post("/").then().statusCode(200); + + listTags(user).when().post("/").then().statusCode(200) + .body(TAGS, equalTo("bare")); + } + + /** The keys an untag request numbers, where dropping the second left its tag behind. */ + @Test + void tagKeysTheRequestNumbersWithAGapAreAllRemoved() { + String user = createUser("gap-untag"); + + iam("TagUser").formParam("UserName", user) + .formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "platform") + .formParam("Tags.member.2.Key", "owner").formParam("Tags.member.2.Value", "ops") + .when().post("/").then().statusCode(200); + + iam("UntagUser").formParam("UserName", user) + .formParam("TagKeys.member.1", "team") + .formParam("TagKeys.member.3", "owner") + .when().post("/").then().statusCode(200); + + listTags(user).when().post("/").then().statusCode(200) + .body(not(containsString("team"))) + .body(not(containsString("owner"))); + } + + /** + * A key past a gap is held to `tagKeyType`, where it used to be dropped unchecked and the + * request went on to remove the keys ahead of it. + */ + @Test + void aTagKeyPastAGapIsHeldToItsConstraints() { + String user = createUser("gap-untag-bad"); + + iam("TagUser").formParam("UserName", user) + .formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "platform") + .when().post("/").then().statusCode(200); + + iam("UntagUser").formParam("UserName", user) + .formParam("TagKeys.member.1", "team") + .formParam("TagKeys.member.3", "cost#center") + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("ValidationError")) + .body(MESSAGE, containsString("Value at 'tagKeys' failed to satisfy constraint")); + + listTags(user).when().post("/").then().statusCode(200) + .body(TAGS, equalTo("team")); + } + + /** `tagKeyListType` binds the keys as sent, so a fifty-first key numbered past a gap is one. */ + @Test + void theTagKeyCountIsTakenOverTheIndicesTheRequestNumbers() { + String user = createUser("gap-untag-count"); + + RequestSpecification request = iam("UntagUser").formParam("UserName", user); + for (int i = 1; i <= 50; i++) { + request.formParam("TagKeys.member." + i, "key" + i); + } + request.formParam("TagKeys.member.52", "key52") + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("ValidationError")) + .body(MESSAGE, containsString("Value at 'tagKeys' failed to satisfy constraint: " + + "Member must have length less than or equal to 50")); + } + + /** + * A provider's thumbprints and client IDs, the generic spelling numbered with a gap and the + * bare one beside it: both lists reach the store with every member the request carried. + */ + @Test + void aProvidersThumbprintsAndClientIdsAreReadOffTheirIndices() { + String arn = iam("CreateOpenIDConnectProvider") + .formParam("Url", "https://oidc.query-indices.example.com/" + unique("provider")) + .formParam("ThumbprintList.member.1", THUMBPRINT) + .formParam("ThumbprintList.member.3", OTHER_THUMBPRINT) + .formParam("ClientIDList.2", "sts.amazonaws.com") + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString( + "CreateOpenIDConnectProviderResponse.CreateOpenIDConnectProviderResult.OpenIDConnectProviderArn"); + cleanup.register(() -> iam("DeleteOpenIDConnectProvider") + .formParam("OpenIDConnectProviderArn", arn).when().post("/").then().statusCode(200)); + + iam("GetOpenIDConnectProvider").formParam("OpenIDConnectProviderArn", arn) + .when().post("/").then().statusCode(200) + .body("GetOpenIDConnectProviderResponse.GetOpenIDConnectProviderResult.ThumbprintList.member", + hasItems(THUMBPRINT, OTHER_THUMBPRINT)) + .body("GetOpenIDConnectProviderResponse.GetOpenIDConnectProviderResult.ClientIDList.member", + equalTo("sts.amazonaws.com")); + } + + /** + * A simulation evaluates every action the request numbers, and reads its documents off the + * bare spelling too. A list whose first member is numbered 2 is a list with a member, where + * reading from 1 answered it as the list that never arrived. + */ + @Test + void everyActionTheRequestNumbersIsSimulated() { + iam("SimulateCustomPolicy") + .formParam("PolicyInputList.1", ALLOW_GET_OBJECT) + .formParam("ActionNames.member.2", "s3:GetObject") + .formParam("ActionNames.member.4", "ec2:RunInstances") + .formParam("ResourceArns.member.1", "*") + .when().post("/").then().statusCode(200) + .body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults" + + ".member.find { it.EvalActionName == 's3:GetObject' }.EvalDecision", + equalTo("allowed")) + .body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults" + + ".member.find { it.EvalActionName == 'ec2:RunInstances' }.EvalDecision", + equalTo("implicitDeny")); + } + + /** + * A context entry numbered past a gap, with its own values numbered past gaps of their own. + * Dropping the entry dropped its key and every value with it, and a set operator over a key + * the request did supply then decided on a context it never saw. + */ + @Test + void aContextEntryPastAGapIsReadWithEveryValueItCarries() { + String policy = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*", + "Condition":{"ForAnyValue:StringEquals":{"dynamodb:LeadingKeys":["USER_alice"]}}} + ]}"""; + + iam("SimulateCustomPolicy") + .formParam("PolicyInputList.member.1", policy) + .formParam("ActionNames.member.1", "dynamodb:GetItem") + .formParam("ResourceArns.member.1", "*") + .formParam("ContextEntries.member.3.ContextKeyName", "dynamodb:LeadingKeys") + .formParam("ContextEntries.member.3.ContextKeyValues.member.2", "USER_bob") + .formParam("ContextEntries.member.3.ContextKeyValues.member.4", "USER_alice") + .when().post("/").then().statusCode(200) + .body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults" + + ".member.EvalDecision", equalTo("allowed")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamTagOnCreateEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamTagOnCreateEnforcementIntegrationTest.java index af6181936f..fef316d7eb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamTagOnCreateEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamTagOnCreateEnforcementIntegrationTest.java @@ -41,6 +41,8 @@ class IamTagOnCreateEnforcementIntegrationTest { private static final String ADMIN = "test"; private static final String ACCOUNT = "000000000000"; private static final String IMAGE = "ami-0abcdef1234567890"; + private static final String TRUST = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}"; private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); @TestHTTPResource("/") @@ -260,19 +262,74 @@ class IamTagOnCreateEnforcementIntegrationTest { void aRoleCreatedWithTagsNeedsTagRole() { User user = user("tag-role"); String role = "tag-role-" + suffix(); - String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," - + "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}"; user.policy(allow("iam:CreateRole")); - refused(user.query("iam", "CreateRole").formParam("RoleName", role).formParam("AssumeRolePolicyDocument", trust) + refused(user.query("iam", "CreateRole").formParam("RoleName", role).formParam("AssumeRolePolicyDocument", TRUST) .formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "blue").post("/").then(), "iam:TagRole"); user.policy(allow("iam:CreateRole") + "," + allow("iam:TagRole")); - user.query("iam", "CreateRole").formParam("RoleName", role).formParam("AssumeRolePolicyDocument", trust) + user.query("iam", "CreateRole").formParam("RoleName", role).formParam("AssumeRolePolicyDocument", TRUST) .formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "blue").post("/").then() .statusCode(200); - cleanup.register(() -> admin("iam").formParam("Action", "DeleteRole").formParam("RoleName", role).post("/")); + deleteRoleLater(role); + } + + /** + * IAM's handler reads every index a request numbers, bare or under {@code member}, so the tags its create is + * checked with are the tags the role gets. A tag numbered only at 2 meets a policy that requires it, where a + * reading that stopped at the first gap saw none and refused a create the handler would have tagged. + */ + @Test + void anIamTagPastAGapMeetsAPolicyRequiringIt() { + User user = user("tag-role-gap"); + String role = "tag-role-gap-" + suffix(); + user.policy("{\"Effect\":\"Allow\",\"Action\":\"iam:CreateRole\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\"}}}," + allow("iam:TagRole")); + + user.query("iam", "CreateRole").formParam("RoleName", role).formParam("AssumeRolePolicyDocument", TRUST) + .formParam("Tags.2.Key", "team").formParam("Tags.2.Value", "blue").post("/").then().statusCode(200); + deleteRoleLater(role); + admin("iam").formParam("Action", "ListRoleTags").formParam("RoleName", role).post("/").then() + .statusCode(200).body(containsString("team")); + } + + /** + * Tags split across the two spellings are one list to the handler, so they are one set to the policy: a deny + * naming both keys holds, where a set per spelling matched neither and let the create through with both tags. + */ + @Test + void iamTagsSplitAcrossSpellingsAreCheckedAsOneSet() { + User user = user("tag-role-split"); + String role = "tag-role-split-" + suffix(); + user.policy(allow("iam:CreateRole") + "," + allow("iam:TagRole") + + ",{\"Effect\":\"Deny\",\"Action\":\"iam:CreateRole\",\"Resource\":\"*\",\"Condition\":" + + "{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\",\"aws:RequestTag/env\":\"prod\"}}}"); + + refused(user.query("iam", "CreateRole").formParam("RoleName", role) + .formParam("AssumeRolePolicyDocument", TRUST) + .formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "blue") + .formParam("Tags.2.Key", "env").formParam("Tags.2.Value", "prod").post("/").then(), "iam:CreateRole"); + admin("iam").formParam("Action", "GetRole").formParam("RoleName", role).post("/").then().statusCode(404); + } + + /** + * A key that is blank but not empty is a key IAM takes, {@code tagKeyType} admitting a separator, so the + * policy is checked with it: a deny naming it holds rather than passing over a key the role would get. + */ + @Test + void anIamTagKeyThatIsBlankIsReadForThePolicyToo() { + User user = user("tag-role-blank"); + String role = "tag-role-blank-" + suffix(); + user.policy(allow("iam:CreateRole") + "," + allow("iam:TagRole") + + ",{\"Effect\":\"Deny\",\"Action\":\"iam:CreateRole\",\"Resource\":\"*\",\"Condition\":" + + "{\"StringEquals\":{\"aws:RequestTag/ \":\"blue\",\"aws:RequestTag/env\":\"prod\"}}}"); + + refused(user.query("iam", "CreateRole").formParam("RoleName", role) + .formParam("AssumeRolePolicyDocument", TRUST) + .formParam("Tags.member.1.Key", " ").formParam("Tags.member.1.Value", "blue") + .formParam("Tags.2.Key", "env").formParam("Tags.2.Value", "prod").post("/").then(), "iam:CreateRole"); + admin("iam").formParam("Action", "GetRole").formParam("RoleName", role).post("/").then().statusCode(404); } @Test @@ -426,6 +483,10 @@ class IamTagOnCreateEnforcementIntegrationTest { .formParam("InstanceId.1", instanceId).post("/")); } + private void deleteRoleLater(String role) { + cleanup.register(() -> admin("iam").formParam("Action", "DeleteRole").formParam("RoleName", role).post("/")); + } + private void deleteQueueLater(Response created) { String url = created.then().statusCode(200).extract().xmlPath() .getString("CreateQueueResponse.CreateQueueResult.QueueUrl");