mirror of
https://github.com/floci-io/floci.git
synced 2026-11-28 08:09:43 -05:00
feat(iam): read the managed-policy family's constraints from the model (#6580)
The declared constraints on IAM's managed-policy operations are read from the pinned model rather than from a hand-written check, through the vendored data tools/aws/regen_iam_shapes.py generates and a Query walk of it. Twelve operations go first: GetPolicy, DeletePolicy, the four policy-version operations, and the six attach and detach pairs. The vendored file carries that wave rather than all 180 operations, as the ECR and Resource Groups files carry theirs, and grows a wave at a time. The machinery was already here for the JSON protocols. request_shapes build_constraints vendors required members, lengths, patterns and enums; RequestConstraintCheck walks a JSON body against them; SmithyValidationErrors already writes the awsQuery wording. What was missing is the walk a Query request needs, which is why QueryConstraintCheck sits beside RequestConstraintCheck rather than inside it: a JSON body arrives as a tree, where a Query request arrives as flat parameters named after the members that carry them, and the violations are collected into one "N validation errors detected" message in the model's member order instead of the first one being thrown. A test sends two broken members in the opposite order to the model's and gets the model's order back, so the ordering is the model's rather than the wire's. What changes for a caller is the status, in the direction #6402 settled for this package: a PolicyArn under arnType's 20 characters, a VersionId outside policyVersionIdType's pattern or an absent required member used to reach the store and answer NoSuchEntity 404, where AWS's validation layer runs ahead of the operation and answers ValidationError 400. AttachRolePolicy's RoleName is the parity case for every value but one: IamService.validateRoleName already answered it from the same bounds and the same pattern, and for a name outside its pattern the message is unchanged by the model taking it over, which a test pins. An empty name is that one value, and the one place the wording moves rather than the status. validateRoleName stops at the first constraint an empty name breaks and reports the minimum alone, where the model also reports the pattern it breaks, so these twelve operations answer two violations where they answered one. That is the reading #6402 merged for a value breaking two of its constraints, and it makes validateRoleName the drift rather than the reference. The operations still on the hand-written check keep the single violation until a later wave takes them over, which a test holds still on CreateRole so that the wave which does has to settle the wording first. Two answers are the package's own rather than new. A member breaking two constraints is reported twice, which is what #6402 merged for a ServiceSpecificCredentialId that breaks both its length and its pattern, so an empty PolicyDocument reports its minimum and its pattern. The offending value stays quoted, as SmithyValidationErrors and validateRoleName already quote it; whether current IAM quotes it at all is an open question, and reading the constraints in one place is what would make that one helper to change rather than every message in the package. Scalars only so far. An operation whose input shape carries a list or a map is refused when the vendored file loads rather than passed over with its constraints unread, since reading one means reading Name.member.N and Name.entry.N.key and naming each index as the request spelled it. A boolean is declared and holds no constraint to be read against, so a SetAsDefault that is neither true nor false still reaches the operation, which reads anything but true as false. A test pins that rather than changing it, since what AWS answers for a malformed boolean is unrecorded here.
This commit is contained in:
1 parent
4b33002784
commit
bb48983b9c
11 files changed
+1019
No files matched your search
@@ -0,0 +1,182 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Checks an AWS Query request against the constraints a {@code tools/aws/regen_*_shapes.py}
|
||||
* generator vendors from botocore through {@code request_shapes.build_constraints}: the members a
|
||||
* structure requires, a string's length, pattern and enum, and a number's range. It reads the same
|
||||
* vendored shape {@link RequestConstraintCheck} reads for the JSON protocols, and walks it
|
||||
* differently because the requests differ: a JSON body arrives as a tree, where a Query request
|
||||
* arrives as flat form parameters named after the members that carry them.
|
||||
*
|
||||
* <p>Every violation is collected rather than the first one thrown, which is what AWS's validation
|
||||
* layer answers: "N validation errors detected" with the violations in the order the model lists
|
||||
* the members, and a member that breaks two constraints reported twice. That is the reading #6402
|
||||
* merged for a `ServiceSpecificCredentialId` breaking both its length and its pattern, and
|
||||
* `docs/services/iam.md` carries it.
|
||||
*
|
||||
* <p>The offending value is quoted, which is what {@link SmithyValidationErrors#lengthOutOfRange}
|
||||
* and this package's `validateRoleName` already answer. Whether current IAM quotes it at all is
|
||||
* what DRIFT-13 asks, and the point of reading the constraints here is that one capture would
|
||||
* change one helper rather than every message in the package.
|
||||
*
|
||||
* <p>A member the request leaves out is absent, and only a required member is reported for one. A
|
||||
* member present and empty is a value: the protocol carries it, so it breaks its minimum length
|
||||
* rather than reading as absent.
|
||||
*
|
||||
* <p>Scalars only for now. An operation whose input shape carries a list or a map is refused when
|
||||
* the file loads rather than passed over quietly, since reading one means reading
|
||||
* {@code Name.member.N} and {@code Name.entry.N.key} and naming each index as the request spelled
|
||||
* it.
|
||||
*/
|
||||
public final class QueryConstraintCheck {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** The shape types a Query parameter can carry on its own, without an index or an entry. */
|
||||
private static final Set<String> SCALAR_TYPES = Set.of("string", "integer", "long", "boolean");
|
||||
|
||||
private final JsonNode operations;
|
||||
private final JsonNode shapes;
|
||||
private final Map<String, Pattern> patterns = new HashMap<>();
|
||||
|
||||
private QueryConstraintCheck(JsonNode model) {
|
||||
this.operations = model.path("operations");
|
||||
this.shapes = model.path("shapes");
|
||||
for (Map.Entry<String, JsonNode> shape : shapes.properties()) {
|
||||
if (shape.getValue().has("pattern")) {
|
||||
patterns.put(shape.getKey(), Pattern.compile(shape.getValue().get("pattern").asText()));
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> operation : operations.properties()) {
|
||||
requireScalarMembers(operation.getKey(), operation.getValue().asText());
|
||||
}
|
||||
}
|
||||
|
||||
/** The vendored resource {@code name}; {@code description} names it in a failure. */
|
||||
public static QueryConstraintCheck load(String name, String description) {
|
||||
return VendoredResources.read(name, description,
|
||||
input -> new QueryConstraintCheck(MAPPER.readTree(input)));
|
||||
}
|
||||
|
||||
public static QueryConstraintCheck of(JsonNode model) {
|
||||
return new QueryConstraintCheck(model);
|
||||
}
|
||||
|
||||
private void requireScalarMembers(String operation, String inputShape) {
|
||||
for (Map.Entry<String, JsonNode> member : shapes.path(inputShape).path("members").properties()) {
|
||||
String type = shapes.path(member.getValue().asText()).path("type").asText();
|
||||
if (!SCALAR_TYPES.contains(type)) {
|
||||
throw new IllegalStateException(operation + "'s " + member.getKey() + " is a " + type
|
||||
+ ", which this check does not read yet");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws the Query protocol's {@code ValidationError} when {@code params} breaks a constraint
|
||||
* the model declares for {@code operation}. An operation the vendored file does not carry
|
||||
* passes, which is how the file grows one wave at a time.
|
||||
*/
|
||||
public void check(String operation, MultivaluedMap<String, String> params) {
|
||||
List<String> violations = violations(operation, params);
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationError(violations);
|
||||
}
|
||||
}
|
||||
|
||||
/** The violations {@code params} carries for {@code operation}, in the model's member order. */
|
||||
public List<String> violations(String operation, MultivaluedMap<String, String> params) {
|
||||
JsonNode shape = shapes.path(operations.path(operation).asText());
|
||||
if (!shape.hasNonNull("members")) {
|
||||
return List.of();
|
||||
}
|
||||
Set<String> required = new LinkedHashSet<>();
|
||||
shape.path("required").forEach(name -> required.add(name.asText()));
|
||||
List<String> violations = new ArrayList<>();
|
||||
for (Map.Entry<String, JsonNode> member : shape.path("members").properties()) {
|
||||
String name = member.getKey();
|
||||
String value = params == null ? null : params.getFirst(name);
|
||||
String path = memberPath(name);
|
||||
if (value == null) {
|
||||
if (required.contains(name)) {
|
||||
violations.add(SmithyValidationErrors.notNull(path));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
violations.addAll(violations(member.getValue().asText(), value, path));
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
/** The member's name as a validation message spells it, which is the request's with a lower
|
||||
* first letter. */
|
||||
private static String memberPath(String name) {
|
||||
return Character.toLowerCase(name.charAt(0)) + name.substring(1);
|
||||
}
|
||||
|
||||
/** Every constraint {@code value} breaks, in the order a shape declares them. */
|
||||
private List<String> violations(String shapeName, String value, String path) {
|
||||
JsonNode shape = shapes.path(shapeName);
|
||||
String type = shape.path("type").asText();
|
||||
if ("integer".equals(type) || "long".equals(type)) {
|
||||
return single(numberViolation(shape, value, path));
|
||||
}
|
||||
if (!"string".equals(type)) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> violations = new ArrayList<>();
|
||||
String length = SmithyValidationErrors.lengthOutOfRange(path, value,
|
||||
shape.path("min").asInt(0), shape.path("max").asInt(Integer.MAX_VALUE));
|
||||
if (length != null) {
|
||||
violations.add(length);
|
||||
}
|
||||
Pattern pattern = patterns.get(shapeName);
|
||||
if (pattern != null && !pattern.matcher(value).matches()) {
|
||||
violations.add(SmithyValidationErrors.pattern(path, value, pattern.pattern()));
|
||||
}
|
||||
violations.addAll(single(enumViolation(shape, value, path)));
|
||||
return violations;
|
||||
}
|
||||
|
||||
private static List<String> single(String violation) {
|
||||
return violation == null ? List.of() : List.of(violation);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* reports it that way is the operation's own reading.
|
||||
*/
|
||||
private static String numberViolation(JsonNode shape, String value, String path) {
|
||||
long number;
|
||||
try {
|
||||
number = Long.parseLong(value.trim());
|
||||
} catch (NumberFormatException expected) {
|
||||
// Not a number at all, so no range of the model's is what it breaks.
|
||||
return null;
|
||||
}
|
||||
return SmithyValidationErrors.outOfRange(path, number,
|
||||
shape.path("min").asLong(Long.MIN_VALUE), shape.path("max").asLong(Long.MAX_VALUE));
|
||||
}
|
||||
|
||||
private static String enumViolation(JsonNode shape, String value, String path) {
|
||||
if (!shape.has("enum")) {
|
||||
return null;
|
||||
}
|
||||
List<String> allowed = new ArrayList<>();
|
||||
shape.path("enum").forEach(choice -> allowed.add(choice.asText()));
|
||||
return allowed.contains(value) ? null : SmithyValidationErrors.notInEnum(value, path, allowed);
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,12 @@ public final class SmithyValidationErrors {
|
||||
+ "Member must have length greater than or equal to " + min;
|
||||
}
|
||||
|
||||
/** The violation for a string that does not match the pattern its shape declares. */
|
||||
public static String pattern(String path, String value, String pattern) {
|
||||
return "Value '" + value + "' at '" + path + "' failed to satisfy constraint: "
|
||||
+ "Member must satisfy regular expression pattern: " + pattern;
|
||||
}
|
||||
|
||||
/** The violation for a value outside its enum, listing the allowed values in the model's order. */
|
||||
public static String notInEnum(String value, String path, List<String> allowed) {
|
||||
return "Value '" + value + "' at '" + path + "' failed to satisfy constraint: "
|
||||
|
||||
@@ -144,6 +144,7 @@ public class IamQueryHandler {
|
||||
LOG.debugv("IAM action: {0}", action);
|
||||
|
||||
try {
|
||||
IamRequestShapes.check(action, params);
|
||||
return switch (action) {
|
||||
// Users
|
||||
case "CreateUser" -> handleCreateUser(params);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.QueryConstraintCheck;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
/**
|
||||
* The declared constraints IAM reads from its model rather than from a hand-written check, as
|
||||
* {@code tools/aws/regen_iam_shapes.py} vendors them into
|
||||
* {@code aws/iam-request-shapes.json}. The check runs ahead of the operation, which is where AWS's
|
||||
* validation layer runs: a request that breaks a declared constraint is a 400 {@code
|
||||
* ValidationError} whether or not the thing it names exists, the ordering #6402 settled for this
|
||||
* package.
|
||||
*
|
||||
* <p>The vendored file carries one wave of operations rather than all 180, and grows a wave at a
|
||||
* time: the managed-policy family first, where no operation checks a declared constraint by hand,
|
||||
* so the model adds the refusals AWS answers without rewording an answer already given.
|
||||
* {@code AttachRolePolicy} and {@code DetachRolePolicy} are the exception and the parity case,
|
||||
* {@code IamService.validateRoleName} already answering {@code roleName} in the same form.
|
||||
*/
|
||||
final class IamRequestShapes {
|
||||
|
||||
private static final QueryConstraintCheck CHECK =
|
||||
QueryConstraintCheck.load("aws/iam-request-shapes.json", "IAM request shapes");
|
||||
|
||||
private IamRequestShapes() {
|
||||
}
|
||||
|
||||
/** Throws {@code ValidationError} when the request breaks a constraint the model declares. */
|
||||
static void check(String action, MultivaluedMap<String, String> params) {
|
||||
CHECK.check(action, params);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user