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

@@ -150,18 +150,38 @@ class IamTest {
* contends with the one the Organizations suite builds for the default account.
*/
private static final String REPORT_MANAGEMENT_ACCOUNT = "555555555557";
private static final String SAML_METADATA_DOCUMENT = "<md:EntityDescriptor "
/** The minimum AWS declares for {@code SAMLMetadataDocument}. */
private static final int SAML_METADATA_MINIMUM = 1000;
private static final String SAML_METADATA_BODY = "<md:EntityDescriptor "
+ "xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\"https://idp.example.test/sdk-test\">"
+ "<md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\"><ds:KeyInfo "
+ "xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data><ds:X509Certificate>"
+ "c2RrLXRlc3QtY2VydGlmaWNhdGU=</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor>"
+ "</md:IDPSSODescriptor></md:EntityDescriptor>";
private static final String SAML_METADATA_DOCUMENT_UPDATED = SAML_METADATA_DOCUMENT
.replace("sdk-test", "sdk-test-updated").replace("c2RrLXRlc3QtY2VydGlmaWNhdGU=", "dXBkYXRlZC1jZXJ0");
+ "</md:IDPSSODescriptor>";
private static final String SAML_METADATA_DOCUMENT = samlMetadata(SAML_METADATA_BODY);
/** The same document under another entity id and certificate, padded on its own: the
* replacements are shorter than what they replace, so padding the first document and editing
* it would leave the second under the minimum. */
private static final String SAML_METADATA_DOCUMENT_UPDATED = samlMetadata(SAML_METADATA_BODY
.replace("sdk-test", "sdk-test-updated").replace("c2RrLXRlc3QtY2VydGlmaWNhdGU=", "dXBkYXRlZC1jZXJ0"));
private static String policyArn;
private static String accessKeyId;
private static String samlProviderArn;
/**
* The document closed off and padded to the minimum AWS declares for it. A document carrying
* nothing but an entity id and one signing key is about a third of that, and the service holds
* the member to its published bound, so the filler comment brings it up: it parses as nothing,
* the entity id and the certificate being what the provider is read from.
*/
private static String samlMetadata(String body) {
String end = "</md:EntityDescriptor>";
String open = "<!-- ";
String close = " -->";
int filler = SAML_METADATA_MINIMUM - body.length() - end.length() - open.length() - close.length();
return body + open + "x".repeat(Math.max(1, filler)) + close + end;
}
@BeforeAll
static void setup() {
iam = TestFixtures.iamClient();
+83 -16
View File
@@ -190,10 +190,10 @@ reads "Map value must satisfy constraint".
customer managed policies by name, then the AWS managed catalog, and does not yet apply
`OnlyAttached` or `PolicyUsageFilter`.
The declared constraints on the managed-policy family are read from the model rather than from a
hand-written check, `tools/aws/regen_iam_shapes.py` vendoring them for `GetPolicy`, `DeletePolicy`,
`CreatePolicyVersion`, `GetPolicyVersion`, `DeletePolicyVersion`, `SetDefaultPolicyVersion` and the
six attach and detach operations. A `PolicyArn` is held to `arnType`'s 20 to 2048 characters, a
The declared constraints are read from the model rather than from a hand-written check, for every
operation the model constrains: `tools/aws/regen_iam_shapes.py` vendors 162 of IAM's 180, which is
all 164 that declare a required member, a length, a pattern, an enum or a range, bar the two
account alias operations named below. A `PolicyArn` is held to `arnType`'s 20 to 2048 characters, a
`VersionId` to `policyVersionIdType`'s pattern, a `PolicyDocument` to its 1 to 131072 characters and
its pattern, and each principal name to its own bound, which for a role is the 1 to 64 characters of
`[\w+=,.@-]` this service already answered. The check runs ahead of the operation, so a value that
@@ -217,24 +217,91 @@ index for the same reason, which is a reading: two other services here answer on
whole list instead, and nothing recorded says which form AWS answers on this protocol. A list of
no members is how an absent list arrives, so a required one reads as null rather than as a list
breaking a minimum of 1. A structure member arrives as `TaskPolicyArn.Arn` and is named
`taskPolicyArn.arn`. A map is not read yet, nor is anything nested deeper than a list of
structures. The request form is published, `AcquireRole`'s own sample numbering a map as
`ReplacementValues.entry.1.key` and `.entry.1.value`, but the message this service answers for one
names the whole map rather than the entry that broke a constraint, and nothing here says which AWS
names, so reading a map would move a merged answer on a guess. `GetAccountAuthorizationDetails` is
`taskPolicyArn.arn`.
A map is read the same way, from the entries the protocol numbers under its name:
`ReplacementValues.entry.1.key` and `.entry.1.value`, which is the form `AcquireRole`'s own sample
publishes, or the bare `ReplacementValues.1.key`. An entry's value is named under the key that
entry carries, `replacementValues.Department.values` and `properties.Team/Owner`, 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: it is neither counted nor answered. The count is held to the map's own bounds with the
value left out of the message, and a map the request names nowhere is how an absent map arrives, so
a required one reads as null. A key outside its shape's rules is answered with the whole set that
shape declares, nested under the map's own name, `Value at 'properties' failed to satisfy
constraint: Map keys must satisfy constraint: [...]`, which is the form every map key recorded here
carries and what this service already answered for an account property key.
The two maps answered by hand are answered from the model now, and `AcquireRole`'s answers do not
move at all: its count of 30, each entry's required `Values` and the 20 values one entry admits read
exactly as that check read them, by the key the entry was sent under. `PutAccountProperties` keeps
the set it answered for a key 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.
Nothing is nested too deeply to read now. 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, each read under the name the request
gives it and named the way the walk names it anywhere else: `permissions.parameters.1.member` for a
list inside a structure, `contextEntries.1.member.contextKeyValues.2.member` for one inside a
list's member. That is what takes the last operations into the file: the maps on `AcquireRole` and
`PutAccountProperties`, the structure holding a list on `CreateDelegationRequest` and the context
entries on both simulators. `GetAccountAuthorizationDetails` is
the first operation read through the walk, and nothing of it was read before: a `Filter` member
outside the model's enum, a `MaxItems` outside 1 to 1000 and a `Marker` breaking its length or its
pattern were all answered with a 200. A number too large for a 64-bit integer is a number all the
same, so a `MaxItems` of `9223372036854775808` breaks the maximum rather than reading as no number
at all.
Every other paged operation joined that wave (see [Pagination](#pagination)), most with their whole
request. Six join with `MaxItems` and `Marker` alone and keep the reading they have for the rest:
the three report readers, whose `JobId` is answered as one fixed length ("length equal to 36") and
whose `SortKey` is held to its enum by hand, `ListPoliciesGrantingServiceAccess`, whose empty
`ServiceNamespaces` is answered `InvalidInput`, and `SimulateCustomPolicy` and
`SimulatePrincipalPolicy`, whose `ContextEntries` nest a list inside a list of structures, which the
walk does not read.
Every paged operation is read too (see [Pagination](#pagination)), each with its whole request.
The two alias operations are the only ones left out at all, their single member being answered in
AWS's own wording, and a constraint the model changes on anything the file carries makes it stale,
which the generator's own check answers.
Eight operations are vendored without the model's required members: `CreateLoginProfile`,
`UpdateLoginProfile`, `UploadServerCertificate`, `UploadSigningCertificate`, `UploadSSHPublicKey`,
`CreateOpenIDConnectProvider`, `RemoveClientIDFromOpenIDConnectProvider` and
`UpdateOpenIDConnectProviderThumbprint`. Each answers a member the request leaves out with AWS's
own Query wording, "The request must contain the parameter CertificateBody.", which is the form
this emulator answers for a missing Query parameter in several services, and nothing recorded says
IAM answers the validation layer's null violation there instead. So their lengths and patterns are
read from the model while that refusal stands, and the vendored file carries their shapes with the
required list left off rather than rewording an answer no capture covers.
A blank value is a value wherever a member is read, so a request sending one empty breaks the
minimum length its shape declares rather than reading as absent, and only a member the request
names nowhere is answered as null. That is the model's reading and it holds for every operation the
file carries, which is what the check behind it used to answer the other way. That check still
answers a blank as an absent member for a member the model gives no minimum, and for the two alias
operations the file does not carry, so nothing reaches an operation with a blank where it used to be
refused.
Nine wordings this service wrote for itself are gone with the checks that wrote them, each replaced
by the words the model's own violation carries: `MinimumPasswordLength must be between 6 and 128.`,
the same for `MaxPasswordAge` and `PasswordReusePrevention`, `UserName must be 1-128 characters
matching [\w+=,.@-].` and the group, server certificate and instance profile names beside it, the
path refusal that spelled out its own rule, `AuthenticationCode1 must be exactly 6 digits.`,
`VirtualMFADeviceName must be at least 1 character matching [\w+=,.@-].` and `SerialNumber must be
9-256 characters matching [\w+=/:,.@-].`. 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`, which is
the wording a report's 36-character job id already answered and which now comes from one writer for
every member like it. The two checks that stay, on a name and a path, are reached by a caller inside
the emulator rather than by a request, a seeded configuration or a role template, and they answer
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. A service-linked role's principal and suffix answer
`InvalidInput` rather than a validation error at all, and so does an empty `ServiceNamespaces` on
`ListPoliciesGrantingServiceAccess`. An account alias carries AWS's own sentence about its own
bounds, which is why neither alias operation is read at all. `statusType`, on all four operations
that take it, is answered without the offending value and without the permitted set, which is what
the recorded refusal carries and what the walk would spell out. `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
settles which one AWS answers on this protocol, and these operations keep the one they merged.
Every constraint violation IAM answers names the member and leaves the offending value out,
`Value at 'roleName' failed to satisfy constraint: Member must have length greater than or equal to
@@ -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.
File diff suppressed because it is too large. Load diff
@@ -56,6 +56,26 @@ class QueryConstraintCheckTest {
}
""";
private static final String MAP_MODEL = """
{
"operations": {"Acquire": "AcquireRequest"},
"shapes": {
"AcquireRequest": {"type": "structure", "required": ["Values"], "members": {
"Values": "valueMap", "Nested": "nestedType", "Entries": "entryList"}},
"valueMap": {"type": "map", "key": "keyType", "value": "valueType", "max": 2},
"nestedType": {"type": "structure", "members": {
"Arn": "arnType", "Parameters": "nameList"}},
"entryList": {"type": "list", "member": "entryType"},
"entryType": {"type": "structure", "members": {
"Name": "keyType", "Values": "nameList"}},
"nameList": {"type": "list", "member": "keyType", "max": 2},
"keyType": {"type": "string", "min": 1, "max": 4},
"valueType": {"type": "string", "max": 3, "pattern": "[a-z]*"},
"arnType": {"type": "string", "min": 20, "max": 2048}
}
}
""";
private static final String ARN = "arn:aws:iam::000000000000:role/r";
private static QueryConstraintCheck check() throws Exception {
@@ -66,6 +86,10 @@ class QueryConstraintCheckTest {
return QueryConstraintCheck.of(MAPPER.readTree(LIST_MODEL));
}
private static QueryConstraintCheck maps() throws Exception {
return QueryConstraintCheck.of(MAPPER.readTree(MAP_MODEL));
}
private static MultivaluedMap<String, String> params(String... pairs) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
for (int pair = 0; pair < pairs.length; pair += 2) {
@@ -197,60 +221,59 @@ class QueryConstraintCheckTest {
}
/**
* A map is read from numbered entries whose key is a value of its own, and this package answers
* one today against the whole map rather than against an entry, so an operation carrying one is
* refused when the file loads rather than passed over without its constraints. So is anything
* nested deeper than a list of structures or a structure of scalars.
* Every member of every operation is read whatever it nests, so what the file refuses to load
* is a shape of a type this walk would pass over without reading: letting one through would
* answer a 200 for a request nothing checked. A shape that holds itself is read once rather
* than forever, which is what lets the walk go all the way down.
*/
@Test
void anOperationCarryingAMapOrDeeperNestingIsRefusedWhenTheFileLoads() throws Exception {
JsonNode map = MAPPER.readTree("""
void aShapeOfATypeTheWalkCannotReadIsRefusedWhenTheFileLoads() throws Exception {
JsonNode unread = MAPPER.readTree("""
{
"operations": {"Put": "PutRequest"},
"shapes": {
"PutRequest": {"type": "structure", "members": {"Properties": "propertyMap"}},
"propertyMap": {"type": "map", "key": "nameType", "value": "nameType"},
"nameType": {"type": "string", "min": 1}
"PutRequest": {"type": "structure", "members": {"Body": "blobType"}},
"blobType": {"type": "blob"}
}
}
""");
IllegalStateException refused =
assertThrows(IllegalStateException.class, () -> QueryConstraintCheck.of(map));
assertTrue(refused.getMessage().contains("Put's Properties is a map"), refused.getMessage());
assertThrows(IllegalStateException.class, () -> QueryConstraintCheck.of(unread));
assertTrue(refused.getMessage().contains("Put's Body is a blob"), refused.getMessage());
JsonNode listOfLists = MAPPER.readTree("""
JsonNode nestedUnread = MAPPER.readTree("""
{
"operations": {"Put": "PutRequest"},
"shapes": {
"PutRequest": {"type": "structure", "members": {"Rows": "rowList"}},
"rowList": {"type": "list", "member": "nameList"},
"nameList": {"type": "list", "member": "nameType"},
"nameType": {"type": "string", "min": 1}
}
}
""");
IllegalStateException nested =
assertThrows(IllegalStateException.class, () -> QueryConstraintCheck.of(listOfLists));
assertTrue(nested.getMessage().contains("Put's Rows is a list of list"), nested.getMessage());
JsonNode structureInStructure = MAPPER.readTree("""
{
"operations": {"Put": "PutRequest"},
"shapes": {
"PutRequest": {"type": "structure", "members": {"Target": "targetType"}},
"targetType": {"type": "structure", "members": {"Inner": "innerType"}},
"innerType": {"type": "structure", "members": {"Name": "nameType"}},
"nameType": {"type": "string", "min": 1}
"rowList": {"type": "list", "member": "rowType"},
"rowType": {"type": "structure", "members": {"At": "stampType"}},
"stampType": {"type": "timestamp"}
}
}
""");
IllegalStateException deeper = assertThrows(IllegalStateException.class,
() -> QueryConstraintCheck.of(structureInStructure));
assertTrue(deeper.getMessage().contains("Put's Target.Inner is a structure"),
deeper.getMessage());
() -> QueryConstraintCheck.of(nestedUnread));
assertTrue(deeper.getMessage().contains("Put's Rows.At is a timestamp"), deeper.getMessage());
JsonNode holdsItself = MAPPER.readTree("""
{
"operations": {"Put": "PutRequest"},
"shapes": {
"PutRequest": {"type": "structure", "members": {"Node": "nodeType"}},
"nodeType": {"type": "structure", "members": {
"Name": "nameType", "Children": "nodeList"}},
"nodeList": {"type": "list", "member": "nodeType"},
"nameType": {"type": "string", "min": 1}
}
}
""");
assertEquals(List.of("Value '' at 'node.name' failed to satisfy constraint: Member must"
+ " have length greater than or equal to 1"),
QueryConstraintCheck.of(holdsItself).violations("Put", params("Node.Name", "")));
}
/**
@@ -276,6 +299,17 @@ class QueryConstraintCheckTest {
"the bare numbered form is a member too");
}
/**
* A scalar member's value lives at its own name, so an index the request numbered only under a
* deeper key is no member of the list: nothing reads a value there, and reading one would
* answer an empty string the request never sent.
*/
@Test
void anIndexNumberedOnlyUnderADeeperKeyIsNoMemberOfAListOfScalars() throws Exception {
assertEquals(List.of(), lists().violations("Vend", params(
"Audience.member.1", "ok", "Target.Arn", ARN, "Names.member.1.Nested", "x")));
}
/**
* The count is held to the list's own bounds, with the value left out of the message: quoting it
* would echo every member of the list back. A list of no members is how an absent list arrives
@@ -445,4 +479,90 @@ class QueryConstraintCheckTest {
"SigningAlgorithm", "RS256", "Tags.member.1.Key", "Team")),
"a tag is a list of structures, named under the index the request spelled");
}
/**
* A map's entries arrive numbered under its own name, and an entry's value is named under the
* key that entry carries rather than under the number it was sent with. The key and the value
* each carry their own shape, so an entry can break both, and the map's own bounds hold the
* count with the value left out of the message.
*/
@Test
void aMapsValueIsNamedUnderTheKeyTheEntryCarries() throws Exception {
assertEquals(List.of(), maps().violations("Acquire",
params("Values.entry.1.key", "k", "Values.entry.1.value", "ok")));
assertEquals(List.of(
"Value 'toolong' at 'values' failed to satisfy constraint: Map keys must satisfy"
+ " constraint: [Member must have length less than or equal to 4, Member"
+ " must have length greater than or equal to 1]",
"Value 'NOPE' at 'values.toolong' failed to satisfy constraint: Member must"
+ " have length less than or equal to 3",
"Value 'NOPE' at 'values.toolong' failed to satisfy constraint: Member must"
+ " satisfy regular expression pattern: [a-z]*"),
maps().violations("Acquire",
params("Values.entry.1.key", "toolong", "Values.entry.1.value", "NOPE")));
assertEquals(List.of("Value at 'values' failed to satisfy constraint: Member must have"
+ " length less than or equal to 2"),
maps().violations("Acquire", params(
"Values.entry.1.key", "a", "Values.entry.1.value", "x",
"Values.entry.2.key", "b", "Values.entry.2.value", "y",
"Values.entry.3.key", "c", "Values.entry.3.value", "z")));
}
/** A map the request names nowhere is the required member reading as null. */
@Test
void aMapNamedNowhereIsTheRequiredMemberReadingAsNull() throws Exception {
assertEquals(List.of("Value null at 'values' failed to satisfy constraint: Member must not"
+ " be null"), maps().violations("Acquire", params()));
}
/**
* An entry is read off its key, so one numbered with a value and no key of its own is not an
* entry the map could hold: it is neither counted nor answered, and a map of nothing else is
* the required member reading as null.
*/
@Test
void anEntryNumberedWithNoKeyIsNoEntryAtAll() throws Exception {
assertEquals(List.of("Value null at 'values' failed to satisfy constraint: Member must not"
+ " be null"), maps().violations("Acquire", params("Values.entry.1.value", "ok")));
assertEquals(List.of(), maps().violations("Acquire", params(
"Values.entry.1.key", "k", "Values.entry.1.value", "ok",
"Values.entry.2.value", "x", "Values.entry.3.value", "y")),
"an entry with no key is not one of the two the map admits either");
}
/** The bare form the protocol also accepts, {@code Values.1.key}, reads the same way. */
@Test
void aMapEntryIsReadWithoutTheEntrySegmentToo() throws Exception {
assertEquals(List.of("Value 'toolong' at 'values' failed to satisfy constraint: Map keys"
+ " must satisfy constraint: [Member must have length less than or equal to 4,"
+ " Member must have length greater than or equal to 1]"),
maps().violations("Acquire", params("Values.1.key", "toolong", "Values.1.value", "x")));
}
/**
* A structure's field may be a list, and a list's member a structure holding one, each read
* under the name the request gives it and named the way the walk names a list anywhere.
*/
@Test
void aListInsideAStructureAndInsideAListsMemberAreBothRead() throws Exception {
assertEquals(List.of(
"Value 'toolong' at 'nested.parameters.1.member' failed to satisfy constraint:"
+ " Member must have length less than or equal to 4"),
maps().violations("Acquire", params(
"Values.entry.1.key", "k", "Values.entry.1.value", "ok",
"Nested.Parameters.member.1", "toolong")));
assertEquals(List.of(
"Value at 'entries.1.member.values' failed to satisfy constraint: Member must have"
+ " length less than or equal to 2"),
maps().violations("Acquire", params(
"Values.entry.1.key", "k", "Values.entry.1.value", "ok",
"Entries.member.1.Name", "n",
"Entries.member.1.Values.member.1", "a",
"Entries.member.1.Values.member.2", "b",
"Entries.member.1.Values.member.3", "c")));
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.SamlMetadata;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.bouncycastle.asn1.x500.X500Name;
@@ -207,9 +208,7 @@ class AssumeRoleWithSamlValidationIntegrationTest {
@Test
void duplicateProviderCreationIsRejected() {
String metadata = "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\""
+ ISSUER + "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\"><ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data><ds:X509Certificate>"
+ certificateBase64 + "</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
String metadata = SamlMetadata.forEntity(ISSUER, certificateBase64);
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateSAMLProvider").formParam("Name", PROVIDER_NAME)
.formParam("SAMLMetadataDocument", metadata)
@@ -303,9 +302,7 @@ class AssumeRoleWithSamlValidationIntegrationTest {
}
private static void registerProvider() {
String metadata = "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\"" + ISSUER
+ "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\"><ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data><ds:X509Certificate>"
+ certificateBase64 + "</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
String metadata = SamlMetadata.forEntity(ISSUER, certificateBase64);
given().contentType("application/x-www-form-urlencoded").formParam("Action", "CreateSAMLProvider")
.formParam("Name", PROVIDER_NAME).formParam("SAMLMetadataDocument", metadata)
.header("Authorization", auth("iam")).when().post("/").then().statusCode(200);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.AwsQueryController;
import io.github.hectorvent.floci.testing.SamlMetadata;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -723,7 +724,7 @@ class IamIntegrationTest {
void getAccessKeyLastUsedReturnsNeverUsedShape() {
given()
.formParam("Action", "GetAccessKeyLastUsed")
.formParam("AccessKeyId", "AKIAEXAMPLE")
.formParam("AccessKeyId", "AKIAIOSFODNN7EXAMPLE")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
@@ -792,8 +793,7 @@ class IamIntegrationTest {
@Order(54)
void getSamlProviderDoesNotCrossAccountBoundaries() {
String providerName = "cross-account-saml-" + System.nanoTime();
String metadata = "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\"https://idp.example.test/"
+ providerName + "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\"><ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data><ds:X509Certificate>Y2VydA==</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
String metadata = SamlMetadata.forEntity("https://idp.example.test/" + providerName);
String ownerAuth = "AWS4-HMAC-SHA256 Credential=111111111111/20260227/us-east-1/iam/aws4_request";
String otherAccountAuth = "AWS4-HMAC-SHA256 Credential=222222222222/20260227/us-east-1/iam/aws4_request";
given().formParam("Action", "CreateSAMLProvider").formParam("Name", providerName)
@@ -1728,8 +1728,10 @@ class IamIntegrationTest {
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at"
+ " 'roleName' failed to satisfy constraint: Member must have length greater than or equal to 1"));
.body("ErrorResponse.Error.Message", equalTo("2 validation errors detected: Value at"
+ " 'roleName' failed to satisfy constraint: Member must have length greater"
+ " than or equal to 1; Value at 'roleName' failed to satisfy constraint:"
+ " Member must satisfy regular expression pattern: [\\w+=,.@-]+"));
given()
.formParam("Action", "CreateRole")
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.testing.SamlMetadata;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
@@ -977,11 +978,7 @@ class IamListPaginationIntegrationTest {
}
private static String samlMetadata(String entityId) {
return "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\""
+ entityId + "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\">"
+ "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data>"
+ "<ds:X509Certificate>cGFnaW5n</ds:X509Certificate></ds:X509Data></ds:KeyInfo>"
+ "</md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
return SamlMetadata.forEntity(entityId, "cGFnaW5n");
}
/** One fixture per paginated operation, each listing at least two items where it can. */
@@ -10,8 +10,8 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
/**
* The declared constraints the managed-policy family and {@code GetAccountAuthorizationDetails} are
* now read against, from the model rather than from a hand-written check. What they change is the
* The declared constraints every operation is read against, from the model rather than from a
* hand-written check. What they change is the
* status: a value that breaks a declared constraint used to reach the store and answer
* {@code NoSuchEntity}, or on the second of those to be answered with a 200, where AWS's validation
* layer runs ahead of the operation and answers {@code ValidationError}, which is the ordering
@@ -175,13 +175,16 @@ class IamRequestConstraintsIntegrationTest {
+ " Value at 'roleName' failed to satisfy constraint: Member must satisfy"
+ " regular expression pattern: [\\w+=,.@-]+"));
// The same empty name on an operation this wave leaves alone, reported the older way.
// And the same empty name on `CreateRole`, which is read from the model as well now, so
// both constraints are reported there too where the hand-written check stopped at one.
iam("CreateRole")
.formParam("RoleName", "")
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.when().post("/").then().statusCode(400)
.body(MESSAGE, equalTo("1 validation error detected: Value at 'roleName' failed to"
+ " satisfy constraint: Member must have length greater than or equal to 1"));
.body(MESSAGE, equalTo("2 validation errors detected: Value at 'roleName' failed to"
+ " satisfy constraint: Member must have length greater than or equal to 1;"
+ " Value at 'roleName' failed to satisfy constraint: Member must satisfy"
+ " regular expression pattern: [\\w+=,.@-]+"));
}
/**
@@ -305,4 +308,78 @@ class IamRequestConstraintsIntegrationTest {
+ " equal to 1"))
.body(MESSAGE, containsString("Member must satisfy regular expression pattern:"));
}
/**
* A map's key is held to every rule its shape declares, answered as a set under the map's own
* name, and its value is held to its shape under the key the entry carried. The key's own
* length and pattern were read before this, by a hand-written check the model now answers for;
* an empty value reached the store.
*/
@Test
void aMapsKeyAndValueAreEachHeldToTheirShape() {
iam("PutAccountProperties")
.formParam("Properties.entry.1.key", "1-not-a-key")
.formParam("Properties.entry.1.value", "v")
.when().post("/").then().statusCode(400)
.body(CODE, equalTo("ValidationError"))
.body(MESSAGE, equalTo("1 validation error detected: Value at 'properties' failed to"
+ " satisfy constraint: Map keys must satisfy constraint: [Member must have"
+ " length less than or equal to 50, Member must have length greater than or"
+ " equal to 1, Member must satisfy regular expression pattern:"
+ " ^[A-Za-z][A-Za-z0-9/_-]*$]"));
iam("PutAccountProperties")
.formParam("Properties.entry.1.key", "Ok/Value")
.formParam("Properties.entry.1.value", "")
.when().post("/").then().statusCode(400)
.body(MESSAGE, equalTo("1 validation error detected: Value at 'properties.Ok/Value'"
+ " failed to satisfy constraint: Member must have length greater than or"
+ " equal to 1"));
// 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"
+ " to satisfy constraint: Member must not be null"));
}
/**
* A map whose value is a structure holding a list is read all the way down, which is the
* deepest request this service models: {@code AcquireRole} numbers its replacement values as
* entries and each entry's structure carries a list of its own. An entry the request numbered
* with a key is an entry, so what the structure under it requires is answered inside it, named
* under that key, which is the answer the hand-written check this replaces already gave.
*/
@Test
void aMapValuesStructureAndTheListInsideItAreRead() {
iam("AcquireRole")
.formParam("TemplateArn", "arn:aws:iam::000000000000:policy-template/t")
.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"
+ " 'replacementValues.Department.values' failed to satisfy constraint: Member"
+ " must not be null"));
}
/**
* A structure's field may be a list, and its members structures of their own. The name of a
* policy parameter is 5 characters at least, which nothing read before.
*/
@Test
void aListInsideAStructureIsReadUnderTheNamesTheRequestGives() {
iam("CreateDelegationRequest")
.formParam("Description", "a delegation")
.formParam("RequestorWorkflowId", "wf-0001")
.formParam("NotificationChannel", "channel")
.formParam("SessionDuration", "3600")
.formParam("Permissions.PolicyTemplateArn", "arn:aws:iam::000000000000:policy/t")
.formParam("Permissions.Parameters.member.1.Name", "abc")
.formParam("Permissions.Parameters.member.1.Type", "string")
.when().post("/").then().statusCode(400)
.body(CODE, equalTo("ValidationError"))
.body(MESSAGE, equalTo("1 validation error detected: Value at"
+ " 'permissions.parameters.1.member.name' failed to satisfy constraint:"
+ " Member must have length greater than or equal to 5"));
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.SamlMetadata;
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
@@ -304,13 +305,8 @@ class IamResourceScopedPolicyEnforcementIntegrationTest {
.statusCode(200);
}
/** The shape {@code SAMLProviderLifecycleIntegrationTest} already establishes as acceptable. */
private static String samlMetadata(String entityId) {
return "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\""
+ entityId + "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\">"
+ "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data>"
+ "<ds:X509Certificate>c2NvcGVk</ds:X509Certificate></ds:X509Data></ds:KeyInfo>"
+ "</md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
return SamlMetadata.forEntity(entityId, "c2NvcGVk");
}
private String createUser(String name, String... extraParams) {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.SamlMetadata;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
@@ -25,11 +26,8 @@ class IamTagValidationIntegrationTest {
private static final String POLICY_DOCUMENT = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
private static final String THUMBPRINT = "9e99a48a9960b14926bb7f3b02e22da2b0ab7280";
private static final String SAML_METADATA = "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\""
+ " entityID=\"https://idp.example.test/untag-key\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\">"
+ "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data>"
+ "<ds:X509Certificate>dW50YWc=</ds:X509Certificate></ds:X509Data></ds:KeyInfo>"
+ "</md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
private static final String SAML_METADATA =
SamlMetadata.forEntity("https://idp.example.test/untag-key", "dW50YWc=");
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
@@ -300,9 +300,11 @@ class OrganizationsAccessReportIntegrationTest {
.formParam("EntityPath", "o-a1b2c3d4e5")
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at"
+ " 'entityPath' failed to satisfy constraint: Member must have length"
+ " greater than or equal to 19"));
.body("ErrorResponse.Error.Message", equalTo("2 validation errors detected: Value"
+ " at 'entityPath' failed to satisfy constraint: Member must have length"
+ " greater than or equal to 19; Value at 'entityPath' failed to satisfy"
+ " constraint: Member must satisfy regular expression pattern:"
+ " ^o-[0-9a-z]{10,32}\\/r-[0-9a-z]{4,32}[0-9a-z-\\/]*"));
iam(MANAGEMENT_ACCOUNT, "GenerateOrganizationsAccessReport")
.formParam("EntityPath", "o-a1b2c3d4e5/x-0000/not a path")
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.SamlMetadata;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
@@ -21,11 +22,7 @@ class SAMLProviderLifecycleIntegrationTest {
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static String metadataFor(String entityId, String certBase64) {
return "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\""
+ entityId + "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\">"
+ "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data>"
+ "<ds:X509Certificate>" + certBase64 + "</ds:X509Certificate></ds:X509Data></ds:KeyInfo>"
+ "</md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
return SamlMetadata.forEntity(entityId, certBase64);
}
private static RequestSpecification iam(String action) {
@@ -78,19 +75,25 @@ class SAMLProviderLifecycleIntegrationTest {
* An omitted SAMLMetadataDocument is a no-op (above), but an explicitly empty one is
* invalid input, the same as CreateSAMLProvider already rejects it as: the two are
* distinguishable at the wire level (parameter absent vs. present with an empty value),
* and only the former should be treated as "nothing to update."
* and only the former should be treated as "nothing to update." An empty one is refused ahead
* of that by the document's own minimum length.
*/
@Test
void updateSamlProviderWithAnExplicitlyEmptyMetadataDocumentReturnsInvalidInput() {
String name = "update-empty-metadata-saml-" + System.nanoTime();
String arn = createProvider(name, "https://idp.example.test/not-emptied", "bm90ZW1wdGllZA==");
// The document declares a minimum of 1000 characters, so an empty one never reaches the
// parse that would call it invalid input: it is the constraint that refuses it.
iam("UpdateSAMLProvider")
.formParam("SAMLProviderArn", arn)
.formParam("SAMLMetadataDocument", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at"
+ " 'sAMLMetadataDocument' failed to satisfy constraint: Member must have"
+ " length greater than or equal to 1000"));
iam("GetSAMLProvider").formParam("SAMLProviderArn", arn)
.when().post("/").then()
@@ -103,9 +106,11 @@ class SAMLProviderLifecycleIntegrationTest {
String name = "update-bad-metadata-saml-" + System.nanoTime();
String arn = createProvider(name, "https://idp.example.test/ok", "b2s=");
// Long enough to clear the document's own minimum, so what refuses it is the parse.
iam("UpdateSAMLProvider")
.formParam("SAMLProviderArn", arn)
.formParam("SAMLMetadataDocument", "<not-a-valid-saml-document/>")
.formParam("SAMLMetadataDocument",
"<not-a-valid-saml-document/>" + "<!-- " + "x".repeat(1000) + " -->")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
@@ -221,10 +221,10 @@ class ServiceSpecificCredentialIntegrationTest {
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("credentialAgeDays"))
// The range report builds its message across two string literals, so a sweep
// for the phrase missed it while every other one was prefixed.
// The range comes from the model now, in the words every other range violation
// carries, where this operation wrote one of its own.
.body(containsString("1 validation error detected"))
.body(containsString("Member must be between"));
.body(containsString("Member must have value"));
}
// And both ends of the range are accepted, so the bounds are not off by one.
@@ -73,7 +73,7 @@ class StsRequestConstraintsIntegrationTest {
.body(MESSAGE, equalTo("2 validation errors detected: Value 'bad#serial' at"
+ " 'serialNumber' failed to satisfy constraint: Member must satisfy regular"
+ " expression pattern: [\\w+=/:,.@-]*; Value '12345' at 'tokenCode' failed to"
+ " satisfy constraint: Member must have length greater than or equal to 6"));
+ " satisfy constraint: Member must have length equal to 6"));
sts("GetSessionToken")
.formParam("TokenCode", "abcdef")
@@ -187,7 +187,7 @@ class StsRequestConstraintsIntegrationTest {
.when().post("/").then().statusCode(400)
.body(MESSAGE, equalTo("1 validation error detected: Value 'HS25' at"
+ " 'signingAlgorithm' failed to satisfy constraint: Member must have length"
+ " greater than or equal to 5"))
+ " equal to 5"))
.body(MESSAGE, not(containsString("enum value set")));
}
@@ -268,7 +268,8 @@ class WebIdentityTokenIntegrationTest {
/**
* {@code jwtAlgorithmType} publishes a fixed length of 5 and no enum, so the length is the
* declared constraint and the two values the Reference names are read from it.
* declared constraint, answered for the length it fixes rather than for a bound a value sits
* under, and the two values the Reference names are read from it.
*/
@Test
void aSigningAlgorithmIsHeldToItsLengthAndThenToTheTwoValues() {
@@ -276,7 +277,7 @@ class WebIdentityTokenIntegrationTest {
token("RS25").when().post("/").then().statusCode(400)
.body(MESSAGE, containsString("Value 'RS25' at 'signingAlgorithm' failed to satisfy"
+ " constraint: Member must have length greater than or equal to 5"));
+ " constraint: Member must have length equal to 5"));
token("HS256").when().post("/").then().statusCode(400)
.body(MESSAGE, containsString("Value 'HS256' at 'signingAlgorithm' failed to satisfy"
@@ -64,7 +64,9 @@ public final class DynamoDbAuthorizationFixtures {
}
public String user(String policy) {
return userNamed(prefix + UUID.randomUUID(), policy);
// Eight characters of a UUID rather than a whole one: a user name is held to the 64
// characters its shape declares, which a prefix plus a whole UUID can break.
return userNamed(prefix + UUID.randomUUID().toString().substring(0, 8), policy);
}
/** A user whose name the caller chooses, for a policy that has to name it. */
@@ -16,7 +16,9 @@ public final class LogsAuthorizationFixtures {
public static String user(PartitionCleanup cleanup, int port, String account, String prefix,
String policyName, String statements) {
String name = prefix + UUID.randomUUID();
// Eight characters of a UUID rather than a whole one: a user name is held to the 64
// characters its shape declares, which a prefix plus a whole UUID can break.
String name = prefix + UUID.randomUUID().toString().substring(0, 8);
String root = EnforcementFixtures.auth(account, "iam");
String key = EnforcementFixtures.createUser(cleanup, port, root, name).accessKeyId();
given().port(port).header("Authorization", root).formParam("Action", "PutUserPolicy")
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.testing;
/**
* The SAML metadata document a test registers a provider with. AWS declares
* {@code SAMLMetadataDocument} at a minimum of 1000 characters, which a document carrying nothing
* but an entity id and one signing key does not reach, so the filler comment brings it to that
* length. The document is built here rather than copied into each test: six of them registered a
* provider with a document of their own, and the constraints read off the model hold every one of
* them to the same bound.
*/
public final class SamlMetadata {
/** The minimum the model declares for the document. */
public static final int MINIMUM_LENGTH = 1000;
private static final String DEFAULT_CERTIFICATE = "Y2VydA==";
private SamlMetadata() {
}
/** The document for {@code entityId}, carrying a stand-in signing certificate. */
public static String forEntity(String entityId) {
return forEntity(entityId, DEFAULT_CERTIFICATE);
}
/** The same, carrying {@code certificateBase64} as the signing certificate. */
public static String forEntity(String entityId, String certificateBase64) {
String document = "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\""
+ " entityID=\"" + entityId + "\"><md:IDPSSODescriptor>"
+ "<md:KeyDescriptor use=\"signing\">"
+ "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data>"
+ "<ds:X509Certificate>" + certificateBase64 + "</ds:X509Certificate>"
+ "</ds:X509Data></ds:KeyInfo></md:KeyDescriptor></md:IDPSSODescriptor>";
String end = "</md:EntityDescriptor>";
return document + padding(document.length() + end.length()) + end;
}
/**
* A comment long enough to bring the document to the model's minimum, which parses as nothing
* at all: the document's entity id and signing certificate are what the service reads.
*/
private static String padding(int length) {
int wanted = MINIMUM_LENGTH - length;
if (wanted <= 0) {
return "";
}
String open = "<!-- ";
String close = " -->";
int filler = Math.max(1, wanted - open.length() - close.length());
return open + "x".repeat(filler) + close;
}
}
@@ -46,10 +46,15 @@ public final class SignedIamUsers {
* Creates a user named {@code namePrefix} plus a random suffix, with one access key and the
* inline policy {@code policyName} holding {@code policyDocument}. If a later step fails, the
* parts already made are removed before the failure is rethrown.
*
* <p>The suffix is eight characters of a UUID rather than a whole one, which keeps the name
* inside the 64 characters {@code userNameType} declares: the constraints read ahead of the
* operation hold it to the bound AWS holds it to, where a prefix plus a whole UUID reaches 66
* and is refused before the user is made.
*/
public static User createUser(URI endpoint, String namePrefix, String policyName, String policyDocument)
throws Exception {
String name = namePrefix + UUID.randomUUID();
String name = namePrefix + UUID.randomUUID().toString().substring(0, 8);
iam(endpoint, "CreateUser", Map.of("UserName", name)).then().statusCode(200);
User user = new User(endpoint, name, policyName, null, null);
try {
+127 -52
View File
@@ -3,8 +3,8 @@
`IamRequestShapes` checks the operations listed here against the vendored file through the shared
`QueryConstraintCheck`: required members, lengths, patterns and enum values, as the model states
them. The list grows an operation at a time, each one taken off the hand-written checks in the
same change, so a wave is always reviewable against the messages it replaces.
them. The list is every operation the model constrains, bar the two the comment beside it names,
nothing being left out for the shape of its request any more.
Run from anywhere in the repo:
python3 tools/aws/regen_iam_shapes.py # rewrite the vendored file in place
@@ -21,71 +21,146 @@ from request_shapes import REPO_ROOT
OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-request-shapes.json"
MODEL = Path("iam/2010-05-08")
# One wave per group, each chosen so that no operation in it checks a declared constraint by hand,
# which is what keeps the vendored shapes adding the refusals AWS answers rather than rewording an
# answer already given.
# Every operation IAM models with a constraint of its own: a required member, a length, a pattern,
# an enum or a range. Nothing is left out for the shape of its request any more, the walk reading a
# map and anything one nests, so the maps on `AcquireRole` and `PutAccountProperties`, the
# structure holding a list on `CreateDelegationRequest` and the simulators' context entries are
# read here with the rest.
#
# The managed-policy family, every member a scalar. `AttachRolePolicy` and `DetachRolePolicy` are
# the exception and the parity case: `IamService.validateRoleName` already answers `roleName` in
# Smithy's form.
#
# `GetAccountAuthorizationDetails` is the first operation read through the list walk. Its three
# members are declared and none of them is read at all today: `Filter` is a list of an enum,
# `MaxItems` a range and `Marker` a length and a pattern.
#
# The list operations follow it: every operation `aws/iam-paginators.json` pages, so `MaxItems`
# (1 to 1000) and `Marker` (1 to 320 characters) are held to the model here and nowhere else.
# `CreateAccountAlias` and `DeleteAccountAlias` carry one member each, and AWS answers it in its
# own wording, "The specified value for accountAlias is invalid. It must be a minimum length of 3
# characters ...", so there is nothing left for the walk to read on them.
OPERATIONS = (
"AttachGroupPolicy", "AttachRolePolicy", "AttachUserPolicy",
"DetachGroupPolicy", "DetachRolePolicy", "DetachUserPolicy",
"GetPolicy", "DeletePolicy",
"CreatePolicyVersion", "GetPolicyVersion", "DeletePolicyVersion", "SetDefaultPolicyVersion",
"GetAccountAuthorizationDetails",
"GetGroup",
"ListAccessKeys", "ListAccountAliases", "ListAttachedGroupPolicies", "ListAttachedRolePolicies",
"ListAttachedUserPolicies", "ListDelegationRequests", "ListEntitiesForPolicy",
"ListGroupPolicies", "ListGroups", "ListGroupsForUser", "ListInstanceProfileTags",
"ListInstanceProfiles", "ListInstanceProfilesForRole", "ListMFADeviceTags", "ListMFADevices",
"ListOpenIDConnectProviderTags", "ListPolicies",
"ListPolicyTags", "ListPolicyVersions", "ListRolePolicies", "ListRoleTags", "ListRoles",
"ListSAMLProviderTags", "ListSSHPublicKeys", "ListServerCertificateTags",
"ListServerCertificates", "ListServiceSpecificCredentials", "ListSigningCertificates",
"ListUserPolicies", "ListUserTags", "ListUsers", "ListVirtualMFADevices",
"AcceptDelegationRequest", "AcquireRole", "AddClientIDToOpenIDConnectProvider",
"AddRoleToInstanceProfile", "AddUserToGroup", "AssociateDelegationRequest",
"AttachGroupPolicy", "AttachRolePolicy", "AttachUserPolicy", "ChangePassword",
"CreateAccessKey", "CreateDelegationRequest", "CreateGroup", "CreateInstanceProfile",
"CreateLoginProfile", "CreateOpenIDConnectProvider", "CreatePolicy", "CreatePolicyVersion",
"CreateRole", "CreateSAMLProvider", "CreateServiceLinkedRole",
"CreateServiceSpecificCredential", "CreateUser", "CreateVirtualMFADevice",
"DeactivateMFADevice", "DeleteAccessKey", "DeleteGroup", "DeleteGroupPolicy",
"DeleteInstanceProfile", "DeleteLoginProfile", "DeleteOpenIDConnectProvider", "DeletePolicy",
"DeletePolicyVersion", "DeleteRole", "DeleteRolePermissionsBoundary", "DeleteRolePolicy",
"DeleteSAMLProvider", "DeleteSSHPublicKey", "DeleteServerCertificate",
"DeleteServiceLinkedRole", "DeleteServiceSpecificCredential", "DeleteSigningCertificate",
"DeleteUser", "DeleteUserPermissionsBoundary", "DeleteUserPolicy", "DeleteVirtualMFADevice",
"DetachGroupPolicy", "DetachRolePolicy", "DetachUserPolicy", "EnableMFADevice",
"GenerateOrganizationsAccessReport", "GenerateServiceLastAccessedDetails",
"GetAccessKeyLastUsed", "GetAccountAuthorizationDetails", "GetContextKeysForCustomPolicy",
"GetContextKeysForPrincipalPolicy", "GetDelegationRequest", "GetGroup", "GetGroupPolicy",
"GetHumanReadableSummary", "GetInstanceProfile", "GetLoginProfile", "GetMFADevice",
"GetOpenIDConnectProvider", "GetOrganizationsAccessReport", "GetPolicy", "GetPolicyVersion",
"GetRole", "GetRolePolicy", "GetRoleTemplateVersion", "GetSAMLProvider", "GetSSHPublicKey",
"GetServerCertificate", "GetServiceLastAccessedDetails",
"GetServiceLastAccessedDetailsWithEntities", "GetServiceLinkedRoleDeletionStatus", "GetUser",
"GetUserPolicy", "ListAccessKeys", "ListAccountAliases", "ListAttachedGroupPolicies",
"ListAttachedRolePolicies", "ListAttachedUserPolicies", "ListDelegationRequests",
"ListEntitiesForPolicy", "ListGroupPolicies", "ListGroups", "ListGroupsForUser",
"ListInstanceProfileTags", "ListInstanceProfiles", "ListInstanceProfilesForRole",
"ListMFADeviceTags", "ListMFADevices", "ListOpenIDConnectProviderTags", "ListPolicies",
"ListPoliciesGrantingServiceAccess", "ListPolicyTags", "ListPolicyVersions",
"ListRolePolicies", "ListRoleTags", "ListRoles", "ListSAMLProviderTags", "ListSSHPublicKeys",
"ListServerCertificateTags", "ListServerCertificates", "ListServiceSpecificCredentials",
"ListSigningCertificates", "ListUserPolicies", "ListUserTags", "ListUsers",
"ListVirtualMFADevices", "PutAccountProperties", "PutGroupPolicy",
"PutRolePermissionsBoundary", "PutRolePolicy", "PutUserPermissionsBoundary", "PutUserPolicy",
"RejectDelegationRequest", "RemoveClientIDFromOpenIDConnectProvider",
"RemoveRoleFromInstanceProfile", "RemoveUserFromGroup", "ResetServiceSpecificCredential",
"ResyncMFADevice", "SendDelegationToken", "SetDefaultPolicyVersion",
"SetSecurityTokenServicePreferences", "SimulateCustomPolicy", "SimulatePrincipalPolicy",
"TagInstanceProfile", "TagMFADevice", "TagOpenIDConnectProvider", "TagPolicy", "TagRole",
"TagSAMLProvider", "TagServerCertificate", "TagUser", "UntagInstanceProfile",
"UntagMFADevice", "UntagOpenIDConnectProvider", "UntagPolicy", "UntagRole",
"UntagSAMLProvider", "UntagServerCertificate", "UntagUser", "UpdateAccessKey",
"UpdateAccountPasswordPolicy", "UpdateAssumeRolePolicy", "UpdateDelegationRequest",
"UpdateGroup", "UpdateLoginProfile", "UpdateOpenIDConnectProviderThumbprint", "UpdateRole",
"UpdateRoleDescription", "UpdateSAMLProvider", "UpdateSSHPublicKey",
"UpdateServerCertificate", "UpdateServiceSpecificCredential", "UpdateSigningCertificate",
"UpdateUser", "UploadSSHPublicKey", "UploadServerCertificate", "UploadSigningCertificate",
)
# Paged operations vendored with their paging members alone, so `MaxItems` and `Marker` are still
# the model's while the rest of the request keeps the reading it has today.
PAGING_MEMBERS = ("Marker", "MaxItems")
PAGING_ONLY = (
# `JobId` is answered by hand as one fixed-length constraint ("length equal to 36"), which the
# walk would reword as a minimum; `SortKey` is held to its enum by hand too.
"GetOrganizationsAccessReport", "GetServiceLastAccessedDetails",
"GetServiceLastAccessedDetailsWithEntities",
# An empty `ServiceNamespaces` is answered by hand with `InvalidInput`, not the walk's null.
"ListPoliciesGrantingServiceAccess",
# `ContextEntries` nests a list inside a list of structures, which the walk refuses.
"SimulateCustomPolicy", "SimulatePrincipalPolicy",
# Operations that answer a member the request leaves out with AWS's own Query wording, "The request
# must contain the parameter CertificateBody.", rather than with the validation layer's null
# violation. Their shapes are vendored without the model's `required` list, so the lengths and the
# patterns are read here while the operation keeps the refusal it answers today.
REQUIRED_BY_HAND = (
"CreateLoginProfile", "UpdateLoginProfile",
"UploadServerCertificate", "UploadSigningCertificate", "UploadSSHPublicKey",
"CreateOpenIDConnectProvider", "RemoveClientIDFromOpenIDConnectProvider",
"UpdateOpenIDConnectProviderThumbprint",
)
def paging_only(model: dict, operations: tuple[str, ...] = PAGING_ONLY) -> dict:
"""`model` with each of `operations` reduced to its paging members, `PAGING_ONLY` by default."""
# Members an operation answers in a wording the walk would move, each with the reason it keeps.
#
# A service-linked role's principal and suffix answer `InvalidInput` rather than a validation error
# at all. `ServiceNamespaces` on `ListPoliciesGrantingServiceAccess` answers `InvalidInput` too
# when the list arrives empty. `statusType` is answered without the offending 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.
MEMBERS_BY_HAND = {
"CreateServiceLinkedRole": ("AWSServiceName", "CustomSuffix"),
"ListPoliciesGrantingServiceAccess": ("ServiceNamespaces",),
"UpdateAccessKey": ("Status",),
"UpdateSSHPublicKey": ("Status",),
"UpdateServiceSpecificCredential": ("Status",),
"UpdateSigningCertificate": ("Status",),
"GetSSHPublicKey": ("Encoding",),
"SimulateCustomPolicy": ("ActionNames", "PolicyInputList"),
"SimulatePrincipalPolicy": ("ActionNames", "PolicyInputList", "PolicySourceArn"),
"UntagInstanceProfile": ("TagKeys",),
"UntagMFADevice": ("TagKeys",),
"UntagOpenIDConnectProvider": ("TagKeys",),
"UntagPolicy": ("TagKeys",),
"UntagRole": ("TagKeys",),
"UntagSAMLProvider": ("TagKeys",),
"UntagServerCertificate": ("TagKeys",),
"UntagUser": ("TagKeys",),
}
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
shapes = dict(model["shapes"])
for operation in operations:
name = model["operations"][operation]["input"]["shape"]
request = shapes[name]
shapes[name] = {"type": request["type"],
"members": {k: v for k, v in request["members"].items() if k in PAGING_MEMBERS}}
for operation, names in members.items():
shape = model["operations"][operation]["input"]["shape"]
request = shapes[shape]
kept = {k: v for k, v in request["members"].items() if k not in names}
required = [r for r in request.get("required", ()) if r not in names]
shapes[shape] = {**request, "members": kept}
if required:
shapes[shape]["required"] = required
else:
shapes[shape].pop("required", None)
return {**model, "shapes": shapes}
# What the vendored file carries: the operations read whole, then the paged ones read in part.
VENDORED = OPERATIONS + PAGING_ONLY
def required_by_hand(model: dict, operations: tuple[str, ...] = REQUIRED_BY_HAND) -> dict:
"""`model` with each of `operations` carrying no required member, `REQUIRED_BY_HAND` by
default."""
shapes = dict(model["shapes"])
for operation in operations:
name = model["operations"][operation]["input"]["shape"]
shapes[name] = {k: v for k, v in shapes[name].items() if k != "required"}
return {**model, "shapes": shapes}
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))
def main(argv: list[str] | None = None) -> int:
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
description=__doc__, operations=VENDORED, prepare=paging_only)
description=__doc__, operations=OPERATIONS, prepare=prepare)
if __name__ == "__main__":
+43 -46
View File
@@ -1,9 +1,9 @@
"""Tests for regen_iam_shapes: what this generator does that the shared one does not.
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 is the paging
reduction: an operation vendored for its `MaxItems` and `Marker` alone, with the rest of its
request left to the reading it has today.
`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.
Run with: pytest tools/aws -q (or: make aws-data-test)
"""
@@ -12,7 +12,6 @@ from __future__ import annotations
import json
import regen_iam_shapes as r
from request_shapes import build_constraints
def test_every_paged_operation_is_held_to_the_model():
@@ -20,52 +19,50 @@ def test_every_paged_operation_is_held_to_the_model():
# table pages and this wave leaves out would take any limit and any marker length.
paged = json.loads((r.OUTPUT.parent / "iam-paginators.json").read_text(encoding="utf-8"))["operations"]
assert sorted(set(paged) - set(r.VENDORED)) == []
assert sorted(set(paged) - set(r.OPERATIONS)) == []
def test_the_vendored_file_carries_every_paged_request_reduced():
# What says the reduction is wired into the generation rather than only tested on its own: a
# driver that never ran it would vendor these requests whole, with the members this wave leaves
# to the reading they have today.
def test_an_operation_that_answers_required_members_itself_carries_none():
model = {
"operations": {"Upload": {"input": {"shape": "UploadRequest"}}},
"shapes": {
"UploadRequest": {"type": "structure", "required": ["Body"], "members": {
"Body": {"shape": "bodyType"}, "Name": {"shape": "nameType"},
}},
"bodyType": {"type": "string", "min": 1},
"nameType": {"type": "string", "min": 1, "max": 128},
},
}
reduced = r.required_by_hand(model, ("Upload",))
assert reduced["shapes"]["UploadRequest"] == {"type": "structure", "members": {
"Body": {"shape": "bodyType"}, "Name": {"shape": "nameType"}}}
# The members and their shapes stay: it is the required list alone that comes off.
assert reduced["shapes"]["bodyType"] == model["shapes"]["bodyType"]
assert r.required_by_hand(model, ()) == model
def test_the_vendored_file_carries_both_reductions():
# What says each reduction is wired into the generation rather than only tested on its own.
doc = json.loads(r.OUTPUT.read_text(encoding="utf-8"))
for operation in r.PAGING_ONLY:
members = doc["shapes"][doc["operations"][operation]]["members"]
# `ListPoliciesGrantingServiceAccess` pages on a `Marker` alone, so what holds for all of
# them is that nothing but a paging member is left, and that one of them is.
assert members and set(members) <= set(r.PAGING_MEMBERS), operation
for operation, members in r.MEMBERS_BY_HAND.items():
shape = doc["shapes"][doc["operations"][operation]]
assert not set(members) & set(shape["members"]), operation
for operation in r.REQUIRED_BY_HAND:
shape = doc["shapes"][doc["operations"][operation]]
assert "required" not in shape, operation
assert shape["members"], operation
def test_a_paging_only_operation_keeps_its_paging_members_alone():
model = {
"operations": {"ListThings": {"input": {"shape": "ListThingsRequest"}}},
"shapes": {
"ListThingsRequest": {"type": "structure", "required": ["JobId"], "members": {
"JobId": {"shape": "jobIDType"}, "Marker": {"shape": "markerType"},
"MaxItems": {"shape": "maxItemsType"},
}},
"jobIDType": {"type": "string", "min": 36, "max": 36},
"markerType": {"type": "string", "min": 1, "max": 320},
"maxItemsType": {"type": "integer", "min": 1, "max": 1000},
},
}
def test_the_vendored_file_carries_the_listed_operations_and_no_others():
# The list is what says which operations are read, so a file holding one it does not name, or
# missing one it does, is a file that drifted from the list rather than from the model: the
# staleness check answers the model. The two alias operations are the only ones deliberately
# left out, their single member being answered in AWS's own wording.
doc = json.loads(r.OUTPUT.read_text(encoding="utf-8"))
left_out = {"CreateAccountAlias", "DeleteAccountAlias"}
# The composition the generator hands the shared driver: the reduced model and the full list.
doc = build_constraints(r.paging_only(model, ("ListThings",)), ("ListThings",), "botocore test",
"tools/aws/regen_iam_shapes.py")
assert doc["shapes"]["ListThingsRequest"] == {
"type": "structure", "members": {"Marker": "markerType", "MaxItems": "maxItemsType"}}
assert "jobIDType" not in doc["shapes"]
def test_the_paging_reduction_leaves_every_other_operation_whole():
model = {
"operations": {"GetThing": {"input": {"shape": "GetThingRequest"}}},
"shapes": {
"GetThingRequest": {"type": "structure", "members": {"JobId": {"shape": "jobIDType"}}},
"jobIDType": {"type": "string", "min": 36, "max": 36},
},
}
assert r.paging_only(model, ()) == model
assert set(doc["operations"]) == set(r.OPERATIONS)
assert left_out - set(r.OPERATIONS) == left_out
+5 -4
View File
@@ -293,7 +293,7 @@ def test_constraints_check_reports_a_changed_constraint(tmp_path, monkeypatch):
def test_main_builds_from_the_prepared_model_and_checks_against_it(tmp_path, monkeypatch):
# The one thing a generator may do to the model before the build, which IAM hands the driver to
# vendor a paged request for its paging members alone. Dropping the callback, or running it
# vendor a request without the members it answers for itself. Dropping the callback, or running it
# after the build, would vendor the model as loaded, so the file is read both ways here: it
# carries what `prepare` left, and the staleness check calls that file up to date only when it
# prepares the model the same way.
@@ -324,10 +324,11 @@ def test_build_constraints_output_is_stable():
@pytest.mark.parametrize("script, model, output, extra", [
# IAM vendors some operations for their paging members alone, so it hands the driver the
# reduction as well as the list.
# IAM vendors some operations in part, so it hands the driver its reductions as well as the
# list: the required members an operation answers for itself and the members it answers in a
# wording of its own.
(regen_iam_shapes, "iam/2010-05-08", "iam-request-shapes.json",
{"prepare": regen_iam_shapes.paging_only}),
{"prepare": regen_iam_shapes.prepare}),
(regen_sts_shapes, "sts/2011-06-15", "sts-request-shapes.json", {}),
])
def test_each_constraints_script_runs_the_shared_main_with_its_operations(script, model, output, extra,