feat(iam): read every modelled operation's constraints from the model (#6965)

The vendored file carried 52 of IAM's operations and carries 162 now, which
is every one of the 164 that declares a required member, a length, a pattern,
an enum or a range, bar the two account alias operations: those answer their
single member in AWS's own wording, so there is nothing left for the walk to
read on them.

What takes the last of them in is a walk that reads a Query map and anything
nested under one. A map arrives as entries numbered under its own name,
`ReplacementValues.entry.1.key` and `.entry.1.value`, and an entry's value is
named under the key that entry carried, `replacementValues.Department.values`,
which is how both maps this service answered by hand already named one and how
the JSON protocols name a map's value here. An entry is read off its key, so
one numbered with a value and no key is not an entry the map could hold. A
structure's field may be a list, a list's member may hold a list of its own
and a map's value may be a structure, so `AcquireRole`,
`PutAccountProperties`, `CreateDelegationRequest` and both simulators are read
with the rest, and the file refuses to load only for a shape of a type the
walk would pass over unread.

The two hand-written map checks come off with that. `AcquireRole`'s answers do
not move at all: the count of 30, each entry's required `Values` and the 20
values one entry admits read exactly as its own check read them, named by the
key the entry was sent under, which is what the tests it already had pin.
`PutAccountProperties` keeps the set it answered for a key, `Map keys must
satisfy constraint: [...]`, with the minimum length of 1 the model declares
now inside it where the hand-written set listed the maximum and the pattern
alone, and a value outside its bounds is answered in the words every other
member carries rather than the `must have length between 1 and 1024` that
check wrote. The `Namespace/PropertyName` rule stays exactly where it was,
being a rule the service applies after the format is good rather than a
constraint the model declares.

Two reductions keep an answer that is AWS's own rather than rewording it, both
through the hook the shared driver already takes. Eight operations answer a
member the request leaves out with "The request must contain the parameter
CertificateBody.", the wording this emulator answers for a missing Query
parameter in several services, so their shapes are vendored without the
model's required list and keep that refusal while their lengths and patterns
are read. Seventeen more are vendored without a member they answer in a
wording of their own: a service-linked role's principal and suffix, an empty
`ServiceNamespaces`, `statusType` on all four operations that take it,
`Encoding` on `GetSSHPublicKey`, the simulators' empty `ActionNames`,
`PolicyInputList` and `PolicySourceArn`, and `TagKeys` on the eight untag
operations.

Nine wordings this service wrote for itself go with the checks that wrote
them: the three password-policy ranges, the name refusal that spelled out its
own bounds and the group, server certificate and instance profile names beside
it, the path refusal, the authentication code, the virtual MFA device name and
the serial number. Each is answered by the model's own violation now, through
the one writer this package already had.

A member whose shape fixes one length is answered for that length rather than
for a bound it sits under, `Member must have length equal to 6`. That is the
wording a report's 36-character job id already answered by hand, which is why
the three report readers can be read from the model at all, and it reaches
STS through the same writer, whose `TokenCode` and `SigningAlgorithm` each fix
one length too.

Two test fixtures carried values AWS refuses and now carry values it takes.
`SignedIamUsers` named a user with a prefix plus a whole UUID, which reaches
66 characters where `userNameType` declares 64, and the two sibling fixtures
that named one the same way follow it onto the shorter suffix. The SDK suite
registered a SAML provider with a 375-character metadata document where AWS
declares 1000, so each of its two documents is padded to that bound on its
own.

`docs/services/iam.md` carries each reading, the maps among them.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-29 20:32:48 -05:00
1 parent 361b3177b8
commit 98a3d2a346
27 files changed
+2638 -482

No files matched your search

@@ -46,10 +46,19 @@ import java.util.regex.Pattern;
* the count is held to the list's own bounds with the value left out of the message. A structure
* member arrives as {@code TaskPolicyArn.Arn} and is named {@code taskPolicyArn.arn}.
*
* <p>A map is refused when the file loads rather than passed over quietly: this package answers one
* today in a form of its own, {@code Map keys must satisfy constraint: [...]} against the whole map,
* and which of the two forms AWS answers for a Query map is a question no source here settles. So is
* anything nested deeper than a list of structures or a structure of scalars.
* <p>A map arrives as entries numbered under its own name, {@code Properties.entry.1.key} and
* {@code Properties.entry.1.value}, or bare as {@code Properties.1.key}. An entry's value is named
* under the key the entry carries, {@code properties.Team/Owner}, which is how the hand-written
* checks these waves replace already named one and how {@link RequestConstraintCheck} names a map's
* value on the JSON protocols. An entry numbered with no key of its own is no entry the map could
* hold, so it is neither counted nor answered. A key outside its shape's rules is answered with the
* whole set the shape declares, nested under the map's own name, which is the form AWS answers for
* a map key everywhere this repository has one recorded.
*
* <p>Every one of those may hold any of the others: a structure's field may be a list, a list's
* member a map, a map's value a structure. A shape of some other type is one this walk would pass
* over without reading, so the file refuses to load rather than letting a request through
* unchecked.
*/
public final class QueryConstraintCheck {
@@ -105,40 +114,34 @@ public final class QueryConstraintCheck {
private void requireReadableMembers(String operation, String inputShape) {
for (Map.Entry<String, JsonNode> member : shapes.path(inputShape).path("members").properties()) {
requireReadableMember(operation, member.getKey(), member.getValue().asText());
requireReadable(operation, member.getKey(), member.getValue().asText(), new LinkedHashSet<>());
}
}
private void requireReadableMember(String operation, String member, String shapeName) {
String type = shapes.path(shapeName).path("type").asText();
if (SCALAR_TYPES.contains(type)) {
/**
* Every member of every operation the file carries is read, whatever it nests. {@code seen}
* carries the shapes on the way down, so a shape that holds itself is read once rather than
* forever.
*/
private void requireReadable(String operation, String member, String shapeName, Set<String> seen) {
JsonNode shape = shapes.path(shapeName);
String type = shape.path("type").asText();
if (SCALAR_TYPES.contains(type) || !seen.add(shapeName)) {
return;
}
switch (type) {
case "list" -> requireReadableElement(operation, member, shapes.path(shapeName).path("member").asText());
case "structure" -> requireScalarFields(operation, member, shapeName);
default -> throw refusal(operation, member, type);
}
}
private void requireReadableElement(String operation, String member, String elementShape) {
String type = shapes.path(elementShape).path("type").asText();
if (SCALAR_TYPES.contains(type)) {
return;
}
if ("structure".equals(type)) {
requireScalarFields(operation, member, elementShape);
return;
}
throw refusal(operation, member, "list of " + type);
}
private void requireScalarFields(String operation, String member, String structure) {
for (Map.Entry<String, JsonNode> field : shapes.path(structure).path("members").properties()) {
String type = shapes.path(field.getValue().asText()).path("type").asText();
if (!SCALAR_TYPES.contains(type)) {
throw refusal(operation, member + "." + field.getKey(), type);
case "list" -> requireReadable(operation, member, shape.path("member").asText(), seen);
case "map" -> {
requireReadable(operation, member + ".key", shape.path("key").asText(), seen);
requireReadable(operation, member + ".value", shape.path("value").asText(), seen);
}
case "structure" -> {
for (Map.Entry<String, JsonNode> field : shape.path("members").properties()) {
requireReadable(operation, member + "." + field.getKey(),
field.getValue().asText(), seen);
}
}
default -> throw refusal(operation, member, type);
}
}
@@ -202,11 +205,7 @@ public final class QueryConstraintCheck {
String param = prefix + name;
boolean mandatory = required.contains(name);
JsonNode shape = shapes.path(shapeName);
List<String> own = switch (shape.path("type").asText()) {
case "list" -> listViolations(shape, param, memberPath, mandatory, params);
case "structure" -> nestedViolations(shape, param, memberPath, mandatory, params);
default -> scalarViolations(shapeName, param, memberPath, mandatory, params);
};
List<String> own = memberViolations(shapeName, param, memberPath, mandatory, params);
violations.addAll(own);
if (own.isEmpty() && documented.containsKey(name) && carries(params, param)) {
violations.add(documented.get(name));
@@ -226,6 +225,75 @@ public final class QueryConstraintCheck {
|| params.keySet().stream().anyMatch(key -> key.startsWith(param + ".")));
}
/**
* One member, whatever its shape nests: a scalar at its own name, a list or a map numbered
* under it, a structure's fields below it.
*/
private List<String> memberViolations(String shapeName, String param, String path,
boolean required, MultivaluedMap<String, String> params) {
JsonNode shape = shapes.path(shapeName);
return switch (shape.path("type").asText()) {
case "list" -> listViolations(shape, param, path, required, params);
case "map" -> mapViolations(shape, param, path, required, params);
case "structure" -> nestedViolations(shape, param, path, required, params);
default -> scalarViolations(shapeName, param, path, required, params);
};
}
/**
* A map's entries, held to the map's own bounds and then each key and value to its shape. An
* entry arrives as {@code Properties.entry.1.key} and {@code Properties.entry.1.value}, and
* the value is named under the key the entry carries. An entry is read off that key, as the
* count of one has always been here, so one numbered with no key is not an entry the map could
* hold: it is neither counted nor answered.
*/
private List<String> mapViolations(JsonNode shape, String param, String path, boolean required,
MultivaluedMap<String, String> params) {
List<AwsQueryLists.IndexedMember> entries = params == null
? List.of()
: AwsQueryLists.members(params, param, "entry").stream()
.filter(entry -> params.getFirst(entry.prefix() + ".key") != null)
.toList();
if (entries.isEmpty()) {
return required ? List.of(SmithyValidationErrors.notNull(path)) : List.of();
}
String valueShape = shape.path("value").asText();
boolean structure = "structure".equals(shapes.path(valueShape).path("type").asText());
List<String> violations = new ArrayList<>();
violations.addAll(single(SmithyValidationErrors.sizeOutOfRange(path, entries.size(),
shape.path("min").asInt(0), shape.path("max").asInt(Integer.MAX_VALUE))));
for (AwsQueryLists.IndexedMember entry : entries) {
String key = params.getFirst(entry.prefix() + ".key");
violations.addAll(keyViolations(shape.path("key").asText(), key, path));
String valueParam = entry.prefix() + ".value";
String valuePath = path + "." + key;
if (structure) {
// An entry the request numbered with a key is an entry, so what the structure
// under it requires is answered inside it rather than the value reading as absent.
violations.addAll(structureViolations(shapes.path(valueShape), valueParam + ".",
valuePath + ".", params, Map.of()));
} else {
violations.addAll(memberViolations(valueShape, valueParam, valuePath, true, params));
}
}
return violations;
}
/**
* A map key outside its shape's rules, answered with the whole set that shape declares rather
* than with the one rule the key broke. Which rules a key breaks is read the way every other
* value is, so one object decides whether a key is good and another how a map words it.
*/
private List<String> keyViolations(String shapeName, String key, String path) {
if (violations(shapeName, key, path).isEmpty()) {
return List.of();
}
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))));
}
/**
* A member one parameter carries. A request naming it at all carries a value, so only one it
* names nowhere is absent, and a required member is what an absent one is reported for.
@@ -246,25 +314,30 @@ public final class QueryConstraintCheck {
*/
private List<String> listViolations(JsonNode shape, String param, String path, boolean required,
MultivaluedMap<String, String> params) {
String elementShape = shape.path("member").asText();
boolean scalar = SCALAR_TYPES.contains(shapes.path(elementShape).path("type").asText());
// A scalar member's value lives at its own name, so an index the request numbered only
// under a deeper key carries no value and is no member of the list: nothing reads one
// there either. A member present and empty is a member all the same.
List<AwsQueryLists.IndexedMember> members = params == null
? List.of()
: AwsQueryLists.members(params, param, null);
: AwsQueryLists.members(params, param, null).stream()
.filter(member -> !scalar || params.getFirst(member.prefix()) != null)
.toList();
if (members.isEmpty()) {
return required ? List.of(SmithyValidationErrors.notNull(path)) : List.of();
}
List<String> violations = new ArrayList<>();
violations.addAll(single(SmithyValidationErrors.sizeOutOfRange(path, members.size(),
shape.path("min").asInt(0), shape.path("max").asInt(Integer.MAX_VALUE))));
String elementShape = shape.path("member").asText();
boolean structure = "structure".equals(shapes.path(elementShape).path("type").asText());
for (AwsQueryLists.IndexedMember member : members) {
String memberPath = path + "." + member.index() + ".member";
if (structure) {
violations.addAll(structureViolations(shapes.path(elementShape),
member.prefix() + ".", memberPath + ".", params, Map.of()));
if (scalar) {
violations.addAll(violations(elementShape, params.getFirst(member.prefix()),
memberPath));
} else {
String value = params.getFirst(member.prefix());
violations.addAll(violations(elementShape, value == null ? "" : value, memberPath));
violations.addAll(memberViolations(elementShape, member.prefix(), memberPath,
false, params));
}
}
return violations;
@@ -357,11 +430,17 @@ public final class QueryConstraintCheck {
}
private String enumViolation(JsonNode shape, String value, String path) {
if (!shape.has("enum")) {
List<String> allowed = allowedValues(shape);
if (allowed.isEmpty()) {
return null;
}
List<String> allowed = new ArrayList<>();
shape.path("enum").forEach(choice -> allowed.add(choice.asText()));
return allowed.contains(value) ? null : messages.notInEnum(value, path, allowed);
}
/** The values a shape's enum admits, in the model's order, or none for a shape without one. */
private static List<String> allowedValues(JsonNode shape) {
List<String> allowed = new ArrayList<>();
shape.path("enum").forEach(choice -> allowed.add(choice.asText()));
return allowed;
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.core.common;
import java.util.ArrayList;
import java.util.List;
/**
@@ -128,6 +129,29 @@ public final class SmithyValidationErrors {
return Violations.QUOTED.notInEnum(value, path, allowed);
}
/**
* The rules a string shape declares, worded the way AWS lists them inside a nested constraint
* set and in the order every capture of one here reads: the maximum length first, then the
* minimum, then the pattern, then the enum. A bound the shape does not declare is left out, a
* minimum of zero being no bound at all.
*/
public static List<String> constraintSet(int min, int max, String pattern, List<String> allowed) {
List<String> rules = new ArrayList<>();
if (max != Integer.MAX_VALUE) {
rules.add("Member must have length less than or equal to " + max);
}
if (min > 0) {
rules.add("Member must have length greater than or equal to " + min);
}
if (pattern != null) {
rules.add("Member must satisfy regular expression pattern: " + pattern);
}
if (allowed != null && !allowed.isEmpty()) {
rules.add("Member must satisfy enum value set: " + allowed);
}
return rules;
}
/**
* The violation for a list holding a value outside its members' enum. The list is checked as a
* whole, so the whole list is the offending value and the enum constraint is nested.
@@ -189,16 +213,23 @@ public final class SmithyValidationErrors {
return constraint(path, value, "Member must have value less than or equal to " + max);
}
/** The violation for a string outside its length bounds, or null for one inside. */
/**
* The violation for a string outside its length bounds, or null for one inside. A shape
* whose bounds are the same length names that length rather than the bound the value sits
* under, "Member must have length equal to 36", which is what this package answers for a
* report's job id and what the recorded refusals for such a member carry.
*/
public String lengthOutOfRange(String path, String value, int min, int max) {
int length = value.codePointCount(0, value.length());
if (length < min) {
return lengthTooShort(path, value, min);
if (length >= min && length <= max) {
return null;
}
if (length > max) {
return constraint(path, value, "Member must have length less than or equal to " + max);
if (min == max) {
return constraint(path, value, "Member must have length equal to " + min);
}
return null;
return length < min
? lengthTooShort(path, value, min)
: constraint(path, value, "Member must have length less than or equal to " + max);
}
/** The violation for a string under {@code min} characters, an empty one included. */
@@ -211,6 +242,16 @@ public final class SmithyValidationErrors {
return constraint(path, value, "Member must satisfy regular expression pattern: " + pattern);
}
/**
* The violation a map answers for a key outside the rules its key shape declares. The
* whole set is nested under the map's own name, whichever rule the key broke, rather than
* the entry that carried it being named: that is what IAM answers for an account property
* key and what eight other services here answer for a map of their own.
*/
public String mapKeys(String path, String value, List<String> rules) {
return constraint(path, value, "Map keys must satisfy constraint: " + rules);
}
/** The violation for a value outside its enum, the values in the model's order. */
public String notInEnum(String value, String path, List<String> allowed) {
return constraint(path, value, "Member must satisfy enum value set: " + allowed);
@@ -1,7 +1,6 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.*;
import io.github.hectorvent.floci.core.common.AwsQueryLists;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
@@ -53,7 +52,6 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@@ -82,19 +80,6 @@ public class IamQueryHandler {
private static final int USER_NAME_MIN_LENGTH = 1;
private static final int USER_NAME_MAX_LENGTH = 64;
private static final Pattern USER_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]+");
/** {@code mapStringReplacementValueEntry} on {@code AcquireRole}: at most 30 entries. */
private static final int REPLACEMENT_VALUES_MAX_ENTRIES = 30;
/** {@code replacementValueListType}, the values one entry carries: 1 to 20 of them. */
private static final int REPLACEMENT_VALUES_MAX_PER_ENTRY = 20;
/** The Query spelling of a {@code ReplacementValues} entry, which carries a key and a value. */
private static final String REPLACEMENT_VALUES_ENTRY = "ReplacementValues.entry.";
/**
* One entry's key, capturing the prefix the rest of that entry is read back under: an index is
* taken as the request spells it, and ordered by the number it reads as, an index that is no
* number sorting after every index that is one.
*/
private static final Pattern REPLACEMENT_VALUES_ENTRY_KEY =
Pattern.compile("(" + Pattern.quote(REPLACEMENT_VALUES_ENTRY) + "[^.]+)\\.key");
/** {@code sortKeyType} on {@code GetOrganizationsAccessReport}. */
private static final Set<String> SORT_KEYS = Set.of("SERVICE_NAMESPACE_ASCENDING",
"SERVICE_NAMESPACE_DESCENDING", "LAST_AUTHENTICATED_TIME_ASCENDING",
@@ -1484,74 +1469,16 @@ public class IamQueryHandler {
* one: it reads "the specified role template is disabled", which is an answer about a template
* that exists, and role manager's own switch, the {@code RoleManager/Enabled} account property,
* is a different question again. An ARN naming no template is the 404.
*
* <p>{@code ReplacementValues} is held to the shape the model declares for it, the map's own
* count and each entry's required values among it, by {@link IamRequestShapes} ahead of this.
*/
private Response handleAcquireRole(MultivaluedMap<String, String> params) {
String templateArn = requiredArn(params, "TemplateArn");
requireIntegerIfPresent(params, "TemplateMinorVersion");
requireReplacementValuesWithinDeclaredShape(params);
throw noSuchRoleTemplate(templateArn);
}
/**
* {@code ReplacementValues} is declared with at most 30 entries, and each entry holds a
* {@code ReplacementValueEntry}, which declares {@code Values} required and bounds
* {@code replacementValueListType} at 1 to 20 values. The API Reference spells the same thing
* out, "Map Entries: Maximum number of 30 items" on the map and, on the entry,
* "Array Members: Minimum number of 1 item. Maximum number of 20 items" with "Required: Yes".
* All of it is read ahead of the template lookup, so a request that breaks any of it is the 400
* the validation layer answers rather than a 404 that ignored the map it was handed.
*
* <p>The map's own length is reported before its entries, which is the order the shape is
* walked, and every entry that is broken is reported rather than only the first: the validation
* layer answers with each member it found broken. An entry is read off its key, as the map's
* own count has always been, so a value sent under no key is not an entry the map could hold
* and is not one here either, and an entry is read back under the index the request spelled
* rather than under the number that index reads as, the parameters that carry it being named
* after the spelling. The count takes every key, as it has since the cap landed, so two
* spellings of one number are two entries to it and each is answered on its own.
*
* <p>An entry's values arrive as {@code ReplacementValues.entry.N.value.Values.member.M}, read
* through the helper the other Query services read a list with, and they are counted by the
* member being present rather than by what it holds: the list's members publish no constraint
* of their own, so a replacement value sent empty is a value, where reading it as absent would
* answer the required-member violation for a list that has one. A list of no members at all is
* how an absent member reaches a Query service, so the lower bound of 1 is never reached on its
* own, and an entry carrying nothing is the required member reading as null. The violation names
* the entry by its key, the way the account properties map names one, rather than by whatever
* index the request numbered it with.
*/
private static void requireReplacementValuesWithinDeclaredShape(
MultivaluedMap<String, String> params) {
List<String> entries = params.keySet().stream()
.map(REPLACEMENT_VALUES_ENTRY_KEY::matcher)
.filter(Matcher::matches)
.map(matcher -> matcher.group(1))
.sorted(Comparator.<String>comparingInt(AwsQueryLists::memberIndex)
.thenComparing(Comparator.naturalOrder()))
.toList();
List<String> violations = new ArrayList<>();
if (entries.size() > REPLACEMENT_VALUES_MAX_ENTRIES) {
violations.add("Value at 'replacementValues' failed to satisfy constraint: Member "
+ "must have length less than or equal to " + REPLACEMENT_VALUES_MAX_ENTRIES);
}
for (String entry : entries) {
String path = "replacementValues." + params.getFirst(entry + ".key") + ".values";
Pattern members = AwsQueryLists.memberKeys(entry + ".value.Values", null);
long values = params.keySet().stream()
.filter(name -> members.matcher(name).matches())
.count();
if (values == 0) {
violations.add(SmithyValidationErrors.notNull(path));
} else if (values > REPLACEMENT_VALUES_MAX_PER_ENTRY) {
violations.add("Value at '" + path + "' failed to satisfy constraint: Member must "
+ "have length less than or equal to " + REPLACEMENT_VALUES_MAX_PER_ENTRY);
}
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationError(violations);
}
}
private static AwsException noSuchRoleTemplate(String templateArn) {
return new AwsException("NoSuchEntity",
"The role template with ARN " + templateArn + " cannot be found.", 404);
@@ -3680,6 +3607,11 @@ public class IamQueryHandler {
* A required request member. {@link #getParam} returns null for an absent one, which lets a
* malformed request read as a valid empty answer, so anything the model marks required is read
* through here instead.
*
* <p>A blank value is a value the request carries, and the constraints read ahead of this
* answer it against the minimum length its shape declares. What is left here is a member the
* model gives no minimum and an operation the vendored file does not carry, where a blank is
* still read as a member that never arrived rather than passed to the operation.
*/
private String requireParam(MultivaluedMap<String, String> params, String name) {
String value = params.getFirst(name);
@@ -14,16 +14,24 @@ import jakarta.ws.rs.core.MultivaluedMap;
* <p>The violations read as IAM writes them, naming the member with no value beside it, which is
* {@link IamValidationErrors}' reading of the captures rather than the walk's own default.
*
* <p>The vendored file carries a wave of operations rather than all 180, and grows a wave at a
* time, each one chosen where no operation checks a declared constraint by hand, so the model adds
* <p>The vendored file carries 162 of IAM's 180 operations, which is every one the model
* constrains bar the two account alias operations: those answer their single member in AWS's own
* wording, so there is nothing left for the walk to read on them. It arrived a wave at a time,
* each wave chosen where no operation checked a declared constraint by hand, so the model added
* the refusals AWS answers without rewording an answer already given. The managed-policy family
* came first, with {@code AttachRolePolicy} and {@code DetachRolePolicy} as the exception and the
* parity case, {@code IamService.validateRoleName} already answering {@code roleName} in the same
* form. {@code GetAccountAuthorizationDetails} is the first read through the list walk, its
* {@code Filter}, {@code MaxItems} and {@code Marker} having been read by nothing at all. Every
* other paged operation follows, so {@code MaxItems} and {@code Marker} are held to the model here
* rather than by the paging itself; six of them carry only those two members, the rest of their
* request being answered by hand or nested past what the walk reads.
* form. {@code GetAccountAuthorizationDetails} was the first read through the list walk, its
* {@code Filter}, {@code MaxItems} and {@code Marker} having been read by nothing at all, and the
* last wave took the operations whose requests nest a map or a list deeper than the walk read:
* {@code AcquireRole}, {@code PutAccountProperties}, {@code CreateDelegationRequest} and both
* simulators. {@code MaxItems} and {@code Marker} are held to the model here rather than by the
* paging itself, for every paged operation.
*
* <p>Two hand-written checks answered a map before this read one, and the answers they gave are
* the answers it gives: an entry's value is named under the key the entry carried, and a key
* outside its shape's rules carries the whole set the shape declares. {@code docs/services/iam.md}
* records what moved with them and what did not.
*/
final class IamRequestShapes {
@@ -157,20 +157,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final String ACCOUNT_PASSWORD_POLICY_KEY = "account-password-policy";
private static final String STS_PREFERENCES_KEY = "sts-preferences";
private static final String OUTBOUND_FEDERATION_KEY = "outbound-web-identity-federation";
/** accountPropertiesMapType's key: 1 to 50 of this, and a value of 1 to 1024. */
private static final Pattern ACCOUNT_PROPERTY_KEY_PATTERN =
Pattern.compile("^[A-Za-z][A-Za-z0-9/_-]*$");
private static final int MAX_ACCOUNT_PROPERTY_KEY_LENGTH = 50;
private static final int MAX_ACCOUNT_PROPERTY_VALUE_LENGTH = 1024;
/** globalEndpointTokenVersion's only two values. */
private static final Set<String> GLOBAL_ENDPOINT_TOKEN_VERSIONS = Set.of("v1Token", "v2Token");
/** AWS-documented bounds for the account password policy's numeric fields. */
private static final int MIN_PASSWORD_LENGTH_FLOOR = 6;
private static final int MIN_PASSWORD_LENGTH_CEILING = 128;
private static final int MAX_PASSWORD_AGE_FLOOR = 1;
private static final int MAX_PASSWORD_AGE_CEILING = 1095;
private static final int PASSWORD_REUSE_PREVENTION_FLOOR = 1;
private static final int PASSWORD_REUSE_PREVENTION_CEILING = 24;
/**
* AWS's documented {@code passwordType} pattern for Create/UpdateLoginProfile: printable
* ASCII and Latin-1 Supplement (space through code point 0xFF), plus tab/LF/CR, 1-128 chars.
@@ -307,16 +296,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* types" (IAM User Guide). Floci models only virtual devices, so this bounds those alone.
*/
private static final int MAX_MFA_DEVICES_PER_USER = 8;
/** {@code AuthenticationCode1}/{@code 2}: fixed length of 6, pattern {@code [\d]+}. */
private static final Pattern AUTHENTICATION_CODE_PATTERN = Pattern.compile("[0-9]{6}");
/**
* {@code virtualMFADeviceName}: a minimum of 1 and this pattern, with no maximum length. IAM's
* other name types are all capped at 64 or 128; this one is deliberately not.
* The largest window {@code PasswordReusePrevention} accepts, which the model declares and the
* constraints read ahead of the operation hold a request to. It stays here for the password
* history that window bounds: nothing can be asked about a password further back than this.
*/
private static final int PASSWORD_REUSE_PREVENTION_CEILING = 24;
/**
* {@code serialNumberType}'s maximum, which bounds the serial number a virtual device is minted
* with rather than one a request sends: that one is read against the model with the rest of the
* request. The name and the path together make the serial, so neither member's own bound says
* what the pair may produce.
*/
private static final Pattern VIRTUAL_MFA_DEVICE_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]+");
/** {@code serialNumberType}: 9-256 characters, and a wider pattern than a name, allowing ARNs. */
private static final Pattern SERIAL_NUMBER_PATTERN = Pattern.compile("[\\w+=/:,.@-]+");
private static final int SERIAL_NUMBER_MIN_LENGTH = 9;
private static final int SERIAL_NUMBER_MAX_LENGTH = 256;
/**
* How far the code pair may sit from the current 30-second window. Enabling a device is done
@@ -2702,7 +2693,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* their documented defaults instead of carrying over the previous policy's value.
*/
public AccountPasswordPolicy updateAccountPasswordPolicy(AccountPasswordPolicy policy) {
validateAccountPasswordPolicy(policy);
passwordPolicies.put(ACCOUNT_PASSWORD_POLICY_KEY, policy);
LOG.infov("Updated IAM account password policy");
return policy;
@@ -2722,29 +2712,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
LOG.infov("Deleted IAM account password policy");
}
private void validateAccountPasswordPolicy(AccountPasswordPolicy policy) {
int minLength = policy.getMinimumPasswordLength();
if (minLength < MIN_PASSWORD_LENGTH_FLOOR || minLength > MIN_PASSWORD_LENGTH_CEILING) {
throw new AwsException("ValidationError",
"MinimumPasswordLength must be between " + MIN_PASSWORD_LENGTH_FLOOR + " and "
+ MIN_PASSWORD_LENGTH_CEILING + ".", 400);
}
Integer maxAge = policy.getMaxPasswordAge();
if (maxAge != null && (maxAge < MAX_PASSWORD_AGE_FLOOR || maxAge > MAX_PASSWORD_AGE_CEILING)) {
throw new AwsException("ValidationError",
"MaxPasswordAge must be between " + MAX_PASSWORD_AGE_FLOOR + " and "
+ MAX_PASSWORD_AGE_CEILING + ".", 400);
}
Integer reusePrevention = policy.getPasswordReusePrevention();
if (reusePrevention != null
&& (reusePrevention < PASSWORD_REUSE_PREVENTION_FLOOR
|| reusePrevention > PASSWORD_REUSE_PREVENTION_CEILING)) {
throw new AwsException("ValidationError",
"PasswordReusePrevention must be between " + PASSWORD_REUSE_PREVENTION_FLOOR + " and "
+ PASSWORD_REUSE_PREVENTION_CEILING + ".", 400);
}
}
// =========================================================================
// Login Profiles
// =========================================================================
@@ -2969,20 +2936,40 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
}
/**
* A name held to the pattern every IAM name type declares. The constraints read ahead of the
* operation answer this for a request that arrives through the Query protocol, so what reaches
* here is a caller inside the emulator, a seeded configuration or a template, and the wording
* is the same either way.
*/
private void validateIamResourceName(String value, String paramName) {
if (value == null || !IAM_RESOURCE_NAME_PATTERN.matcher(value).matches()) {
throw new AwsException("ValidationError",
paramName + " must be 1-128 characters matching [\\w+=,.@-].", 400);
if (value == null) {
throw SmithyValidationErrors.validationError(
SmithyValidationErrors.notNull(memberPath(paramName)));
}
if (!IAM_RESOURCE_NAME_PATTERN.matcher(value).matches()) {
throw IamValidationErrors.validationError(memberPath(paramName), value,
"Member must satisfy regular expression pattern: "
+ IAM_RESOURCE_NAME_PATTERN.pattern());
}
}
/** The member's name as a validation message spells it, the request's with a lower first letter. */
private static String memberPath(String paramName) {
return Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1);
}
/** The same for a path, which the model holds to its own length and pattern. */
private void validateIamPath(String value, String paramName) {
if (value == null) return;
if (value.length() > IAM_PATH_MAX_LENGTH || !IAM_PATH_PATTERN.matcher(value).matches()) {
throw new AwsException("ValidationError",
paramName + " must be at most " + IAM_PATH_MAX_LENGTH
+ " characters, either a bare forward slash or a string that begins and ends "
+ "with a forward slash.", 400);
String path = memberPath(paramName);
if (value.codePointCount(0, value.length()) > IAM_PATH_MAX_LENGTH) {
throw IamValidationErrors.validationError(path, value,
"Member must have length less than or equal to " + IAM_PATH_MAX_LENGTH);
}
if (!IAM_PATH_PATTERN.matcher(value).matches()) {
throw IamValidationErrors.validationError(path, value,
"Member must satisfy regular expression pattern: " + IAM_PATH_PATTERN.pattern());
}
}
@@ -3012,8 +2999,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
String namespace = null;
for (Map.Entry<String, String> entry : properties.entrySet()) {
String keyNamespace = validateAccountPropertyKey(entry.getKey());
validateAccountPropertyValue(entry.getKey(), entry.getValue());
String keyNamespace = accountPropertyNamespace(entry.getKey());
if (namespace == null) {
namespace = keyNamespace;
} else if (!namespace.equals(keyNamespace)) {
@@ -3032,25 +3018,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
/**
* The namespace half of the key, having checked the whole key against the model.
* The namespace half of the key, whose own length and pattern, and whose value's length, the
* model declares and {@code IamRequestShapes} answers ahead of this.
*
* <p>The two rejections here are not the same kind of error. The length and the pattern are
* <p>What is left here is not the same kind of error as those. The length and the pattern are
* published constraints on the parameter, and the API Reference defines {@code ValidationError}
* as the common error for input that "doesn't meet the required format or constraints". The
* {@code Namespace/PropertyName} rule is not expressible in the published pattern, which admits
* no slash, several, and a trailing one, so it is a rule the service applies after the format
* is already satisfied: that is {@code InvalidInput}, "an invalid or out-of-range value".
*/
private String validateAccountPropertyKey(String key) {
if (key == null || key.isEmpty() || key.length() > MAX_ACCOUNT_PROPERTY_KEY_LENGTH
|| !ACCOUNT_PROPERTY_KEY_PATTERN.matcher(key).matches()) {
throw IamValidationErrors.validationError("properties", key,
"Map keys must satisfy constraint: [Member must have length less than or "
+ "equal to " + MAX_ACCOUNT_PROPERTY_KEY_LENGTH + ", Member must "
+ "satisfy regular expression pattern: "
+ ACCOUNT_PROPERTY_KEY_PATTERN.pattern() + "]");
}
int separator = key.indexOf('/');
private String accountPropertyNamespace(String key) {
int separator = key == null ? -1 : key.indexOf('/');
if (separator <= 0 || separator != key.lastIndexOf('/') || separator == key.length() - 1) {
throw new AwsException("InvalidInput",
"The property key '" + key + "' is not Namespace/PropertyName: a key has "
@@ -3060,16 +3039,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return key.substring(0, separator);
}
private void validateAccountPropertyValue(String key, String value) {
if (value == null || value.isEmpty()
|| value.length() > MAX_ACCOUNT_PROPERTY_VALUE_LENGTH) {
throw SmithyValidationErrors.validationError(
"Value at 'properties." + key + "' failed to "
+ "satisfy constraint: Member must have length between 1 and "
+ MAX_ACCOUNT_PROPERTY_VALUE_LENGTH);
}
}
/** The account's global endpoint token version, {@code v1Token} or {@code v2Token}. */
public void setSecurityTokenServicePreferences(String globalEndpointTokenVersion) {
if (globalEndpointTokenVersion == null
@@ -4087,7 +4056,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* it. A caller that seeds a TOTP app from a Floci device gets working codes.
*/
public VirtualMfaDevice createVirtualMfaDevice(String name, String path, Map<String, String> tags) {
validateVirtualMfaDeviceName(name);
validateIamPath(path, "Path");
String normalizedPath = normalizePath(path);
// The serial number is the ARN, and the ARN embeds the path, so two devices of the same
@@ -4152,7 +4120,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* documented DeleteConflict rather than a silent detach.
*/
public void deleteVirtualMfaDevice(String serialNumber) {
validateSerialNumber(serialNumber);
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
if (device.isAssigned()) {
@@ -4172,9 +4139,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public void enableMfaDevice(String userName, String serialNumber, String code1, String code2) {
validateIamResourceName(userName, "UserName");
validateSerialNumber(serialNumber);
validateAuthenticationCode(code1, "AuthenticationCode1");
validateAuthenticationCode(code2, "AuthenticationCode2");
synchronized (mfaDeviceLock) {
// The user's existence is confirmed under the same lock DeleteUser checks for devices
// under. Checked outside it, a DeleteUser that saw no devices could remove the user
@@ -4207,7 +4171,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* The seed survives, so the same authenticator entry keeps working if it is re-enabled.
*/
public void deactivateMfaDevice(String userName, String serialNumber) {
validateSerialNumber(serialNumber);
getUser(userName);
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
@@ -4231,10 +4194,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public void resyncMfaDevice(String userName, String serialNumber, String code1, String code2) {
validateIamResourceName(userName, "UserName");
validateSerialNumber(serialNumber);
validateAuthenticationCode(code1, "AuthenticationCode1");
getUser(userName);
validateAuthenticationCode(code2, "AuthenticationCode2");
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
if (!userName.equals(device.getUserName())) {
@@ -4253,7 +4213,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void tagMfaDevice(String serialNumber, Map<String, String> newTags) {
validateSerialNumber(serialNumber);
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
device.setTags(mergeTagsWithinQuota(device.getTags(), newTags, "TagsPerMFADevice", false));
@@ -4262,7 +4221,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void untagMfaDevice(String serialNumber, List<String> tagKeys) {
validateSerialNumber(serialNumber);
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
Map<String, String> remaining = new LinkedHashMap<>(device.getTags());
@@ -4275,7 +4233,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public Map<String, String> listMfaDeviceTags(String serialNumber) {
validateSerialNumber(serialNumber);
return getVirtualMfaDevice(serialNumber).getTags();
}
@@ -4296,42 +4253,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
.toList();
}
private void validateAuthenticationCode(String code, String paramName) {
if (code == null || !AUTHENTICATION_CODE_PATTERN.matcher(code).matches()) {
throw new AwsException("ValidationError",
paramName + " must be exactly 6 digits.", 400);
}
}
/**
* {@code virtualMFADeviceName} carries a minimum and a pattern but, unlike every other IAM
* name type, no maximum length. So this cannot reuse
* {@link #validateIamResourceName(String, String)}: capping the name at 128 would reject a
* name AWS accepts.
*/
private void validateVirtualMfaDeviceName(String name) {
if (name == null || name.isEmpty() || !VIRTUAL_MFA_DEVICE_NAME_PATTERN.matcher(name).matches()) {
throw new AwsException("ValidationError",
"VirtualMFADeviceName must be at least 1 character matching [\\w+=,.@-].", 400);
}
}
/**
* {@code serialNumberType}: 9 to 256 characters of {@code [\w+=/:,.@-]}. Checked before the
* device is looked up, so a malformed serial number is the ValidationError AWS returns rather
* than a NoSuchEntity for a device that could never have existed under that name.
*/
private void validateSerialNumber(String serialNumber) {
if (serialNumber == null
|| serialNumber.length() < SERIAL_NUMBER_MIN_LENGTH
|| serialNumber.length() > SERIAL_NUMBER_MAX_LENGTH
|| !SERIAL_NUMBER_PATTERN.matcher(serialNumber).matches()) {
throw new AwsException("ValidationError",
"SerialNumber must be " + SERIAL_NUMBER_MIN_LENGTH + "-" + SERIAL_NUMBER_MAX_LENGTH
+ " characters matching [\\w+=/:,.@-].", 400);
}
}
/**
* Rejects the request unless the two codes are consecutive outputs of the device's seed,
* allowing the counter to start anywhere within {@code driftSteps} of the current window.