feat(iam): dispatch GetMFADevice, AcquireRole and GetRoleTemplateVersion (#6453)

The last three operations the IAM model publishes and Floci did not dispatch.
All three can only ever answer NoSuchEntity here, and that is the argument for
dispatching them rather than against it: a 404 both their API pages model beats
the UnsupportedOperation 400 an undispatched action answers, which no SDK maps
to anything for these operations.

GetMFADevice reads a FIDO security key. The reference says of its serial number
that "For this API, we only accept FIDO security key ARNs", and nothing in the
IAM API creates such a device: CreateVirtualMFADevice is the only operation that
mints one here and it mints an mfa/ device, so there is never a FIDO key to
find. A virtual device's serial is refused the same way, deliberately, since
answering with it would hand back a device AWS would not return for the same
request. The page models NoSuchEntity and ServiceFailure and nothing else, so
there is no validation answer to prefer over the 404.

Role templates are AWS's own. The user guide has role manager using "AWS-managed
role templates" and a role created from one with iam:AcquireRole and the
template's ARN, and the model agrees from the other side: GetRoleTemplateVersion
is the only operation that names a template and there is no create, list, update
or delete, so nothing a client can call puts a template into an account. Both
operations answer NoSuchEntity naming the ARN they were handed.
RoleTemplateDisabled is the other refusal AcquireRole models and it is not this
one: it reads "the specified role template is disabled", which is a statement
about a template that exists.

That this is a reading, and what would change it, is written into
docs/services/iam.md rather than left in a commit message. The guide publishes
the template ARNs but not their bodies, so a published body would turn those
ARNs into answers and leave the 404 for every other, and RoleManager/Enabled,
role manager's own switch, is a separate question this does not read.

The declared constraints are read before the lookup, as #6402 put them
elsewhere in this package: SerialNumber to serialNumberType's 9 to 256 and its
pattern, UserName to userNameType whenever the request carries the member, a
blank one included, the member being present whatever it holds, TemplateArn to
arnType's 20 to 2048, the two minor versions to being integers, answering
InvalidInput for a value that is not a number, and ReplacementValues to the 30
entries it declares. The ARN check is #6402's, read through one helper now
rather than copied, and the member path validation messages spell is a helper
too.

role-template leaves ResourceArnBuilder.UNRESOLVED_TYPES, which is empty now.
GetRoleTemplateVersion carries the template's ARN, so the type resolves like any
other the request names, in the aws account rather than the caller's.
AcquireRole stays on *, AWS's service reference publishing no action for it.

Eleven tests. Five on GetMFADevice: the FIDO serial reported missing rather
than unsupported, a virtual device refused and still listed afterwards, the
serial's length and pattern as counted violations, a user the account does not
hold reported instead of the device, and a blank UserName read as a value
rather than as absent, which breaks both of userNameType's constraints when it
is empty and its pattern when it is whitespace. Six on the templates: both
operations' 404s, TemplateArn under its length and absent on each, a minor
version that is not a number on each, and 31 replacement values refused where
30 reach the 404. The unresolved-types test lost a guard an empty map would
fail and gained the claim that emptied it.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-24 20:22:23 -05:00
1 parent 55b060b891
commit 32663a24ad
9 files changed
+566 -16

No files matched your search

+49 -3
View File
@@ -83,6 +83,40 @@ or at the AWS Sign-In host of a region in the deployment's partition; any other
A role `Description` is held to the shape AWS publishes for it on every action that takes one, `CreateRole`, `UpdateRole`, `UpdateRoleDescription` and `CreateServiceLinkedRole`: at most 1000 characters of `[\u0009\u000A\u000D\u0020-\u007E\u00A1-\u00FF]`, which admits tab, newline and carriage return and no other control character, otherwise `ValidationError`. The check runs before the role is looked up or created, so a refused description never reaches a stored role, and the `Role` these actions and `GetRole` answer always stays parsable XML.
### Role Templates
| Action | Description |
|--------|-------------|
| AcquireRole | Creates a role from a role template. Answers `NoSuchEntity` for every template ARN, since no account holds a template. |
| GetRoleTemplateVersion | Reads one version of a role template. Answers `NoSuchEntity` for the same reason. |
Role templates are AWS's own rather than an account's. The IAM User Guide has role manager using
"AWS-managed role templates", publishes a directory of template ARNs with the parameters each one
takes, and says versions are immutable, AWS publishing a new version rather than changing one. The
API agrees from the other side: `GetRoleTemplateVersion` is the only operation in the model that
names a template, and there is no create, list, update or delete, so nothing a client can call
puts a template into an account.
Floci therefore holds no templates, and both operations answer `NoSuchEntity` 404 naming the ARN
they were given. They are dispatched rather than left out because the alternative is worse: an
action Floci does not dispatch answers `UnsupportedOperation` 400, which neither operation models,
so a client receives an error its SDK cannot map, where the 404 is modeled by both.
This is Floci's reading of an API whose data AWS has not published, and these are the parts that
would change if it did. The guide names the template ARNs but not their bodies, so there is
nothing to answer `GetRoleTemplateVersion` with even for the ARNs in that directory; a published
body would turn those into answers and leave the 404 for every other ARN. `AcquireRole` also
models `RoleTemplateDisabled`, which Floci never answers: that error reads "the specified role
template is disabled", a statement about a template that exists, so an ARN naming none is the 404
instead. Role manager's own switch, the `RoleManager/Enabled` account property, is a separate
question and is not read here either.
The declared constraints are read before the template is looked for, which is the order AWS
validates in: `TemplateArn` is held to `arnType`'s 20 to 2048 characters, `MinorVersion` and
`TemplateMinorVersion` are held to being integers and answer `InvalidInput` for a value that is
not a number, and `ReplacementValues` is held to the 30 entries it declares. A request malformed
in any of those is a 400 rather than the 404.
### Policies
| Action | Description |
@@ -629,6 +663,7 @@ never overlap.
| DeactivateMFADevice | Detaches a device from its user, leaving the device itself in place. |
| ResyncMFADevice | Re-synchronizes an assigned device, again against two consecutive codes. |
| ListMFADevices | Lists the devices assigned to a user. |
| GetMFADevice | Reads one device by serial number. Answers `NoSuchEntity` for every serial, since the API accepts FIDO security key ARNs only and Floci mints virtual devices. |
| TagMFADevice / UntagMFADevice / ListMFADeviceTags | Manage a device's tags. |
The seed is real. `CreateVirtualMFADevice` generates a 160-bit secret from `SecureRandom` and
@@ -671,9 +706,20 @@ encoder dependency for a field whose content is derivable: it encodes
`Base32StringSeed` that *is* returned. `aws iam create-virtual-mfa-device` works against Floci with
`--bootstrap-method Base32StringSeed`, and fails only when asked for the QR code specifically.
`GetMFADevice` is not implemented: AWS states "for this API, we only accept FIDO security key
ARNs", and Floci models virtual devices only. Hardware TOTP tokens and FIDO security keys are not
modeled either, so `ListMFADevices` returns only virtual devices where AWS would return every type.
`GetMFADevice` is dispatched and answers `NoSuchEntity` for every serial number. AWS states "for
this API, we only accept FIDO security key ARNs", and nothing in the IAM API creates a FIDO key:
`CreateVirtualMFADevice` is the only operation that mints a device here and it mints an `mfa/`
one, so there is never a device for this reader to find. A virtual device's serial is refused the
same way, deliberately, because answering with it would hand back a device AWS would not return
for the same request. That 404 is also the only refusal the operation models, together with
`ServiceFailure`, which is why it is dispatched at all: an action Floci does not dispatch answers
`UnsupportedOperation` 400, and no SDK models that for this operation, so a client gets an error
it cannot map. The declared shapes are read first, so a `SerialNumber` outside 9 to 256 characters
or outside its pattern is a `ValidationError`, and a request naming a user the account does not
hold reports that user instead.
Hardware TOTP tokens and FIDO security keys are not modeled, so `ListMFADevices` returns only
virtual devices where AWS would return every type.
#### What a device does not yet affect
+1 -1
View File
@@ -23,7 +23,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 177 |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 180 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 10 |
| [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |
| [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 |
@@ -68,9 +68,19 @@ public class IamQueryHandler {
private static final int MAX_MAX_ITEMS = 1000;
/** {@code jobIDType} on every report reader: min 36 and max 36, which is a UUID string. */
private static final int JOB_ID_LENGTH = 36;
/** {@code arnType} on {@code PolicySourceArn}: 20 to 2048, with no pattern. */
/** {@code arnType} on {@code PolicySourceArn} and {@code TemplateArn}: 20 to 2048, no pattern. */
private static final int ARN_MIN_LENGTH = 20;
private static final int ARN_MAX_LENGTH = 2048;
/** {@code serialNumberType} on every MFA member: 9 to 256, pattern {@code [\w+=/:,.@-]+}. */
private static final int SERIAL_NUMBER_MIN_LENGTH = 9;
private static final int SERIAL_NUMBER_MAX_LENGTH = 256;
private static final Pattern SERIAL_NUMBER_PATTERN = Pattern.compile("[\\w+=/:,.@-]+");
/** {@code userNameType}: 1 to 64, pattern {@code [\w+=,.@-]+}. */
private static final int USER_NAME_MIN_LENGTH = 1;
private static final int USER_NAME_MAX_LENGTH = 64;
private static final Pattern USER_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]+");
/** {@code mapStringReplacementValueEntry} on {@code AcquireRole}: at most 30 entries. */
private static final int REPLACEMENT_VALUES_MAX_ENTRIES = 30;
/** {@code sortKeyType} on {@code GetOrganizationsAccessReport}. */
private static final Set<String> SORT_KEYS = Set.of("SERVICE_NAMESPACE_ASCENDING",
"SERVICE_NAMESPACE_DESCENDING", "LAST_AUTHENTICATED_TIME_ASCENDING",
@@ -159,6 +169,7 @@ public class IamQueryHandler {
case "DeactivateMFADevice" -> handleDeactivateMFADevice(params, authorization);
case "ResyncMFADevice" -> handleResyncMFADevice(params);
case "ListMFADevices" -> handleListMFADevices(params, authorization);
case "GetMFADevice" -> handleGetMFADevice(params);
case "TagMFADevice" -> handleTagMFADevice(params);
case "UntagMFADevice" -> handleUntagMFADevice(params);
case "ListMFADeviceTags" -> handleListMFADeviceTags(params);
@@ -230,6 +241,10 @@ public class IamQueryHandler {
case "ListInstanceProfileTags" -> handleListInstanceProfileTags(params);
case "ListRoleTags" -> handleListRoleTags(params);
// Role templates
case "AcquireRole" -> handleAcquireRole(params);
case "GetRoleTemplateVersion" -> handleGetRoleTemplateVersion(params);
// Managed Policies
case "CreatePolicy" -> handleCreatePolicy(params);
case "GetPolicy" -> handleGetPolicy(params);
@@ -568,6 +583,40 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("ListMFADeviceTags", AwsNamespaces.IAM, xml.build())).build();
}
/**
* {@code GetMFADevice} reads a FIDO security key, and no IAM operation creates one, so
* {@code NoSuchEntity} is the only answer it can give. The reference says of
* {@code SerialNumber} that "For this API, we only accept FIDO security key ARNs", and the
* page models that 404 and {@code ServiceFailure} and nothing else, so there is no other
* refusal to prefer for a serial naming nothing.
*
* <p>A virtual device's serial is refused the same way, deliberately.
* {@code CreateVirtualMFADevice} is the only operation here that mints a device and it mints
* one under {@code mfa/}, which is not a FIDO key, so answering with it would hand back a
* device AWS would not return for the same request. Reading one is still better than refusing
* the action outright, which is what this answered before: a 404 the SDK models beats an
* {@code UnsupportedOperation} it does not.
*
* <p>The declared shapes are read first, as the validation ahead of the operation does. A
* {@code UserName} the request carries is a value even when it is blank, the member being
* present whatever it holds, so an empty name breaks {@code userNameType}'s lower bound
* rather than reading as no name at all. The user is resolved when the request names one, an
* absent user being the same 404 under a message of its own.
*/
private Response handleGetMFADevice(MultivaluedMap<String, String> params) {
String serialNumber = requireParam(params, "SerialNumber");
requireMemberShape(serialNumber, "serialNumber", SERIAL_NUMBER_MIN_LENGTH,
SERIAL_NUMBER_MAX_LENGTH, SERIAL_NUMBER_PATTERN);
String userName = getParam(params, "UserName");
if (userName != null) {
requireMemberShape(userName, "userName", USER_NAME_MIN_LENGTH, USER_NAME_MAX_LENGTH,
USER_NAME_PATTERN);
iamService.getUser(userName);
}
throw new AwsException("NoSuchEntity",
"The MFA device with serial number " + serialNumber + " cannot be found.", 404);
}
private Response handleCreateLoginProfile(MultivaluedMap<String, String> params, String authorization) {
String userName = resolveUserName(params, authorization);
String password = getParam(params, "Password");
@@ -1482,6 +1531,68 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("ListRoleTags", AwsNamespaces.IAM, result)).build();
}
// =========================================================================
// Role templates
// =========================================================================
/**
* {@code GetRoleTemplateVersion} reads a template AWS publishes, and the model has no
* operation that creates, lists, updates or deletes one, so no account holds a template and
* {@code NoSuchEntity} is the only answer. The user guide has role manager using "AWS-managed
* role templates" and a role created from one "with the {@code iam:AcquireRole} API with the
* template's ARN", so a template is AWS's rather than the customer's, and what the guide
* publishes is a directory of template ARNs rather than their bodies: there is nothing
* recorded to answer with.
*
* <p>{@code TemplateArn} is held to its declared length first and {@code MinorVersion} is read
* as the integer it is declared to be, so a request malformed in either is the 400 ahead of
* the lookup rather than this 404.
*/
private Response handleGetRoleTemplateVersion(MultivaluedMap<String, String> params) {
String templateArn = requiredArn(params, "TemplateArn");
requireIntegerIfPresent(params, "MinorVersion");
throw noSuchRoleTemplate(templateArn);
}
/**
* {@code AcquireRole} creates a role from a template, and there is never a template to create
* it from, for the reason {@link #handleGetRoleTemplateVersion} gives, so this answers
* {@code NoSuchEntity} for the ARN it was handed.
*
* <p>{@code RoleTemplateDisabled} is the other refusal the operation models and it is not this
* one: it reads "the specified role template is disabled", which is an answer about a template
* that exists, and role manager's own switch, the {@code RoleManager/Enabled} account property,
* is a different question again. An ARN naming no template is the 404.
*/
private Response handleAcquireRole(MultivaluedMap<String, String> params) {
String templateArn = requiredArn(params, "TemplateArn");
requireIntegerIfPresent(params, "TemplateMinorVersion");
requireReplacementValuesWithinDeclaredSize(params);
throw noSuchRoleTemplate(templateArn);
}
/**
* {@code ReplacementValues} is declared with at most 30 entries, and a Query map arrives as
* {@code ReplacementValues.entry.N.key}, so the keys are counted rather than the indices
* walked: a caller numbering them sparsely still sends as many values as it sends.
*/
private static void requireReplacementValuesWithinDeclaredSize(
MultivaluedMap<String, String> params) {
long entries = params.keySet().stream()
.filter(name -> name.startsWith("ReplacementValues.entry.") && name.endsWith(".key"))
.count();
if (entries > REPLACEMENT_VALUES_MAX_ENTRIES) {
throw SmithyValidationErrors.validationError("Value at 'replacementValues' failed to "
+ "satisfy constraint: Member must have length less than or equal to "
+ REPLACEMENT_VALUES_MAX_ENTRIES);
}
}
private static AwsException noSuchRoleTemplate(String templateArn) {
return new AwsException("NoSuchEntity",
"The role template with ARN " + templateArn + " cannot be found.", 404);
}
// =========================================================================
// Managed Policies
// =========================================================================
@@ -2481,12 +2592,25 @@ public class IamQueryHandler {
if (arn == null || arn.isBlank()) {
return arn;
}
return arnOfDeclaredLength(arn, "policySourceArn");
}
/**
* A required {@code arnType} member, held to the same 20 to 2048 characters before whatever it
* names is looked up. {@code TemplateArn} is read through here on both role template
* operations, which have nothing to look it up in.
*/
private String requiredArn(MultivaluedMap<String, String> params, String name) {
return arnOfDeclaredLength(requireParam(params, name), memberPath(name));
}
private static String arnOfDeclaredLength(String arn, String path) {
if (arn.length() < ARN_MIN_LENGTH) {
throw SmithyValidationErrors.validationError("Value at 'policySourceArn' failed to satisfy "
throw SmithyValidationErrors.validationError("Value at '" + path + "' failed to satisfy "
+ "constraint: Member must have length greater than or equal to " + ARN_MIN_LENGTH);
}
if (arn.length() > ARN_MAX_LENGTH) {
throw SmithyValidationErrors.validationError("Value at 'policySourceArn' failed to satisfy "
throw SmithyValidationErrors.validationError("Value at '" + path + "' failed to satisfy "
+ "constraint: Member must have length less than or equal to " + ARN_MAX_LENGTH);
}
return arn;
@@ -3587,11 +3711,59 @@ public class IamQueryHandler {
String value = params.getFirst(name);
if (value == null || value.isBlank()) {
throw SmithyValidationErrors.validationError(
SmithyValidationErrors.notNull(Character.toLowerCase(name.charAt(0)) + name.substring(1)));
SmithyValidationErrors.notNull(memberPath(name)));
}
return value;
}
/** 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);
}
/**
* A member held to the length and the pattern its shape declares, reporting one violation per
* constraint broken and naming only the length bound the value missed, which is how every
* recorded IAM length violation reads.
*/
private static void requireMemberShape(String value, String path, int min, int max,
Pattern pattern) {
List<String> violations = new ArrayList<>();
if (value.length() < min) {
violations.add("Member must have length greater than or equal to " + min);
} else if (value.length() > max) {
violations.add("Member must have length less than or equal to " + max);
}
if (!pattern.matcher(value).matches()) {
violations.add("Member must satisfy regular expression pattern: " + pattern.pattern());
}
if (violations.isEmpty()) {
return;
}
throw SmithyValidationErrors.validationError(violations.stream()
.map(violation -> "Value at '" + path + "' failed to satisfy constraint: " + violation)
.toList());
}
/**
* An integer member read before the lookup it precedes. A value that is not a number answers
* {@code InvalidInput}, as {@code MaxItems} does, since neither of the two members read here
* publishes bounds to report a range against.
*/
private void requireIntegerIfPresent(MultivaluedMap<String, String> params, String name) {
String raw = params.getFirst(name);
if (raw == null || raw.isBlank()) {
return;
}
try {
Integer.parseInt(raw.trim());
} catch (NumberFormatException e) {
throw new AwsException("InvalidInput",
"The value " + raw + " at '" + memberPath(name) + "' is not a number.", 400);
}
}
private int getIntParam(MultivaluedMap<String, String> params, String name, int defaultValue) {
String value = params.getFirst(name);
if (value == null) return defaultValue;
@@ -249,6 +249,11 @@ public class ResourceArnBuilder {
* belongs to an action the handler does not dispatch, so there is no request to name a
* resource for.
*
* <p>Empty since {@code GetRoleTemplateVersion} was dispatched: {@code role-template} was the
* last entry and the action carries its ARN, so the type is resolved through
* {@link #IAM_ARN_PARAMETERS} like any other the request names. The map stays because the next
* action AWS publishes a type for arrives before Floci dispatches it.
*
* <p>Declared rather than implied so that a type which is neither resolved nor listed here
* fails a test naming it, instead of quietly putting that action back on {@code *}. The
* resolver's fallback for a type it does not know is the permissive answer, so a regeneration
@@ -260,8 +265,7 @@ public class ResourceArnBuilder {
* its type would leave it evaluated against {@code *}, which is the fail-open this class
* exists to close.
*/
static final Map<String, String> UNRESOLVED_TYPES = Map.of(
"role-template", "GetRoleTemplateVersion is not dispatched");
static final Map<String, String> UNRESOLVED_TYPES = Map.of();
/**
* The IAM actions whose target the request carries as an ARN, and the parameter holding it.
@@ -342,6 +346,9 @@ public class ResourceArnBuilder {
"GenerateServiceLastAccessedDetails", "ListPoliciesGrantingServiceAccess");
arnParameter(parameters, "PolicySourceArn",
"GetContextKeysForPrincipalPolicy", "SimulatePrincipalPolicy");
// AWS owns role templates, so the ARN names one in the aws account rather than the
// caller's, and it is still the resource the action is authorized against.
arnParameter(parameters, "TemplateArn", "GetRoleTemplateVersion");
return Map.copyOf(parameters);
}
@@ -145,7 +145,8 @@ class IamActionResourcesTest {
"access-report",
// Derived from an id the request carries.
"delegation-request",
// Only on actions the handler does not dispatch.
// Named by an ARN the request carries, in the aws account rather than the
// caller's.
"role-template"),
inUse,
"AWS has changed which resource types IAM actions are authorized against; "
@@ -295,9 +295,11 @@ class ResourceArnBuilderTest {
}
/**
* A policy, MFA device, SAML provider or OIDC provider is named by an ARN the request already
* carries, so it is passed through. Rebuilding it from parts would only invent a second
* spelling of the resource the caller already named.
* A policy, MFA device, SAML provider, OIDC provider or role template is named by an ARN the
* request already carries, so it is passed through. Rebuilding it from parts would only invent
* a second spelling of the resource the caller already named, and a role template's ARN could
* not be rebuilt at all: it names the {@code aws} account rather than the caller's, and
* carries a major version after a colon.
*/
@Test
void iamPassesThroughAnArnTheRequestAlreadyCarries() {
@@ -317,6 +319,10 @@ class ResourceArnBuilderTest {
assertEquals("arn:aws:iam::000000000000:user/bob",
resourceOf(builder, "Action=SimulatePrincipalPolicy"
+ "&PolicySourceArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Auser%2Fbob"));
assertEquals("arn:aws:iam::aws:role-template/ec2.amazonaws.com/AmazonEC2RoleforSSM:1",
resourceOf(builder, "Action=GetRoleTemplateVersion"
+ "&TemplateArn=arn%3Aaws%3Aiam%3A%3Aaws%3Arole-template%2F"
+ "ec2.amazonaws.com%2FAmazonEC2RoleforSSM%3A1"));
}
/**
@@ -0,0 +1,164 @@
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 two role template operations over the wire. Both answer {@code NoSuchEntity} for every ARN,
* and that is the faithful answer rather than a stub: role templates are AWS's own, the user guide
* having role manager use "AWS-managed role templates", and the model publishes no operation that
* creates, lists, updates or deletes one, so no account holds a template to read or to acquire a
* role from.
*
* <p>What these hold is that the 404 is reached the way AWS reaches it. The declared constraints
* are read first, so a malformed request is the 400 the validation ahead of the operation answers,
* and the refusal names the template rather than something else. Dispatching them at all is what
* the tests are really for: before this, both answered {@code UnsupportedOperation} 400, which no
* SDK models for either operation, where the 404 is modelled by both.
*
* <p>If AWS ever publishes the template bodies the guide's ARN directory names, these answers are
* what would change: the ARNs in that directory would have a version to return, and only those.
*/
@QuarkusTest
class RoleTemplateIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261024/us-east-1/iam/aws4_request";
/** One of the template ARNs the user guide's directory publishes, as a client would send it. */
private static final String TEMPLATE_ARN =
"arn:aws:iam::aws:role-template/ec2.amazonaws.com/AmazonEC2RoleforSSM:1";
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
}
@Test
void readingATemplateVersionIsReportedMissingRatherThanUnsupported() {
iam("GetRoleTemplateVersion")
.formParam("TemplateArn", TEMPLATE_ARN)
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"))
.body("ErrorResponse.Error.Message",
equalTo("The role template with ARN " + TEMPLATE_ARN + " cannot be found."))
.body(not(containsString("UnsupportedOperation")));
}
@Test
void acquiringARoleFromATemplateIsReportedMissingRatherThanUnsupported() {
// No state assertion to make here: the role's name comes from the template, so a request
// that is refused for naming no template names nothing to look up afterwards either.
iam("AcquireRole")
.formParam("TemplateArn", TEMPLATE_ARN)
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"))
.body("ErrorResponse.Error.Message",
equalTo("The role template with ARN " + TEMPLATE_ARN + " cannot be found."))
.body(not(containsString("UnsupportedOperation")));
}
/**
* {@code TemplateArn} is {@code arnType}, min 20, on both operations, and a value under it is
* refused on its shape before anything is looked for. The member is required, so an absent one
* is the null violation rather than the 404.
*/
@Test
void aTemplateArnOutsideItsDeclaredLengthIsAValidationError() {
for (String action : new String[] {"GetRoleTemplateVersion", "AcquireRole"}) {
iam(action).formParam("TemplateArn", "arn:aws:iam::aws")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value "
+ "at 'templateArn' failed to satisfy constraint: Member must have length "
+ "greater than or equal to 20"))
.body(not(containsString("NoSuchEntity")));
iam(action)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value "
+ "null at 'templateArn' failed to satisfy constraint: Member must not be "
+ "null"))
.body(not(containsString("NoSuchEntity")));
}
}
/**
* Each operation names its minor version differently, {@code MinorVersion} on the read and
* {@code TemplateMinorVersion} on the acquire, and both are declared integers with no bounds,
* so a value that is not a number is {@code InvalidInput} as it is for {@code MaxItems}.
*/
@Test
void aMinorVersionThatIsNotANumberIsRefusedBeforeTheTemplateIsLookedFor() {
iam("GetRoleTemplateVersion")
.formParam("TemplateArn", TEMPLATE_ARN)
.formParam("MinorVersion", "latest")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message",
equalTo("The value latest at 'minorVersion' is not a number."));
iam("AcquireRole")
.formParam("TemplateArn", TEMPLATE_ARN)
.formParam("TemplateMinorVersion", "latest")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message",
equalTo("The value latest at 'templateMinorVersion' is not a number."));
// A number is carried through to the 404, so the check is on the value and not on the
// member being present.
iam("GetRoleTemplateVersion")
.formParam("TemplateArn", TEMPLATE_ARN)
.formParam("MinorVersion", "3")
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
/**
* {@code ReplacementValues} is declared with at most 30 entries. The Query form spells a map
* as {@code ReplacementValues.entry.N.key}, and 31 of them is a length violation ahead of the
* lookup rather than a 404 that ignored them.
*/
@Test
void moreReplacementValuesThanTheDeclaredMaximumIsAValidationError() {
RequestSpecification request = iam("AcquireRole").formParam("TemplateArn", TEMPLATE_ARN);
for (int entry = 1; entry <= 31; entry++) {
request.formParam("ReplacementValues.entry." + entry + ".key", "Parameter" + entry)
.formParam("ReplacementValues.entry." + entry + ".value.Values.member.1", "v");
}
request.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at "
+ "'replacementValues' failed to satisfy constraint: Member must have length "
+ "less than or equal to 30"));
}
@Test
void thirtyReplacementValuesAreCarriedThroughToTheMissingTemplate() {
RequestSpecification request = iam("AcquireRole").formParam("TemplateArn", TEMPLATE_ARN);
for (int entry = 1; entry <= 30; entry++) {
request.formParam("ReplacementValues.entry." + entry + ".key", "Parameter" + entry)
.formParam("ReplacementValues.entry." + entry + ".value.Values.member.1", "v");
}
request.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
}
@@ -22,6 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
* <p>It matters because the failure is silent and fail-open. Dispatching such an action without
* teaching the resolver its type leaves the action evaluated against {@code *}, so a policy
* statement naming the resource never applies, which is the gap this builder exists to close.
*
* <p>The map is empty since {@code GetRoleTemplateVersion} was dispatched, so the first test
* holds nothing today and the second holds what emptied it: the type that used to be declared is
* resolved from the ARN the request carries. That one is the regression worth a test, since an
* empty map asserts nothing and dropping the parameter would put the action back on {@code *}.
*/
@QuarkusTest
class UnresolvedResourceTypesIntegrationTest {
@@ -31,8 +36,6 @@ class UnresolvedResourceTypesIntegrationTest {
@Test
void everyTypeDeclaredUnresolvedIsCarriedOnlyByActionsNobodyDispatches() {
assertFalse(ResourceArnBuilder.UNRESOLVED_TYPES.isEmpty(),
"nothing is declared unresolved any more, so this test has nothing to hold");
for (Map.Entry<String, String> declared : ResourceArnBuilder.UNRESOLVED_TYPES.entrySet()) {
Set<String> actions = actionsCarrying(declared.getKey());
assertFalse(actions.isEmpty(), declared.getKey()
@@ -55,6 +58,33 @@ class UnresolvedResourceTypesIntegrationTest {
}
}
/**
* {@code role-template} was the last declared-unresolved type, and dispatching
* {@code GetRoleTemplateVersion} is what took it out: the action carries the template's ARN,
* so the type resolves like any other the request names. Held over the wire as well as in the
* table, because the action being dispatched is half of the claim.
*/
@Test
void theTypeThatWasDeclaredUnresolvedIsResolvedFromTheArnTheRequestCarries() {
assertEquals("TemplateArn",
ResourceArnBuilder.IAM_ARN_PARAMETERS.get("GetRoleTemplateVersion"),
"GetRoleTemplateVersion no longer resolves its template from the ARN it carries, "
+ "so role-template is back to * unless it is declared unresolved again");
assertEquals(List.of("role-template"),
IamActionResources.typesOf("GetRoleTemplateVersion"),
"AWS has changed which resource type GetRoleTemplateVersion is authorized "
+ "against, so the parameter above may name the wrong thing");
Response response = given().header("Authorization", IAM_AUTH)
.formParam("Action", "GetRoleTemplateVersion")
.formParam("TemplateArn", "arn:aws:iam::aws:role-template/ec2.amazonaws.com/X:1")
.when().post("/");
assertEquals(404, response.statusCode(),
"GetRoleTemplateVersion is not dispatched any more, so role-template belongs in "
+ "UNRESOLVED_TYPES again rather than being resolved here");
assertEquals("NoSuchEntity", response.xmlPath().getString("ErrorResponse.Error.Code"));
}
private static String reason(Map.Entry<String, String> declared, String action) {
return action + " is dispatched now, so '" + declared.getKey() + "' is no longer a type "
+ "only undispatched actions carry (" + declared.getValue() + "). Resolve it in "
@@ -14,6 +14,7 @@ import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -723,4 +724,127 @@ class VirtualMfaIntegrationTest {
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("LimitExceeded"));
}
/**
* {@code GetMFADevice} reads a FIDO security key, which nothing in the IAM API creates, so the
* answer is always {@code NoSuchEntity}. That is still the answer AWS's own SDKs model for the
* operation, where refusing it outright is not, which is the whole reason it is dispatched.
*/
@Test
void aFidoKeySerialIsReportedMissingRatherThanUnsupported() {
iam("GetMFADevice")
.formParam("SerialNumber", "arn:aws:iam::000000000000:u2f/root/testFidoKey-R1234")
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"))
.body("ErrorResponse.Error.Message", equalTo("The MFA device with serial number "
+ "arn:aws:iam::000000000000:u2f/root/testFidoKey-R1234 cannot be found."));
}
/**
* A virtual device is refused the same way, deliberately. The reference says of this
* operation's serial number that "we only accept FIDO security key ARNs", and the device
* created here is an {@code mfa/} one, so answering with it would hand back a device AWS would
* not return for the same request.
*/
@Test
void aVirtualDeviceIsNotReadableAsAFidoKey() {
Device device = createDevice("mfa-fido-read-" + suffix());
iam("GetMFADevice")
.formParam("SerialNumber", device.serialNumber())
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
// And it is still the user's device, listed as before: the refusal reads nothing out and
// changes nothing.
String userName = createUser("mfa-fido-read-user-" + suffix());
enable(userName, device);
iam("ListMFADevices").formParam("UserName", userName)
.when().post("/").then()
.statusCode(200)
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.SerialNumber",
equalTo(device.serialNumber()));
}
/**
* The declared shapes are read before the device is looked for, as the validation ahead of the
* operation does. {@code serialNumberType} is 9 to 256 with a pattern, so a short serial and
* one carrying a character outside it are each a counted violation, and a value breaking both
* is two.
*/
@Test
void aSerialOutsideItsDeclaredShapeIsAValidationError() {
iam("GetMFADevice").formParam("SerialNumber", "u2f/root")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at "
+ "'serialNumber' failed to satisfy constraint: Member must have length "
+ "greater than or equal to 9"));
iam("GetMFADevice").formParam("SerialNumber", "u2f root key!")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at "
+ "'serialNumber' failed to satisfy constraint: Member must satisfy regular "
+ "expression pattern: [\\w+=/:,.@-]+"));
iam("GetMFADevice").formParam("SerialNumber", "u2f key!")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Message", startsWith("2 validation errors detected"));
}
/**
* A {@code UserName} the request carries is read as a value even when it is blank, because the
* member is present whatever it holds: an empty name breaks both of {@code userNameType}'s
* constraints and a whitespace one breaks its pattern. Reading a blank name as no name would
* answer for the device under a name AWS would never accept, and would skip the user
* resolution the request asked for.
*/
@Test
void aBlankUserNameIsReadAsAValueRatherThanAsAbsent() {
iam("GetMFADevice")
.formParam("SerialNumber", "arn:aws:iam::000000000000:u2f/root/testFidoKey-R1234")
.formParam("UserName", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("2 validation errors detected: Value at "
+ "'userName' failed to satisfy constraint: Member must have length greater "
+ "than or equal to 1; Value at 'userName' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: [\\w+=,.@-]+"));
iam("GetMFADevice")
.formParam("SerialNumber", "arn:aws:iam::000000000000:u2f/root/testFidoKey-R1234")
.formParam("UserName", " ")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at "
+ "'userName' failed to satisfy constraint: Member must satisfy regular "
+ "expression pattern: [\\w+=,.@-]+"));
}
/**
* The user is resolved when the request names one, because an absent user is the same
* {@code NoSuchEntity} under a message of its own, and the user this operation reads a device
* for is the one half of the request that can exist.
*/
@Test
void aUserTheAccountDoesNotHoldIsReportedBeforeTheDevice() {
String missing = "mfa-fido-nobody-" + suffix();
iam("GetMFADevice")
.formParam("SerialNumber", "arn:aws:iam::000000000000:u2f/root/testFidoKey-R1234")
.formParam("UserName", missing)
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"))
.body("ErrorResponse.Error.Message",
equalTo("The user with name " + missing + " cannot be found."));
}
}