Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): read declared constraints before the lookup they precede (#6402)
Priamo Germosen62c202f0730d
diff --git a/docs/services/iam.md b/docs/services/iam.mdindex 3d6b901f48..7fbc9f52b9 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -445,15 +445,21 @@ key in. A role named as the policy source is not a session, so there is no sessi`aws:userid` and no documented `aws:PrincipalType` for it; those keys stay absent and a statementmatching on one does not match.-`PolicySourceArn` on `SimulatePrincipalPolicy` and `GetContextKeysForPrincipalPolicy` resolves an IAM-user or role only, not a group. `SimulateCustomPolicy` accepts only one-`PermissionsBoundaryPolicyInputList` document, matching AWS's own documented limit; extra documents-beyond the first are ignored. Neither simulation action evaluates a resource-based policy-(`ResourcePolicy`) or `OrderedOrganizationPolicyInputList`, and neither returns-`MatchedStatements`, `ResourceSpecificResults`, or a `PermissionsBoundaryDecisionDetail`: only the-top-level `EvalDecision` is populated. `ContextEntries.member.N.ContextKeyType` is accepted but not-read; the comparison is driven entirely by the policy's own condition operator (`Bool`,-`NumericEquals`, `DateEquals`, and so on), not by the declared type.+`PolicySourceArn` on `SimulatePrincipalPolicy` and `GetContextKeysForPrincipalPolicy` resolves an+IAM user or role only, not a group. It is held to the 20 characters `arnType` declares before it+is resolved, so a value too short to be any ARN is a `ValidationError` with status 400 naming the+length rather than an entity resolved out of whatever follows its last slash. A value that clears+20 characters and still parses as no ARN is resolved as before: the member publishes a length and+no pattern, and no source records what AWS answers for one, so inventing a refusal would be a+guess. The length wording follows the captures of real IAM length violations, naming only the+bound the value broke and leaving the value itself out of the message. `SimulateCustomPolicy`+accepts only one `PermissionsBoundaryPolicyInputList` document, matching AWS's own documented+limit; extra documents beyond the first are ignored. Neither simulation action evaluates a+resource-based policy (`ResourcePolicy`) or `OrderedOrganizationPolicyInputList`, and neither+returns `MatchedStatements`, `ResourceSpecificResults`, or a `PermissionsBoundaryDecisionDetail`:+only the top-level `EvalDecision` is populated. `ContextEntries.member.N.ContextKeyType` is+accepted but not read; the comparison is driven entirely by the policy's own condition operator+(`Bool`, `NumericEquals`, `DateEquals`, and so on), not by the declared type.### Last-Accessed Reporting@@ -510,6 +516,16 @@ entity's own, names no entity and is rejected rather than falling back to a samejob belongs to the account that created it, an unknown `JobId` is `NoSuchEntity`, and `Granularity`is validated against `SERVICE_LEVEL`/`ACTION_LEVEL` and echoed back as `JobType`.+Declared constraints are read before any of those lookups, because the validation AWS runs ahead of+an operation never reaches its store: a request that breaks one is a 400 whether or not the job or+the entity exists, and checking it afterwards would answer `NoSuchEntity` 404 for a request AWS+refuses with a `ValidationError`. So `JobId` is held to the fixed 36 characters `jobIDType`+declares, `MaxItems` and `Marker` are read before the job they page is fetched, and `Granularity` is+read before the ARN it is filed against is resolved. A fixed length reports as one constraint,+"Member must have length equal to 36", which is the form Auto Scaling already uses for the same+shape, and the offending value is left out, which is how the most recent IAM length and pattern+recordings render one. Whether an id that clears the shape names a job is still a 404.+The report is produced when the job is created and stored with it, matching AWS, where`GenerateServiceLastAccessedDetails` produces a report and the `Get*` operations retrieve that one.So a completed job keeps answering what it answered first: editing the policies afterwards does not@@ -994,7 +1010,11 @@ the model's `[\w]+` before anything goes looking for it, so one carrying charactclass is a `ValidationError` with status 400 quoting the pattern, while an id that satisfies thepattern and names no credential of that user is `NoSuchEntity` with status 404 and the message"No such credential `<id>` exists". The published length of 20 to 128 is enforced the same way, and-an id breaking both constraints is reported as two validation errors rather than one.+an id breaking both constraints is reported as two validation errors rather than one. A length+violation names only the bound the id broke, "Member must have length greater than or equal to 20"+for a short one and "Member must have length less than or equal to 128" for a long one, which is+how every recorded IAM length violation reads; reporting both at once would refuse a short id for a+ceiling it is nowhere near.A user that still owns a credential cannot be deleted: `DeleteUser` is `DeleteConflict` with status409. Where access keys, policies and group memberships each get a message naming what is in thediff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.javaindex 9431bd6ed6..6fb77af085 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@@ -66,6 +66,11 @@ public class IamQueryHandler {/** {@code MaxItems} on the readers that page through {@link #paginate}: "defaults to 100", range 1 to 1000. */private static final int DEFAULT_MAX_ITEMS = 100;private static final int MAX_MAX_ITEMS = 1000;+ /** {@code jobIDType} on every report reader: min 36 and max 36, which is a UUID string. */+ private static final int JOB_ID_LENGTH = 36;+ /** {@code arnType} on {@code PolicySourceArn}: 20 to 2048, with no pattern. */+ private static final int ARN_MIN_LENGTH = 20;+ private static final int ARN_MAX_LENGTH = 2048;/** {@code sortKeyType} on {@code GetOrganizationsAccessReport}. */private static final Set<String> SORT_KEYS = Set.of("SERVICE_NAMESPACE_ASCENDING","SERVICE_NAMESPACE_DESCENDING", "LAST_AUTHENTICATED_TIME_ASCENDING",@@ -2159,7 +2164,7 @@ public class IamQueryHandler {}private Response handleSimulatePrincipalPolicy(MultivaluedMap<String, String> params) {- String policySourceArn = getParam(params, "PolicySourceArn");+ String policySourceArn = validatedPolicySourceArn(params);CallerContext caller = iamService.resolvePrincipalContext(policySourceArn);List<String> actionNames = requireActionNames(params);List<String> resourceArns = extractResourceArnsOrWildcard(params);@@ -2249,7 +2254,7 @@ public class IamQueryHandler {}private Response handleGetContextKeysForPrincipalPolicy(MultivaluedMap<String, String> params) {- String policySourceArn = getParam(params, "PolicySourceArn");+ String policySourceArn = validatedPolicySourceArn(params);// "Only context keys referenced by the identity-based policies attached to the specified// entity, and any additional policies that you provide, are included": a grant the account// applies without attaching it is therefore not read here, though a simulation evaluates@@ -2276,6 +2281,9 @@ public class IamQueryHandler {String authorization) {String accountId = accountResolver.resolve(authorization);String arn = requireParam(params, "Arn");+ // The same rule as the readers below: the granularity is a declared enum, so it is read+ // before the ARN is resolved rather than inside the generate it is passed to.+ ServiceLastAccessedService.validateGranularity(params.getFirst("Granularity"));AccessAdvisorTarget target = resolveAccessAdvisorTarget(accountId, arn);// Already sorted and expanded, including the wildcard and NotAction grants that name no// namespace of their own.@@ -2294,8 +2302,10 @@ public class IamQueryHandler {*/private Response handleGetServiceLastAccessedDetails(MultivaluedMap<String, String> params,String authorization) {+ String jobId = validatedJobId(params);+ validatePagingInputs(params);ServiceLastAccessedJob job = serviceLastAccessedService.get(- accountResolver.resolve(authorization), requireParam(params, "JobId"));+ accountResolver.resolve(authorization), jobId);Page<String> page = paginate(job.getServiceNamespaces(), Function.identity(), params);XmlBuilder xml = new XmlBuilder().elem("JobStatus", "COMPLETED")@@ -2352,10 +2362,11 @@ public class IamQueryHandler {*/private Response handleGetOrganizationsAccessReport(MultivaluedMap<String, String> params,String authorization) {- String jobId = requireParam(params, "JobId");+ String jobId = validatedJobId(params);// Read before the lookup, because a value outside the enum is a bad request whether or not// the job exists: validating it after would answer NoSuchEntity for a request AWS rejects.String sortKey = validatedSortKey(params);+ validatePagingInputs(params);OrganizationsAccessReportJob job = organizationsAccessReportService.get(accountResolver.resolve(authorization), jobId);XmlBuilder xml = new XmlBuilder()@@ -2394,6 +2405,93 @@ public class IamQueryHandler {AwsNamespaces.IAM, xml.build())).build();}+ /**+ * {@code MaxItems} if the request carries one inside the range the reference publishes, null if+ * it carries none. Read without the list it will page, so a reader can check it before it looks+ * anything up.+ */+ private static Integer validatedMaxItems(MultivaluedMap<String, String> params) {+ String raw = params.getFirst("MaxItems");+ if (raw == null || raw.isBlank()) {+ return null;+ }+ int limit;+ try {+ limit = Integer.parseInt(raw.trim());+ } catch (NumberFormatException e) {+ throw new AwsException("InvalidInput",+ "The value " + raw + " at 'maxItems' is not a number.", 400);+ }+ if (limit < 1) {+ throw validationError(raw, "maxItems", "Member must have value greater than or equal to 1");+ }+ if (limit > MAX_MAX_ITEMS) {+ throw validationError(raw, "maxItems",+ "Member must have value less than or equal to " + MAX_MAX_ITEMS);+ }+ return limit;+ }++ /**+ * {@code JobId} held to the fixed 36 characters {@code jobIDType} declares, before the job is+ * looked up. The order is the whole point: a value that breaks a declared constraint is a bad+ * request whether or not the job exists, and the validation AWS runs ahead of an operation+ * never reaches its store, so checking it afterwards answers {@code NoSuchEntity} 404 where+ * AWS answers 400.+ *+ * <p>A fixed length reports as one constraint rather than as both bounds, the form+ * {@code lifecycleActionToken} already uses for the same shape in Auto Scaling, and the+ * offending value is left out, which is how the most recent IAM recordings render one.+ */+ private String validatedJobId(MultivaluedMap<String, String> params) {+ String jobId = requireParam(params, "JobId");+ if (jobId.length() != JOB_ID_LENGTH) {+ throw SmithyValidationErrors.validationError("Value at 'jobId' failed to satisfy "+ + "constraint: Member must have length equal to " + JOB_ID_LENGTH);+ }+ return jobId;+ }++ /**+ * The paging members, read ahead of the lookup whose result they page, for the reason+ * {@link #validatedJobId} is. {@link #paginate} reads them again when it runs: most of the+ * readers paged there look nothing up first, and a check only one caller performs is one the+ * next caller forgets.+ */+ private void validatePagingInputs(MultivaluedMap<String, String> params) {+ validatedMaxItems(params);+ String marker = params.getFirst("Marker");+ if (marker != null && !marker.isBlank() && markers.cursorOf(marker.trim()) == null) {+ markerIndex(marker);+ }+ }++ /**+ * {@code PolicySourceArn} held to the 20 to 2048 characters {@code arnType} declares, before+ * the entity it names is resolved. IAM answers that minimum on a sibling ARN member with a+ * {@code ValidationError} naming the length, so a value too short to be any ARN is refused on+ * its shape rather than resolved to whatever follows its last slash.+ *+ * <p>A value that clears 20 characters and still parses as no ARN is left alone: the member+ * publishes a length and no pattern, and what AWS answers for one is not recorded. An absent+ * or blank value is left alone too, the resolver below reporting that one.+ */+ private String validatedPolicySourceArn(MultivaluedMap<String, String> params) {+ String arn = getParam(params, "PolicySourceArn");+ if (arn == null || arn.isBlank()) {+ return arn;+ }+ if (arn.length() < ARN_MIN_LENGTH) {+ throw SmithyValidationErrors.validationError("Value at 'policySourceArn' failed to satisfy "+ + "constraint: Member must have length greater than or equal to " + ARN_MIN_LENGTH);+ }+ if (arn.length() > ARN_MAX_LENGTH) {+ throw SmithyValidationErrors.validationError("Value at 'policySourceArn' failed to satisfy "+ + "constraint: Member must have length less than or equal to " + ARN_MAX_LENGTH);+ }+ return arn;+ }+/*** {@code SortKey} if the request carries one the enum permits, null if it carries none. A* request that carries the member is held to the enum whatever it carries: an empty value is@@ -2437,9 +2535,11 @@ public class IamQueryHandler {*/private Response handleGetServiceLastAccessedDetailsWithEntities(MultivaluedMap<String, String> params,String authorization) {- ServiceLastAccessedJob job = serviceLastAccessedService.get(- accountResolver.resolve(authorization), requireParam(params, "JobId"));+ String jobId = validatedJobId(params);String namespace = requireParam(params, "ServiceNamespace");+ validatePagingInputs(params);+ ServiceLastAccessedJob job = serviceLastAccessedService.get(+ accountResolver.resolve(authorization), jobId);// The report named the services it covers, so an entity is only reported for one of those.List<ServiceLastAccessedEntity> reported = job.getServiceNamespaces().contains(namespace)? job.getEntities() : List.of();@@ -2841,22 +2941,9 @@ public class IamQueryHandler {// it would be against AWS. Operations that model no MaxItems at all pass through whole.int limit = maxItemsModeled ? DEFAULT_MAX_ITEMS : items.size();if (maxItemsModeled) {- String raw = params.getFirst("MaxItems");- if (raw != null && !raw.isBlank()) {- try {- limit = Integer.parseInt(raw.trim());- } catch (NumberFormatException e) {- throw new AwsException("InvalidInput",- "The value " + raw + " at 'maxItems' is not a number.", 400);- }- if (limit < 1) {- throw validationError(raw, "maxItems",- "Member must have value greater than or equal to 1");- }- if (limit > MAX_MAX_ITEMS) {- throw validationError(raw, "maxItems",- "Member must have value less than or equal to " + MAX_MAX_ITEMS);- }+ Integer asked = validatedMaxItems(params);+ if (asked != null) {+ limit = asked;}}if (from >= items.size()) {diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex 65877f0e22..0d8590651f 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -3941,19 +3941,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {* that matches nothing gets {@code NoSuchEntity}. Different mistakes, different answers.** <p>The API Reference publishes a length of 20 to 128 as well as the pattern, so both are- * checked, and both are reported when both are broken, in the order it prints them. The- * pattern message is the one recorded against AWS; the length wording is the form AWS uses for- * a member carrying both bounds, which {@link #validatePassword} spells the same- * way.+ * checked, and both are reported when both are broken, in the order it prints them.+ *+ * <p>Each message names the one bound the value broke, rather than both at once: every+ * recorded IAM length violation reads that way, "Member must have length less than or equal to+ * 64" for a user name over 64 and "Member must have length greater than or equal to 20" for an+ * ARN under 20, and a short id told about a 128-character ceiling it is nowhere near would be+ * reporting a constraint it did not break. The pattern message is the one recorded against+ * AWS.*/private void requireCredentialIdFormat(String credentialId) {String id = credentialId == null ? "" : credentialId;List<String> violations = new ArrayList<>();- if (id.length() < SERVICE_CREDENTIAL_ID_MIN_LENGTH- || id.length() > SERVICE_CREDENTIAL_ID_MAX_LENGTH) {- violations.add("Member must have length less than or equal to "- + SERVICE_CREDENTIAL_ID_MAX_LENGTH + " and greater than or equal to "+ if (id.length() < SERVICE_CREDENTIAL_ID_MIN_LENGTH) {+ violations.add("Member must have length greater than or equal to "+ SERVICE_CREDENTIAL_ID_MIN_LENGTH);+ } else if (id.length() > SERVICE_CREDENTIAL_ID_MAX_LENGTH) {+ violations.add("Member must have length less than or equal to "+ + SERVICE_CREDENTIAL_ID_MAX_LENGTH);}if (!SERVICE_CREDENTIAL_ID_PATTERN.matcher(id).matches()) {violations.add("Member must satisfy regular expression pattern: [\\w]+");diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.java b/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.javaindex a6f87f2704..8e970c4a01 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.java@@ -47,6 +47,20 @@ public class ServiceLastAccessedService {this.jobs = new IamJobStore<>(jobs, ServiceLastAccessedJob::getJobId);}+ /**+ * {@code AccessAdvisorUsageGranularityType}, checked on its own so the handler can read it+ * before it resolves the ARN the report is for: an enum AWS declares is refused whether or not+ * the entity exists. {@link #generate} checks it too, being reachable without the handler.+ */+ public static void validateGranularity(String granularity) {+ if (granularity != null && !GRANULARITIES.contains(granularity)) {+ throw SmithyValidationErrors.validationError(+ "Value '" + granularity + "' at 'granularity' "+ + "failed to satisfy constraint: Member must satisfy enum value set: "+ + "[SERVICE_LEVEL, ACTION_LEVEL]");+ }+ }+/*** Records a completed job for {@code arn} together with the report it produced, and returns* it. The report is computed by the caller and stored here, because AWS fixes a report at@@ -56,12 +70,7 @@ public class ServiceLastAccessedService {public ServiceLastAccessedJob generate(String accountId, String arn, String granularity,List<String> serviceNamespaces,List<ServiceLastAccessedEntity> entities) {- if (granularity != null && !GRANULARITIES.contains(granularity)) {- throw SmithyValidationErrors.validationError(- "Value '" + granularity + "' at 'granularity' "- + "failed to satisfy constraint: Member must satisfy enum value set: "- + "[SERVICE_LEVEL, ACTION_LEVEL]");- }+ validateGranularity(granularity);Instant now = Instant.now();// jobIDType is min 36 / max 36, which is exactly a UUID string.ServiceLastAccessedJob job = new ServiceLastAccessedJob(UUID.randomUUID().toString(), arn,diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.javaindex d57ffdde82..96ace60dba 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java@@ -555,6 +555,47 @@ class IamIntegrationTest {contains("aws:CurrentTime", "aws:username"));}+ /**+ * {@code PolicySourceArn} is {@code arnType}, min 20, and the simulator used to resolve the+ * entity out of whatever followed the last slash, so a value far too short to be an ARN+ * simulated against a user named after its tail. IAM answers that minimum with a+ * {@code ValidationError} naming the length, which is what both principal readers answer now.+ *+ * <p>A value that clears 20 characters and still parses as no ARN is deliberately untouched:+ * the member publishes no pattern and nothing records what AWS answers for one.+ */+ @Test+ @Order(88)+ void aPolicySourceArnUnderItsDeclaredLengthIsAValidationError() {+ String expected = "1 validation error detected: Value at 'policySourceArn' failed to "+ + "satisfy constraint: Member must have length greater than or equal to 20";++ given()+ .formParam("Action", "SimulatePrincipalPolicy")+ .formParam("PolicySourceArn", ":user/bob")+ .formParam("ActionNames.member.1", "s3:GetObject")+ .header("Authorization",+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", equalTo(expected));++ given()+ .formParam("Action", "GetContextKeysForPrincipalPolicy")+ .formParam("PolicySourceArn", ":role/admin")+ .header("Authorization",+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", equalTo(expected));+ }+@Test@Order(41)void getContextKeysForPrincipalPolicyMergesAttachedAndExtraPolicies() {diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportIntegrationTest.javaindex 41f042dc76..d343926d21 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportIntegrationTest.java@@ -460,4 +460,38 @@ class OrganizationsAccessReportIntegrationTest {assertEquals("OrganizationalUnitNotFoundException",report.getString(result("ErrorDetails.Code")));}++ /**+ * The ordering DRIFT-3 was about, on this reader. {@code jobIDType} is a fixed 36 characters,+ * so the shape is refused before anything is resolved: no organization is built here, and none+ * has to be, which is the point.+ */+ @Test+ void aJobIdOutsideItsDeclaredLengthIsRefusedWithoutAnOrganization() {+ iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport").formParam("JobId", "nope")+ .when().post("/").then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", equalTo(+ "1 validation error detected: Value at 'jobId' failed to satisfy constraint: "+ + "Member must have length equal to 36"));+ }++ /**+ * A well-formed id no job carries, with a {@code MaxItems} the model refuses: the paging+ * members are read before the job lookup, so this is a 400 rather than the 404 the missing job+ * would answer first.+ */+ @Test+ void anUnknownJobWithAMalformedMaxItemsIsAValidationErrorRatherThanNotFound() {+ iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")+ .formParam("JobId", "00000000-0000-4000-8000-000000000000")+ .formParam("MaxItems", "1001")+ .when().post("/").then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", equalTo(+ "1 validation error detected: Value '1001' at 'maxItems' failed to satisfy "+ + "constraint: Member must have value less than or equal to 1000"));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.javaindex ac5aa980a4..fd67ddeae5 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java@@ -39,6 +39,9 @@ class ServiceLastAccessedIntegrationTest {return given().header("Authorization", IAM_AUTH).formParam("Action", action);}+ /** Well formed at the 36 characters jobIDType declares, and carried by no job. */+ private static final String UNKNOWN_JOB_ID = "00000000-0000-4000-8000-000000000000";+private static String suffix() {return Long.toString(System.nanoTime(), 36);}@@ -1090,9 +1093,8 @@ class ServiceLastAccessedIntegrationTest {*/@Testvoid theRemainingEnumReportsAlsoOpenWithTheCount() {- // GenerateServiceLastAccessedDetails: the Granularity enum. The ARN has to resolve first,- // because the handler looks the target up before the granularity is checked, so a- // nonexistent one answers NoSuchEntity and never reaches it.+ // GenerateServiceLastAccessedDetails: the Granularity enum, on an ARN that resolves. The+ // enum is read ahead of that lookup now, which the test below pins on an ARN that does not.String arn = createUser("granularity-" + suffix());iam("GenerateServiceLastAccessedDetails").formParam("Arn", arn)@@ -1109,4 +1111,79 @@ class ServiceLastAccessedIntegrationTest {.body(containsString("1 validation error detected")).body(containsString("Member must satisfy enum value set"));}++ /**+ * The ordering DRIFT-3 was about. {@code jobIDType} is a fixed 36 characters, so an id of the+ * wrong length is a bad request on its shape and never reaches the store: AWS validates ahead+ * of the operation, and the store it would have been looked up in is behind it.+ */+ @Test+ void aJobIdOutsideItsDeclaredLengthIsRefusedBeforeTheLookup() {+ iam("GetServiceLastAccessedDetails").formParam("JobId", "nope")+ .when().post("/").then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", equalTo(+ "1 validation error detected: Value at 'jobId' failed to satisfy constraint: "+ + "Member must have length equal to 36"))+ .body(not(containsString("NoSuchEntity")));+ }++ /** The same shape on the entities reader, which pages the same job through the same id. */+ @Test+ void theWithEntitiesReaderHoldsTheSameJobIdShape() {+ iam("GetServiceLastAccessedDetailsWithEntities")+ .formParam("JobId", "nope").formParam("ServiceNamespace", "s3")+ .when().post("/").then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", containsString("Member must have length equal to 36"));+ }++ /**+ * The other half of the ordering: a well-formed id that no job carries, with a {@code MaxItems}+ * the model refuses. The paging members are read before the job is looked up, so this is the+ * 400 AWS answers rather than the 404 the missing job would otherwise produce first.+ */+ @Test+ void anUnknownJobWithAMalformedMaxItemsIsAValidationErrorRatherThanNotFound() {+ iam("GetServiceLastAccessedDetails")+ .formParam("JobId", UNKNOWN_JOB_ID).formParam("MaxItems", "0")+ .when().post("/").then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", containsString("at 'maxItems'"))+ .body(not(containsString("NoSuchEntity")));++ // And a marker that is no marker at all, on the same unknown job.+ iam("GetServiceLastAccessedDetails")+ .formParam("JobId", UNKNOWN_JOB_ID).formParam("Marker", "not-a-marker")+ .when().post("/").then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("InvalidInput"));++ // The unknown job on its own is still a 404, so the ordering is what changed and not the+ // answer for a request that breaks nothing.+ iam("GetServiceLastAccessedDetails").formParam("JobId", UNKNOWN_JOB_ID)+ .when().post("/").then()+ .statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));+ }++ /**+ * The same rule on the generator: {@code Granularity} is a declared enum, so it is refused+ * whether or not the ARN names anything. It used to be read inside the generate, behind the+ * lookup that resolves the target.+ */+ @Test+ void theGranularityIsRefusedWhateverTheArnNames() {+ iam("GenerateServiceLastAccessedDetails")+ .formParam("Arn", "arn:aws:iam::000000000000:user/laa-nobody-" + suffix())+ .formParam("Granularity", "HOURLY")+ .when().post("/").then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message", containsString("Member must satisfy enum value set"))+ .body(not(containsString("NoSuchEntity")));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialIntegrationTest.javaindex f815fde783..685e51c524 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialIntegrationTest.java@@ -646,22 +646,33 @@ class ServiceSpecificCredentialIntegrationTest {* The id's other published constraint is a length of 20 to 128. A short id satisfies* {@code [\w]+} and still fails, and one that breaks both constraints is reported as two* validation errors rather than one, which is what the counted prefix is for.+ *+ * <p>Each message names the one bound the value broke. Every recorded IAM length violation+ * reads that way, and a short id told about a 128-character ceiling would be refused for a+ * constraint it did not break.*/@Testvoid anIdOutsideItsPublishedLengthIsAValidationError() {String userName = user();- create(userName, CODECOMMIT);+ String credentialId = create(userName, CODECOMMIT);- for (String id : List.of("tooshort", "W".repeat(129))) {- iam("DeleteServiceSpecificCredential")- .formParam("UserName", userName)- .formParam("ServiceSpecificCredentialId", id)- .when().post("/").then().statusCode(400)- .body(containsString("1 validation error detected"))- .body(containsString("Member must have length less than or equal to 128 and "- + "greater than or equal to 20"))- .body(not(containsString("NoSuchEntity")));- }+ iam("DeleteServiceSpecificCredential")+ .formParam("UserName", userName)+ .formParam("ServiceSpecificCredentialId", "tooshort")+ .when().post("/").then().statusCode(400)+ .body(containsString("1 validation error detected"))+ .body(containsString("Member must have length greater than or equal to 20"))+ .body(not(containsString("less than or equal to 128")))+ .body(not(containsString("NoSuchEntity")));++ iam("DeleteServiceSpecificCredential")+ .formParam("UserName", userName)+ .formParam("ServiceSpecificCredentialId", "W".repeat(129))+ .when().post("/").then().statusCode(400)+ .body(containsString("1 validation error detected"))+ .body(containsString("Member must have length less than or equal to 128"))+ .body(not(containsString("greater than or equal to 20")))+ .body(not(containsString("NoSuchEntity")));// Short and outside the pattern at once: both constraints are reported.iam("DeleteServiceSpecificCredential")@@ -679,6 +690,12 @@ class ServiceSpecificCredentialIntegrationTest {.formParam("ServiceSpecificCredentialId", "A".repeat(20)).when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));++ // The refusals deleted nothing. The validation runs ahead of the delete it precedes, so+ // the credential created above is still the user's.+ iam("ListServiceSpecificCredentials").formParam("UserName", userName)+ .when().post("/").then().statusCode(200)+ .body(containsString(credentialId));}@Test