mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(sts): read a Query request's declared constraints from the model (#6891)
`GetAccessKeyInfo`, `GetSessionToken` and `GetWebIdentityToken` are held to the constraints botocore's STS model declares, which `tools/aws/regen_sts_shapes.py` vendors into `aws/sts-request-shapes.json` and `StsRequestShapes` reads through the same `QueryConstraintCheck` walk IAM reads its own file with. The two services share the protocol, the message wording and the generator, so what is new is which operations are read rather than how. What it adds is on `GetSessionToken`: `SerialNumber`, `TokenCode` and `MinimumSessionTokenSize` are declared and nothing read them, so a serial number under 9 characters, a token code that is not six digits and a size past 4096 answer `ValidationError` where they answered credentials. The size is still only validated, the token staying the length this emulator mints. `GetAccessKeyInfo` and `GetWebIdentityToken` keep the messages they already answered, from the same bounds and the same patterns, and about 130 lines of hand-written audience, tag and access-key checks come out. One answer moves: a value breaking two constraints is answered for both, where the if-else chain stopped at the first. That is the reading #6402 settled and #6580 already took for an empty role name. `jwtAlgorithmType` publishes a fixed length of 5 and no enum, the two values coming from the reference, so the walk takes a documented constraint keyed by member name and reports it in that member's place, which keeps a collected message in the model's order. It is reported only for a member the request carries that breaks nothing the model declares, which is the exclusivity the hand-written helper had. A value that is no number at all stays `InvalidParameterValue`, answered before the constraints, since the model declares a range and says nothing about what counts as a number; a digit string is a number of any width, so a `DurationSeconds` of `99999999999` breaks the maximum rather than being called no integer, as #6625 settled for an oversized `MaxItems`. Each operation asks for its violations where its own check ran rather than ahead of the switch, because `GetSessionToken` refuses session credentials before it reads anything. The whitespace around a number comes off wherever this handler reads one. The check takes a padded value and holds it to its range, so the read behind it parses the same text: parsing the value as the request spelled it threw there and fell back to the default, so a ` 3600 ` asking for an hour would have been handed the twelve hours `GetSessionToken` defaults to, or the five minutes a web identity token defaults to. IAM reads its own `MaxItems` that way already. The generator is not new code. `request_shapes.main` already drives the five generators that vendor member types, so it takes an `operations` argument now and both Query-protocol generators hand it their model, output and operations the same two-line way, which takes the hand-rolled driver out of `regen_iam_shapes.py` as well. ECR and Resource Groups still carry theirs and are a refactor of their own. The generator contract tests move with it: that a vendored file carries exactly the operations its generator lists and resolves every shape it names is one parametrized test over all four constraints generators rather than a copy per generator, and `build_constraints`'s own properties are tested once, where the shared module already tested them. The model transform the driver takes is driven through it as well, the file it writes carrying what the transform left and the staleness check calling that file current only when it prepares the model the same way, and IAM's own tests read the vendored file for each paged request reduced. Three sentences this handler wrote out by hand go the same way. The two range refusals and the length refusal on `TargetPrincipal` come from `SmithyValidationErrors`, which already wrote them word for word, and the "Must be an integer." refusal has one writer and three callers. The length comparison counts code points rather than UTF-16 units as a result, which is the reading the rest of the package uses.
This commit is contained in:
1 parent
385ffcfdd0
commit
c9c1c0990b
14 files changed
+986
-391
No files matched your search
@@ -29,6 +29,8 @@
|
||||
# generated from the certificate bundles AWS publishes by tools/aws/regen_rds_ca_certificates.py.
|
||||
# src/main/resources/aws/iam-request-shapes.json, the IAM request constraints of the operations
|
||||
# read from the model, is generated from botocore's IAM model by tools/aws/regen_iam_shapes.py.
|
||||
# src/main/resources/aws/sts-request-shapes.json, the same for STS, is generated from botocore's
|
||||
# STS model by tools/aws/regen_sts_shapes.py.
|
||||
# src/main/resources/aws/emr-serverless-shapes.json, the shapes the Step Functions emr-serverless
|
||||
# integrations recase against, is generated from botocore's EMR Serverless model by
|
||||
# tools/aws/regen_emr_serverless_shapes.py.
|
||||
@@ -240,6 +242,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p
|
||||
$(PYTHON) tools/aws/regen_resource_groups_shapes.py
|
||||
$(PYTHON) tools/aws/regen_ecr_shapes.py
|
||||
$(PYTHON) tools/aws/regen_iam_shapes.py
|
||||
$(PYTHON) tools/aws/regen_sts_shapes.py
|
||||
$(PYTHON) tools/aws/regen_apigateway_types.py
|
||||
$(PYTHON) tools/aws/regen_sesv2_shapes.py
|
||||
$(PYTHON) tools/aws/regen_apigateway_shapes.py
|
||||
@@ -281,6 +284,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_sts_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/sts-request-shapes.json is out of date."; \
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_redshift_serverless_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/redshift-serverless-request-shapes.json is out of date."; \
|
||||
|
||||
+43
-4
@@ -18,6 +18,42 @@
|
||||
| `AssumeRoot` | Opens a privileged session on a member account of the organization |
|
||||
| `GetWebIdentityToken` | Returns a signed JWT representing the calling identity |
|
||||
|
||||
## Request Constraints
|
||||
|
||||
Three operations are held to the constraints their model declares rather than to a check written
|
||||
by hand, `tools/aws/regen_sts_shapes.py` vendoring them for `GetAccessKeyInfo`, `GetSessionToken`
|
||||
and `GetWebIdentityToken` and the walk being the one IAM reads its own file with. One word of the
|
||||
message differs between the two: STS quotes the offending value, `Value 'x' at 'serialNumber'`,
|
||||
where IAM names the member and leaves it out, which is what each service's own captures carry (see
|
||||
the [IAM service doc](iam.md)). Every violation
|
||||
a request carries is reported in one `ValidationError`, in the order the model lists the members,
|
||||
and a member that breaks two constraints is reported for both. A member sent empty is a member the
|
||||
request carries, so it breaks its own length rather than reading as absent, and only a member the
|
||||
request names nowhere is answered as null. A list arrives numbered under its own name,
|
||||
`Audience.member.1` or the bare `Audience.1`, a member of a list of structures carries its fields
|
||||
under that prefix as `Tags.member.1.Key` does, and each is named the way this service already
|
||||
names one, `audience.1.member` and `tags.1.member.key`, under the index the request spelled.
|
||||
|
||||
What that adds is on `GetSessionToken`, whose `SerialNumber`, `TokenCode` and
|
||||
`MinimumSessionTokenSize` were accepted and ignored: each is now held to its shape, so a serial
|
||||
number under 9 characters, a token code that is not six digits or a token size past 4096 answers
|
||||
400 where it used to answer credentials. The size is still only validated: the session token stays
|
||||
the length this emulator mints whatever the request asks for, which is a gap rather than a reading.
|
||||
`GetAccessKeyInfo` and `GetWebIdentityToken` answer the messages they already answered, from the
|
||||
same bounds and the same patterns, and what moves there is that an access key ID breaking both its
|
||||
length and its pattern is answered for both where the check it replaces stopped at the first.
|
||||
|
||||
The model says nothing about what counts as a number, so a `DurationSeconds` or a
|
||||
`MinimumSessionTokenSize` that is no number at all stays `InvalidParameterValue`, answered before
|
||||
the constraints, while a digit string is held to the range whatever width it overflows: a duration
|
||||
of `99999999999` breaks the maximum rather than being called no integer. The whitespace around a
|
||||
number is not part of it, both where the range is read and where the duration is then used, so a
|
||||
`DurationSeconds` of ` 3600 ` is an hour rather than the default a raw parse would have fallen back
|
||||
to, which is how IAM reads its own `maxItems`. Every other operation
|
||||
that takes a member answers an absent one from a check of its own, which names the parameter as
|
||||
the request writes it, `RoleArn` rather than `roleArn`, and reads a blank value as an absent one.
|
||||
Those are drifts of their own, and taking those operations over is what settles them.
|
||||
|
||||
## Privileged Root Sessions
|
||||
|
||||
`AssumeRoot` returns "short term credentials you can use to perform privileged tasks on a member
|
||||
@@ -67,8 +103,8 @@ than the credentials report AWS returns.
|
||||
itself: AWS states that the operation "does not indicate the state of the access key. The key might
|
||||
be active, inactive, or deleted", so an inactive key answers its account the same as an active one.
|
||||
A long-term `AKIA` key resolves through the account that holds it and a temporary `ASIA` key through
|
||||
the session that minted it. The ID is read against its own shape first, 16 to 128 characters of
|
||||
`[\w]`, which answers `ValidationError` before any lookup.
|
||||
the session that minted it. The ID is read against its own shape first, the 16 to 128 characters of
|
||||
`[\w]` the model declares, which answers `ValidationError` before any lookup.
|
||||
|
||||
One answer is Floci's own. The operation models no errors at all, and the reference says only that
|
||||
"providing a deleted access key might return an error that the key doesn't exist", so a well-formed
|
||||
@@ -112,7 +148,8 @@ this package: `Audience` is required and holds 1 to 10 audiences of 1 to 1000 ch
|
||||
`SigningAlgorithm` is required at a fixed length of 5, `DurationSeconds` is 60 to 3600 and defaults
|
||||
to 300, and `Tags` is at most 50 tags whose keys and values carry their own lengths and pattern. An
|
||||
audience sent empty is an audience that is present, so it breaks the minimum length rather than
|
||||
reading as absent.
|
||||
reading as absent, and an audience numbered but never sent is how an absent list arrives, so a
|
||||
request naming none of them is the required member reading as null.
|
||||
|
||||
A session cannot outlive itself. `SessionDurationEscalationException` is what a caller holding
|
||||
temporary credentials gets when the requested duration would run past the moment its own session
|
||||
@@ -140,7 +177,9 @@ under `request_tags` rather than the claim that chooses the token's lifetime.
|
||||
Two answers here are Floci's readings. `jwtAlgorithmType` publishes a fixed length of 5 and no enum, so a
|
||||
five-character value that is neither `RS256` nor `ES384` is answered with the enum violation this
|
||||
package renders for a value outside a documented set, the two values coming from the reference
|
||||
rather than from the model. The global endpoint is refused because the reference says "The
|
||||
rather than from the model. It is reported where the model lists that member, ahead of anything the
|
||||
tags break, and a value the declared length already refuses is not read against the set as well.
|
||||
The global endpoint is refused because the reference says "The
|
||||
GetWebIdentityToken API is not available on the STS Global endpoint" without giving the refusal, so
|
||||
it borrows the wording AWS publishes for `AssumeRoot`; a request to a local host names no such
|
||||
endpoint and is not refused. `JWTPayloadSizeExceededException` is modelled and nothing published
|
||||
|
||||
@@ -161,21 +161,37 @@ public final class QueryConstraintCheck {
|
||||
|
||||
/** The violations {@code params} carries for {@code operation}, in the model's member order. */
|
||||
public List<String> violations(String operation, MultivaluedMap<String, String> params) {
|
||||
return violations(operation, params, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The same, with each violation of {@code documented} reported in its own member's place: a
|
||||
* constraint the service documents where the model declares none, keyed by the member's name as
|
||||
* the model spells it. It is a reading rather than a published shape, so it is reported where
|
||||
* that member's own violations would sit, and only for a member the request carries that breaks
|
||||
* none of the constraints the model declares. A value a declared constraint already refuses is
|
||||
* not read against a documented set as well, which is how the hand-written checks these waves
|
||||
* replace answered one, and a member that never arrived has no value to read against anything.
|
||||
*/
|
||||
public List<String> violations(String operation, MultivaluedMap<String, String> params,
|
||||
Map<String, String> documented) {
|
||||
JsonNode shape = shapes.path(operations.path(operation).asText());
|
||||
if (!shape.hasNonNull("members")) {
|
||||
return List.of();
|
||||
}
|
||||
return structureViolations(shape, "", "", params);
|
||||
return structureViolations(shape, "", "", params, documented);
|
||||
}
|
||||
|
||||
/**
|
||||
* The violations the members of {@code structure} carry, in the order the model lists them.
|
||||
* {@code prefix} is what the request names them under and {@code path} what a message calls
|
||||
* them: both are empty at the top level, and name the member above inside a structure or inside
|
||||
* a list's member.
|
||||
* a list's member. {@code documented} carries the violations the service documents rather than
|
||||
* declares, which only the operation's own members have: a nested walk is handed none.
|
||||
*/
|
||||
private List<String> structureViolations(JsonNode structure, String prefix, String path,
|
||||
MultivaluedMap<String, String> params) {
|
||||
MultivaluedMap<String, String> params,
|
||||
Map<String, String> documented) {
|
||||
Set<String> required = new LinkedHashSet<>();
|
||||
structure.path("required").forEach(name -> required.add(name.asText()));
|
||||
List<String> violations = new ArrayList<>();
|
||||
@@ -186,24 +202,43 @@ public final class QueryConstraintCheck {
|
||||
String param = prefix + name;
|
||||
boolean mandatory = required.contains(name);
|
||||
JsonNode shape = shapes.path(shapeName);
|
||||
switch (shape.path("type").asText()) {
|
||||
case "list" -> violations.addAll(listViolations(shape, param, memberPath, mandatory, params));
|
||||
case "structure" -> violations.addAll(nestedViolations(shape, param, memberPath, mandatory, params));
|
||||
default -> {
|
||||
String value = params == null ? null : params.getFirst(param);
|
||||
if (value == null) {
|
||||
if (mandatory) {
|
||||
violations.add(SmithyValidationErrors.notNull(memberPath));
|
||||
}
|
||||
} else {
|
||||
violations.addAll(violations(shapeName, value, memberPath));
|
||||
}
|
||||
}
|
||||
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);
|
||||
};
|
||||
violations.addAll(own);
|
||||
if (own.isEmpty() && documented.containsKey(name) && carries(params, param)) {
|
||||
violations.add(documented.get(name));
|
||||
}
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the request names {@code param} itself or anything under it, whatever kind of
|
||||
* member it is: a scalar at its own name, a list numbered under it, a structure's fields below
|
||||
* it. An absent member is answered for being required or for nothing at all, so it is not also
|
||||
* answered for a constraint read off a value it never sent.
|
||||
*/
|
||||
private static boolean carries(MultivaluedMap<String, String> params, String param) {
|
||||
return params != null && (params.containsKey(param)
|
||||
|| params.keySet().stream().anyMatch(key -> key.startsWith(param + ".")));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private List<String> scalarViolations(String shapeName, String param, String path,
|
||||
boolean required, MultivaluedMap<String, String> params) {
|
||||
String value = params == null ? null : params.getFirst(param);
|
||||
if (value == null) {
|
||||
return required ? List.of(SmithyValidationErrors.notNull(path)) : List.of();
|
||||
}
|
||||
return violations(shapeName, value, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* A list's members, held to the list's own bounds and then each to its element's. A list of no
|
||||
* members is how an absent list arrives, which is what makes a minimum of 1 unreachable: only a
|
||||
@@ -226,7 +261,7 @@ public final class QueryConstraintCheck {
|
||||
String memberPath = path + "." + member.index() + ".member";
|
||||
if (structure) {
|
||||
violations.addAll(structureViolations(shapes.path(elementShape),
|
||||
member.prefix() + ".", memberPath + ".", params));
|
||||
member.prefix() + ".", memberPath + ".", params, Map.of()));
|
||||
} else {
|
||||
String value = params.getFirst(member.prefix());
|
||||
violations.addAll(violations(elementShape, value == null ? "" : value, memberPath));
|
||||
@@ -246,7 +281,7 @@ public final class QueryConstraintCheck {
|
||||
if (!present) {
|
||||
return required ? List.of(SmithyValidationErrors.notNull(path)) : List.of();
|
||||
}
|
||||
return structureViolations(shape, param + ".", path + ".", params);
|
||||
return structureViolations(shape, param + ".", path + ".", params, Map.of());
|
||||
}
|
||||
|
||||
/** The member's name as a validation message spells it, which is the request's with a lower
|
||||
@@ -283,6 +318,16 @@ public final class QueryConstraintCheck {
|
||||
return violation == null ? List.of() : List.of(violation);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when {@code value} is a number as the protocol writes one, of any width: the model's
|
||||
* bounds are what hold it, so a digit string that overflows a {@code long} is a number all the
|
||||
* same. An operation answering a value that is no number at all asks this rather than keeping a
|
||||
* reading of its own, since the same answer decides whether a range applies.
|
||||
*/
|
||||
public static boolean isInteger(String value) {
|
||||
return value != null && INTEGER.matcher(value.trim()).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* A value that is no number is left to the operation: this package answers one with
|
||||
* {@code InvalidParameterValue} rather than with a constraint violation, and which member
|
||||
@@ -295,7 +340,7 @@ public final class QueryConstraintCheck {
|
||||
*/
|
||||
private String numberViolation(JsonNode shape, String value, String path) {
|
||||
String text = value.trim();
|
||||
if (!INTEGER.matcher(text).matches()) {
|
||||
if (!isInteger(text)) {
|
||||
// Not a number at all, so no range of the model's is what it breaks.
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
|
||||
import io.github.hectorvent.floci.core.common.IamEnforcementFilter;
|
||||
import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;
|
||||
import io.github.hectorvent.floci.core.common.QueryConstraintCheck;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.common.WebIdentityToken;
|
||||
@@ -36,15 +37,12 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Query-protocol handler for STS (Security Token Service) actions.
|
||||
@@ -54,11 +52,6 @@ import java.util.regex.Pattern;
|
||||
@ApplicationScoped
|
||||
public class StsQueryHandler {
|
||||
|
||||
/** accessKeyIdType, the only member GetAccessKeyInfo takes: 16 to 128 characters of {@code [\w]}. */
|
||||
private static final Pattern ACCESS_KEY_ID_PATTERN = Pattern.compile("[\\w]*");
|
||||
private static final int ACCESS_KEY_ID_MIN_LENGTH = 16;
|
||||
private static final int ACCESS_KEY_ID_MAX_LENGTH = 128;
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(StsQueryHandler.class);
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
/** Where the five task policies the guide names for a privileged session live. */
|
||||
@@ -66,27 +59,8 @@ public class StsQueryHandler {
|
||||
/** "the maximum session duration of 900 seconds (15 minutes)", which is also the default here. */
|
||||
private static final int MAX_ROOT_SESSION_SECONDS = 900;
|
||||
private static final int MAX_SESSION_TOKEN_SIZE = 4096;
|
||||
/** {@code webIdentityTokenAudienceListType}: 1 to 10 audiences, each 1 to 1000 characters. */
|
||||
private static final int MAX_TOKEN_AUDIENCES = 10;
|
||||
private static final int MAX_TOKEN_AUDIENCE_LENGTH = 1000;
|
||||
/** {@code jwtAlgorithmType} is a fixed length of 5, which both valid values are. */
|
||||
private static final int SIGNING_ALGORITHM_LENGTH = 5;
|
||||
/** {@code tagListType} on this operation: at most 50 tags, each a key and a value. */
|
||||
private static final int MAX_TOKEN_TAGS = 50;
|
||||
private static final int MAX_TAG_KEY_LENGTH = 128;
|
||||
private static final int MAX_TAG_VALUE_LENGTH = 256;
|
||||
/** {@code tagKeyType} and {@code tagValueType} share this pattern, the value allowing empty. */
|
||||
private static final Pattern TAG_PATTERN = Pattern.compile("[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+");
|
||||
/** A member of {@code Audience}, capturing the prefix it is named under and its index. */
|
||||
private static final Pattern AUDIENCE_MEMBER =
|
||||
Pattern.compile("(Audience(?:\\.member)?\\.([^.]+))");
|
||||
/** A member of {@code Tags}, which carries its key and its value under that prefix. */
|
||||
private static final Pattern TAG_MEMBER =
|
||||
Pattern.compile("(Tags(?:\\.member)?\\.([^.]+))\\.(?:Key|Value)");
|
||||
/** "If not specified, the default duration is 300 seconds (5 minutes)." */
|
||||
private static final int DEFAULT_TOKEN_SECONDS = 300;
|
||||
private static final int MIN_TOKEN_SECONDS = 60;
|
||||
private static final int MAX_TOKEN_SECONDS = 3600;
|
||||
private static final String STS_AUDIENCE = "sts.amazonaws.com"; // partition-literal: web-identity audience; no source outside the commercial partition (P9)
|
||||
|
||||
private final IamService iamService;
|
||||
@@ -323,7 +297,7 @@ public class StsQueryHandler {
|
||||
* nearest that sentence, and {@code docs/services/sts.md} records it as the deviation it is.
|
||||
*/
|
||||
private Response handleGetAccessKeyInfo(MultivaluedMap<String, String> params) {
|
||||
Response validation = validateAccessKeyId(params);
|
||||
Response validation = validateDeclaredConstraints("GetAccessKeyInfo", params);
|
||||
if (validation != null) {
|
||||
return validation;
|
||||
}
|
||||
@@ -337,51 +311,19 @@ public class StsQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelope("GetAccessKeyInfo", AwsNamespaces.STS, result)).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* accessKeyIdType: required, 16 to 128 characters of {@code [\w]*}, which the reference
|
||||
* describes as "any upper- or lowercase letter or digit". Read before the lookup, so a
|
||||
* malformed id answers for its shape rather than for a key that could not exist.
|
||||
*
|
||||
* <p>An absent member and a present empty one are different answers: only the absent one is
|
||||
* "Member must not be null", where {@code AccessKeyId=} is a value that fails the minimum. That
|
||||
* is what IAM answers for an empty {@code RoleName} on this same wire.
|
||||
*
|
||||
* <p>The member is named the way AWS names it in a constraint message, lower camel case, and
|
||||
* the offending value is quoted beside it, which is what the one recorded rendering Floci
|
||||
* follows elsewhere does: {@link IamService} reads {@code roleName} that way, and so does this
|
||||
* handler's own {@code DurationSeconds} check. The older STS operations name the parameter as
|
||||
* written instead, which is a drift of its own rather than something to copy here.
|
||||
*/
|
||||
private Response validateAccessKeyId(MultivaluedMap<String, String> params) {
|
||||
String accessKeyId = params.getFirst("AccessKeyId");
|
||||
String constraint;
|
||||
if (accessKeyId == null) {
|
||||
constraint = "Member must not be null";
|
||||
} else if (accessKeyId.length() < ACCESS_KEY_ID_MIN_LENGTH) {
|
||||
constraint = "Member must have length greater than or equal to " + ACCESS_KEY_ID_MIN_LENGTH;
|
||||
} else if (accessKeyId.length() > ACCESS_KEY_ID_MAX_LENGTH) {
|
||||
constraint = "Member must have length less than or equal to " + ACCESS_KEY_ID_MAX_LENGTH;
|
||||
} else if (!ACCESS_KEY_ID_PATTERN.matcher(accessKeyId).matches()) {
|
||||
constraint = "Member must satisfy regular expression pattern: "
|
||||
+ ACCESS_KEY_ID_PATTERN.pattern();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
String value = accessKeyId == null ? "null" : "'" + accessKeyId + "'";
|
||||
return AwsQueryResponse.error("ValidationError",
|
||||
SmithyValidationErrors.message(List.of("Value " + value
|
||||
+ " at 'accessKeyId' failed to satisfy constraint: " + constraint)),
|
||||
AwsNamespaces.STS, 400);
|
||||
}
|
||||
|
||||
private Response handleGetSessionToken(MultivaluedMap<String, String> params) {
|
||||
if (IamService.isTemporaryAccessKey(callerAccessKeyId())) {
|
||||
return AwsQueryResponse.error("AccessDenied", "Cannot call GetSessionToken with session credentials",
|
||||
AwsNamespaces.STS, 403);
|
||||
}
|
||||
Response durationValidation = validateDurationSeconds(params, 900, 129600);
|
||||
if (durationValidation != null) {
|
||||
return durationValidation;
|
||||
Response integerMembers =
|
||||
validateIntegerMembers(params, "DurationSeconds", "MinimumSessionTokenSize");
|
||||
if (integerMembers != null) {
|
||||
return integerMembers;
|
||||
}
|
||||
Response validation = validateDeclaredConstraints("GetSessionToken", params);
|
||||
if (validation != null) {
|
||||
return validation;
|
||||
}
|
||||
int durationSeconds = getIntParam(params, "DurationSeconds", 43200);
|
||||
String accessKeyId = "ASIA" + randomId(16);
|
||||
@@ -789,14 +731,10 @@ public class StsQueryHandler {
|
||||
return validation;
|
||||
}
|
||||
String targetPrincipal = getParam(params, "TargetPrincipal");
|
||||
if (targetPrincipal.length() < 12 || targetPrincipal.length() > 2048) {
|
||||
String constraint = targetPrincipal.length() < 12
|
||||
? "Member must have length greater than or equal to 12"
|
||||
: "Member must have length less than or equal to 2048";
|
||||
return AwsQueryResponse.error("ValidationError",
|
||||
SmithyValidationErrors.message(List.of("Value '" + targetPrincipal
|
||||
+ "' at 'targetPrincipal' failed to satisfy constraint: " + constraint)),
|
||||
AwsNamespaces.STS, 400);
|
||||
Response principalLength = violation(
|
||||
SmithyValidationErrors.lengthOutOfRange("targetPrincipal", targetPrincipal, 12, 2048));
|
||||
if (principalLength != null) {
|
||||
return principalLength;
|
||||
}
|
||||
Response durationValidation = validateDurationSeconds(params, 0, 900);
|
||||
if (durationValidation != null) {
|
||||
@@ -881,20 +819,10 @@ public class StsQueryHandler {
|
||||
try {
|
||||
size = Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "Value " + value + " for parameter"
|
||||
+ " MinimumSessionTokenSize is invalid. Reason: Must be an integer.",
|
||||
AwsNamespaces.STS, 400);
|
||||
return notANumber("MinimumSessionTokenSize", value);
|
||||
}
|
||||
if (size < 0 || size > MAX_SESSION_TOKEN_SIZE) {
|
||||
String constraint = size < 0
|
||||
? "Member must have value greater than or equal to 0"
|
||||
: "Member must have value less than or equal to " + MAX_SESSION_TOKEN_SIZE;
|
||||
return AwsQueryResponse.error("ValidationError",
|
||||
SmithyValidationErrors.message(List.of("Value '" + size
|
||||
+ "' at 'minimumSessionTokenSize' failed to satisfy constraint: " + constraint)),
|
||||
AwsNamespaces.STS, 400);
|
||||
}
|
||||
return null;
|
||||
return violation(SmithyValidationErrors.outOfRange("minimumSessionTokenSize", size, 0,
|
||||
MAX_SESSION_TOKEN_SIZE));
|
||||
}
|
||||
|
||||
/** The account a {@code TargetPrincipal} names, whether it is an account id or a principal ARN. */
|
||||
@@ -957,6 +885,73 @@ public class StsQueryHandler {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The constraints the model declares for {@code action}, answered the way this handler answers
|
||||
* every other refusal: one {@code ValidationError} naming every violation it found, in the
|
||||
* order the model lists the members. A member the request names at all carries a value, so an
|
||||
* empty one breaks its minimum length where an absent one is the refusal that names it null,
|
||||
* and the member is named as a constraint message spells it, lower camel case with the
|
||||
* offending value quoted beside it.
|
||||
*/
|
||||
private static Response validateDeclaredConstraints(String action,
|
||||
MultivaluedMap<String, String> params) {
|
||||
return validateDeclaredConstraints(action, params, Map.of());
|
||||
}
|
||||
|
||||
/** The same, with a constraint the reference documents where the model declares none. */
|
||||
private static Response validateDeclaredConstraints(String action,
|
||||
MultivaluedMap<String, String> params,
|
||||
Map<String, String> documented) {
|
||||
List<String> violations = StsRequestShapes.violations(action, params, documented);
|
||||
if (violations.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return AwsQueryResponse.error("ValidationError", SmithyValidationErrors.message(violations),
|
||||
AwsNamespaces.STS, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* The members the model declares as numbers, held to being numbers at all. Their ranges are
|
||||
* read from the model, which says nothing about a value that is no number: this package answers
|
||||
* one with {@code InvalidParameterValue}, which is what {@code DurationSeconds} answered before
|
||||
* any of it was read from the model, and a digit string of any width is a number whatever it
|
||||
* overflows.
|
||||
*/
|
||||
private static Response validateIntegerMembers(MultivaluedMap<String, String> params,
|
||||
String... names) {
|
||||
for (String name : names) {
|
||||
String value = params.getFirst(name);
|
||||
if (value != null && !QueryConstraintCheck.isInteger(value)) {
|
||||
return notANumber(name, value);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One violation as this handler answers it, or null where {@code violation} is null. The
|
||||
* wording comes from {@link SmithyValidationErrors} rather than from a sentence written here,
|
||||
* so a member held to its shape by a check of this file's own reads the same as one the model
|
||||
* holds.
|
||||
*/
|
||||
private static Response violation(String violation) {
|
||||
if (violation == null) {
|
||||
return null;
|
||||
}
|
||||
return AwsQueryResponse.error("ValidationError",
|
||||
SmithyValidationErrors.message(List.of(violation)), AwsNamespaces.STS, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* The refusal for a member the protocol cannot read as the number its shape declares, which is
|
||||
* {@code InvalidParameterValue} rather than a constraint violation: no range of the model's is
|
||||
* what such a value breaks.
|
||||
*/
|
||||
private static Response notANumber(String name, String value) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "Value " + value + " for parameter "
|
||||
+ name + " is invalid. Reason: Must be an integer.", AwsNamespaces.STS, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the optional {@code DurationSeconds} parameter against {@code minSeconds}/{@code maxSeconds}.
|
||||
* Returns {@code null} when the parameter is absent or valid; otherwise a {@code ValidationError} (out of
|
||||
@@ -971,23 +966,10 @@ public class StsQueryHandler {
|
||||
try {
|
||||
durationSeconds = Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue",
|
||||
"Value " + value + " for parameter DurationSeconds is invalid. Reason: Must be an integer.",
|
||||
AwsNamespaces.STS, 400);
|
||||
return notANumber("DurationSeconds", value);
|
||||
}
|
||||
if (durationSeconds < minSeconds) {
|
||||
return AwsQueryResponse.error("ValidationError",
|
||||
"1 validation error detected: Value '" + durationSeconds + "' at 'durationSeconds' failed to "
|
||||
+ "satisfy constraint: Member must have value greater than or equal to " + minSeconds,
|
||||
AwsNamespaces.STS, 400);
|
||||
}
|
||||
if (durationSeconds > maxSeconds) {
|
||||
return AwsQueryResponse.error("ValidationError",
|
||||
"1 validation error detected: Value '" + durationSeconds + "' at 'durationSeconds' failed to "
|
||||
+ "satisfy constraint: Member must have value less than or equal to " + maxSeconds,
|
||||
AwsNamespaces.STS, 400);
|
||||
}
|
||||
return null;
|
||||
return violation(SmithyValidationErrors.outOfRange("durationSeconds", durationSeconds,
|
||||
minSeconds, maxSeconds));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -999,14 +981,17 @@ public class StsQueryHandler {
|
||||
* {@code OutboundWebIdentityFederationDisabledException} rather than IAM's own
|
||||
* {@code FeatureDisabled}.
|
||||
*
|
||||
* <p>The declared constraints are read ahead of all of it: {@code Audience} is 1 to 10 members
|
||||
* of 1 to 1000 characters each and required, {@code SigningAlgorithm} is a fixed length of 5
|
||||
* and required, {@code DurationSeconds} is 60 to 3600 and defaults to 300, and {@code Tags} is
|
||||
* at most 50 tags whose keys and values carry their own lengths and pattern. A member sent
|
||||
* empty is a member that is present, so it breaks its length rather than reading as absent.
|
||||
* The duration keeps this file's own check, which answers the first thing it finds and reports
|
||||
* a value that is no integer as {@code InvalidParameterValue}; everything else is reported
|
||||
* together, in the order the model lists the members.
|
||||
* <p>The declared constraints are read ahead of all of it, from the model rather than from a
|
||||
* check written here: {@code Audience} is 1 to 10 members of 1 to 1000 characters each and
|
||||
* required, {@code SigningAlgorithm} is a fixed length of 5 and required,
|
||||
* {@code DurationSeconds} is 60 to 3600 and defaults to 300, and {@code Tags} is at most 50
|
||||
* tags whose keys and values carry their own lengths and pattern. A member sent empty is a
|
||||
* member that is present, so it breaks its length rather than reading as absent. Every
|
||||
* violation is reported together, in the order the model lists the members, with the two
|
||||
* signing algorithms the reference names reported in that member's own place. A
|
||||
* {@code DurationSeconds} that is no number at all is this file's own
|
||||
* {@code InvalidParameterValue}, answered before the constraints: the model declares the range,
|
||||
* not what counts as a number.
|
||||
*
|
||||
* <p>Three things here are readings rather than published behaviour, and the docs say so. The
|
||||
* model publishes no enum for {@code SigningAlgorithm}, only the fixed length, so a five
|
||||
@@ -1033,19 +1018,14 @@ public class StsQueryHandler {
|
||||
+ " for GetWebIdentityToken. You must send this request to a Regional AWS STS"
|
||||
+ " endpoint.", AwsNamespaces.STS, 400);
|
||||
}
|
||||
Response durationValidation =
|
||||
validateDurationSeconds(params, MIN_TOKEN_SECONDS, MAX_TOKEN_SECONDS);
|
||||
if (durationValidation != null) {
|
||||
return durationValidation;
|
||||
Response integerMembers = validateIntegerMembers(params, "DurationSeconds");
|
||||
if (integerMembers != null) {
|
||||
return integerMembers;
|
||||
}
|
||||
List<ListMember> audiences = listMembers(params, AUDIENCE_MEMBER);
|
||||
Map<String, String> tagClaims = new LinkedHashMap<>();
|
||||
List<String> violations = new ArrayList<>(audienceViolations(params, audiences));
|
||||
violations.addAll(signingAlgorithmViolations(params.getFirst("SigningAlgorithm")));
|
||||
violations.addAll(tagViolations(params, tagClaims));
|
||||
if (!violations.isEmpty()) {
|
||||
return AwsQueryResponse.error("ValidationError",
|
||||
SmithyValidationErrors.message(violations), AwsNamespaces.STS, 400);
|
||||
Response validation = validateDeclaredConstraints("GetWebIdentityToken", params,
|
||||
documentedAlgorithms(params));
|
||||
if (validation != null) {
|
||||
return validation;
|
||||
}
|
||||
|
||||
String accessKeyId = callerAccessKeyId();
|
||||
@@ -1079,10 +1059,9 @@ public class StsQueryHandler {
|
||||
regionResolver.buildGlobalArn("iam", regionResolver.getAccountId(), "root"));
|
||||
String token = tokenIssuer.mint(
|
||||
WebIdentityTokenIssuer.Algorithm.valueOf(params.getFirst("SigningAlgorithm")),
|
||||
federation.get().getIssuerIdentifier(), subject,
|
||||
audiences.stream().map(member -> value(params, member)).toList(),
|
||||
federation.get().getIssuerIdentifier(), subject, audiences(params),
|
||||
new WebIdentityTokenIssuer.CustomClaims(regionResolver.getAccountId(),
|
||||
regionResolver.getRegion(), tagClaims),
|
||||
regionResolver.getRegion(), tagClaims(params)),
|
||||
issuedAt, expiration);
|
||||
LOG.debugv("Issued a web identity token for {0} expiring at {1}", subject, expiration);
|
||||
String result = new XmlBuilder()
|
||||
@@ -1094,137 +1073,45 @@ public class StsQueryHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* One member of a Query list: the prefix its parameters are named under, and the index the
|
||||
* request numbered it with, read back as it was spelled rather than as the number it reads as.
|
||||
* The audiences the request carries, in the order their indexes read, each as it was sent: the
|
||||
* model holds every one of them to a minimum length of 1, so by here none is absent.
|
||||
*/
|
||||
private record ListMember(String prefix, String index) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The members of a list, in the order their indexes read. The patterns capture the prefix
|
||||
* because a member of a list of structures carries its fields under it, which
|
||||
* {@link AwsQueryLists#memberKeys} does not match, and because the index a path names is the
|
||||
* one the request sent. A member present with an empty value is still a member.
|
||||
*/
|
||||
private static List<ListMember> listMembers(MultivaluedMap<String, String> params,
|
||||
Pattern names) {
|
||||
return params.keySet().stream()
|
||||
.map(names::matcher)
|
||||
.filter(Matcher::matches)
|
||||
.map(matcher -> new ListMember(matcher.group(1), matcher.group(2)))
|
||||
.distinct()
|
||||
.sorted(Comparator.comparingInt(
|
||||
member -> AwsQueryLists.memberIndex(member.prefix())))
|
||||
private static List<String> audiences(MultivaluedMap<String, String> params) {
|
||||
return AwsQueryLists.members(params, "Audience", null).stream()
|
||||
.map(member -> Objects.requireNonNullElse(params.getFirst(member.prefix()), ""))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static String value(MultivaluedMap<String, String> params, ListMember member) {
|
||||
String value = params.getFirst(member.prefix());
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code Audience} is required, so a list of no members is the required member reading as null:
|
||||
* a Query list of none is how an absent one arrives, which is what makes its minimum of 1
|
||||
* unreachable on its own.
|
||||
* The tags the request turns into claims, the last value winning for a key sent twice, which is
|
||||
* how a Query map's duplicate key resolves elsewhere in this package. {@code Tag} declares both
|
||||
* its fields required, so a member reaching here carries them.
|
||||
*/
|
||||
private static List<String> audienceViolations(MultivaluedMap<String, String> params,
|
||||
List<ListMember> audiences) {
|
||||
if (audiences.isEmpty()) {
|
||||
return List.of(SmithyValidationErrors.notNull("audience"));
|
||||
}
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (audiences.size() > MAX_TOKEN_AUDIENCES) {
|
||||
violations.add("Value at 'audience' failed to satisfy constraint: Member must have"
|
||||
+ " length less than or equal to " + MAX_TOKEN_AUDIENCES);
|
||||
}
|
||||
for (ListMember audience : audiences) {
|
||||
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(
|
||||
"audience." + audience.index() + ".member", value(params, audience), 1,
|
||||
MAX_TOKEN_AUDIENCE_LENGTH));
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
/**
|
||||
* The model gives {@code jwtAlgorithmType} a fixed length of 5 and no enum, and the Reference
|
||||
* names the two values that length is for, so the length is the declared constraint and the
|
||||
* value set is read from the documentation.
|
||||
*/
|
||||
private static List<String> signingAlgorithmViolations(String algorithm) {
|
||||
if (algorithm == null) {
|
||||
return List.of(SmithyValidationErrors.notNull("signingAlgorithm"));
|
||||
}
|
||||
String length = SmithyValidationErrors.lengthOutOfRange("signingAlgorithm", algorithm,
|
||||
SIGNING_ALGORITHM_LENGTH, SIGNING_ALGORITHM_LENGTH);
|
||||
if (length != null) {
|
||||
return List.of(length);
|
||||
}
|
||||
if (!WebIdentityTokenIssuer.Algorithm.names().contains(algorithm)) {
|
||||
return List.of(SmithyValidationErrors.notInEnum(algorithm, "signingAlgorithm",
|
||||
WebIdentityTokenIssuer.Algorithm.names()));
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Each tag is a {@code Tag}, which declares both its key and its value required, so a member
|
||||
* sent with only one of them breaks the other. The claims a valid tag set contributes are
|
||||
* collected here rather than read a second time, the last value winning for a key sent twice,
|
||||
* which is how a Query map's duplicate key resolves elsewhere in this package.
|
||||
*/
|
||||
private static List<String> tagViolations(MultivaluedMap<String, String> params,
|
||||
Map<String, String> claims) {
|
||||
List<ListMember> tags = listMembers(params, TAG_MEMBER);
|
||||
if (tags.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (tags.size() > MAX_TOKEN_TAGS) {
|
||||
violations.add("Value at 'tags' failed to satisfy constraint: Member must have length"
|
||||
+ " less than or equal to " + MAX_TOKEN_TAGS);
|
||||
}
|
||||
for (ListMember tag : tags) {
|
||||
String path = "tags." + tag.index() + ".member.";
|
||||
private static Map<String, String> tagClaims(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> claims = new LinkedHashMap<>();
|
||||
for (AwsQueryLists.IndexedMember tag : AwsQueryLists.members(params, "Tags", null)) {
|
||||
String key = params.getFirst(tag.prefix() + ".Key");
|
||||
String value = params.getFirst(tag.prefix() + ".Value");
|
||||
if (key == null) {
|
||||
violations.add(SmithyValidationErrors.notNull(path + "key"));
|
||||
} else {
|
||||
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(path + "key", key,
|
||||
1, MAX_TAG_KEY_LENGTH));
|
||||
addIfPresent(violations, patternViolation(path + "key", key, false));
|
||||
}
|
||||
if (value == null) {
|
||||
violations.add(SmithyValidationErrors.notNull(path + "value"));
|
||||
} else {
|
||||
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(path + "value",
|
||||
value, 0, MAX_TAG_VALUE_LENGTH));
|
||||
addIfPresent(violations, patternViolation(path + "value", value, true));
|
||||
}
|
||||
if (key != null && value != null) {
|
||||
claims.put(key, value);
|
||||
}
|
||||
}
|
||||
return violations;
|
||||
return claims;
|
||||
}
|
||||
|
||||
/** {@code tagValueType}'s pattern allows an empty value where {@code tagKeyType}'s does not. */
|
||||
private static String patternViolation(String path, String value, boolean emptyAllowed) {
|
||||
if (emptyAllowed && value.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (TAG_PATTERN.matcher(value).matches()) {
|
||||
return null;
|
||||
}
|
||||
return "Value '" + value + "' at '" + path + "' failed to satisfy constraint: Member must"
|
||||
+ " satisfy regular expression pattern: " + TAG_PATTERN.pattern();
|
||||
}
|
||||
|
||||
private static void addIfPresent(List<String> violations, String violation) {
|
||||
if (violation != null) {
|
||||
violations.add(violation);
|
||||
/**
|
||||
* {@code jwtAlgorithmType} publishes a fixed length of 5 and no enum, and the reference names
|
||||
* the two values that length is for, so the value set is documented where the length is
|
||||
* declared. It is read against a value the model's own length accepts, and reported in that
|
||||
* member's place rather than after the members the model lists below it.
|
||||
*/
|
||||
private static Map<String, String> documentedAlgorithms(MultivaluedMap<String, String> params) {
|
||||
String algorithm = params.getFirst("SigningAlgorithm");
|
||||
if (algorithm == null || WebIdentityTokenIssuer.Algorithm.names().contains(algorithm)) {
|
||||
return Map.of();
|
||||
}
|
||||
return Map.of("SigningAlgorithm", SmithyValidationErrors.notInEnum(algorithm,
|
||||
"signingAlgorithm", WebIdentityTokenIssuer.Algorithm.names()));
|
||||
}
|
||||
|
||||
private String credentialsXml(String accessKeyId, String secretKey, String sessionToken, Instant expiration) {
|
||||
@@ -1242,11 +1129,18 @@ public class StsQueryHandler {
|
||||
return params.getFirst(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* The number as the check that let it through read it. {@link QueryConstraintCheck} takes a
|
||||
* Query number with the whitespace around it off, so a padded value satisfies its range, and
|
||||
* the read behind it has to take it off too: parsing the value as the request spelled it would
|
||||
* throw here and fall back to the default, handing out a session or a token of a length nothing
|
||||
* asked for. IAM reads its own `maxItems` the same way.
|
||||
*/
|
||||
private int getIntParam(MultivaluedMap<String, String> params, String name, int defaultValue) {
|
||||
String value = params.getFirst(name);
|
||||
if (value == null) return defaultValue;
|
||||
try {
|
||||
return Integer.parseInt(value);
|
||||
return Integer.parseInt(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.QueryConstraintCheck;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The declared constraints STS reads from its model rather than from a hand-written check, as
|
||||
* {@code tools/aws/regen_sts_shapes.py} vendors them into {@code aws/sts-request-shapes.json}. It
|
||||
* is IAM's walk over STS's own file: the two services share the Query protocol, the message wording
|
||||
* and the generator, and differ in which operations are read and in one word of the message. STS
|
||||
* quotes the offending value where IAM leaves it out, which is what its own capture carries and
|
||||
* what DRIFT-13 settled for both, so the form is named here rather than taken as a default.
|
||||
*
|
||||
* <p>The violations are returned rather than thrown, because each STS operation answers its own
|
||||
* refusals in its own order: {@code GetSessionToken} refuses session credentials before it reads
|
||||
* anything, and a value that is no integer at all is {@code InvalidParameterValue} rather than a
|
||||
* constraint violation. So the operation asks for the violations where its hand-written check ran
|
||||
* and answers them in the namespace it answers everything else in.
|
||||
*
|
||||
* <p>The vendored file carries a wave of operations rather than all 11, and grows a wave at a time,
|
||||
* each one chosen where no operation answers a declared constraint in a wording of its own.
|
||||
* {@code GetAccessKeyInfo} is the parity case, its own check having answered {@code accessKeyId}
|
||||
* from the same bounds and the same pattern; {@code GetSessionToken} brings {@code SerialNumber},
|
||||
* {@code TokenCode} and {@code MinimumSessionTokenSize}, which nothing read at all; and
|
||||
* {@code GetWebIdentityToken} is where the audience and tag checks come off hand-written code.
|
||||
*/
|
||||
final class StsRequestShapes {
|
||||
|
||||
private static final QueryConstraintCheck CHECK = QueryConstraintCheck.load(
|
||||
"aws/sts-request-shapes.json", "STS request shapes",
|
||||
SmithyValidationErrors.Violations.QUOTED);
|
||||
|
||||
private StsRequestShapes() {
|
||||
}
|
||||
|
||||
/** Every constraint the model declares for {@code action} that {@code params} breaks. */
|
||||
static List<String> violations(String action, MultivaluedMap<String, String> params) {
|
||||
return CHECK.violations(action, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same, with a constraint the reference documents and the model declares nowhere reported
|
||||
* in its own member's place, keyed by that member's name.
|
||||
*/
|
||||
static List<String> violations(String action, MultivaluedMap<String, String> params,
|
||||
Map<String, String> documented) {
|
||||
return CHECK.violations(action, params, documented);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
{
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_sts_shapes.py",
|
||||
"botocore": "botocore 1.43.113 (installed package)"
|
||||
},
|
||||
"operations": {
|
||||
"GetAccessKeyInfo": "GetAccessKeyInfoRequest",
|
||||
"GetSessionToken": "GetSessionTokenRequest",
|
||||
"GetWebIdentityToken": "GetWebIdentityTokenRequest"
|
||||
},
|
||||
"shapes": {
|
||||
"GetAccessKeyInfoRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"AccessKeyId"
|
||||
],
|
||||
"members": {
|
||||
"AccessKeyId": "accessKeyIdType"
|
||||
}
|
||||
},
|
||||
"GetSessionTokenRequest": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"DurationSeconds": "durationSecondsType",
|
||||
"SerialNumber": "serialNumberType",
|
||||
"TokenCode": "tokenCodeType",
|
||||
"MinimumSessionTokenSize": "minimumSessionTokenSizeType"
|
||||
}
|
||||
},
|
||||
"GetWebIdentityTokenRequest": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"Audience",
|
||||
"SigningAlgorithm"
|
||||
],
|
||||
"members": {
|
||||
"Audience": "webIdentityTokenAudienceListType",
|
||||
"DurationSeconds": "webIdentityTokenDurationSecondsType",
|
||||
"SigningAlgorithm": "jwtAlgorithmType",
|
||||
"Tags": "tagListType"
|
||||
}
|
||||
},
|
||||
"Tag": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"Key",
|
||||
"Value"
|
||||
],
|
||||
"members": {
|
||||
"Key": "tagKeyType",
|
||||
"Value": "tagValueType"
|
||||
}
|
||||
},
|
||||
"accessKeyIdType": {
|
||||
"type": "string",
|
||||
"min": 16,
|
||||
"max": 128,
|
||||
"pattern": "[\\w]*"
|
||||
},
|
||||
"durationSecondsType": {
|
||||
"type": "integer",
|
||||
"min": 900,
|
||||
"max": 129600
|
||||
},
|
||||
"jwtAlgorithmType": {
|
||||
"type": "string",
|
||||
"min": 5,
|
||||
"max": 5
|
||||
},
|
||||
"minimumSessionTokenSizeType": {
|
||||
"type": "integer",
|
||||
"min": 0,
|
||||
"max": 4096
|
||||
},
|
||||
"serialNumberType": {
|
||||
"type": "string",
|
||||
"min": 9,
|
||||
"max": 256,
|
||||
"pattern": "[\\w+=/:,.@-]*"
|
||||
},
|
||||
"tagKeyType": {
|
||||
"type": "string",
|
||||
"min": 1,
|
||||
"max": 128,
|
||||
"pattern": "[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+"
|
||||
},
|
||||
"tagListType": {
|
||||
"type": "list",
|
||||
"max": 50,
|
||||
"member": "Tag"
|
||||
},
|
||||
"tagValueType": {
|
||||
"type": "string",
|
||||
"min": 0,
|
||||
"max": 256,
|
||||
"pattern": "[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*"
|
||||
},
|
||||
"tokenCodeType": {
|
||||
"type": "string",
|
||||
"min": 6,
|
||||
"max": 6,
|
||||
"pattern": "[\\d]*"
|
||||
},
|
||||
"webIdentityTokenAudienceListType": {
|
||||
"type": "list",
|
||||
"min": 1,
|
||||
"max": 10,
|
||||
"member": "webIdentityTokenAudienceStringType"
|
||||
},
|
||||
"webIdentityTokenAudienceStringType": {
|
||||
"type": "string",
|
||||
"min": 1,
|
||||
"max": 1000
|
||||
},
|
||||
"webIdentityTokenDurationSecondsType": {
|
||||
"type": "integer",
|
||||
"min": 60,
|
||||
"max": 3600
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -374,4 +375,74 @@ class QueryConstraintCheckTest {
|
||||
iam.violations("GetAccountAuthorizationDetails", params("Filter.member.1", "Users")),
|
||||
"the one list this wave opts in resolves to its member's enum");
|
||||
}
|
||||
|
||||
/**
|
||||
* A constraint the service documents and the model declares nowhere is reported where that
|
||||
* member's own violations would sit rather than after the members below it, and not at all
|
||||
* where the member already breaks one it declares: a value a declared constraint refuses is
|
||||
* not read against a documented set as well, which is how the checks these waves replace
|
||||
* answered one.
|
||||
*/
|
||||
@Test
|
||||
void aDocumentedConstraintSitsInItsMembersPlaceAndYieldsToADeclaredOne() throws Exception {
|
||||
Map<String, String> documented = Map.of("Name",
|
||||
"Value 'a' at 'name' failed to satisfy constraint: Member must satisfy enum value"
|
||||
+ " set: [b, c]");
|
||||
|
||||
assertEquals(List.of(
|
||||
"Value 'a' at 'name' failed to satisfy constraint: Member must satisfy enum value"
|
||||
+ " set: [b, c]",
|
||||
"Value null at 'arn' failed to satisfy constraint: Member must not be null"),
|
||||
check().violations("Put", params("Name", "a"), documented),
|
||||
"Name is listed ahead of Arn, so what it is answered for is too");
|
||||
|
||||
assertEquals(List.of(
|
||||
"Value 'a!' at 'name' failed to satisfy constraint: Member must satisfy regular"
|
||||
+ " expression pattern: [\\w+=,.@-]+"),
|
||||
check().violations("Take", params("Name", "a!"), documented),
|
||||
"the shape refuses the value already, so the documented set is not read against it");
|
||||
|
||||
assertEquals(List.of(), check().violations("Take", params(), documented),
|
||||
"an absent member sent no value, so there is nothing to read a set against");
|
||||
|
||||
assertEquals(List.of(
|
||||
"Value null at 'name' failed to satisfy constraint: Member must not be null",
|
||||
"Value null at 'arn' failed to satisfy constraint: Member must not be null"),
|
||||
check().violations("Put", params(), documented),
|
||||
"and a required one absent is answered for that alone");
|
||||
}
|
||||
|
||||
/**
|
||||
* The STS file this wave vendors, loaded as the handler loads it: the three operations resolve,
|
||||
* their required members report in the model's order, and the two lists resolve to their
|
||||
* members. {@code GetSessionToken} declares no required member, so a request naming none of
|
||||
* them breaks nothing.
|
||||
*/
|
||||
@Test
|
||||
void theVendoredStsFileLoadsAndCarriesTheOperationsThisWaveClaims() {
|
||||
QueryConstraintCheck sts =
|
||||
QueryConstraintCheck.load("aws/sts-request-shapes.json", "STS request shapes");
|
||||
|
||||
assertEquals(List.of("Value null at 'accessKeyId' failed to satisfy constraint: Member must"
|
||||
+ " not be null"),
|
||||
sts.violations("GetAccessKeyInfo", params()));
|
||||
|
||||
assertEquals(List.of(
|
||||
"Value null at 'audience' failed to satisfy constraint: Member must not be null",
|
||||
"Value null at 'signingAlgorithm' failed to satisfy constraint: Member must not be"
|
||||
+ " null"),
|
||||
sts.violations("GetWebIdentityToken", params()));
|
||||
|
||||
assertEquals(List.of(), sts.violations("GetSessionToken", params()));
|
||||
assertEquals(List.of("Value 'short' at 'serialNumber' failed to satisfy constraint: Member"
|
||||
+ " must have length greater than or equal to 9"),
|
||||
sts.violations("GetSessionToken", params("SerialNumber", "short")),
|
||||
"a member nothing read until this wave resolves to its own shape");
|
||||
|
||||
assertEquals(List.of("Value null at 'tags.1.member.value' failed to satisfy constraint:"
|
||||
+ " Member must not be null"),
|
||||
sts.violations("GetWebIdentityToken", params("Audience.member.1", "app",
|
||||
"SigningAlgorithm", "RS256", "Tags.member.1.Key", "Team")),
|
||||
"a tag is a list of structures, named under the index the request spelled");
|
||||
}
|
||||
}
|
||||
@@ -153,6 +153,50 @@ class StsQueryHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A duration the constraint check accepted is the duration the caller gets. The check reads a
|
||||
* Query number with the whitespace around it off, so a padded value passes its range, and the
|
||||
* read behind it takes it off as well: parsing the raw value would throw and fall back to the
|
||||
* default, so a request asking for an hour would have been handed the twelve hours
|
||||
* {@code GetSessionToken} defaults to, or the five minutes a web identity token defaults to.
|
||||
*/
|
||||
@Test
|
||||
void aPaddedDurationIsTheOneAskedForRatherThanTheDefault() {
|
||||
Instant now = Instant.parse("2026-01-01T00:00:00Z");
|
||||
Clock clock = Clock.fixed(now, ZoneOffset.UTC);
|
||||
IamService iamService = mock(IamService.class);
|
||||
StsQueryHandler sessions =
|
||||
newHandler(iamService, new RegionResolver(REGION, "000000000000"), clock);
|
||||
setCaller(sessions, "AKIAlongterm", "-");
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("DurationSeconds", " 3600 ");
|
||||
|
||||
Response session = sessions.handle("GetSessionToken", params);
|
||||
|
||||
assertEquals(200, session.getStatus(), (String) session.getEntity());
|
||||
assertEquals("2026-01-01T01:00:00Z", extract(EXPIRATION, (String) session.getEntity()));
|
||||
|
||||
when(iamService.findEnabledOutboundWebIdentityFederation())
|
||||
.thenReturn(Optional.of(enabledFederation()));
|
||||
WebIdentityTokenIssuer tokenIssuer = mock(WebIdentityTokenIssuer.class);
|
||||
when(tokenIssuer.mint(any(), anyString(), anyString(), anyList(), any(), any(), any()))
|
||||
.thenReturn("header.claims.signature");
|
||||
StsQueryHandler tokens = newHandler(iamService, new RegionResolver(REGION, "000000000000"),
|
||||
clock, mock(DelegationRequestService.class), tokenIssuer);
|
||||
setCaller(tokens, "AKIAlongterm", "-");
|
||||
|
||||
MultivaluedMap<String, String> tokenParams = new MultivaluedHashMap<>();
|
||||
tokenParams.putSingle("Audience.member.1", "app");
|
||||
tokenParams.putSingle("SigningAlgorithm", "RS256");
|
||||
tokenParams.putSingle("DurationSeconds", " 1800 ");
|
||||
|
||||
Response token = tokens.handle("GetWebIdentityToken", tokenParams);
|
||||
|
||||
assertEquals(200, token.getStatus(), (String) token.getEntity());
|
||||
assertEquals("2026-01-01T00:30:00Z", extract(EXPIRATION, (String) token.getEntity()));
|
||||
}
|
||||
|
||||
/** The account's federation state with the feature on, which the operation reads the issuer from. */
|
||||
private static OutboundWebIdentityFederation enabledFederation() {
|
||||
OutboundWebIdentityFederation federation = new OutboundWebIdentityFederation();
|
||||
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* The declared constraints STS reads from its model rather than from a check written by hand.
|
||||
*
|
||||
* <p>Three operations are read that way. {@code GetAccessKeyInfo} is the parity case: its own check
|
||||
* answered {@code accessKeyId} from the same bounds and the same pattern, and what changes is that
|
||||
* a value breaking both is answered for both, which is the reading #6402 settled for this package.
|
||||
* {@code GetSessionToken} brings members nothing read at all, so a {@code SerialNumber}, a
|
||||
* {@code TokenCode} or a {@code MinimumSessionTokenSize} outside its shape answers 400 where it
|
||||
* used to be accepted and ignored. {@code GetWebIdentityToken} keeps every message it already
|
||||
* answered, {@link WebIdentityTokenIntegrationTest} holding those, and what is new here is where
|
||||
* the two signing algorithms the reference names are reported once the model holds the rest.
|
||||
*
|
||||
* <p>What the model does not say is what counts as a number: a value that is no number at all
|
||||
* stays this package's own {@code InvalidParameterValue}, and a digit string is held to the range
|
||||
* whatever width it overflows.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class StsRequestConstraintsIntegrationTest {
|
||||
|
||||
private static final String STS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261027/us-east-1/sts/aws4_request";
|
||||
|
||||
private static final String CODE = "ErrorResponse.Error.Code";
|
||||
private static final String MESSAGE = "ErrorResponse.Error.Message";
|
||||
private static final String SESSION_KEY =
|
||||
"GetSessionTokenResponse.GetSessionTokenResult.Credentials.AccessKeyId";
|
||||
|
||||
private static RequestSpecification sts(String action) {
|
||||
return given().header("Authorization", STS_AUTH).formParam("Action", action);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code serialNumberType} and {@code tokenCodeType} are declared and were read by nothing, so
|
||||
* a request naming either is now held to it. Both are reported together, in the order the model
|
||||
* lists them, and a well-formed pair is still accepted and still unused: the MFA check itself
|
||||
* is not built.
|
||||
*/
|
||||
@Test
|
||||
void theMfaMembersAreReadWhereNothingReadThemBefore() {
|
||||
sts("GetSessionToken")
|
||||
.formParam("SerialNumber", "Serial#")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, equalTo("2 validation errors detected: Value 'Serial#' at"
|
||||
+ " 'serialNumber' failed to satisfy constraint: Member must have length"
|
||||
+ " greater than or equal to 9; Value 'Serial#' at 'serialNumber' failed to"
|
||||
+ " satisfy constraint: Member must satisfy regular expression pattern:"
|
||||
+ " [\\w+=/:,.@-]*"));
|
||||
|
||||
sts("GetSessionToken")
|
||||
.formParam("SerialNumber", "bad#serial")
|
||||
.formParam("TokenCode", "12345")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.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"));
|
||||
|
||||
sts("GetSessionToken")
|
||||
.formParam("TokenCode", "abcdef")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value 'abcdef' at 'tokenCode' failed to satisfy"
|
||||
+ " constraint: Member must satisfy regular expression pattern: [\\d]*"));
|
||||
|
||||
sts("GetSessionToken")
|
||||
.formParam("SerialNumber", "arn:aws:iam::000000000000:mfa/user")
|
||||
.formParam("TokenCode", "123456")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(SESSION_KEY, containsString("ASIA"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code MinimumSessionTokenSize} is 0 to 4096, which {@code AssumeRoot} already answered from
|
||||
* a check of its own and this operation answered not at all. The size it asks for is still
|
||||
* ignored here, the token staying the length this emulator mints, which is a gap of its own.
|
||||
*/
|
||||
@Test
|
||||
void aMinimumSessionTokenSizeOutsideItsRangeIsRefused() {
|
||||
sts("GetSessionToken")
|
||||
.formParam("MinimumSessionTokenSize", "4097")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, equalTo("1 validation error detected: Value '4097' at"
|
||||
+ " 'minimumSessionTokenSize' failed to satisfy constraint: Member must have"
|
||||
+ " value less than or equal to 4096"));
|
||||
|
||||
sts("GetSessionToken")
|
||||
.formParam("MinimumSessionTokenSize", "two thousand")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("InvalidParameterValue"))
|
||||
.body(MESSAGE, containsString("Value two thousand for parameter"
|
||||
+ " MinimumSessionTokenSize is invalid. Reason: Must be an integer."));
|
||||
|
||||
sts("GetSessionToken")
|
||||
.formParam("MinimumSessionTokenSize", "1024")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* The range is the model's and reads the same as the check it replaces. A digit string too
|
||||
* large for an {@code int} is a number all the same, so it breaks the maximum rather than
|
||||
* answering that it is no integer, which is the reading #6625 settled for an oversized
|
||||
* {@code MaxItems}.
|
||||
*/
|
||||
@Test
|
||||
void theDurationKeepsItsAnswerAndAnOversizedOneIsHeldToItsRange() {
|
||||
sts("GetSessionToken")
|
||||
.formParam("DurationSeconds", "899")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, equalTo("1 validation error detected: Value '899' at 'durationSeconds'"
|
||||
+ " failed to satisfy constraint: Member must have value greater than or equal"
|
||||
+ " to 900"));
|
||||
|
||||
sts("GetSessionToken")
|
||||
.formParam("DurationSeconds", "99999999999")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, containsString("Value '99999999999' at 'durationSeconds' failed to"
|
||||
+ " satisfy constraint: Member must have value less than or equal to 129600"));
|
||||
|
||||
sts("GetSessionToken")
|
||||
.formParam("DurationSeconds", "notanumber")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("InvalidParameterValue"))
|
||||
.body(MESSAGE, containsString("Reason: Must be an integer."));
|
||||
}
|
||||
|
||||
/**
|
||||
* The id's own check stopped at the first constraint it broke. The model reports every one,
|
||||
* which is what AWS answers in a single message, so an id that is both too short and outside
|
||||
* its pattern is answered for both.
|
||||
*/
|
||||
@Test
|
||||
void anAccessKeyIdBreakingTwoConstraintsIsAnsweredForBoth() {
|
||||
sts("GetAccessKeyInfo")
|
||||
.formParam("AccessKeyId", "AKIA-SHORT")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, equalTo("2 validation errors detected: Value 'AKIA-SHORT' at"
|
||||
+ " 'accessKeyId' failed to satisfy constraint: Member must have length greater"
|
||||
+ " than or equal to 16; Value 'AKIA-SHORT' at 'accessKeyId' failed to satisfy"
|
||||
+ " constraint: Member must satisfy regular expression pattern: [\\w]*"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code jwtAlgorithmType} publishes a length and no enum, so the two values the reference
|
||||
* names are a reading. It is reported where that member sits in the model rather than after
|
||||
* the members listed below it, and a value the declared length already refuses is not read
|
||||
* against the set as well.
|
||||
*/
|
||||
@Test
|
||||
void theDocumentedSigningAlgorithmsAreReportedWhereTheMemberSits() {
|
||||
sts("GetWebIdentityToken")
|
||||
.formParam("Audience.member.1", "app")
|
||||
.formParam("SigningAlgorithm", "HS256")
|
||||
.formParam("Tags.member.1.Key", "Team")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, equalTo("2 validation errors detected: Value 'HS256' at"
|
||||
+ " 'signingAlgorithm' failed to satisfy constraint: Member must satisfy enum"
|
||||
+ " value set: [RS256, ES384]; Value null at 'tags.1.member.value' failed to"
|
||||
+ " satisfy constraint: Member must not be null"));
|
||||
|
||||
sts("GetWebIdentityToken")
|
||||
.formParam("Audience.member.1", "app")
|
||||
.formParam("SigningAlgorithm", "HS25")
|
||||
.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"))
|
||||
.body(MESSAGE, not(containsString("enum value set")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The operation's own refusals keep running first: session credentials cannot ask for a session
|
||||
* token, and that is the answer whatever else the request carries.
|
||||
*/
|
||||
@Test
|
||||
void aSessionCredentialIsStillRefusedAheadOfTheConstraints() {
|
||||
String sessionKey = sts("GetSessionToken").when().post("/").then().statusCode(200)
|
||||
.extract().path(SESSION_KEY);
|
||||
|
||||
given()
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + sessionKey
|
||||
+ "/20261027/us-east-1/sts/aws4_request")
|
||||
.formParam("Action", "GetSessionToken")
|
||||
.formParam("SerialNumber", "Serial#")
|
||||
.when().post("/").then().statusCode(403)
|
||||
.body(CODE, equalTo("AccessDenied"))
|
||||
.body(MESSAGE, containsString("Cannot call GetSessionToken with session credentials"));
|
||||
}
|
||||
}
|
||||
@@ -12,17 +12,14 @@ Run from anywhere in the repo:
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from regen_partitions import resolve_botocore_data, strip_source
|
||||
from request_shapes import REPO_ROOT, build_constraints, load_model
|
||||
import request_shapes
|
||||
from request_shapes import REPO_ROOT
|
||||
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-request-shapes.json"
|
||||
MODEL = Path("iam/2010-05-08")
|
||||
GENERATOR = "tools/aws/regen_iam_shapes.py"
|
||||
|
||||
# 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
|
||||
@@ -71,10 +68,10 @@ PAGING_ONLY = (
|
||||
)
|
||||
|
||||
|
||||
def paging_only(model: dict) -> dict:
|
||||
"""`model` with each `PAGING_ONLY` request reduced to its paging members."""
|
||||
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."""
|
||||
shapes = dict(model["shapes"])
|
||||
for operation in PAGING_ONLY:
|
||||
for operation in operations:
|
||||
name = model["operations"][operation]["input"]["shape"]
|
||||
request = shapes[name]
|
||||
shapes[name] = {"type": request["type"],
|
||||
@@ -82,32 +79,13 @@ def paging_only(model: dict) -> dict:
|
||||
return {**model, "shapes": shapes}
|
||||
|
||||
|
||||
def build(model: dict, provenance: str) -> dict:
|
||||
return build_constraints(paging_only(model), OPERATIONS + PAGING_ONLY, provenance, GENERATOR)
|
||||
|
||||
|
||||
def render(doc: dict) -> str:
|
||||
return json.dumps(doc, indent=2) + "\n"
|
||||
# What the vendored file carries: the operations read whole, then the paged ones read in part.
|
||||
VENDORED = OPERATIONS + PAGING_ONLY
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
|
||||
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
data, provenance = resolve_botocore_data(args.botocore_data)
|
||||
fresh = render(build(load_model(data, MODEL), provenance))
|
||||
if args.check:
|
||||
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
|
||||
if strip_source(current) != strip_source(fresh):
|
||||
print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
args.output.write_text(fresh, encoding="utf-8")
|
||||
shown = args.output.relative_to(REPO_ROOT) if args.output.is_relative_to(REPO_ROOT) else args.output
|
||||
print(f"wrote {shown} from {provenance}")
|
||||
return 0
|
||||
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
|
||||
description=__doc__, operations=VENDORED, prepare=paging_only)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Vendor STS request constraints from botocore's Apache-2.0 service model.
|
||||
|
||||
`StsRequestShapes` checks the operations listed here against the vendored file through the shared
|
||||
`QueryConstraintCheck`, the same walk IAM reads its own file with: required members, lengths,
|
||||
patterns, enum values and ranges, 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.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_sts_shapes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_sts_shapes.py --check # exit 1 when the vendored file is stale
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import request_shapes
|
||||
from request_shapes import REPO_ROOT
|
||||
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/sts-request-shapes.json"
|
||||
MODEL = Path("sts/2011-06-15")
|
||||
|
||||
# One wave per group, each chosen so that no operation in it answers a declared constraint in a
|
||||
# wording of its own, which is what keeps the vendored shapes adding the refusals AWS answers
|
||||
# rather than rewording an answer already given.
|
||||
#
|
||||
# `GetAccessKeyInfo` is the parity case: its hand-written check already answered `accessKeyId` in
|
||||
# Smithy's form, from the same bounds and the same pattern. `GetSessionToken` and
|
||||
# `GetWebIdentityToken` are the first read through the list walk. `SerialNumber`, `TokenCode` and
|
||||
# `MinimumSessionTokenSize` are read by nothing at all today, and the audience and tag checks the
|
||||
# token operation carried by hand named their members the way this file's walk does.
|
||||
#
|
||||
# The seven that are left all answer an absent member through `validateRequired`, which names the
|
||||
# parameter as the request writes it rather than as a constraint message spells it, so taking one
|
||||
# over rewords an answer already merged.
|
||||
OPERATIONS = (
|
||||
"GetAccessKeyInfo",
|
||||
"GetSessionToken",
|
||||
"GetWebIdentityToken",
|
||||
)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
|
||||
description=__doc__, operations=OPERATIONS)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -7,6 +7,8 @@
|
||||
shape of every operation, reduced to the members carried in the JSON body, and for every shape
|
||||
reachable from one, its type and the shapes of its members, list elements or map values.
|
||||
`regen_emr_serverless_shapes.py` keeps every operation's output shape too, with `outputs=True`.
|
||||
`regen_iam_shapes.py` and `regen_sts_shapes.py` name their operations instead, which switches
|
||||
`main()` to `build_constraints()`.
|
||||
|
||||
Members bound to the URI, the query string or a header are left out: they never reach the body.
|
||||
A model without such members, as DynamoDB's, comes out whole.
|
||||
@@ -16,6 +18,7 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from regen_partitions import load_model as load_json_model
|
||||
@@ -119,7 +122,19 @@ def generator_name(script: str) -> str:
|
||||
|
||||
|
||||
def main(argv: list[str] | None, *, script: str, model: Path, output: Path, description: str,
|
||||
outputs: bool = False) -> int:
|
||||
outputs: bool = False, operations: tuple[str, ...] | None = None,
|
||||
prepare: Callable[[dict], dict] | None = None) -> int:
|
||||
"""Drives one generator: parse the flags, read the model, write or check the vendored file.
|
||||
|
||||
`operations` picks the constraints flavour, keeping those operations' declared constraints
|
||||
through `build_constraints` where the default keeps every operation's member types through
|
||||
`build`. The two vendor different things and are driven the same way, which is why the
|
||||
Query-protocol generators share this too rather than each repeating the flags and the
|
||||
staleness check.
|
||||
|
||||
`prepare` is the one thing a generator may do to the model before any of that, for an operation
|
||||
it vendors in part: IAM reduces a paged request to its paging members, the rest of it keeping
|
||||
the reading it has today."""
|
||||
parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
|
||||
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
|
||||
@@ -127,7 +142,12 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path, desc
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
data, provenance = resolve_botocore_data(args.botocore_data)
|
||||
fresh = render(build(load_model(data, model), provenance, generator_name(script), outputs))
|
||||
loaded = load_model(data, model)
|
||||
if prepare is not None:
|
||||
loaded = prepare(loaded)
|
||||
generator = generator_name(script)
|
||||
fresh = render(build_constraints(loaded, operations, provenance, generator) if operations is not None
|
||||
else build(loaded, provenance, generator, outputs))
|
||||
|
||||
if args.check:
|
||||
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
"""Tests for regen_iam_shapes.
|
||||
"""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.
|
||||
|
||||
Run with: pytest tools/aws -q (or: make aws-data-test)
|
||||
"""
|
||||
@@ -6,57 +11,8 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
import regen_iam_shapes as r
|
||||
|
||||
|
||||
MODEL = {
|
||||
"operations": {
|
||||
"GetPolicy": {"input": {"shape": "GetPolicyRequest"}, "output": {"shape": "GetPolicyResponse"}},
|
||||
"ListPolicies": {"input": {"shape": "ListPoliciesRequest"}},
|
||||
},
|
||||
"shapes": {
|
||||
"GetPolicyRequest": {"type": "structure", "required": ["PolicyArn"], "members": {
|
||||
"PolicyArn": {"shape": "arnType"},
|
||||
}},
|
||||
"GetPolicyResponse": {"type": "structure", "members": {"Policy": {"shape": "arnType"}}},
|
||||
"ListPoliciesRequest": {"type": "structure", "members": {"MaxItems": {"shape": "maxItemsType"}}},
|
||||
"arnType": {"type": "string", "min": 20, "max": 2048},
|
||||
"maxItemsType": {"type": "integer", "min": 1, "max": 1000},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_keeps_only_the_listed_operations_with_their_constraints(monkeypatch):
|
||||
monkeypatch.setattr(r, "OPERATIONS", ("GetPolicy",))
|
||||
monkeypatch.setattr(r, "PAGING_ONLY", ())
|
||||
|
||||
doc = r.build(MODEL, "botocore test")
|
||||
|
||||
assert doc["_source"] == {"generator": "tools/aws/regen_iam_shapes.py", "botocore": "botocore test"}
|
||||
assert doc["operations"] == {"GetPolicy": "GetPolicyRequest"}
|
||||
assert "GetPolicyResponse" not in doc["shapes"]
|
||||
assert "maxItemsType" not in doc["shapes"]
|
||||
assert doc["shapes"]["GetPolicyRequest"] == {
|
||||
"type": "structure", "required": ["PolicyArn"], "members": {"PolicyArn": "arnType"}}
|
||||
assert doc["shapes"]["arnType"] == {"type": "string", "min": 20, "max": 2048}
|
||||
|
||||
|
||||
def test_a_misspelled_operation_is_refused_rather_than_skipped(monkeypatch):
|
||||
monkeypatch.setattr(r, "OPERATIONS", ("GetPolciy",))
|
||||
monkeypatch.setattr(r, "PAGING_ONLY", ())
|
||||
|
||||
with pytest.raises(KeyError):
|
||||
r.build(MODEL, "botocore test")
|
||||
|
||||
|
||||
def test_the_vendored_file_carries_every_listed_operation():
|
||||
doc = json.loads(r.OUTPUT.read_text(encoding="utf-8"))
|
||||
|
||||
assert sorted(doc["operations"]) == sorted(r.OPERATIONS + r.PAGING_ONLY)
|
||||
for operation, shape in doc["operations"].items():
|
||||
assert shape in doc["shapes"], operation
|
||||
from request_shapes import build_constraints
|
||||
|
||||
|
||||
def test_every_paged_operation_is_held_to_the_model():
|
||||
@@ -64,10 +20,23 @@ 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.OPERATIONS + r.PAGING_ONLY)) == []
|
||||
assert sorted(set(paged) - set(r.VENDORED)) == []
|
||||
|
||||
|
||||
def test_a_paging_only_operation_keeps_its_paging_members_alone(monkeypatch):
|
||||
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.
|
||||
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
|
||||
|
||||
|
||||
def test_a_paging_only_operation_keeps_its_paging_members_alone():
|
||||
model = {
|
||||
"operations": {"ListThings": {"input": {"shape": "ListThingsRequest"}}},
|
||||
"shapes": {
|
||||
@@ -80,45 +49,23 @@ def test_a_paging_only_operation_keeps_its_paging_members_alone(monkeypatch):
|
||||
"maxItemsType": {"type": "integer", "min": 1, "max": 1000},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(r, "OPERATIONS", ())
|
||||
monkeypatch.setattr(r, "PAGING_ONLY", ("ListThings",))
|
||||
|
||||
doc = r.build(model, "botocore test")
|
||||
# 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_check_ignores_provenance(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(r, "OPERATIONS", ("GetPolicy",))
|
||||
monkeypatch.setattr(r, "PAGING_ONLY", ())
|
||||
output = tmp_path / "shapes.json"
|
||||
output.write_text(r.render(r.build(MODEL, "botocore 0.0.1 (local/aws/botocore)")), encoding="utf-8")
|
||||
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
|
||||
monkeypatch.setattr(r, "load_model", lambda data, model: MODEL)
|
||||
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.main(["--check", "--output", str(output)]) == 0
|
||||
|
||||
|
||||
def test_check_reports_a_changed_constraint(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(r, "OPERATIONS", ("GetPolicy",))
|
||||
monkeypatch.setattr(r, "PAGING_ONLY", ())
|
||||
output = tmp_path / "shapes.json"
|
||||
changed = {**MODEL, "shapes": {**MODEL["shapes"], "arnType": {"type": "string", "min": 1, "max": 2048}}}
|
||||
output.write_text(r.render(r.build(changed, "botocore test")), encoding="utf-8")
|
||||
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
|
||||
monkeypatch.setattr(r, "load_model", lambda data, model: MODEL)
|
||||
|
||||
assert r.main(["--check", "--output", str(output)]) == 1
|
||||
|
||||
|
||||
def test_output_is_stable(monkeypatch):
|
||||
monkeypatch.setattr(r, "OPERATIONS", ("GetPolicy", "ListPolicies"))
|
||||
monkeypatch.setattr(r, "PAGING_ONLY", ())
|
||||
|
||||
first = r.render(r.build(MODEL, "botocore test"))
|
||||
second = r.render(r.build(MODEL, "botocore test"))
|
||||
|
||||
assert first == second
|
||||
assert first.endswith("\n")
|
||||
assert r.paging_only(model, ()) == model
|
||||
@@ -1,6 +1,10 @@
|
||||
"""Tests for request_shapes, the generator behind regen_dynamodb_shapes, regen_sesv2_shapes, regen_apigateway_shapes,
|
||||
regen_ecs_shapes and regen_emr_serverless_shapes, and of the constraints regen_resource_groups_shapes and
|
||||
regen_ecr_shapes vendor.
|
||||
regen_ecs_shapes and regen_emr_serverless_shapes, and of the constraints regen_resource_groups_shapes,
|
||||
regen_ecr_shapes, regen_iam_shapes and regen_sts_shapes vendor.
|
||||
|
||||
Each generator names a model, an output and, for the constraints flavour, its operations, and hands
|
||||
the rest here, so what any one of them does differently is a constant and what they all do is
|
||||
tested once.
|
||||
|
||||
Run with: pytest tools/aws -q (or: make aws-data-test)
|
||||
"""
|
||||
@@ -17,7 +21,10 @@ import regen_dynamodb_shapes
|
||||
import regen_ecr_shapes
|
||||
import regen_ecs_shapes
|
||||
import regen_emr_serverless_shapes
|
||||
import regen_iam_shapes
|
||||
import regen_resource_groups_shapes
|
||||
import regen_sesv2_shapes
|
||||
import regen_sts_shapes
|
||||
import request_shapes as r
|
||||
|
||||
|
||||
@@ -248,6 +255,118 @@ def test_build_constraints_keeps_the_named_operations_with_their_constraints():
|
||||
assert doc["shapes"]["TagMap"] == {"type": "map", "key": "Name", "value": "Kind"}
|
||||
|
||||
|
||||
def test_build_constraints_refuses_an_operation_the_model_does_not_name():
|
||||
# A misspelled name in a generator's OPERATIONS fails the generation rather than vendoring a
|
||||
# file quietly missing that operation, which --check would then call up to date.
|
||||
with pytest.raises(KeyError):
|
||||
r.build_constraints(CONSTRAINED_MODEL, ("Puut",), "botocore test", "tools/aws/regen_x_shapes.py")
|
||||
|
||||
|
||||
def _constraints_main(output: Path, *argv: str, **extra) -> int:
|
||||
return r.main(list(argv) or ["--check", "--output", str(output)], script=r.__file__,
|
||||
model=Path("svc/service-2.json"), output=output, description="test",
|
||||
operations=("Put",), **extra)
|
||||
|
||||
|
||||
def test_constraints_check_ignores_provenance(tmp_path, monkeypatch):
|
||||
output = tmp_path / "shapes.json"
|
||||
output.write_text(r.render(r.build_constraints(CONSTRAINED_MODEL, ("Put",),
|
||||
"botocore 0.0.1 (local/aws/botocore)",
|
||||
"tools/aws/regen_x_shapes.py")), encoding="utf-8")
|
||||
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
|
||||
monkeypatch.setattr(r, "load_model", lambda data, model: CONSTRAINED_MODEL)
|
||||
|
||||
assert _constraints_main(output) == 0
|
||||
|
||||
|
||||
def test_constraints_check_reports_a_changed_constraint(tmp_path, monkeypatch):
|
||||
output = tmp_path / "shapes.json"
|
||||
changed = {**CONSTRAINED_MODEL,
|
||||
"shapes": {**CONSTRAINED_MODEL["shapes"], "Name": {"type": "string", "min": 1, "max": 9}}}
|
||||
output.write_text(r.render(r.build_constraints(changed, ("Put",), "botocore test",
|
||||
"tools/aws/regen_x_shapes.py")), encoding="utf-8")
|
||||
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
|
||||
monkeypatch.setattr(r, "load_model", lambda data, model: CONSTRAINED_MODEL)
|
||||
|
||||
assert _constraints_main(output) == 1
|
||||
|
||||
|
||||
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
|
||||
# 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.
|
||||
output = tmp_path / "shapes.json"
|
||||
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
|
||||
monkeypatch.setattr(r, "load_model", lambda data, model: CONSTRAINED_MODEL)
|
||||
reduced = {**CONSTRAINED_MODEL, "shapes": {
|
||||
**CONSTRAINED_MODEL["shapes"],
|
||||
"PutRequest": {"type": "structure", "members": {"rules": {"shape": "RuleList"}}}}}
|
||||
|
||||
assert _constraints_main(output, "--output", str(output), prepare=lambda model: reduced) == 0
|
||||
|
||||
doc = json.loads(output.read_text(encoding="utf-8"))
|
||||
assert doc["shapes"]["PutRequest"] == {"type": "structure", "members": {"rules": "RuleList"}}
|
||||
# The members the reduction dropped take their shapes with them.
|
||||
assert "Name" not in doc["shapes"]
|
||||
assert _constraints_main(output, "--check", "--output", str(output),
|
||||
prepare=lambda model: reduced) == 0
|
||||
assert _constraints_main(output, "--check", "--output", str(output)) == 1
|
||||
|
||||
|
||||
def test_build_constraints_output_is_stable():
|
||||
first = r.render(r.build_constraints(CONSTRAINED_MODEL, ("Put",), "botocore test", "tools/aws/regen_x_shapes.py"))
|
||||
second = r.render(r.build_constraints(CONSTRAINED_MODEL, ("Put",), "botocore test", "tools/aws/regen_x_shapes.py"))
|
||||
|
||||
assert first == second
|
||||
assert first.endswith("\n")
|
||||
|
||||
|
||||
@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.
|
||||
(regen_iam_shapes, "iam/2010-05-08", "iam-request-shapes.json",
|
||||
{"prepare": regen_iam_shapes.paging_only}),
|
||||
(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,
|
||||
monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(r, "main", lambda argv, **kwargs: calls.append((argv, kwargs)) or 0)
|
||||
|
||||
assert script.main(["--check"]) == 0
|
||||
assert calls == [(["--check"], {
|
||||
"script": script.__file__,
|
||||
"model": Path(model),
|
||||
"output": r.REPO_ROOT / "src/main/resources/aws" / output,
|
||||
"description": script.__doc__,
|
||||
"operations": vendored(script),
|
||||
**extra,
|
||||
})]
|
||||
|
||||
|
||||
def vendored(script) -> tuple[str, ...]:
|
||||
"""The operations a generator's file carries, which is `OPERATIONS` unless it names more."""
|
||||
return getattr(script, "VENDORED", None) or script.OPERATIONS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("script", [
|
||||
regen_ecr_shapes, regen_iam_shapes, regen_resource_groups_shapes, regen_sts_shapes,
|
||||
])
|
||||
def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script):
|
||||
doc = json.loads(script.OUTPUT.read_text(encoding="utf-8"))
|
||||
|
||||
assert sorted(doc["operations"]) == sorted(vendored(script))
|
||||
for operation, shape in doc["operations"].items():
|
||||
assert shape in doc["shapes"], operation
|
||||
for name, shape in doc["shapes"].items():
|
||||
named = list(shape.get("members", {}).values())
|
||||
named.extend(shape[side] for side in ("member", "key", "value") if side in shape)
|
||||
for child in named:
|
||||
assert child in doc["shapes"], f"{name} names {child}"
|
||||
|
||||
|
||||
def test_ecr_shapes_name_the_ecr_model_and_its_registry_setting_actions():
|
||||
assert regen_ecr_shapes.MODEL == Path("ecr/2015-09-21")
|
||||
assert regen_ecr_shapes.OUTPUT.name == "ecr-request-shapes.json"
|
||||
|
||||
Reference in new issue
Block a user