diff --git a/docs/services/iam.md b/docs/services/iam.md index 9cd15ea0b2..94ef45b5a2 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -291,17 +291,14 @@ the emulator rather than by a request, a seeded configuration or a role template in those same words. Some refusals stay as this service answers them, and the members behind them are left out of the -vendored shapes so the walk cannot reword them. `CreateServiceLinkedRole` validates its required -`AWSServiceName` through IAM's validation layer: missing, empty, overlong and pattern-invalid values -answer `ValidationError` with the corresponding member constraint. The pattern error follows a -captured AWS response; the other cases follow IAM's validation conventions. `CustomSuffix` remains -`InvalidInput`, as does an empty `ServiceNamespaces` on `ListPoliciesGrantingServiceAccess`. An +vendored shapes so the walk cannot reword them. A service-linked role's custom suffix answers +`InvalidInput` rather than a validation error at all, "Custom suffix is not allowed for +``", which is a recorded refusal across roughly eighty principals, and so does an empty +`ServiceNamespaces` on `ListPoliciesGrantingServiceAccess`. The principal beside that suffix is +read off the model, which the section below sets out. An account alias carries AWS's own sentence about its own bounds, which is why neither alias operation -is read at all. For `statusType` on the four credential -updates, a missing `Status` answers `Member must not be null`; an invalid value answers `Member must -satisfy enum value set: [Expired, Active, Inactive]` without echoing that value. These wordings -follow the newer AWS capture. `Encoding` on `GetSSHPublicKey` -answers the modelled `UnrecognizedPublicKeyEncoding` rather than a constraint violation. And +is read at all. `Encoding` on `GetSSHPublicKey` answers the modelled +`UnrecognizedPublicKeyEncoding` rather than a constraint violation. And `TagKeys` on the eight untag operations is answered against the list as a whole, `Value at 'tagKeys' failed to satisfy constraint: Member must satisfy constraint: [...]`, where the walk names the member that broke it under its own index: both forms are readings, nothing recorded @@ -325,11 +322,48 @@ was already this service's choice for a list over its limit, and it is now what whatever it breaks. Other services do quote a list, Lambda's `Value '[x86_64, arm64]' at 'architectures'` being a captured one, which is why this is IAM's reading and not a rule. -A captured missing `Status` on the four credential updates reads `Value at 'status' failed to satisfy -constraint: Member must not be null`, without `null` after `Value`. Other omitted required members -may still use `Value null at ''`; this capture does not settle their wording. IAM's form for -violations with a supplied value is chosen in one place, so a future capture that shows IAM carrying -those values again moves it back in one edit rather than across the service. +A required member the request leaves out reads the same way, `Value at 'status' failed to satisfy +constraint: Member must not be null`, with no `null` standing where the value would. That was the +one message carrying a word in the value's place until 2026-10-31, when a capture from a real +account answered an omitted `Status` and showed the word gone with every other value this service +leaves out. The form is chosen in one place, so the capture moved it in one edit rather than across +the service, and the services that do quote their values, STS among them, still write `Value null at +''`. + +### Two answers the model carries since a capture settled them + +`statusType` and `CreateServiceLinkedRole`'s `AWSServiceName` were answered by hand here until +2026-10-31, each on the reading that AWS worded them differently from the model. Captures from a +real account, on [#6042](https://github.com/floci-io/floci/issues/6042), showed otherwise, so both +are read off the vendored shapes with everything else. + +A `Status` outside the set is `Value at 'status' failed to satisfy constraint: Member must satisfy +enum value set: [Expired, Active, Inactive]`, naming the set where this service named none, and an +omitted one is the required-member violation rather than the same enum sentence, which is what one +hand-written check could not tell apart. Both read the same on all four operations that share the +shape. The set is listed in the order AWS lists it, which is not the order the vendored model +declares: the values are the model's and only their order is read from the capture. + +A principal that breaks `AWSServiceName`'s pattern is `Value at 'aWSServiceName' failed to satisfy +constraint: Member must satisfy regular expression pattern: [\w+=.@-]*`, where this service +answered `InvalidInput` with a sentence about the member's bounds. An omitted one is the +required-member violation, a principal over 128 characters the maximum, and one sent empty breaks +both the minimum and the pattern, which is what every other string member here answers for an empty +value. A principal that satisfies the pattern and names no service AWS has is still `InvalidInput`, +"The request must include a valid AWSServiceName, for example es.amazonaws.com.", which is the +layering the capture leaves in place: the shape first, then whether the service exists. + +The pattern quoted there is the one AWS quotes, not the one the shape declares, and those differ. +botocore aliases `AWSServiceName` to the shape it gives a group name, `[\w+=,.@-]+` at 1 to 128 +characters, while AWS's message gives `[\w+=.@-]*`: the comma is gone and a `*` stands where the +model sets a minimum of 1. Only the message is in hand rather than the shape, so the vendored shape +records AWS's text beside its own and the walk quotes the capture while holding a value to the +model. A comma is therefore still admitted, and an empty principal is still refused. That is the +same split the enum order above takes, the captured rendering over the model's, and one object +decides which text any violation quotes, so no other member moves with it. + +What a second capture would settle is the comma: `CreateServiceLinkedRole` with one in the +principal, which AWS either refuses as a pattern violation or takes. ### Permission Boundaries @@ -425,10 +459,11 @@ the user resolved from the signing access key, the same fallback `GetUser` uses. `Status` takes any of the three values `statusType` publishes, `Active`, `Inactive` and `Expired`, which is what the reference's Valid Values line on `UpdateAccessKey` lists, and it is held to that set the same way `UpdateSigningCertificate`, `UpdateSSHPublicKey` and -`UpdateServiceSpecificCredential` hold theirs. It is read before the key is looked up, so a status -outside the set answers `ValidationError` whether or not the key exists. The `AWS::IAM::AccessKey` -CloudFormation resource takes the same three, its Allowed values line reading "Active | Inactive | -Expired" as well. +`UpdateServiceSpecificCredential` hold theirs, all four from the model since the capture above. It +is read before the key is looked up, so a status outside the set answers `ValidationError` whether +or not the key exists, and an omitted one answers the required member it is. The +`AWS::IAM::AccessKey` CloudFormation resource takes the same three, its Allowed values line +reading "Active | Inactive | Expired" as well. ### Account Aliases diff --git a/src/main/java/io/github/hectorvent/floci/core/common/QueryConstraintCheck.java b/src/main/java/io/github/hectorvent/floci/core/common/QueryConstraintCheck.java index e4a0ef01b6..de1ad49da8 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/QueryConstraintCheck.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/QueryConstraintCheck.java @@ -255,7 +255,7 @@ public final class QueryConstraintCheck { .filter(entry -> params.getFirst(entry.prefix() + ".key") != null) .toList(); if (entries.isEmpty()) { - return required ? List.of(SmithyValidationErrors.notNull(path)) : List.of(); + return required ? List.of(messages.notNull(path)) : List.of(); } String valueShape = shape.path("value").asText(); boolean structure = "structure".equals(shapes.path(valueShape).path("type").asText()); @@ -291,7 +291,7 @@ public final class QueryConstraintCheck { JsonNode shape = shapes.path(shapeName); return List.of(messages.mapKeys(path, key, SmithyValidationErrors.constraintSet( shape.path("min").asInt(0), shape.path("max").asInt(Integer.MAX_VALUE), - shape.path("pattern").asText(null), allowedValues(shape)))); + VendoredPatterns.quoted(shape), allowedValues(shape)))); } /** @@ -302,7 +302,7 @@ public final class QueryConstraintCheck { boolean required, MultivaluedMap params) { String value = params == null ? null : params.getFirst(param); if (value == null) { - return required ? List.of(SmithyValidationErrors.notNull(path)) : List.of(); + return required ? List.of(messages.notNull(path)) : List.of(); } return violations(shapeName, value, path); } @@ -325,7 +325,7 @@ public final class QueryConstraintCheck { .filter(member -> !scalar || params.getFirst(member.prefix()) != null) .toList(); if (members.isEmpty()) { - return required ? List.of(SmithyValidationErrors.notNull(path)) : List.of(); + return required ? List.of(messages.notNull(path)) : List.of(); } List violations = new ArrayList<>(); violations.addAll(single(SmithyValidationErrors.sizeOutOfRange(path, members.size(), @@ -352,7 +352,7 @@ public final class QueryConstraintCheck { boolean present = params != null && params.keySet().stream().anyMatch(key -> key.startsWith(param + ".")); if (!present) { - return required ? List.of(SmithyValidationErrors.notNull(path)) : List.of(); + return required ? List.of(messages.notNull(path)) : List.of(); } return structureViolations(shape, param + ".", path + ".", params, Map.of()); } @@ -382,8 +382,10 @@ public final class QueryConstraintCheck { Pattern pattern = patterns.get(shapeName); if (pattern != null && !pattern.matcher(value).matches()) { // Quoted as the model declares it, which is what AWS answers and what the service docs - // carry, rather than as it was compiled: a wide escape is rewritten to match on. - violations.add(messages.pattern(path, value, shape.path("pattern").asText())); + // carry, rather than as it was compiled: a wide escape is rewritten to match on. One + // member is quoted from a capture instead, where AWS gives a pattern of its own for a + // shape botocore shares, and one object decides which text that is. + violations.add(messages.pattern(path, value, VendoredPatterns.quoted(shape))); } violations.addAll(single(enumViolation(shape, value, path))); return violations; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestConstraintCheck.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestConstraintCheck.java index e094b8dab6..2dc0864ea8 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/RequestConstraintCheck.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestConstraintCheck.java @@ -96,7 +96,7 @@ public final class RequestConstraintCheck { throw messages.bounds(path, type, min, max, size); } if (patterns.containsKey(name) && !patterns.get(name).matcher(value.asText()).matches()) { - throw messages.pattern(path, shape.get("pattern").asText()); + throw messages.pattern(path, VendoredPatterns.quoted(shape)); } if (shape.has("enum")) { boolean known = false; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SmithyValidationErrors.java b/src/main/java/io/github/hectorvent/floci/core/common/SmithyValidationErrors.java index 367ec7bbbf..ca7c765111 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/SmithyValidationErrors.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/SmithyValidationErrors.java @@ -168,9 +168,12 @@ public final class SmithyValidationErrors { * what {@code docs/services/iam.md} records as the reading. Choosing a form here rather than at * each message means a later capture changes one object instead of a package. * - *

This form applies only to violations that carry a value. Required-member omissions use - * {@link #notNull} or {@link #notNullWithoutValue}, depending on the operation. List size and - * whole-list checks use {@link #sizeOutOfRange} and {@link #notAllInEnum} separately. + *

A required member the request leaves out differs too, the word {@code null} sitting where + * the value would: a service that quotes its values carries it and one that does not leaves the + * member named alone, which is what {@link #notNull(String)} picks between. A list held to its + * member count and a list checked as a whole read the same either way, the list being what AWS + * names there rather than a value, so {@link SmithyValidationErrors#sizeOutOfRange} and + * {@link SmithyValidationErrors#notAllInEnum} stay outside this form. */ public static final class Violations { @@ -186,6 +189,18 @@ public final class SmithyValidationErrors { this.quoted = quoted; } + /** + * The violation for a required member the request leaves out. The word {@code null} stands + * where the value would, so a form that quotes its values writes it and a form that does + * not names the member alone, "Value at 'status' failed to satisfy constraint: Member must + * not be null", which is what IAM was captured answering for an omitted {@code Status}. + */ + public String notNull(String path) { + return quoted + ? SmithyValidationErrors.notNull(path) + : SmithyValidationErrors.notNullWithoutValue(path); + } + /** One violation naming {@code constraint}, carrying {@code value} where this form does. */ public String constraint(String path, String value, String constraint) { String member = quoted ? "Value '" + value + "' at '" : "Value at '"; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/VendoredPatterns.java b/src/main/java/io/github/hectorvent/floci/core/common/VendoredPatterns.java index 9a49ecaba5..18505ff2de 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/VendoredPatterns.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/VendoredPatterns.java @@ -1,11 +1,13 @@ package io.github.hectorvent.floci.core.common; +import com.fasterxml.jackson.databind.JsonNode; + import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Compiles a pattern a vendored AWS model declares, in the dialect the model writes it in rather - * than in Java's. + * than in Java's, and answers which text a violation on it quotes. * *

One thing differs between the two. A model writes a code point above U+FFFF as a backslash-u * escape of five or six hex digits, the U+10000 to U+10FFFF range on STS's {@code arnType} among @@ -36,6 +38,21 @@ public final class VendoredPatterns { return Pattern.compile(rewrite(pattern)); } + /** + * The pattern a violation on {@code shape} quotes: the text AWS quotes for that member where + * the vendored shape records one, and the pattern the model declares everywhere else, which is + * also what a value is matched against either way. + * + *

The two differ where AWS's message gives a pattern of its own for a member botocore + * aliases to a shape it shares, IAM's {@code AWSServiceName} on {@code CreateServiceLinkedRole} + * being the one such member vendored today: AWS quotes a class without the comma the shape + * admits. Only the message is in hand rather than the shape, so the generator records AWS's + * text beside the model's and what the request is held to stays the model's own. + */ + public static String quoted(JsonNode shape) { + return shape.path("quotedPattern").asText(shape.path("pattern").asText(null)); + } + /** * {@code pattern} with every wide escape written in Java's form. The digits are read longest * first, so six of them name the top of Unicode rather than five of them and a stray F, and a diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java index ab2d23f38e..f58fcd69eb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java @@ -5,7 +5,6 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsRegionFacts; import io.github.hectorvent.floci.core.common.AwsRegions; -import io.github.hectorvent.floci.core.common.SmithyValidationErrors; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.iam.model.DelegationPermission; @@ -753,7 +752,7 @@ public class DelegationRequestService { */ private static AwsException constraintViolation(String value, String member, String constraint) { if (value == null) { - return SmithyValidationErrors.validationError(SmithyValidationErrors.notNull(member)); + return IamValidationErrors.notNull(member); } return IamValidationErrors.validationError(member, value, constraint); } 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 30c18c5522..c615d7b421 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 @@ -1409,8 +1409,7 @@ public class IamQueryHandler { // empty Description is a value that clears the description, not an absent member. String description = params.getFirst("Description"); if (description == null) { - throw SmithyValidationErrors.validationError( - SmithyValidationErrors.notNull("description")); + throw IamValidationErrors.notNull("description"); } IamRole role = iamService.updateRoleDescription(getParam(params, "RoleName"), description); String result = new XmlBuilder().start("Role").raw(roleXml(role, true)).end("Role").build(); @@ -3616,8 +3615,7 @@ public class IamQueryHandler { private String requireParam(MultivaluedMap params, String name) { String value = params.getFirst(name); if (value == null || value.isBlank()) { - throw SmithyValidationErrors.validationError( - SmithyValidationErrors.notNull(memberPath(name))); + throw IamValidationErrors.notNull(memberPath(name)); } return value; } 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.java index 32c34f285c..b929c711a6 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 @@ -186,8 +186,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider { /** CSPRNG for long-term secret access keys; ordinary resource IDs keep using {@link ThreadLocalRandom}. */ private final SecureRandom secureRandom = new SecureRandom(); - /** AWSServiceName as AWS constrains it: 1-128 characters of {@code [\w+=,.@-]}. */ - private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}"); /** CustomSuffix as AWS constrains it: 1-64 characters of {@code [\w+=,.@-]}. */ private static final Pattern CUSTOM_SUFFIX_PATTERN = Pattern.compile("[\\w+=,.@-]{1,64}"); private static final int ROLE_DESCRIPTION_MAX_LENGTH = 1000; @@ -284,16 +282,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final Set SSH_PUBLIC_KEY_ENCODINGS = Set.of("SSH", "PEM"); /** certificateIdType is 24 to 128 of [\w]+, so a 32-character id sits inside that. */ private static final int SIGNING_CERTIFICATE_ID_LENGTH = 32; + /** Two of {@code statusType}'s values, which this service writes itself where the model reads the set. */ private static final String CREDENTIAL_STATUS_ACTIVE = "Active"; private static final String CREDENTIAL_STATUS_EXPIRED = "Expired"; - /** - * statusType's values, shared by access keys, signing certificates, SSH public keys and - * service-specific credentials: Active, Inactive and Expired. Each operation's prose explains - * only the first two, so the third is easy to reject by mistake, while the API Reference lists - * all three as valid on each of them. - */ - private static final Set CREDENTIAL_STATUSES = - Set.of(CREDENTIAL_STATUS_ACTIVE, "Inactive", CREDENTIAL_STATUS_EXPIRED); /** {@code certificateBodyType} and {@code privateKeyType} are both 1 to 16384 characters. */ private static final int MAX_CERTIFICATE_BODY_LENGTH = 16384; /** {@code certificateChainType} is far larger, at 1 to 2097152. */ @@ -1274,7 +1265,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * five entities and passes everything else through, which would make the {@code Role} this * action and {@code GetRole} answer unparsable. * - *

The rendering keeps the refused description out of the error body, where a control + *

The rendering names the member and not the offending value, which is IAM's form + * throughout. It also keeps the refused description out of the error body, where a control * character would break the answer it is being refused for. */ private static void validateRoleDescription(String description) { @@ -1308,7 +1300,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return; } if (roleName == null) { - throw SmithyValidationErrors.validationError(SmithyValidationErrors.notNull("roleName")); + throw IamValidationErrors.notNull("roleName"); } throw IamValidationErrors.validationError("roleName", roleName, constraint); } @@ -1423,22 +1415,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * {@code _}, and that attribute forces replacement, so a name without one never converges. */ public IamRole createServiceLinkedRole(String awsServiceName, String customSuffix, String description) { - if (awsServiceName == null) { - throw SmithyValidationErrors.validationError(SmithyValidationErrors.notNull("aWSServiceName")); - } - String constraint; - if (awsServiceName.isEmpty()) { - constraint = "Member must have length greater than or equal to 1"; - } else if (awsServiceName.length() > 128) { - constraint = "Member must have length less than or equal to 128"; - } else if (!SERVICE_PRINCIPAL_PATTERN.matcher(awsServiceName).matches()) { - constraint = "Member must satisfy regular expression pattern: [\\w+=.@-]*"; - } else { - constraint = null; - } - if (constraint != null) { - throw IamValidationErrors.validationError("aWSServiceName", awsServiceName, constraint); - } if (customSuffix != null && !customSuffix.isEmpty() && !CUSTOM_SUFFIX_PATTERN.matcher(customSuffix).matches()) { throw new AwsException("InvalidInput", @@ -2446,12 +2422,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } /** - * Sets an access key's status, validated before the key is looked up the way the other three - * {@code statusType} operations validate theirs: a status outside the enum is answered for the - * status whether or not the key exists. + * Sets an access key's status. The status is held to {@code statusType} ahead of this, by the + * model the Query front door reads, so a value outside the set and an omitted one are both + * answered before any key is looked up. The CloudFormation provisioner validates the status it + * resolves from a template before it calls here, that path having no front door of its own. */ public void updateAccessKey(String userName, String accessKeyId, String status) { - requireStatusFromEnum(status); synchronized (accessKeyLock) { AccessKey key = userAccessKey(userName, accessKeyId); key.setStatus(status); @@ -2920,8 +2896,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ private static void validatePassword(String password, String member) { if (password == null) { - throw SmithyValidationErrors.validationError( - SmithyValidationErrors.notNull(member)); + throw IamValidationErrors.notNull(member); } if (!LOGIN_PROFILE_PASSWORD_PATTERN.matcher(password).matches()) { throw SmithyValidationErrors.validationError( @@ -2963,8 +2938,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ private void validateIamResourceName(String value, String paramName) { if (value == null) { - throw SmithyValidationErrors.validationError( - SmithyValidationErrors.notNull(memberPath(paramName))); + throw IamValidationErrors.notNull(memberPath(paramName)); } if (!IAM_RESOURCE_NAME_PATTERN.matcher(value).matches()) { throw IamValidationErrors.validationError(memberPath(paramName), value, @@ -3013,8 +2987,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ public void putAccountProperties(Map properties) { if (properties == null || properties.isEmpty()) { - throw SmithyValidationErrors.validationError( - SmithyValidationErrors.notNull("properties")); + throw IamValidationErrors.notNull("properties"); } String namespace = null; for (Map.Entry entry : properties.entrySet()) { @@ -3458,25 +3431,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return getServerCertificate(name).getTags(); } - // Credential status, shared by the four operations that take statusType - // ========================================================================= - - /** - * {@code statusType} is shared by four credential updates. AWS distinguishes a missing member - * from an invalid value and lists the permitted values in its recorded error-message order. - */ - private void requireStatusFromEnum(String status) { - if (status == null) { - throw SmithyValidationErrors.validationError( - SmithyValidationErrors.notNullWithoutValue("status")); - } - if (!CREDENTIAL_STATUSES.contains(status)) { - throw SmithyValidationErrors.validationError( - IamValidationErrors.MESSAGES.notInEnum(status, "status", - List.of(CREDENTIAL_STATUS_EXPIRED, CREDENTIAL_STATUS_ACTIVE, "Inactive"))); - } - } - // Signing certificates // ========================================================================= @@ -3532,7 +3486,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } public void updateSigningCertificate(String userName, String certificateId, String status) { - requireStatusFromEnum(status); synchronized (signingCertificateLock) { SigningCertificate certificate = userSigningCertificate(userName, certificateId); certificate.setStatus(status); @@ -3696,7 +3649,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } public void updateSshPublicKey(String userName, String keyId, String status) { - requireStatusFromEnum(status); synchronized (sshPublicKeyLock) { SshPublicKey stored = userSshPublicKey(userName, keyId); stored.setStatus(status); @@ -3970,7 +3922,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void updateServiceSpecificCredential(String userName, String credentialId, String status) { requireCredentialIdFormat(credentialId); - requireStatusFromEnum(status); synchronized (serviceCredentialLock) { ServiceSpecificCredential credential = userServiceCredential(userName, credentialId); credential.setStatus(status); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamValidationErrors.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamValidationErrors.java index 4933765c92..a52f3efa48 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamValidationErrors.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamValidationErrors.java @@ -10,9 +10,12 @@ import io.github.hectorvent.floci.core.common.SmithyValidationErrors; * where the older ones quoted the value, and STS still quotes it, so this names IAM's side of that * split in one place. {@code docs/services/iam.md} records the reading and the captures behind it. * - *

A list checked as a whole can carry the list and is not forced through here. Required-member - * omissions use operation-specific wording: the captured missing {@code Status} on credential - * updates reads {@code Value at 'status'} without {@code null}. + *

A message AWS itself writes with the value is not forced through here: a list checked as a + * whole carries the list. A required member the request leaves out used to read + * {@code Value null at ''} for want of a capture either way; one arrived on 2026-10-31, + * answering an omitted {@code Status} as {@code Value at 'status' failed to satisfy constraint: + * Member must not be null}, so the word {@code null} comes out with every other value this service + * leaves out and {@link #notNull} is where that is decided. */ final class IamValidationErrors { @@ -23,6 +26,15 @@ final class IamValidationErrors { private IamValidationErrors() { } + /** + * The 400 {@code ValidationError} for a required member the request leaves out, named with no + * value and no {@code null} beside it. Captured from a real account on 2026-10-31 against the + * {@code Status} the four credential operations share. + */ + static AwsException notNull(String path) { + return SmithyValidationErrors.validationError(MESSAGES.notNull(path)); + } + /** * The 400 {@code ValidationError} for one violation of {@code constraint} by {@code value} at * {@code path}. The value is taken even though IAM's form leaves it out, so that the one place diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportService.java b/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportService.java index 65bbe7381e..8c8b8c3911 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportService.java @@ -2,7 +2,6 @@ package io.github.hectorvent.floci.services.iam; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.core.common.SmithyValidationErrors; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.iam.model.OrganizationsAccessReportJob; @@ -282,7 +281,7 @@ public class OrganizationsAccessReportService { */ private static AwsException validationError(String value, String at, String constraint) { if (value == null) { - return SmithyValidationErrors.validationError(SmithyValidationErrors.notNull(at)); + return IamValidationErrors.notNull(at); } return IamValidationErrors.validationError(at, value, constraint); } diff --git a/src/main/resources/aws/iam-request-shapes.json b/src/main/resources/aws/iam-request-shapes.json index 87b45594e0..df5be90958 100644 --- a/src/main/resources/aws/iam-request-shapes.json +++ b/src/main/resources/aws/iam-request-shapes.json @@ -459,7 +459,11 @@ }, "CreateServiceLinkedRoleRequest": { "type": "structure", + "required": [ + "AWSServiceName" + ], "members": { + "AWSServiceName": "aWSServiceNameType", "Description": "roleDescriptionType" } }, @@ -1860,11 +1864,13 @@ "UpdateAccessKeyRequest": { "type": "structure", "required": [ - "AccessKeyId" + "AccessKeyId", + "Status" ], "members": { "UserName": "existingUserNameType", - "AccessKeyId": "accessKeyIdType" + "AccessKeyId": "accessKeyIdType", + "Status": "statusType" } }, "UpdateAccountPasswordPolicyRequest": { @@ -1967,11 +1973,13 @@ "type": "structure", "required": [ "UserName", - "SSHPublicKeyId" + "SSHPublicKeyId", + "Status" ], "members": { "UserName": "userNameType", - "SSHPublicKeyId": "publicKeyIdType" + "SSHPublicKeyId": "publicKeyIdType", + "Status": "statusType" } }, "UpdateServerCertificateRequest": { @@ -1988,21 +1996,25 @@ "UpdateServiceSpecificCredentialRequest": { "type": "structure", "required": [ - "ServiceSpecificCredentialId" + "ServiceSpecificCredentialId", + "Status" ], "members": { "UserName": "userNameType", - "ServiceSpecificCredentialId": "serviceSpecificCredentialId" + "ServiceSpecificCredentialId": "serviceSpecificCredentialId", + "Status": "statusType" } }, "UpdateSigningCertificateRequest": { "type": "structure", "required": [ - "CertificateId" + "CertificateId", + "Status" ], "members": { "UserName": "existingUserNameType", - "CertificateId": "certificateIdType" + "CertificateId": "certificateIdType", + "Status": "statusType" } }, "UpdateUserRequest": { @@ -2041,6 +2053,13 @@ "CertificateBody": "certificateBodyType" } }, + "aWSServiceNameType": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[\\w+=,.@-]+", + "quotedPattern": "[\\w+=.@-]*" + }, "accessKeyIdType": { "type": "string", "min": 16, @@ -2424,6 +2443,14 @@ "LAST_AUTHENTICATED_TIME_DESCENDING" ] }, + "statusType": { + "type": "string", + "enum": [ + "Expired", + "Active", + "Inactive" + ] + }, "stringType": { "type": "string" }, diff --git a/src/test/java/io/github/hectorvent/floci/core/common/QueryConstraintCheckTest.java b/src/test/java/io/github/hectorvent/floci/core/common/QueryConstraintCheckTest.java index bd057b914a..82de104f38 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/QueryConstraintCheckTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/QueryConstraintCheckTest.java @@ -155,6 +155,31 @@ class QueryConstraintCheckTest { "Status", "Pending"))); } + /** + * One member quotes a pattern AWS gives for it rather than the one the model declares, which + * the vendored shape records beside it. What a value is held to stays the model's: the comma + * the model admits and the quoted text does not is still admitted. + */ + @Test + void aShapeRecordingACapturedPatternQuotesItAndStillMatchesTheModels() throws Exception { + QueryConstraintCheck check = QueryConstraintCheck.of(MAPPER.readTree(""" + { + "operations": {"Link": "LinkRequest"}, + "shapes": { + "LinkRequest": {"type": "structure", "required": ["Principal"], "members": { + "Principal": "principalType"}}, + "principalType": {"type": "string", "min": 1, "max": 128, + "pattern": "[\\\\w+=,.@-]+", "quotedPattern": "[\\\\w+=.@-]*"} + } + } + """)); + + assertEquals(List.of("Value 'not a principal' at 'principal' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: [\\w+=.@-]*"), + check.violations("Link", params("Principal", "not a principal"))); + assertEquals(List.of(), check.violations("Link", params("Principal", "es,amazonaws.com"))); + } + /** A number is held to its range, and one that is no number at all is left to the operation. */ @Test void aNumberIsHeldToItsRangeAndANonNumberIsLeftToTheOperation() throws Exception { diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestConstraintCheckTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestConstraintCheckTest.java index 4e2912d067..5cf87f9be0 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/RequestConstraintCheckTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestConstraintCheckTest.java @@ -20,8 +20,9 @@ class RequestConstraintCheckTest { "shapes": { "PutInput": {"type": "structure", "required": ["name"], "members": {"name": "Name", "items": "Items", "count": "Count", "labels": "Labels", - "kind": "Kind"}}, + "kind": "Kind", "quoted": "Quoted"}}, "Name": {"type": "string", "min": 2, "max": 5, "pattern": "[a-z]+"}, + "Quoted": {"type": "string", "pattern": "[a-z]+", "quotedPattern": "[a-z]*"}, "Items": {"type": "list", "max": 2, "member": "Item"}, "Item": {"type": "structure", "required": ["id"], "members": {"id": "Name"}}, "Count": {"type": "integer", "min": 1, "max": 10}, @@ -82,6 +83,8 @@ class RequestConstraintCheckTest { assertEquals("bounds Put.name string 2..5 1", violation("{\"name\":\"a\"}")); assertEquals("bounds Put.name string 2..5 6", violation("{\"name\":\"abcdef\"}")); assertEquals("pattern Put.name [a-z]+", violation("{\"name\":\"AB\"}")); + // A shape recording the pattern AWS quotes for its member hands that text over instead. + assertEquals("pattern Put.quoted [a-z]*", violation("{\"name\":\"ab\",\"quoted\":\"AB\"}")); assertEquals("bounds Put.count integer 1..10 11", violation("{\"name\":\"ab\",\"count\":11}")); assertEquals("type Put.count integer", violation("{\"name\":\"ab\",\"count\":1.5}")); assertEquals("enum Put.kind [A, B]", violation("{\"name\":\"ab\",\"kind\":\"C\"}")); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/VendoredPatternsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/VendoredPatternsTest.java index afb7300f84..a045a76b70 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/VendoredPatternsTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/VendoredPatternsTest.java @@ -1,11 +1,13 @@ package io.github.hectorvent.floci.core.common; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.util.regex.Pattern; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -67,4 +69,27 @@ class VendoredPatternsTest { assertTrue(asWritten.matcher(c1Control).matches(), "and admits what the model excludes"); } + + /** + * Which text a violation quotes is this object's other answer. It is the pattern the model + * declares, except for a member whose message AWS gives a pattern of its own for, where the + * vendored shape records both: what is matched on stays the model's either way. + */ + @Test + void theQuotedTextIsTheCapturedPatternWhereTheShapeRecordsOneAndTheModelsOtherwise() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + + assertEquals("[\\w+=.@-]*", VendoredPatterns.quoted(mapper.readTree(""" + {"type": "string", "min": 1, "max": 128, + "pattern": "[\\\\w+=,.@-]+", "quotedPattern": "[\\\\w+=.@-]*"} + """))); + assertEquals("[\\w+=,.@-]+", VendoredPatterns.quoted(mapper.readTree(""" + {"type": "string", "pattern": "[\\\\w+=,.@-]+"} + """)), + "a shape recording no captured text quotes the one it declares"); + assertNull(VendoredPatterns.quoted(mapper.readTree(""" + {"type": "string", "min": 1} + """)), + "and a shape with no pattern at all quotes none"); + } } 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 857fbfd18b..2ffa2b3ca4 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 @@ -150,13 +150,14 @@ class AccountPropertiesIntegrationTest { void anAbsentPropertiesMapIsRejected() { iam("PutAccountProperties").when().post("/").then().statusCode(400) .body(containsString("ValidationError")) - // Recorded against AWS on SNS's own map member, down to the phrasing: - // "1 validation error detected: Value null at 'attributes' failed to satisfy - // constraint: Member must not be null". + // IAM's own form, captured from a real account on 2026-10-31 against the Status the + // four credential operations share: "1 validation error detected: Value at 'status' + // failed to satisfy constraint: Member must not be null". SNS, which quotes its + // values, carries a null where the value would go; IAM leaves it out with the rest. .body(containsString("1 validation error detected")) // The apostrophes around the member name come back XML-escaped, so the assertion // stops at the parts that survive escaping. - .body(containsString("Value null at ")) + .body(containsString("Value at ")) .body(containsString("properties")) .body(containsString("Member must not be null")); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamAccessKeyStatusIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamAccessKeyStatusIntegrationTest.java index 3be9c8680a..75941c7211 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamAccessKeyStatusIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamAccessKeyStatusIntegrationTest.java @@ -25,8 +25,12 @@ import static org.hamcrest.Matchers.equalTo; * implicitly based on the AWS access key ID used to sign the request", the sentence this operation * shares with DeleteAccessKey and ListAccessKeys. * - *

The four operations share {@code IamService.requireStatusFromEnum}; the latest AWS captures - * distinguish an absent status from a present value outside the enum. + *

Both refusals were captured from a real account on 2026-10-31, against all four operations + * that share this shape: a value outside the set is answered with the set named and the value left + * out, in the order AWS lists it rather than the order the model declares, and an omitted status is + * answered as the required member it is rather than as a value outside the set. Both are the + * model's own wording, read through the Query front door, where three hand-written renderings + * stood before. */ @QuarkusTest class IamAccessKeyStatusIntegrationTest { @@ -66,6 +70,10 @@ class IamAccessKeyStatusIntegrationTest { assertStatusStillActive(userName); } + /** + * An omitted status is the required member reading as null, not a value outside the set, which + * is what the capture answers and what the rendering this replaced could not tell apart. + */ @Test void anAbsentStatusNamesTheMissingMember() { String userName = user("absent-status"); @@ -91,7 +99,7 @@ class IamAccessKeyStatusIntegrationTest { void anAbsentAccessKeyIdNamesItself() { update(ACCOUNT, Map.of("UserName", user("absent-id"), "Status", "Inactive")).statusCode(400) .body("ErrorResponse.Error.Code", equalTo("ValidationError")) - .body("ErrorResponse.Error.Message", containsString("Value null at 'accessKeyId'")); + .body("ErrorResponse.Error.Message", containsString("Value at 'accessKeyId'")); } @Test 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.java index ec97adb436..3da8323584 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 @@ -1717,8 +1717,8 @@ class IamIntegrationTest { .when().post("/").then() .statusCode(400) .body("ErrorResponse.Error.Code", equalTo("ValidationError")) - .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value null" - + " at 'roleName' failed to satisfy constraint: Member must not be null")); + .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at" + + " 'roleName' failed to satisfy constraint: Member must not be null")); given() .formParam("Action", "CreateRole") diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestConstraintsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestConstraintsIntegrationTest.java index be973618dc..7c5912fd4e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestConstraintsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestConstraintsIntegrationTest.java @@ -65,7 +65,7 @@ class IamRequestConstraintsIntegrationTest { void aRequiredMemberLeftOutIsReportedAsNull() { iam("DeletePolicy").when().post("/").then().statusCode(400) .body(CODE, equalTo("ValidationError")) - .body(MESSAGE, equalTo("1 validation error detected: Value null at 'policyArn' failed" + .body(MESSAGE, equalTo("1 validation error detected: Value at 'policyArn' failed" + " to satisfy constraint: Member must not be null")); } @@ -339,7 +339,7 @@ class IamRequestConstraintsIntegrationTest { // A map the request names nowhere is the required member reading as null. iam("PutAccountProperties") .when().post("/").then().statusCode(400) - .body(MESSAGE, equalTo("1 validation error detected: Value null at 'properties' failed" + .body(MESSAGE, equalTo("1 validation error detected: Value at 'properties' failed" + " to satisfy constraint: Member must not be null")); } @@ -357,7 +357,7 @@ class IamRequestConstraintsIntegrationTest { .formParam("ReplacementValues.entry.1.key", "Department") .when().post("/").then().statusCode(400) .body(CODE, equalTo("ValidationError")) - .body(MESSAGE, equalTo("1 validation error detected: Value null at" + .body(MESSAGE, equalTo("1 validation error detected: Value at" + " 'replacementValues.Department.values' failed to satisfy constraint: Member" + " must not be null")); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleDescriptionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleDescriptionIntegrationTest.java index b94c1a4ded..c5757f39c1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleDescriptionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleDescriptionIntegrationTest.java @@ -147,7 +147,7 @@ class IamRoleDescriptionIntegrationTest { update(Map.of("RoleName", roleName)).statusCode(400) .body("ErrorResponse.Error.Code", equalTo("ValidationError")) .body("ErrorResponse.Error.Message", - equalTo("1 validation error detected: Value null at 'description' failed " + equalTo("1 validation error detected: Value at 'description' failed " + "to satisfy constraint: Member must not be null")); admin("GetRole", Map.of("RoleName", roleName)).statusCode(200) diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java index b0c0f2987b..bfb0962e6c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java @@ -145,6 +145,12 @@ class IamServiceLinkedRoleIntegrationTest { equalTo("AWSServiceRoleForEs_debug")); } + /** + * The member is required in the model, so it is answered as a required member rather than as a + * value that failed its pattern. The whole operation moved onto the model on 2026-10-31, when + * a capture from a real account showed AWS answering a bad principal as a constraint violation + * and not as the {@code InvalidInput} this service used to write for itself. + */ @Test @Order(5) void aMissingServiceNameIsRejected() { @@ -156,9 +162,8 @@ class IamServiceLinkedRoleIntegrationTest { .then() .statusCode(400) .body("ErrorResponse.Error.Code", equalTo("ValidationError")) - .body("ErrorResponse.Error.Message", equalTo( - "1 validation error detected: Value null at 'aWSServiceName' failed to satisfy constraint: " - + "Member must not be null")); + .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at" + + " 'aWSServiceName' failed to satisfy constraint: Member must not be null")); } @Test @@ -322,6 +327,12 @@ class IamServiceLinkedRoleIntegrationTest { equalTo("AWSServiceRoleForAutoScaling_CustomResource")); } + /** + * The captured answer, from a real account on 2026-10-31: a principal that breaks the pattern + * is a constraint violation naming the member, with no value beside it and with AWS's own + * pattern quoted, which is the one the vendored shape carries for this member's message. The + * whole message is pinned, so a value leaking back into it fails here. + */ @Test @Order(15) void aServiceNameWithSpacesMatchesAwsValidationError() { @@ -339,7 +350,12 @@ class IamServiceLinkedRoleIntegrationTest { + "Member must satisfy regular expression pattern: [\\w+=.@-]*")); } - /** The documented name pattern rejects these characters before any role lookup. */ + /** + * AWS constrains AWSServiceName to 1 to 128 characters of its own pattern; anything else must + * not reach storage. Each of these is a constraint the model declares, so each is a + * {@code ValidationError} naming the member: the first four break the pattern and the last the + * maximum length. + */ @Test @Order(15) void aServiceNameOutsideTheAwsPatternIsRejected() { @@ -352,10 +368,17 @@ class IamServiceLinkedRoleIntegrationTest { .post("/") .then() .statusCode(400) - .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("at 'aWSServiceName'")); } } + /** + * A principal sent empty breaks the minimum and the pattern at once, and the walk reports each + * constraint the value broke rather than the first, which is what every other string member + * here answers for an empty value. Nothing captured covers an empty principal: the two + * constraints are the model's and the form is this service's own. + */ @Test @Order(15) void anEmptyServiceNameUsesIamValidationError() { @@ -369,8 +392,10 @@ class IamServiceLinkedRoleIntegrationTest { .statusCode(400) .body("ErrorResponse.Error.Code", equalTo("ValidationError")) .body("ErrorResponse.Error.Message", equalTo( - "1 validation error detected: Value at 'aWSServiceName' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1")); + "2 validation errors detected: Value at 'aWSServiceName' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1; Value at 'aWSServiceName'" + + " failed to satisfy constraint: Member must satisfy regular expression" + + " pattern: [\\w+=.@-]*")); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java index 7e86974d65..fa6af4343d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java @@ -1241,7 +1241,7 @@ class IamServiceTest { AwsException missing = assertThrows(AwsException.class, () -> iamService.changePassword("alice", null, "An0ther$ecret!")); assertEquals("ValidationError", missing.getErrorCode()); - assertTrue(missing.getMessage().contains("Value null at 'oldPassword'"), missing.getMessage()); + assertTrue(missing.getMessage().contains("Value at 'oldPassword'"), missing.getMessage()); // An empty member is a value that fails the pattern rather than a member never supplied, // and the message names the one that failed, there being two password members here. @@ -2181,37 +2181,6 @@ class IamServiceTest { } } - @Test - void anAccessKeyStatusIsReadBeforeTheKeyIsFound() { - // The key does not exist either, and the status is what answers: AWS reads a request's - // shape before it resolves anything, so the lookup's NoSuchEntity does not get there first. - iamService.createUser("alice", "/"); - - AwsException error = assertThrows(AwsException.class, - () -> iamService.updateAccessKey("alice", "AKIANOSUCHKEY00000", "Disabled")); - - assertEquals("ValidationError", error.getErrorCode()); - // AWS lists the allowed values in its error message, even when the key is unknown. - assertEquals("1 validation error detected: Value at 'status' failed to satisfy " - + "constraint: Member must satisfy enum value set: [Expired, Active, Inactive]", - error.getMessage()); - } - - @Test - void anAbsentAccessKeyStatusNamesTheMissingMember() { - iamService.createUser("alice", "/"); - AccessKey key = iamService.createAccessKey("alice"); - - AwsException error = assertThrows(AwsException.class, - () -> iamService.updateAccessKey("alice", key.getAccessKeyId(), null)); - - assertEquals("ValidationError", error.getErrorCode()); - assertEquals("1 validation error detected: Value at 'status' failed to satisfy " - + "constraint: Member must not be null", error.getMessage()); - // And the key is as it was: the status is read before the lookup, so nothing is written. - assertEquals("Active", iamService.listAccessKeys("alice").getFirst().getStatus()); - } - @Test void aSessionWithNoRoleAndNoRecordedIssuerIsNoCredential() { // How GetSessionToken stored its sessions before it recorded the key that minted them. Such 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.java index b2c421ed05..7b7de99439 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 @@ -316,7 +316,7 @@ class OrganizationsAccessReportIntegrationTest { iam(MANAGEMENT_ACCOUNT, "GenerateOrganizationsAccessReport") .when().post("/").then().statusCode(400) .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value" - + " null at 'entityPath' failed to satisfy constraint: Member must not be" + + " at 'entityPath' failed to satisfy constraint: Member must not be" + " null")); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/RoleTemplateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/RoleTemplateIntegrationTest.java index ed13f69877..1348e1256c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/RoleTemplateIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/RoleTemplateIntegrationTest.java @@ -87,7 +87,7 @@ class RoleTemplateIntegrationTest { .statusCode(400) .body("ErrorResponse.Error.Code", equalTo("ValidationError")) .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value " - + "null at 'templateArn' failed to satisfy constraint: Member must not be " + + "at 'templateArn' failed to satisfy constraint: Member must not be " + "null")) .body(not(containsString("NoSuchEntity"))); } @@ -175,7 +175,7 @@ class RoleTemplateIntegrationTest { .when().post("/").then() .statusCode(400) .body("ErrorResponse.Error.Code", equalTo("ValidationError")) - .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value null " + .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value " + "at 'replacementValues.Department.values' failed to satisfy constraint: " + "Member must not be null")) .body(not(containsString("NoSuchEntity"))); @@ -254,7 +254,7 @@ class RoleTemplateIntegrationTest { .formParam("ReplacementValues.entry.01.key", "Department") .when().post("/").then() .statusCode(400) - .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value null " + .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value " + "at 'replacementValues.Department.values' failed to satisfy constraint: " + "Member must not be null")); } @@ -280,8 +280,8 @@ class RoleTemplateIntegrationTest { .body("ErrorResponse.Error.Code", equalTo("ValidationError")) .body("ErrorResponse.Error.Message", equalTo("3 validation errors detected: Value at " + "'replacementValues' failed to satisfy constraint: Member must have length " - + "less than or equal to 30; Value null at 'replacementValues.Parameter2." - + "values' failed to satisfy constraint: Member must not be null; Value null " + + "less than or equal to 30; Value at 'replacementValues.Parameter2." + + "values' failed to satisfy constraint: Member must not be null; Value " + "at 'replacementValues.Parameter10.values' failed to satisfy constraint: " + "Member must not be null")); } diff --git a/tools/aws/regen_iam_shapes.py b/tools/aws/regen_iam_shapes.py index db26fe711c..2a393ef17a 100644 --- a/tools/aws/regen_iam_shapes.py +++ b/tools/aws/regen_iam_shapes.py @@ -93,25 +93,28 @@ REQUIRED_BY_HAND = ( # Members an operation answers in a wording the walk would move, each with the reason it keeps. # -# `CreateServiceLinkedRole` keeps its principal and suffix in this hand-written list because the -# service method applies the IAM validation helper to `AWSServiceName`, while `CustomSuffix` still -# answers `InvalidInput`. `ServiceNamespaces` on `ListPoliciesGrantingServiceAccess` answers -# `InvalidInput` too when the list arrives empty. `statusType` is answered without the value or the -# permitted set, on all four operations that take it, which is what the recorded refusal carries, -# and `Encoding` on `GetSSHPublicKey` is answered with the modelled `UnrecognizedPublicKeyEncoding` -# rather than as a constraint at all. The simulators answer an empty `ActionNames`, -# `PolicyInputList` or `PolicySourceArn` with a sentence of their own, "At least one ActionNames -# member is required.", which no capture here moves. And `TagKeys` on the untag -# operations is answered against the list as a whole, "Value at 'tagKeys' failed to satisfy -# constraint: Member must satisfy constraint: [...]", where the walk names the member that broke -# it under its own index: both forms are readings, and this is the one those operations merged. +# A service-linked role's custom suffix answers `InvalidInput` rather than a validation error at +# all, "Custom suffix is not allowed for ", which is a recorded refusal across roughly +# eighty principals. `ServiceNamespaces` on `ListPoliciesGrantingServiceAccess` answers +# `InvalidInput` too when the list arrives empty, and `Encoding` on `GetSSHPublicKey` is answered +# with the modelled `UnrecognizedPublicKeyEncoding` rather than as a constraint at all. The +# simulators answer an empty `ActionNames`, `PolicyInputList` or `PolicySourceArn` with a sentence +# of their own, "At least one ActionNames member is required.", which no capture here moves. And +# `TagKeys` on the untag operations is answered against the list as a whole, "Value at 'tagKeys' +# failed to satisfy constraint: Member must satisfy constraint: [...]", where the walk names the +# member that broke it under its own index: both forms are readings, and this is the one those +# operations merged. +# +# Two entries came off this list on 2026-10-31, when captures from a real account answered them on +# issue #6042. `AWSServiceName` was held back because the operation answered it as `InvalidInput` +# with a sentence about its own bounds; AWS answers `ValidationError` naming the declared pattern, +# so the walk reads it. `Status` on the four operations that share `statusType` was held back +# because a 2025 recording carried neither the offending value nor the permitted set; AWS names the +# set, and answers an omitted `Status` as a required member rather than as a value outside it, so +# all four are read here with their `required` lists intact. MEMBERS_BY_HAND = { - "CreateServiceLinkedRole": ("AWSServiceName", "CustomSuffix"), + "CreateServiceLinkedRole": ("CustomSuffix",), "ListPoliciesGrantingServiceAccess": ("ServiceNamespaces",), - "UpdateAccessKey": ("Status",), - "UpdateSSHPublicKey": ("Status",), - "UpdateServiceSpecificCredential": ("Status",), - "UpdateSigningCertificate": ("Status",), "GetSSHPublicKey": ("Encoding",), "SimulateCustomPolicy": ("ActionNames", "PolicyInputList"), "SimulatePrincipalPolicy": ("ActionNames", "PolicyInputList", "PolicySourceArn"), @@ -126,6 +129,73 @@ MEMBERS_BY_HAND = { } +# The permitted set AWS lists inside a validation message, where this model declares the same values +# in another order. `statusType`'s message was captured from a real account on 2026-10-31, on issue +# #6042, as "Member must satisfy enum value set: [Expired, Active, Inactive]", which is the order +# AWS's own model declares rather than the order botocore lists. The values are the model's either +# way and the check below holds them to it: only the order is read from the capture. +ENUM_ORDER = { + "statusType": ("Expired", "Active", "Inactive"), +} + + +def enum_order(model: dict, orders: dict[str, tuple[str, ...]] | None = None) -> dict: + """`model` with each named shape's enum in the order AWS lists it in, `ENUM_ORDER` by default.""" + orders = ENUM_ORDER if orders is None else orders + shapes = dict(model["shapes"]) + for name, order in orders.items(): + declared = shapes[name]["enum"] + if sorted(declared) != sorted(order): + raise SystemExit(f"{name} declares {declared}, which is not a reordering of " + f"{list(order)}: the capture is stale, read the model again") + shapes[name] = {**shapes[name], "enum": list(order)} + return {**model, "shapes": shapes} + + +# The pattern AWS quotes inside a validation message, where this model declares another one for the +# same member. Each entry names the shape the member resolves to and the pattern that shape +# declares, so a model that changes either stops the run rather than quoting a text the capture no +# longer answers for. Only the quoted text is read from the capture: what a value is held to stays +# the model's. +# +# `CreateServiceLinkedRole`'s `AWSServiceName` resolves to `groupNameType`, the shape botocore gives +# a group name, 1 to 128 characters of `[\w+=,.@-]+`. The capture on issue #6042, from a real +# account on 2026-10-31, quotes `[\w+=.@-]*` for it, without the comma this model admits and with a +# `*` where the model sets a minimum of 1. Only AWS's message is in hand rather than its shape, so +# the member carries a shape of its own here with AWS's text beside the model's: the message is the +# captured one and a comma is still admitted, which nothing in hand settles either way. +QUOTED_PATTERNS = { + ("CreateServiceLinkedRole", "AWSServiceName"): ("groupNameType", r"[\w+=,.@-]+", r"[\w+=.@-]*"), +} + + +def quoted_patterns(model: dict, quoted: dict | None = None) -> dict: + """`model` with each named member on a shape of its own, carrying the pattern AWS quotes beside + the one the model declares, `QUOTED_PATTERNS` by default. + + The shape is named after the member as the wire names it, `AWSServiceName` reading + `aWSServiceName` in a message and so taking `aWSServiceNameType`, since the shape it is copied + from is one several members share and only this one's message differs.""" + quoted = QUOTED_PATTERNS if quoted is None else quoted + shapes = dict(model["shapes"]) + for (operation, member), (shape_name, declared, text) in quoted.items(): + request = model["operations"][operation]["input"]["shape"] + members = shapes[request]["members"] + if member not in members: + raise SystemExit(f"{operation} vendors no {member} to quote a pattern for: it is " + f"answered by hand again, or the model dropped it") + if members[member]["shape"] != shape_name: + raise SystemExit(f"{operation}.{member} resolves to {members[member]['shape']}, not " + f"{shape_name}: the capture is stale, read the model again") + if shapes[shape_name].get("pattern") != declared: + raise SystemExit(f"{shape_name} declares {shapes[shape_name].get('pattern')}, not " + f"{declared}: the capture is stale, read the model again") + own = member[0].lower() + member[1:] + "Type" + shapes[own] = {**shapes[shape_name], "quotedPattern": text} + shapes[request] = {**shapes[request], "members": {**members, member: {"shape": own}}} + return {**model, "shapes": shapes} + + def members_by_hand(model: dict, members: dict[str, tuple[str, ...]] | None = None) -> dict: """`model` with each operation's named members dropped, `MEMBERS_BY_HAND` by default.""" members = MEMBERS_BY_HAND if members is None else members @@ -154,9 +224,11 @@ def required_by_hand(model: dict, operations: tuple[str, ...] = REQUIRED_BY_HAND def prepare(model: dict) -> dict: - """The two reductions this generator makes, in the order they read: the required members an - operation answers for itself, and the members it answers in a wording of its own.""" - return members_by_hand(required_by_hand(model)) + """The four readings this generator makes, in the order they apply: the required members an + operation answers for itself, the members it answers in a wording of its own, the enum whose set + AWS lists in an order of its own, and the member whose pattern AWS quotes in a text of its + own.""" + return quoted_patterns(enum_order(members_by_hand(required_by_hand(model)))) def main(argv: list[str] | None = None) -> int: diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.py index 364b297347..ea196ced4f 100644 --- a/tools/aws/request_shapes.py +++ b/tools/aws/request_shapes.py @@ -79,8 +79,9 @@ def build(model: dict, provenance: str, generator: str, outputs: bool = False) - def build_constraints(model: dict, operations: tuple[str, ...], provenance: str, generator: str) -> dict: """The input shapes of `operations` with the constraints `RequestConstraintCheck` reads: for every - shape reachable from one, its type, required members, min, max, pattern and enum, and the shapes - of its members, list elements or map keys and values. Unlike `build`, it keeps members bound to + shape reachable from one, its type, required members, min, max, pattern, the pattern a violation + quotes where that is not the one matched on, and enum, and the shapes of its members, list + elements or map keys and values. Unlike `build`, it keeps members bound to the URI, query string or headers, so it suits the JSON protocols, whose members all travel in the body.""" kept: dict[str, dict] = {} @@ -89,7 +90,8 @@ def build_constraints(model: dict, operations: tuple[str, ...], provenance: str, if name in kept: return shape = model["shapes"][name] - entry = {k: shape[k] for k in ("type", "required", "min", "max", "pattern", "enum") if k in shape} + entry = {k: shape[k] for k in ("type", "required", "min", "max", "pattern", "quotedPattern", "enum") + if k in shape} kept[name] = entry if shape["type"] == "structure": entry["members"] = {k: v["shape"] for k, v in shape.get("members", {}).items()} diff --git a/tools/aws/test_regen_iam_shapes.py b/tools/aws/test_regen_iam_shapes.py index 8d245ff992..0d3dfc4903 100644 --- a/tools/aws/test_regen_iam_shapes.py +++ b/tools/aws/test_regen_iam_shapes.py @@ -2,8 +2,11 @@ The driver, the staleness check and the file contract every constraints generator must hold are `request_shapes.main`'s and are tested in test_request_shapes. What is IAM's own are its two -reductions: an operation vendored without the model's required members because it answers those for -itself in AWS's Query wording, and one vendored without a member it answers in a wording of its own. +reductions, its one reorder and its one quoted pattern: an operation vendored without the model's +required members because it answers those for itself in AWS's Query wording, one vendored without a +member it answers in a wording of its own, a shape whose enum is vendored in the order AWS lists it +inside a validation message rather than the order botocore declares, and a member whose message +quotes a pattern AWS gives for it rather than the one its shape declares. Run with: pytest tools/aws -q (or: make aws-data-test) """ @@ -11,6 +14,8 @@ from __future__ import annotations import json +import pytest + import regen_iam_shapes as r @@ -66,3 +71,121 @@ def test_the_vendored_file_carries_the_listed_operations_and_no_others(): assert set(doc["operations"]) == set(r.OPERATIONS) assert left_out - set(r.OPERATIONS) == left_out + + +def test_a_named_enum_is_vendored_in_the_order_aws_lists_it(): + model = { + "operations": {}, + "shapes": { + "statusType": {"type": "string", "enum": ["Active", "Expired", "Inactive"]}, + "nameType": {"type": "string", "min": 1, "max": 128}, + }, + } + + reordered = r.enum_order(model, {"statusType": ("Expired", "Active", "Inactive")}) + + assert reordered["shapes"]["statusType"] == { + "type": "string", "enum": ["Expired", "Active", "Inactive"]} + # Every other shape is left as it was, and so is the model handed in: the generator reads this + # model again for the staleness check, so a reorder in place would compare it against itself. + assert reordered["shapes"]["nameType"] == model["shapes"]["nameType"] + assert model["shapes"]["statusType"]["enum"] == ["Active", "Expired", "Inactive"] + assert r.enum_order(model, {}) == model + + +@pytest.mark.parametrize("order", [ + ("Expired", "Active", "Inactive", "Enabled"), + ("Expired", "Active"), + ("Expired", "Active", "Active"), +]) +def test_an_order_that_is_not_a_reordering_of_the_models_values_stops_the_run(order): + # Only the order is read from the capture; the values are the model's. So a capture naming a + # value the model does not declare, dropping one it does, or repeating one is a stale capture + # rather than a new set, and vendoring it would hold clients to an enum AWS never published. + model = {"operations": {}, "shapes": { + "statusType": {"type": "string", "enum": ["Active", "Expired", "Inactive"]}}} + + with pytest.raises(SystemExit): + r.enum_order(model, {"statusType": order}) + + +def test_the_vendored_file_carries_the_listed_enum_orders(): + # What says the reorder is wired into the generation rather than only tested on its own. + doc = json.loads(r.OUTPUT.read_text(encoding="utf-8")) + + for name, order in r.ENUM_ORDER.items(): + assert doc["shapes"][name]["enum"] == list(order), name + + +def test_a_member_whose_message_quotes_another_pattern_carries_a_shape_of_its_own(): + model = { + "operations": {"Link": {"input": {"shape": "LinkRequest"}}}, + "shapes": { + "LinkRequest": {"type": "structure", "required": ["Principal"], "members": { + "Principal": {"shape": "nameType"}, "Suffix": {"shape": "nameType"}, + }}, + "nameType": {"type": "string", "min": 1, "max": 128, "pattern": "[a-z,]+"}, + }, + } + + quoted = r.quoted_patterns(model, {("Link", "Principal"): ("nameType", "[a-z,]+", "[a-z]*")}) + + assert quoted["shapes"]["principalType"] == { + "type": "string", "min": 1, "max": 128, "pattern": "[a-z,]+", "quotedPattern": "[a-z]*"} + assert quoted["shapes"]["LinkRequest"]["members"]["Principal"] == {"shape": "principalType"} + # The bounds and the pattern matched on are the shape's own, and the member that shares that + # shape is left on it: it is one member's message that differs, not the shape's rules. + assert quoted["shapes"]["LinkRequest"]["members"]["Suffix"] == {"shape": "nameType"} + assert quoted["shapes"]["nameType"] == model["shapes"]["nameType"] + assert "quotedPattern" not in quoted["shapes"]["nameType"] + assert model["shapes"]["LinkRequest"]["members"]["Principal"] == {"shape": "nameType"} + assert r.quoted_patterns(model, {}) == model + + +@pytest.mark.parametrize("entry", [ + ("otherType", "[a-z,]+", "[a-z]*"), + ("nameType", "[a-z]+", "[a-z]*"), +]) +def test_a_quoted_pattern_recorded_against_another_shape_or_pattern_stops_the_run(entry): + # The entry names the shape the member resolves to and the pattern that shape declares, so a + # model that moves the member or rewrites the pattern must stop the run: the captured text was + # read against what the model said then, and quoting it against something else is a guess. + model = { + "operations": {"Link": {"input": {"shape": "LinkRequest"}}}, + "shapes": { + "LinkRequest": {"type": "structure", "members": {"Principal": {"shape": "nameType"}}}, + "nameType": {"type": "string", "pattern": "[a-z,]+"}, + "otherType": {"type": "string", "pattern": "[a-z,]+"}, + }, + } + + with pytest.raises(SystemExit): + r.quoted_patterns(model, {("Link", "Principal"): entry}) + + +def test_a_quoted_pattern_for_a_member_this_generator_drops_stops_the_run(): + # A member put back on the by-hand list, or dropped by the model, is answered somewhere else: + # quoting a pattern for one the vendored file does not carry would be quoting nothing. + model = { + "operations": {"Link": {"input": {"shape": "LinkRequest"}}}, + "shapes": { + "LinkRequest": {"type": "structure", "members": {"Suffix": {"shape": "nameType"}}}, + "nameType": {"type": "string", "pattern": "[a-z,]+"}, + }, + } + + with pytest.raises(SystemExit): + r.quoted_patterns(model, {("Link", "Principal"): ("nameType", "[a-z,]+", "[a-z]*")}) + + +def test_the_vendored_file_carries_the_listed_quoted_patterns(): + # What says the quoted text is wired into the generation rather than only tested on its own, + # and that the shape it was copied from keeps the message it had. + doc = json.loads(r.OUTPUT.read_text(encoding="utf-8")) + + for (operation, member), (shape_name, declared, text) in r.QUOTED_PATTERNS.items(): + own = doc["shapes"][doc["operations"][operation]]["members"][member] + assert own != shape_name, member + assert doc["shapes"][own]["pattern"] == declared, member + assert doc["shapes"][own]["quotedPattern"] == text, member + assert "quotedPattern" not in doc["shapes"][shape_name], shape_name