fix(iam): take service-linked role names and suffix support from AWS evidence (#5293)

CreateServiceLinkedRole guessed both things it cannot derive. The role name came
from capitalising the principal, which is wrong for 141 of the 162 services the
table covers: acm.amazonaws.com is AWSServiceRoleForCertificateManager on AWS and
was AWSServiceRoleForAcm here. And a CustomSuffix was accepted for every service,
where AWS refuses one for 68 of the 71 it has been recorded against, so the
emulator minted roles AWS would have rejected outright.

Both now come from iam/service-linked-roles.tsv, generated by
tools/slr/service_linked_roles.py and gated by make slr-check. One table, because
both facts come out of one pass over the same AWS-validated snapshot: the name
from a recorded create response, the suffix verdict from the test's own
parameterisation. Writing either by hand only captures what someone noticed, and
every finding behind this change came from grepping.

Sources, each row recording its own: recording, actual create responses and the only
source that can establish suffix support; policy-documents, role ARNs in the vendored
AWS managed policies, names only; and docs, from AWS's own service-linked role
pages, quoted and linked in the generator. Counts live in the table's header, where
this script keeps them right.

Two shapes in the policy documents have to be refused rather than read, and both
were being read. A name followed by `*` is a prefix pattern: the policy writes
AWSServiceRoleForAmazonCognitoIdpEmail* where the recorded create returns
AWSServiceRoleForAmazonCognitoIdpEmailService, so reading the prefix invents a role
AWS never mints. Twenty-one principals rested on nothing but such a prefix. And a
role name is unique per account, which these documents ignore: they point
maintenance.elasticbeanstalk at the parent's AWSServiceRoleForElasticBeanstalk, so
taking that at face value made the sibling's create fail as a duplicate of a role
it does not own. A collision guard drops the weaker row back to the derived
fallback and says so; an unresolvable collision is an error for a human.

KNOWN_SOURCE_CONFLICTS is empty as a result. Its one entry was never a
disagreement between sources, only that truncated prefix read as a name. The
mechanism stays for a real one.

make slr-check runs offline: policy-documents rows must still match the vendored
JSON, every vendored service must be in the table, it must be sorted, and a suffix
verdict on a non-recording row is an error because nothing but a recording can
establish one. Three extraction traps have a test each, all three being ones the
real data walked into: an underscore can be part of a name, so splitting on the
CustomSuffix separator truncates ApplicationAutoScaling_CassandraTable; a policy
matching suffixed roles writes the prefix with a trailing separator; and a
wildcard ARN names a role without saying which principal mints it, which is how an
earlier pass handed plain GuardDuty the MalwareProtection role's name.

The name was not only wrong against AWS, it was inconsistent within the tree.
ConnectService built an ARN for AWSServiceRoleForAmazonConnect while
CreateServiceLinkedRole minted AWSServiceRoleForConnect for the same principal:
two roles for one purpose. GuardDutyService, MacieController and RamController
each hard-coded their own name too, and all four were right where IamService was
wrong. They read the table now, and a test fails if a principal any of them builds
an ARN for loses its row, since the fallback would quietly derive a name again.

ApplicationAutoScalingService was wrong a different way. It maps a namespace to a
dimension itself, and had no arm for appstream, cassandra, ec2 or sagemaker, so
all four fell to CustomResource where AWS names them AppStreamFleet,
CassandraTable, EC2SpotFleetRequest and SageMakerEndpoint. It prefers the table
now and keeps its switch for the namespaces nothing records, where the shape is
right even when the dimension is a guess. Its dynamodb arm is gone with the rest:
the table covers that namespace, so the arm was unreachable and a second copy of a
fact the table owns, free to disagree with it while never running. A test pins
dynamodb resolving through the table, since removing the arm is what left nothing
else covering it.

Two behaviour changes worth calling out. rds.amazonaws.com is AWSServiceRoleForRDS
rather than the derived Rds, which flipped one existing expectation. And two table
names are long enough that a suffix alone breaches the 64-character RoleName
limit, ApplicationDiscoveryService's ContinuousExport role leaving three
characters and SageMakerEndpoint six, so that check now reports "The role name"
rather than "The derived role name", which stopped being true.

cloud9 is in the table because deleting IamService's three-entry override map
dropped it: autoscaling and ram were covered, cloud9 was not, and it regressed to
the derived AWSServiceRoleForCloud9. Two tests caught it. Rather than restore the
literal, which is the circular sourcing this work exists to remove, its User Guide
settles it and the row carries that citation.

The table is registered in quarkus.native.resources.includes rather than exempted
from it. AwsManagedPolicies is exempt because parsing its 3.5 MB at image build time
and keeping the result in the heap beats shipping the source twice; at 13 KB that
saving is not worth depending on the static initialiser running at build time, and
NativeImageResourceIncludesTest is the thing that says so.

The header records the sha256 of the snapshot the recording rows came from, because
that half cannot be rechecked offline and --check can only say so rather than fix
it. A digest makes the next --refresh a diff against a known source: an unchanged
digest means any difference in the table came from the vendored policy documents,
and a changed one says the recordings moved with it. --check cannot verify the
digest without the snapshot, but it does reject a table that has quietly lost the
line, or one claiming no snapshot while carrying recording rows.

Refs #5084
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-08 07:49:50 -05:00
1 parent e452ce8671
commit df4fa58ea1
19 files changed
+1657 -56

No files matched your search

@@ -76,6 +76,36 @@ class ApplicationAutoScalingServiceTest {
return config;
}
/**
* Application Auto Scaling has one service-linked role per scalable dimension, and AWS names
* five of them in evidence the role table carries. Those must come from the table rather than
* from the switch below it, which has no arm for sagemaker and would fall to CustomResource.
*
* <p>The case above covers the other direction, ecs, which no recording names: it keeps the
* switch's own dimension. Without a covered namespace tested here, preferring the table was
* not pinned by anything.
*/
@Test
void aDimensionAwsNamesComesFromTheRoleTableRatherThanTheLocalSwitch() {
ScalableTarget target = service.registerScalableTarget("sagemaker",
"endpoint/my-endpoint/variant/my-variant",
"sagemaker:variant:DesiredInstanceCount", 1, 10, null, null, Map.of(), REGION);
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/"
+ "sagemaker.application-autoscaling.amazonaws.com/"
+ "AWSServiceRoleForApplicationAutoScaling_SageMakerEndpoint",
target.getRoleArn());
// dynamodb is the one namespace the switch used to name itself. Its arm is gone, so this
// is what proves the table serves it: without the case, nothing else would.
ScalableTarget fromTable = service.registerScalableTarget("dynamodb", "table/my-table",
"dynamodb:table:WriteCapacityUnits", 1, 10, null, null, Map.of(), REGION);
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/"
+ "dynamodb.application-autoscaling.amazonaws.com/"
+ "AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
fromTable.getRoleArn());
}
@Test
void registerCreatesTargetWithArnAndServiceLinkedRole() {
ScalableTarget target = register();
@@ -64,7 +64,12 @@ class ConnectIntegrationTest {
.body("Instance.InstanceAlias", equalTo("floci-integration"))
.body("Instance.InboundCallsEnabled", equalTo(true))
.body("Instance.OutboundCallsEnabled", equalTo(false))
.body("Instance.ServiceRole", containsString(":role/"))
// The service-linked role name comes from iam/service-linked-roles.tsv, where AWS
// mints AmazonConnect rather than the Connect a principal would derive. Asserted in
// full: containsString(":role/") passed whatever the name was.
.body("Instance.ServiceRole", equalTo("arn:aws:iam::000000000000:role/"
+ "aws-service-role/connect.amazonaws.com/"
+ "AWSServiceRoleForAmazonConnect_" + instanceId))
.body("Instance.InstanceAccessUrl", containsString("floci-integration"))
.body("Instance.CreatedTime", notNullValue())
.body("Instance.Tags.team", equalTo("cx"));
@@ -11,6 +11,8 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.List;
import io.quarkus.test.junit.QuarkusTest;
import static io.restassured.RestAssured.given;
@@ -238,8 +240,9 @@ class IamServiceLinkedRoleIntegrationTest {
.post("/")
.then()
.statusCode(200)
// The table carries AWS's recorded name, RDS rather than the derived Rds.
.body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName",
equalTo("AWSServiceRoleForRds"));
equalTo("AWSServiceRoleForRDS"));
given()
.formParam("Action", "CreateServiceLinkedRole")
@@ -249,6 +252,8 @@ class IamServiceLinkedRoleIntegrationTest {
.post("/")
.then()
.statusCode(200)
// No recording covers this dimension, so it keeps the derived name. The point of
// the case is that the two principals stay distinct, which holds either way.
.body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName",
equalTo("AWSServiceRoleForRdsApplicationAutoscaling"));
}
@@ -605,4 +610,136 @@ class IamServiceLinkedRoleIntegrationTest {
equalTo("arn:aws:iam::000000000000:role/aws-service-role/cloud9.amazonaws.com/"
+ "AWSServiceRoleForAWSCloud9"));
}
/**
* Most services refuse a {@code CustomSuffix}. AWS answers {@code InvalidInput} "Custom suffix
* is not allowed for &lt;service&gt;", recorded under {@code @markers.aws.validated} for 68 of
* the 71 service principals LocalStack exercises.
*/
@Test
@Order(26)
void aCustomSuffixIsRefusedByAServiceRecordedAsRefusingOne() {
for (String service : List.of("ecs.amazonaws.com", "rds.amazonaws.com",
"elasticloadbalancing.amazonaws.com")) {
given()
.formParam("Action", "CreateServiceLinkedRole")
.formParam("AWSServiceName", service)
.formParam("CustomSuffix", "debug")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message",
equalTo("Custom suffix is not allowed for " + service));
}
}
/**
* And the three that do take one still do, so the check is a denylist of what AWS was recorded
* refusing rather than a blanket refusal.
*/
@Test
@Order(27)
void theServicesRecordedAsTakingASuffixStillTakeOne() {
given()
.formParam("Action", "CreateServiceLinkedRole")
.formParam("AWSServiceName", "connect.amazonaws.com")
.formParam("CustomSuffix", "allowed")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName",
equalTo("AWSServiceRoleForAmazonConnect_allowed"));
}
/**
* A service the recordings do not cover keeps taking a suffix. This pins the decision rather
* than the behaviour: refusing an unrecorded service would be inventing AWS behaviour, and
* {@code es} is not in the recorded set at all, so it stays permitted.
*/
@Test
@Order(28)
void aServiceTheRecordingsDoNotCoverStillTakesASuffix() {
given()
.formParam("Action", "CreateServiceLinkedRole")
.formParam("AWSServiceName", "unrecordedprobe.amazonaws.com")
.formParam("CustomSuffix", "kept")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName",
equalTo("AWSServiceRoleForUnrecordedprobe_kept"));
}
/**
* Creating the same service-linked role twice is {@code InvalidInput} naming the role, not the
* parameter: "Service role name AWSServiceRoleForBatch has been taken in this account, please
* try a different suffix." Recorded against AWS for a second plain create of
* {@code batch.amazonaws.com}.
*/
@Test
@Order(29)
void creatingTheSameRoleTwiceNamesTheRoleThatIsTaken() {
given()
.formParam("Action", "CreateServiceLinkedRole")
.formParam("AWSServiceName", "takenprobe.amazonaws.com")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
given()
.formParam("Action", "CreateServiceLinkedRole")
.formParam("AWSServiceName", "takenprobe.amazonaws.com")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message",
equalTo("Service role name AWSServiceRoleForTakenprobe has been taken in this "
+ "account, please try a different suffix."));
}
/**
* A table name plus a suffix can breach the 64-character RoleName limit even though the name
* alone fits. Two entries are close enough for that to matter, and neither has a recording
* refusing a suffix, so the limit is the only thing standing between a caller and a role AWS
* could not name.
*/
@Test
@Order(30)
void aSuffixThatPushesATableNamePastTheRoleNameLimitIsRejected() {
// AWSServiceRoleForApplicationAutoScaling_SageMakerEndpoint is 57 characters, so a
// seven-character suffix is one too many.
given()
.formParam("Action", "CreateServiceLinkedRole")
.formParam("AWSServiceName", "sagemaker.application-autoscaling.amazonaws.com")
.formParam("CustomSuffix", "sevench")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message", containsString("exceeds the 64-character"));
// Six fits, and the name is the table's rather than the derived one.
given()
.formParam("Action", "CreateServiceLinkedRole")
.formParam("AWSServiceName", "sagemaker.application-autoscaling.amazonaws.com")
.formParam("CustomSuffix", "sixchr")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName",
equalTo("AWSServiceRoleForApplicationAutoScaling_SageMakerEndpoint_sixchr"));
}
}
@@ -0,0 +1,142 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Holds the tree to {@code iam/service-linked-roles.tsv}.
*
* <p>The table replaced a three-entry override map in {@link IamService} and a hard-coded name in
* each of four other services, which disagreed with it: creating the Connect role through
* {@code CreateServiceLinkedRole} gave {@code AWSServiceRoleForConnect} while
* {@code ConnectService} worked with {@code AWSServiceRoleForAmazonConnect}, two roles for one
* purpose. These cases exist so a row going missing shows up here rather than as a silent fallback
* to the derived name.
*/
class ServiceLinkedRolesTest {
/**
* The principals another service builds an ARN for. Each must be in the table: without a row,
* {@link ServiceLinkedRoles#roleName} quietly derives a name instead, which is the drift the
* table exists to end.
*/
private static final Map<String, String> CONSUMED_BY_OTHER_SERVICES = Map.of(
ServicePrincipals.of("connect"), "AWSServiceRoleForAmazonConnect",
ServicePrincipals.of("guardduty"), "AWSServiceRoleForAmazonGuardDuty",
ServicePrincipals.of("macie"), "AWSServiceRoleForAmazonMacie",
ServicePrincipals.of("ram"), "AWSServiceRoleForResourceAccessManager");
@Test
void everyPrincipalAnotherServiceBuildsAnArnForIsInTheTable() {
List<String> missing = new ArrayList<>();
for (Map.Entry<String, String> expected : CONSUMED_BY_OTHER_SERVICES.entrySet()) {
if (ServiceLinkedRoles.find(expected.getKey()).isEmpty()) {
missing.add(expected.getKey());
}
}
assertTrue(missing.isEmpty(),
"These principals are used to build a role ARN elsewhere in the tree, so a missing "
+ "row means that service and CreateServiceLinkedRole disagree about the "
+ "role name again: " + missing);
}
@Test
void theNamesThoseServicesNeedAreTheOnesAwsMints() {
for (Map.Entry<String, String> expected : CONSUMED_BY_OTHER_SERVICES.entrySet()) {
assertEquals(expected.getValue(), ServiceLinkedRoles.roleName(expected.getKey()).orElseThrow(),
expected.getKey() + " must resolve to the name AWS mints");
}
}
/** A sample of names that no capitalisation of the principal would produce. */
@Test
void aNameTheTableCarriesIsNotTheDerivedOne() {
assertEquals("AWSServiceRoleForCertificateManager",
ServiceLinkedRoles.roleName(ServicePrincipals.of("acm")).orElseThrow());
assertEquals("AWSServiceRoleForECS",
ServiceLinkedRoles.roleName(ServicePrincipals.of("ecs")).orElseThrow());
assertEquals("AWSServiceRoleForLakeFormationDataAccess",
ServiceLinkedRoles.roleName(ServicePrincipals.of("lakeformation")).orElseThrow());
assertEquals("AWSServiceRoleForAmazonGuardDutyMalwareProtection",
ServiceLinkedRoles.roleName(
ServicePrincipals.of("malware-protection.guardduty")).orElseThrow());
}
/** A principal the table does not cover keeps the name this emulator always derived. */
@Test
void anUncoveredPrincipalFallsBackToTheDerivedName() {
assertEquals("AWSServiceRoleForUnrecordedprobe",
ServiceLinkedRoles.roleName("unrecordedprobe.amazonaws.com").orElseThrow());
assertTrue(ServiceLinkedRoles.roleName("").isEmpty(),
"a principal with nothing to derive from must not become a bare prefix");
}
/** A legacy partition spelling reaches the same row. */
@Test
void aPartitionFormOfAPrincipalResolvesToTheSameRow() {
assertEquals(ServiceLinkedRoles.roleName(ServicePrincipals.of("acm")).orElseThrow(),
ServiceLinkedRoles.roleName("acm.amazonaws.com.cn").orElseThrow());
}
@Test
void suffixSupportIsWhatWasRecordedAndPermissiveWhenNothingWas() {
assertEquals(ServiceLinkedRoles.CustomSuffixSupport.ALLOWED,
ServiceLinkedRoles.customSuffixSupport(ServicePrincipals.of("autoscaling")));
assertEquals(ServiceLinkedRoles.CustomSuffixSupport.REFUSED,
ServiceLinkedRoles.customSuffixSupport(ServicePrincipals.of("ecs")));
assertEquals(ServiceLinkedRoles.CustomSuffixSupport.UNKNOWN,
ServiceLinkedRoles.customSuffixSupport("unrecordedprobe.amazonaws.com"));
}
/**
* Only a recorded create can establish suffix support, so a row from any other source must say
* {@code UNKNOWN}. The generator checks this too; it is here because this is the copy that runs.
*/
@Test
void onlyARecordingEverClaimsSuffixSupport() {
List<String> wrong = new ArrayList<>();
for (ServiceLinkedRoles.Entry entry : ServiceLinkedRoles.all().values()) {
if (!"recording".equals(entry.source())
&& entry.customSuffix() != ServiceLinkedRoles.CustomSuffixSupport.UNKNOWN) {
wrong.add(entry.principal() + " is " + entry.source() + " but claims "
+ entry.customSuffix());
}
}
assertTrue(wrong.isEmpty(), "suffix support can only come from a recorded create: " + wrong);
}
/**
* {@link ServiceLinkedRoles#all()} promises the table's own order, which is sorted by
* principal. Worth a case because the obvious way to make the map immutable, {@code Map.copyOf},
* silently does not keep it, and a failure message listing rows in hash order is harder to read.
*/
@Test
void theTableIteratesInTheOrderTheFileHasIt() {
List<String> actual = new ArrayList<>(ServiceLinkedRoles.all().keySet());
List<String> sorted = new ArrayList<>(actual);
sorted.sort(null);
assertEquals(sorted, actual, "the table is sorted by principal, so iteration should be too");
}
@Test
void theTableLoadedAndEveryNameLooksLikeAServiceLinkedRole() {
Map<String, ServiceLinkedRoles.Entry> all = ServiceLinkedRoles.all();
// A floor rather than the exact count, which belongs in the file's own header where the
// generator keeps it right. The point here is that the resource loaded at all.
assertTrue(all.size() > 100, "the table should carry the whole generated set, got " + all.size());
List<String> malformed = new ArrayList<>();
for (ServiceLinkedRoles.Entry entry : all.values()) {
if (!entry.roleName().startsWith(ServiceLinkedRoles.ROLE_NAME_PREFIX)) {
malformed.add(entry.principal() + " -> " + entry.roleName());
}
}
assertTrue(malformed.isEmpty(), "every role name starts with the AWS prefix: " + malformed);
}
}
@@ -112,4 +112,24 @@ class MacieOrganizationIntegrationTest {
+ "/20260101/us-east-1/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
/**
* GetMacieSession returns the service-linked role ARN, and its name comes from
* {@code iam/service-linked-roles.tsv}: AWS mints AmazonMacie where capitalising the principal
* would give Macie. Nothing asserted this role before, so replacing the name with a wrong one
* broke no test.
*/
@Test
void theMacieSessionReportsTheServiceLinkedRoleAwsMints() {
// requireSession answers 404 until Macie is enabled for the region.
given().contentType("application/json")
.header("Authorization", auth(ADMIN_ACCOUNT, "macie2"))
.body("{}").post("/macie").then().statusCode(200);
given().header("Authorization", auth(ADMIN_ACCOUNT, "macie2"))
.get("/macie").then().statusCode(200)
.body("serviceRole", equalTo("arn:aws:iam::" + ADMIN_ACCOUNT
+ ":role/aws-service-role/macie.amazonaws.com/"
+ "AWSServiceRoleForAmazonMacie"));
}
}