Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Priamo Germosendf4fa58ea17d
diff --git a/.github/workflows/partition-literals.yml b/.github/workflows/partition-literals.yml
index 20402a3462..0634952d03 100644
--- a/.github/workflows/partition-literals.yml
+++ b/.github/workflows/partition-literals.yml
@@ -17,6 +17,9 @@ on:
- 'src/main/resources/aws/**'
- 'tools/partition/**'
- 'tools/aws/**'
+ - 'tools/slr/**'
+ - 'src/main/resources/iam/service-linked-roles.tsv'
+ - 'src/main/resources/iam/managed-policy-documents.json'
- 'Makefile'
- '.github/workflows/partition-literals.yml'
push:
@@ -27,6 +30,9 @@ on:
- 'src/main/resources/aws/**'
- 'tools/partition/**'
- 'tools/aws/**'
+ - 'tools/slr/**'
+ - 'src/main/resources/iam/service-linked-roles.tsv'
+ - 'src/main/resources/iam/managed-policy-documents.json'
- 'Makefile'
- '.github/workflows/partition-literals.yml'
@@ -90,3 +96,13 @@ jobs:
- name: Check the vendored IAM namespace list is well-formed
run: make iam-namespaces-check
+ # Also offline: the service-linked role table is checked against the vendored managed
+ # policy documents in the repository, never against AWS. The half that comes from a
+ # recorded create cannot be re-derived without the snapshot, which is why every row in
+ # the table carries the source it rests on.
+ - name: Run the service-linked role generator tests
+ run: make slr-test
+
+ - name: Check the service-linked role table against the vendored policy documents
+ run: make slr-check
+
diff --git a/Makefile b/Makefile
index acb82aa1f7..0adb2079ef 100644
--- a/Makefile
+++ b/Makefile
@@ -44,6 +44,7 @@ PREFIX ?= $(HOME)/.local
.DEFAULT_GOAL := help
.PHONY: help dev build test native native-host run-native native-install native-image native-up native-down native-logs clean-sidecars clean-volumes compat docker-tests \
docs-sync docs-check docs-test partition-check partition-baseline partition-audit partition-test \
+ slr-check slr-table slr-audit slr-test \
aws-data-sync aws-data-check aws-data-test \
iam-namespaces-sync iam-namespaces-check iam-namespaces-verify iam-namespaces-test
@@ -174,6 +175,28 @@ partition-audit: ## Print the per-package table of remaining partition literals
partition-test: ## Run the partition tooling's unit tests
$(PYTHON) -m pytest tools/partition -q
+slr-check: ## CI gate: the service-linked role table must match the vendored AWS data
+ @$(PYTHON) tools/slr/service_linked_roles.py --check || { \
+ echo ""; \
+ echo "error: src/main/resources/iam/service-linked-roles.tsv drifted (see above)."; \
+ echo " Run 'make slr-table SNAPSHOT=<localstack iam snapshot>' and commit the result."; \
+ exit 1; \
+ }
+
+slr-table: ## Regenerate the service-linked role table from an AWS-validated snapshot
+ @test -n "$(SNAPSHOT)" || { \
+ echo "error: set SNAPSHOT to a LocalStack tests/aws/services/iam/test_iam.snapshot.json"; \
+ echo " the suffix column can only come from a recorded create"; \
+ exit 1; \
+ }
+ $(PYTHON) tools/slr/service_linked_roles.py --refresh "$(SNAPSHOT)"
+
+slr-audit: ## Print the service-linked role table, marking names that are not derivable
+ @$(PYTHON) tools/slr/service_linked_roles.py --audit
+
+slr-test: ## Run the service-linked role tooling's unit tests
+ $(PYTHON) -m pytest tools/slr -q
+
aws-data-sync: ## Regenerate src/main/resources/aws/*.json from botocore, the CDK and Terraform (commit the result)
$(PYTHON) tools/aws/regen_partitions.py
$(PYTHON) tools/aws/regen_region_facts.py
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 1f17518426..039597880d 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1249,13 +1249,28 @@ linked service to go through instead. `TagRole` and `UntagRole` are allowed, as
IAM API `DeleteServiceLinkedRole` is the only way to remove such a role — the emulator's own
`/_floci/state/reset` still clears it along with everything else.
-Three deviations to be aware of:
-
-- **The role name is derived locally and will not match AWS for most services.** AWS lets each
- linked service choose the name, and it is not computable from the service principal —
- `lex.amazonaws.com` yields `AWSServiceRoleForLexBots` there, where Floci derives
- `AWSServiceRoleForLex`. Read the name back from the create response rather than hardcoding
- it, and do not rely on a name observed locally matching the one AWS mints.
+Four deviations to be aware of:
+
+- **The role name comes from a table of AWS evidence, and is derived only where that table does
+ not reach.** The name is not computable from the service principal: `acm.amazonaws.com` is
+ `AWSServiceRoleForCertificateManager` and `lex.amazonaws.com` is `AWSServiceRoleForLexBots`,
+ where capitalising the principal would give `AWSServiceRoleForAcm` and `AWSServiceRoleForLex`.
+ `src/main/resources/iam/service-linked-roles.tsv` carries the name AWS mints, with the count in
+ its own header where the generator keeps it right, generated by
+ `tools/slr/service_linked_roles.py` and gated by `make slr-check`, and
+ each row records whether it rests on a recorded create, on a role ARN in AWS's own managed policy
+ documents, or on a cited page of AWS documentation. A principal outside the table still gets the
+ derived name, so reading the name back from the create response is still better than computing
+ it, but for a service in the table it now matches AWS.
+- **A `CustomSuffix` is refused for the services AWS is recorded refusing it.** The API Reference
+ says only that "some services do not support the CustomSuffix parameter" without listing them, so
+ the same table carries the recorded answer: 68 services reply `InvalidInput` "Custom suffix is not
+ allowed for `<service>`" and three take one, `autoscaling`, `connect` and `lexv2`. Only a recorded
+ create can establish this, so a service the recordings miss keeps taking a suffix rather than
+ being refused on an inference. Two table names are long enough that a suffix alone breaches the
+ 64-character `RoleName` limit, which is `InvalidInput` for the length rather than for the suffix.
+ Creating the same service-linked role twice is `InvalidInput` naming the role, "Service role name
+ `<name>` has been taken in this account, please try a different suffix."
- **Deletion is synchronous.** `DeleteServiceLinkedRole` completes before it returns, so the
task id it hands back is already finished and `GetServiceLinkedRoleDeletionStatus` always
reports `SUCCEEDED`. The `IN_PROGRESS`, `NOT_STARTED` and `FAILED` states never occur, and no
diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java
index 5f70a5336d..64ff2a9ea2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTr
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
+import io.github.hectorvent.floci.services.iam.ServiceLinkedRoles;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -483,10 +484,20 @@ public class ApplicationAutoScalingService {
* emulator synthesizes one in the same shape to keep the Computed attribute stable.
*/
private String serviceLinkedRoleArn(String serviceNamespace) {
+ String principal = ServicePrincipals.of(serviceNamespace + ".application-autoscaling");
+ // Application Auto Scaling has one role per scalable dimension, and AWS names five of
+ // them in evidence the table carries. The switch below is only for the namespaces nothing
+ // records, where its shape is right even when the dimension is a guess, so it carries no
+ // arm for a namespace the table covers: that would be a second copy of the same fact,
+ // unreachable and free to drift from it.
+ Optional<ServiceLinkedRoles.Entry> recorded = ServiceLinkedRoles.find(principal);
+ if (recorded.isPresent()) {
+ return regionResolver.buildGlobalArn("iam",
+ "role/aws-service-role/" + principal + "/" + recorded.get().roleName());
+ }
String suffix = switch (serviceNamespace) {
case "ecs" -> "ECSService";
case "kafka" -> "KafkaCluster";
- case "dynamodb" -> "DynamoDBTable";
case "lambda" -> "LambdaConcurrency";
case "rds" -> "RDSCluster";
case "elasticache" -> "ElastiCacheRG";
diff --git a/src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java b/src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java
index 4da9131619..cb5010b891 100644
--- a/src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.connect.model.ConnectInstance;
import io.github.hectorvent.floci.services.connect.model.ConnectStorageConfig;
+import io.github.hectorvent.floci.services.iam.ServiceLinkedRoles;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -132,8 +133,9 @@ public class ConnectService implements TagHandler {
instance.setDirectoryId(directoryId);
instance.setCreatedTime(Instant.now());
instance.setServiceRole(regionResolver.buildGlobalArn("iam",
- "role/aws-service-role/" + ServicePrincipals.of("connect")
- + "/AWSServiceRoleForAmazonConnect_" + instanceId));
+ "role/aws-service-role/" + ServicePrincipals.of("connect") + "/"
+ + ServiceLinkedRoles.roleName(ServicePrincipals.of("connect")).orElseThrow()
+ + "_" + instanceId));
instance.setInboundCallsEnabled(inboundCallsEnabled);
instance.setOutboundCallsEnabled(outboundCallsEnabled);
if (instanceAlias != null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java
index 91377384d5..dc979114be 100644
--- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature;
import io.github.hectorvent.floci.services.guardduty.model.OrganizationAdditionalConfiguration;
import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration;
import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature;
+import io.github.hectorvent.floci.services.iam.ServiceLinkedRoles;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -567,7 +568,8 @@ public class GuardDutyService {
private static String serviceRoleArn(String region, String accountId) {
return AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
- "role/aws-service-role/" + ServicePrincipals.of("guardduty") + "/AWSServiceRoleForAmazonGuardDuty")
+ "role/aws-service-role/" + ServicePrincipals.of("guardduty") + "/"
+ + ServiceLinkedRoles.roleName(ServicePrincipals.of("guardduty")).orElseThrow())
.toString();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index f117f4db20..8fb533c8ca 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -160,12 +160,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private final SecureRandom secureRandom = new SecureRandom();
private static final String SERVICE_LINKED_ROLE_PATH = "/aws-service-role/";
- private static final String SERVICE_LINKED_ROLE_NAME_PREFIX = "AWSServiceRoleFor";
- private static final Map<String, String> SERVICE_LINKED_ROLE_NAMES = Map.of(
- ServicePrincipals.of("autoscaling"), "AutoScaling",
- ServicePrincipals.of("cloud9"), "AWSCloud9",
- ServicePrincipals.of("ram"), "ResourceAccessManager"
- );
/** AWSServiceName as AWS constrains it: 1-128 characters of {@code [\w+=,.@-]}. */
private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}");
/** CustomSuffix as AWS constrains it: 1-64 characters of {@code [\w+=,.@-]}. */
@@ -1114,14 +1108,32 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
throw new AwsException("InvalidInput",
"CustomSuffix must be 1-64 characters matching [\\w+=,.@-].", 400);
}
- String roleName = SERVICE_LINKED_ROLE_NAME_PREFIX + derivedServiceName(awsServiceName)
+ // Most services refuse a suffix outright. The table carries what AWS was recorded
+ // doing, and UNKNOWN keeps taking one rather than refusing on an inference: the name
+ // as the caller sent it, since every recording used the canonical form and the two
+ // cannot be told apart from the evidence.
+ if (customSuffix != null && !customSuffix.isEmpty()
+ && ServiceLinkedRoles.customSuffixSupport(awsServiceName)
+ == ServiceLinkedRoles.CustomSuffixSupport.REFUSED) {
+ throw new AwsException("InvalidInput",
+ "Custom suffix is not allowed for " + awsServiceName, 400);
+ }
+ String baseName = ServiceLinkedRoles.roleName(awsServiceName)
+ .orElseThrow(() -> new AwsException("InvalidInput",
+ "The request must include a valid AWSServiceName, for example "
+ + "es.amazonaws.com.", 400)); // partition-literal: AWS's own message text
+ String roleName = baseName
+ (customSuffix == null || customSuffix.isEmpty() ? "" : "_" + customSuffix);
- // AWSServiceName allows 128 characters, but AWS caps RoleName at 64 — on every action that
- // takes one, and on the Role this action returns — so a longer principal would derive a
- // name AWS could not represent.
+ // AWSServiceName allows 128 characters and a CustomSuffix another 64, but AWS caps
+ // RoleName at 64, on every action that takes one and on the Role this action returns,
+ // so the two together can name a role AWS could not represent. The name is no longer
+ // always derived, now that the table carries what AWS mints, and a few of its entries are
+ // long enough that a suffix alone breaches the limit. The boundary is pinned by a test
+ // rather than counted here, since a margin quoted in a comment goes stale the moment the
+ // table changes.
if (roleName.length() > ROLE_NAME_MAX_LENGTH) {
throw new AwsException("InvalidInput",
- "The derived role name " + roleName + " exceeds the "
+ "The role name " + roleName + " exceeds the "
+ ROLE_NAME_MAX_LENGTH + "-character role name limit.", 400);
}
synchronized (resourceNameLock) {
@@ -1129,7 +1141,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// duplicate-suffix case is an InvalidInput as far as its published error list is concerned.
if (containsNameIgnoreCase(roles, IamRole::getRoleName, roleName)) {
throw new AwsException("InvalidInput",
- "A role named " + roleName + " already exists; supply a different CustomSuffix.", 400);
+ "Service role name " + roleName + " has been taken in this account, "
+ + "please try a different suffix.", 400);
}
// A legacy spelling (es.amazonaws.com.cn) names the same role, so its path and trust
// policy carry the universal principal the name was derived from.
@@ -1172,32 +1185,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return deletionTaskId;
}
- /**
- * Every dot- and hyphen-separated label contributes, because the leading one alone is not unique:
- * {@code rds.amazonaws.com} and {@code rds.application-autoscaling.amazonaws.com} are separate
- * roles on AWS, and a config declaring both must not collide on one name here.
- */
- private static String derivedServiceName(String awsServiceName) {
- // The principal may arrive in the partition form AWS accepted before the universal one
- // (es.amazonaws.com.cn); the derived name is the same either way.
- String canonicalName = SERVICE_LINKED_ROLE_NAMES.get(ServicePrincipals.canonical(awsServiceName));
- if (canonicalName != null) {
- return canonicalName;
- }
- String core = awsServiceName == null ? "" : ServicePrincipals.serviceName(awsServiceName);
- StringBuilder derived = new StringBuilder();
- for (String segment : core.split("[.-]")) {
- if (!segment.isEmpty()) {
- derived.append(Character.toUpperCase(segment.charAt(0))).append(segment.substring(1));
- }
- }
- if (derived.isEmpty()) {
- throw new AwsException("InvalidInput",
- "The request must include a valid AWSServiceName, for example es.amazonaws.com.", 400); // partition-literal: AWS's own message text
- }
- return derived.toString();
- }
-
public String getServiceLinkedRoleDeletionStatus(String deletionTaskId) {
if (deletionTaskId == null || serviceLinkedRoleDeletions.get(deletionTaskId).isEmpty()) {
throw new AwsException("NoSuchEntity",
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLinkedRoles.java b/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLinkedRoles.java
new file mode 100644
index 0000000000..c12c50122b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLinkedRoles.java
@@ -0,0 +1,144 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.core.common.ServicePrincipals;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * What AWS does with a service-linked role for a given service principal, from
+ * {@code iam/service-linked-roles.tsv}.
+ *
+ * <p>Two things about a service-linked role cannot be worked out from the principal. The role name
+ * is not a capitalisation of it: {@code acm.amazonaws.com} gives
+ * {@code AWSServiceRoleForCertificateManager}, and deriving it is wrong for most of the services
+ * the table covers. And whether the service takes a {@code CustomSuffix} varies, which the API
+ * Reference says without saying which services those are.
+ *
+ * <p>The table is generated by {@code tools/slr/service_linked_roles.py} from AWS evidence, and
+ * {@code make slr-check} gates it. Each row records the authority it rests on, so a name that
+ * nothing can confirm is visible as such rather than looking like the rest.
+ *
+ * <p>A principal the table does not cover keeps the old derived name and keeps accepting a suffix.
+ * Both are deliberate: inventing a refusal for a service no recording covers would be worse than
+ * accepting one AWS might reject, and the derived name is at least what this emulator has always
+ * returned.
+ */
+public final class ServiceLinkedRoles {
+
+ /** Whether AWS accepts a {@code CustomSuffix} for a service, as far as anything records it. */
+ public enum CustomSuffixSupport {
+ /** A recorded create accepted a suffix. */
+ ALLOWED,
+ /** A recorded create answered {@code InvalidInput} for a suffix. */
+ REFUSED,
+ /** No recording covers it, so the suffix is accepted rather than refused on a guess. */
+ UNKNOWN
+ }
+
+ /** One row: the principal, the role AWS mints, suffix support, and where that came from. */
+ public record Entry(String principal, String roleName, CustomSuffixSupport customSuffix,
+ String source) {
+ }
+
+ static final String ROLE_NAME_PREFIX = "AWSServiceRoleFor";
+ private static final String RESOURCE_NAME = "iam/service-linked-roles.tsv";
+ private static final Map<String, Entry> BY_PRINCIPAL = load();
+
+ private ServiceLinkedRoles() {
+ }
+
+ /** The row for a principal in any partition form, empty when the table does not cover it. */
+ public static Optional<Entry> find(String awsServiceName) {
+ if (awsServiceName == null) {
+ return Optional.empty();
+ }
+ return Optional.ofNullable(BY_PRINCIPAL.get(ServicePrincipals.canonical(awsServiceName)));
+ }
+
+ /**
+ * The role name AWS mints for a principal, falling back to the derived form.
+ *
+ * <p>Returns empty only when the principal carries nothing to derive a name from, which is a
+ * {@code ValidationError} for the caller to raise rather than a name of {@code AWSServiceRoleFor}.
+ */
+ public static Optional<String> roleName(String awsServiceName) {
+ Optional<Entry> entry = find(awsServiceName);
+ if (entry.isPresent()) {
+ return Optional.of(entry.get().roleName());
+ }
+ String derived = derivedRoleName(awsServiceName);
+ return ROLE_NAME_PREFIX.equals(derived) ? Optional.empty() : Optional.of(derived);
+ }
+
+ /** Suffix support for a principal, {@code UNKNOWN} when nothing records it. */
+ public static CustomSuffixSupport customSuffixSupport(String awsServiceName) {
+ return find(awsServiceName).map(Entry::customSuffix).orElse(CustomSuffixSupport.UNKNOWN);
+ }
+
+ /**
+ * The name this emulator derived before the table existed: the principal's service part with
+ * each dot- or hyphen-delimited segment capitalised. Kept as the fallback, and kept here rather
+ * than in the caller so the generator's own fallback has one counterpart to match.
+ *
+ * <p>Every label contributes, because the leading one alone is not unique:
+ * {@code rds.amazonaws.com} and {@code rds.application-autoscaling.amazonaws.com} are separate
+ * roles on AWS, and both must not collapse onto one name here.
+ */
+ static String derivedRoleName(String awsServiceName) {
+ String core = awsServiceName == null ? "" : ServicePrincipals.serviceName(awsServiceName);
+ StringBuilder derived = new StringBuilder(ROLE_NAME_PREFIX);
+ for (String segment : core.split("[.\\-]")) {
+ if (!segment.isEmpty()) {
+ derived.append(Character.toUpperCase(segment.charAt(0))).append(segment.substring(1));
+ }
+ }
+ return derived.toString();
+ }
+
+ /** Every row, in the table's order, for tests that hold the tree to it. */
+ static Map<String, Entry> all() {
+ return BY_PRINCIPAL;
+ }
+
+ private static Map<String, Entry> load() {
+ try (InputStream in = Thread.currentThread().getContextClassLoader()
+ .getResourceAsStream(RESOURCE_NAME)) {
+ if (in == null) {
+ throw new IllegalStateException(
+ "service-linked role table not found on the classpath: " + RESOURCE_NAME);
+ }
+ Map<String, Entry> rows = new LinkedHashMap<>();
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(in, StandardCharsets.UTF_8));
+ String line;
+ while ((line = reader.readLine()) != null) {
+ String trimmed = line.strip();
+ if (trimmed.isEmpty() || trimmed.startsWith("#")) {
+ continue;
+ }
+ String[] columns = trimmed.split("\t");
+ if (columns.length != 4) {
+ throw new IllegalStateException(
+ RESOURCE_NAME + " needs four tab-separated columns, got: " + trimmed);
+ }
+ Entry entry = new Entry(columns[0], columns[1],
+ CustomSuffixSupport.valueOf(columns[2].toUpperCase(Locale.ROOT)), columns[3]);
+ rows.put(entry.principal(), entry);
+ }
+ // Not Map.copyOf: that does not keep insertion order, and the table is sorted
+ // by principal, so iterating it in file order keeps a failure message readable.
+ return Collections.unmodifiableMap(rows);
+ } catch (IOException e) {
+ throw new IllegalStateException("cannot read " + RESOURCE_NAME, e);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java b/src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java
index 32cb91c1c7..179397b540 100644
--- a/src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
+import io.github.hectorvent.floci.services.iam.ServiceLinkedRoles;
import io.github.hectorvent.floci.services.macie2.model.MacieMember;
import io.github.hectorvent.floci.services.macie2.model.MacieState;
import jakarta.inject.Inject;
@@ -65,7 +66,8 @@ public class MacieController {
ObjectNode response = objectMapper.createObjectNode();
response.put("status", "ENABLED");
response.put("serviceRole", regionResolver.buildGlobalArn("iam",
- "role/aws-service-role/" + ServicePrincipals.of("macie") + "/AWSServiceRoleForAmazonMacie"));
+ "role/aws-service-role/" + ServicePrincipals.of("macie") + "/"
+ + ServiceLinkedRoles.roleName(ServicePrincipals.of("macie")).orElseThrow()));
return Response.ok(response).build();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java
index 3c92609715..a0b151a06a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.ServiceLinkedRoles;
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
import io.github.hectorvent.floci.services.ram.model.PrincipalAssociation;
import io.github.hectorvent.floci.services.ram.model.ResourceShare;
@@ -73,7 +74,8 @@ public class RamController {
public Response enableSharingWithAwsOrganization() {
String callerAccountId = regionResolver.getAccountId();
organizationsService.enableAWSServiceAccess(callerAccountId, ServicePrincipals.of("ram"));
- if (iamService.findRole(callerAccountId, "AWSServiceRoleForResourceAccessManager").isEmpty()) {
+ String ramRoleName = ServiceLinkedRoles.roleName(ServicePrincipals.of("ram")).orElseThrow();
+ if (iamService.findRole(callerAccountId, ramRoleName).isEmpty()) {
iamService.createServiceLinkedRole(ServicePrincipals.of("ram"), null,
"Allows AWS Resource Access Manager to access AWS Organizations on your behalf.");
}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 8808b4a91b..9b8f36de8b 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -50,10 +50,11 @@ quarkus:
# ClassLoader#getResourceAsStream. Quarkus's static resource analysis
# cannot detect these dynamically-built paths, so they are registered
# explicitly to ensure GraalVM includes every file in the native image.
- # The IAM managed-policy catalog (iam/*) is not listed on purpose.
- # AwsManagedPolicies parses it while the image is built and the parsed
- # catalog lives in the image heap, so the 3.5 MB of source files would
- # only be a second copy of the same data.
+ # The IAM managed-policy catalog is not listed on purpose. AwsManagedPolicies
+ # parses it while the image is built and the parsed catalog lives in the image
+ # heap, so the 3.5 MB of source files would only be a second copy of the same
+ # data. The service-linked role table is listed, because at 13 KB that saving
+ # is not worth depending on the static initialiser running at build time.
includes:
- pricing-snapshots/**
- ui/*.html
@@ -64,6 +65,7 @@ quarkus:
- kms/*.yaml
- eks/*.json
- aws/*.json
+ - iam/service-linked-roles.tsv
- cloudformation/*.json
- redshift/*.sql
- i18n/*.properties
diff --git a/src/main/resources/iam/service-linked-roles.tsv b/src/main/resources/iam/service-linked-roles.tsv
new file mode 100644
index 0000000000..ea816134c3
--- /dev/null
+++ b/src/main/resources/iam/service-linked-roles.tsv
@@ -0,0 +1,167 @@
+# Service-linked roles: the role name AWS mints for a principal, and whether the service
+# takes a CustomSuffix.
+#
+# Columns: principal, role name, suffix support, source.
+#
+# Generated by tools/slr/service_linked_roles.py. Do not hand-edit: run
+# `make slr-table` to regenerate, or `make slr-check` to see what drifted.
+#
+# Neither column can be derived from the principal. Capitalising the principal gives the
+# wrong name for 125 of these 144 services, and the API Reference says only that
+# "some services do not support the CustomSuffix parameter" without listing which.
+#
+# Suffix support is only ever known from a recorded create: `unknown` means no recording
+# covers it, and CreateServiceLinkedRole keeps taking a suffix there rather than refusing
+# on an inference. Source is the authority the row rests on, weakest last:
+#
+# recording an AWS-validated create response, and the only source for suffix
+# policy-documents a role ARN in vendored AWS managed policy documents, name only
+# docs AWS's own service-linked role page for that service, cited in
+# DOCUMENTED in the generator so the claim can be rechecked
+#
+# 144 services: 3 docs, 70 policy-documents, 71 recording / suffix 3 allowed, 68 refused, 73 unknown
+# recordings: bedf7cb0bdd1fbd9113a4aab0bd849b71db3a6987ab28836948b8fbb16712e01 (sha256 of the LocalStack tests/aws/services/iam/test_iam.snapshot.json the recording rows came from)
+access-analyzer.amazonaws.com AWSServiceRoleForAccessAnalyzer unknown policy-documents
+accountdiscovery.ssm.amazonaws.com AWSServiceRoleForAmazonSSM_AccountDiscovery refused recording
+acm.amazonaws.com AWSServiceRoleForCertificateManager refused recording
+aco-automation.amazonaws.com AWSServiceRoleForComputeOptimizerAutomation unknown policy-documents
+agent-registry.amazonaws.com AWSServiceRoleForAgentRegistry unknown policy-documents
+airflow-serverless.amazonaws.com AWSServiceRoleForAmazonMWAAServerless unknown policy-documents
+airflow.amazonaws.com AWSServiceRoleForAmazonMWAA unknown policy-documents
+apidestinations.events.amazonaws.com AWSServiceRoleForAmazonEventBridgeApiDestinations unknown policy-documents
+appfabric.amazonaws.com AWSServiceRoleForAppFabric unknown policy-documents
+application-insights.amazonaws.com AWSServiceRoleForApplicationInsights unknown policy-documents
+application-signals.cloudwatch.amazonaws.com AWSServiceRoleForCloudWatchApplicationSignals unknown policy-documents
+appmesh.amazonaws.com AWSServiceRoleForAppMesh refused recording
+apprunner.amazonaws.com AWSServiceRoleForAppRunner unknown policy-documents
+appstream.application-autoscaling.amazonaws.com AWSServiceRoleForApplicationAutoScaling_AppStreamFleet unknown policy-documents
+artifact.amazonaws.com AWSServiceRoleForArtifact unknown policy-documents
+autoscaling-plans.amazonaws.com AWSServiceRoleForAutoScalingPlans_EC2AutoScaling refused recording
+autoscaling.amazonaws.com AWSServiceRoleForAutoScaling allowed recording
+backup.amazonaws.com AWSServiceRoleForBackup refused recording
+batch.amazonaws.com AWSServiceRoleForBatch refused recording
+bedrock-agentcore.amazonaws.com AWSServiceRoleForBedrockAgentCoreGatewayNetwork unknown policy-documents
+bugbust.amazonaws.com AWSServiceRoleForBugBust unknown policy-documents
+cassandra-streams.amazonaws.com AWSServiceRoleForAmazonKeyspacesCDC unknown policy-documents
+cassandra.application-autoscaling.amazonaws.com AWSServiceRoleForApplicationAutoScaling_CassandraTable refused recording
+channels.lex.amazonaws.com AWSServiceRoleForLexChannels unknown policy-documents
+chime.amazonaws.com AWSServiceRoleForAmazonChime unknown policy-documents
+cks.kms.amazonaws.com AWSServiceRoleForKeyManagementServiceCustomKeyStores refused recording
+cloud9.amazonaws.com AWSServiceRoleForAWSCloud9 unknown docs
+cloudtrail.amazonaws.com AWSServiceRoleForCloudTrail refused recording
+codeguru-reviewer.amazonaws.com AWSServiceRoleForAmazonCodeGuruReviewer unknown policy-documents
+codestar-notifications.amazonaws.com AWSServiceRoleForCodeStarNotifications refused recording
+compute-optimizer.amazonaws.com AWSServiceRoleForComputeOptimizer unknown policy-documents
+config-conforms.amazonaws.com AWSServiceRoleForConfigConforms unknown policy-documents
+config.amazonaws.com AWSServiceRoleForConfig refused recording
+connect.amazonaws.com AWSServiceRoleForAmazonConnect allowed recording
+cost-optimization-hub.bcm.amazonaws.com AWSServiceRoleForCostOptimizationHub unknown policy-documents
+datasync.amazonaws.com AWSServiceRoleForDataSync unknown policy-documents
+delivery.logs.amazonaws.com AWSServiceRoleForLogDelivery unknown policy-documents
+devops-guru.amazonaws.com AWSServiceRoleForDevOpsGuru unknown policy-documents
+dms-fleet-advisor.amazonaws.com AWSServiceRoleForDMSFleetAdvisor refused recording
+dms.amazonaws.com AWSServiceRoleForDMSServerless refused recording
+docdb-elastic.amazonaws.com AWSServiceRoleForDocDB-Elastic refused recording
+dynamodb.application-autoscaling.amazonaws.com AWSServiceRoleForApplicationAutoScaling_DynamoDBTable unknown policy-documents
+ec2-instance-connect.amazonaws.com AWSServiceRoleForEc2InstanceConnect refused recording
+ec2.application-autoscaling.amazonaws.com AWSServiceRoleForApplicationAutoScaling_EC2SpotFleetRequest refused recording
+ec2fastlaunch.amazonaws.com AWSServiceRoleForEC2FastLaunch unknown policy-documents
+ecr.amazonaws.com AWSServiceRoleForECRTemplate refused recording
+ecs.amazonaws.com AWSServiceRoleForECS refused recording
+eks-connector.amazonaws.com AWSServiceRoleForAmazonEKSConnector refused recording
+eks-fargate.amazonaws.com AWSServiceRoleForAmazonEKSForFargate refused recording
+eks-nodegroup.amazonaws.com AWSServiceRoleForAmazonEKSNodegroup refused recording
+eks.amazonaws.com AWSServiceRoleForAmazonEKS refused recording
+elasticache.amazonaws.com AWSServiceRoleForElastiCache refused recording
+elasticbeanstalk.amazonaws.com AWSServiceRoleForElasticBeanstalk refused recording
+elasticfilesystem.amazonaws.com AWSServiceRoleForAmazonElasticFileSystem refused recording
+elasticloadbalancing.amazonaws.com AWSServiceRoleForElasticLoadBalancing refused recording
+elasticmapreduce.amazonaws.com AWSServiceRoleForEMRCleanup unknown policy-documents
+email.cognito-idp.amazonaws.com AWSServiceRoleForAmazonCognitoIdpEmailService refused recording
+emr-containers.amazonaws.com AWSServiceRoleForAmazonEMRContainers refused recording
+emrwal.amazonaws.com AWSServiceRoleForEMRWAL refused recording
+fis.amazonaws.com AWSServiceRoleForFIS refused recording
+fms.amazonaws.com AWSServiceRoleForFMS unknown policy-documents
+grafana.amazonaws.com AWSServiceRoleForAmazonGrafana refused recording
+guardduty.amazonaws.com AWSServiceRoleForAmazonGuardDuty unknown docs
+imagebuilder.amazonaws.com AWSServiceRoleForImageBuilder refused recording
+inspector.amazonaws.com AWSServiceRoleForAmazonInspector unknown policy-documents
+internetmonitor.amazonaws.com AWSServiceRoleForInternetMonitor unknown policy-documents
+iotmanagedintegrations.amazonaws.com AWSServiceRoleForIoTManagedIntegrations refused recording
+justintimeaccess.ssm.amazonaws.com AWSServiceRoleForSystemsManagerJustInTimeAccess unknown policy-documents
+kafka.amazonaws.com AWSServiceRoleForKafka refused recording
+kafkaconnect.amazonaws.com AWSServiceRoleForKafkaConnect refused recording
+lakeformation.amazonaws.com AWSServiceRoleForLakeFormationDataAccess refused recording
+lambda.amazonaws.com AWSServiceRoleForLambda unknown policy-documents
+lex.amazonaws.com AWSServiceRoleForLexBots refused recording
+lexv2.amazonaws.com AWSServiceRoleForLexV2Bots allowed recording
+license-management.marketplace.amazonaws.com AWSServiceRoleForMarketplaceLicenseManagement unknown policy-documents
+license-manager.member-account.amazonaws.com AWSServiceRoleForAWSLicenseManagerMemberAccountRole unknown policy-documents
+lightsail.amazonaws.com AWSServiceRoleForLightsail refused recording
+m2.amazonaws.com AWSServiceRoleForAWSM2 refused recording
+macie.amazonaws.com AWSServiceRoleForAmazonMacie unknown policy-documents
+malware-protection.guardduty.amazonaws.com AWSServiceRoleForAmazonGuardDutyMalwareProtection unknown docs
+memorydb.amazonaws.com AWSServiceRoleForMemoryDB refused recording
+monitoring.thinclient.amazonaws.com AWSServiceRoleForAmazonWorkSpacesThinClientMonitoring unknown policy-documents
+mq.amazonaws.com AWSServiceRoleForAmazonMQ refused recording
+mrk.kms.amazonaws.com AWSServiceRoleForKeyManagementServiceMultiRegionKeys refused recording
+neptune-graph.amazonaws.com AWSServiceRoleForNeptuneGraph unknown policy-documents
+network-firewall.amazonaws.com AWSServiceRoleForNetworkFirewall unknown policy-documents
+network.bedrock-agentcore.amazonaws.com AWSServiceRoleForBedrockAgentCoreNetwork unknown policy-documents
+notifications.amazonaws.com AWSServiceRoleForAwsUserNotifications refused recording
+notifications.ssm.amazonaws.com AWSServiceRoleForSystemsManagerNotifications unknown policy-documents
+observability.aoss.amazonaws.com AWSServiceRoleForAmazonOpenSearchServerless refused recording
+opensearchservice.amazonaws.com AWSServiceRoleForAmazonOpenSearchService refused recording
+ops.apigateway.amazonaws.com AWSServiceRoleForAPIGateway refused recording
+ops.athena.amazonaws.com AWSServiceRoleForAmazonAthena unknown policy-documents
+ops.emr-serverless.amazonaws.com AWSServiceRoleForAmazonEMRServerless refused recording
+opsdatasync.ssm.amazonaws.com AWSServiceRoleForSystemsManagerOpsDataSync refused recording
+opsinsights.ssm.amazonaws.com AWSServiceRoleForAmazonSSM_OpsInsights refused recording
+orgsdatasync.servicecatalog.amazonaws.com AWSServiceRoleForServiceCatalogOrgsDataSync unknown policy-documents
+osis.amazonaws.com AWSServiceRoleForAmazonOpenSearchIngestionService unknown policy-documents
+private-marketplace.marketplace.amazonaws.com AWSServiceRoleForPrivateMarketplaceAdmin unknown policy-documents
+pullthroughcache.ecr.amazonaws.com AWSServiceRoleForECRPullThroughCache refused recording
+ram.amazonaws.com AWSServiceRoleForResourceAccessManager refused recording
+rds.amazonaws.com AWSServiceRoleForRDS refused recording
+redshift.amazonaws.com AWSServiceRoleForRedshift refused recording
+remediation.config.amazonaws.com AWSServiceRoleForConfigRemediation unknown policy-documents
+replication.cassandra.amazonaws.com AWSServiceRoleForKeyspacesReplication refused recording
+replication.ecr.amazonaws.com AWSServiceRoleForECRReplication refused recording
+reporting.trustedadvisor.amazonaws.com AWSServiceRoleForTrustedAdvisorReporting unknown policy-documents
+repository.sync.codeconnections.amazonaws.com AWSServiceRoleForGitSync refused recording
+resource-explorer-2.amazonaws.com AWSServiceRoleForResourceExplorer refused recording
+rolesanywhere.amazonaws.com AWSServiceRoleForRolesAnywhere refused recording
+route53resolver.amazonaws.com AWSServiceRoleForRoute53Resolver unknown policy-documents
+rum.amazonaws.com AWSServiceRoleForRealUserMonitoring unknown policy-documents
+runtime-identity.bedrock-agentcore.amazonaws.com AWSServiceRoleForBedrockAgentCoreRuntimeIdentity unknown policy-documents
+runtime-instances.bedrock-agentcore.amazonaws.com AWSServiceRoleForBedrockAgentCoreRuntimeInstances unknown policy-documents
+s3-outposts.amazonaws.com AWSServiceRoleForS3OnOutposts refused recording
+sagemaker.amazonaws.com AWSServiceRoleForAmazonSageMakerNotebooks unknown policy-documents
+sagemaker.application-autoscaling.amazonaws.com AWSServiceRoleForApplicationAutoScaling_SageMakerEndpoint unknown policy-documents
+schemas.amazonaws.com AWSServiceRoleForSchemas unknown policy-documents
+sdmp.amazonaws.com AWSServiceRoleForSDMP unknown policy-documents
+security-ir.amazonaws.com AWSServiceRoleForSecurityIncidentResponse unknown policy-documents
+securitylake.amazonaws.com AWSServiceRoleForSecurityLake unknown policy-documents
+servicecatalog-appregistry.amazonaws.com AWSServiceRoleForAWSServiceCatalogAppRegistry unknown policy-documents
+servicequotas.amazonaws.com AWSServiceRoleForServiceQuotas unknown policy-documents
+ses.amazonaws.com AWSServiceRoleForAmazonSES refused recording
+shield.amazonaws.com AWSServiceRoleForAWSShield refused recording
+spot.amazonaws.com AWSServiceRoleForEC2Spot unknown policy-documents
+ssm-incidents.amazonaws.com AWSServiceRoleForIncidentManager refused recording
+ssm-quicksetup.amazonaws.com AWSServiceRoleForSSMQuickSetup refused recording
+ssm-sap.amazonaws.com AWSServiceRoleForAWSSSMForSAP unknown policy-documents
+ssm.amazonaws.com AWSServiceRoleForAmazonSSM refused recording
+sso.amazonaws.com AWSServiceRoleForSSO refused recording
+support.amazonaws.com AWSServiceRoleForSupport unknown policy-documents
+supportplans.amazonaws.com AWSServiceRoleForSupportPlans unknown policy-documents
+sync.proton.amazonaws.com AWSServiceRoleForProtonSync unknown policy-documents
+thirdparty.config.amazonaws.com AWSServiceRoleForConfigThirdParty unknown policy-documents
+timestream-influxdb.amazonaws.com AWSServiceRoleForTimestreamInfluxDB unknown policy-documents
+transform-custom.amazonaws.com AWSServiceRoleForAWSTransformCustom unknown policy-documents
+transitgateway.amazonaws.com AWSServiceRoleForVPCTransitGateway unknown policy-documents
+triage.security-ir.amazonaws.com AWSServiceRoleForSecurityIncidentResponse_Triage unknown policy-documents
+user-attribute-cost-allocation-data.amazonaws.com AWSServiceRoleForUserAttributeCostAllocation unknown policy-documents
+vpc-lattice.amazonaws.com AWSServiceRoleForVpcLattice unknown policy-documents
+vpcorigin.cloudfront.amazonaws.com AWSServiceRoleForCloudFrontVPCOrigin refused recording
+waf.amazonaws.com AWSServiceRoleForWAFLogging refused recording
+wafv2.amazonaws.com AWSServiceRoleForWAFV2Logging refused recording
diff --git a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java
index 974e62a480..dd596100fa 100644
--- a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java
@@ -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();
diff --git a/src/test/java/io/github/hectorvent/floci/services/connect/ConnectIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/connect/ConnectIntegrationTest.java
index 471dd6025e..18a04ab6dc 100644
--- a/src/test/java/io/github/hectorvent/floci/services/connect/ConnectIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/connect/ConnectIntegrationTest.java
@@ -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"));
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java
index 0c0257794d..08094b8580 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java
@@ -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"));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLinkedRolesTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLinkedRolesTest.java
new file mode 100644
index 0000000000..8000122bcf
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLinkedRolesTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/macie2/MacieOrganizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/macie2/MacieOrganizationIntegrationTest.java
index 5a95d0bd31..8360d3cfe1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/macie2/MacieOrganizationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/macie2/MacieOrganizationIntegrationTest.java
@@ -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"));
+ }
}
diff --git a/tools/slr/service_linked_roles.py b/tools/slr/service_linked_roles.py
new file mode 100644
index 0000000000..6152846db9
--- /dev/null
+++ b/tools/slr/service_linked_roles.py
@@ -0,0 +1,523 @@
+#!/usr/bin/env python3
+"""Generate and check the service-linked role table in src/main/resources/iam.
+
+CreateServiceLinkedRole has to know two things per service principal that cannot be
+derived from the principal: the role name AWS mints, and whether the service takes a
+CustomSuffix. Capitalising the principal gets the name wrong for most of the services
+covered here, and the API Reference says only that "some services do not support the
+CustomSuffix parameter" without listing them. The counts live in the generated table's
+own header, where this script keeps them right; quoting them here only creates a second
+number to go stale.
+
+Two sources, in order of authority:
+
+ recording An AWS-validated LocalStack snapshot. These are recorded create
+ responses, so the role name is what AWS actually returned, and the
+ test parameterisation says whether the suffix was accepted. Highest
+ authority, and the only source for the suffix column.
+ policy-documents src/main/resources/iam/managed-policy-documents.json, which is
+ vendored AWS data. Role ARNs there carry the principal and the role
+ name together. Names only: a policy document says nothing about
+ suffix support.
+ docs AWS's own per-service service-linked role page, which names the
+ role and the principal in prose and usually shows the full ARN.
+ Weaker than a recording only because nothing re-checks it offline,
+ so every such row carries the URL it came from.
+
+--check runs offline and is the CI gate: the policy-documents rows must still match the
+vendored JSON, and the table must be internally well formed. Recording-sourced rows
+cannot be re-derived without the snapshot, which is why every row carries its source.
+
+--refresh takes a snapshot path and re-derives the recording rows, so pulling in new
+AWS evidence is a deliberate act rather than a side effect of running the tool.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+TABLE = REPO_ROOT / "src/main/resources/iam/service-linked-roles.tsv"
+POLICY_DOCUMENTS = REPO_ROOT / "src/main/resources/iam/managed-policy-documents.json"
+
+ROLE_PREFIX = "AWSServiceRoleFor"
+
+# A role ARN inside a policy document. Two shapes have to be rejected rather than read.
+#
+# The principal path is required: a wildcard like
+# role/*AWSServiceRoleForAmazonGuardDutyMalwareProtection names a role without saying which
+# principal mints it, and guessing from those once gave GuardDuty the MalwareProtection
+# role's name.
+#
+# And a name followed by `*` is a prefix pattern, not a name. email.cognito-idp proves it:
+# the policy writes AWSServiceRoleForAmazonCognitoIdpEmail* where the recorded create
+# returns AWSServiceRoleForAmazonCognitoIdpEmailService. Reading the prefix as a name
+# invents a role AWS never mints, so the terminator is captured and checked.
+ROLE_ARN_RE = re.compile(
+ r"aws-service-role/(?P<principal>[A-Za-z0-9.\-]+)/(?P<role>AWSServiceRoleFor[A-Za-z0-9_\-]*)"
+ r"(?P<terminator>.?)"
+)
+
+SUFFIX_ALLOWED = "allowed"
+SUFFIX_REFUSED = "refused"
+SUFFIX_UNKNOWN = "unknown"
+
+# Where both sources name a service and disagree, the recording wins: it is an actual
+# create response, where a policy document may reference a related or superseded role.
+# Listed rather than silently resolved, so a new disagreement is a failure and not a
+# preference.
+# Empty, and worth staying that way. The one entry this held was never a disagreement between
+# sources: the policy wrote AWSServiceRoleForAmazonCognitoIdpEmail* and the prefix was being read
+# as a name, where the recorded create returns AWSServiceRoleForAmazonCognitoIdpEmailService.
+# Skipping wildcard patterns removed the cause. A genuine disagreement still belongs here.
+KNOWN_SOURCE_CONFLICTS: dict[str, tuple[str, str]] = {}
+
+# Services neither machine-readable source covers, taken from AWS's own documentation.
+# The URL is part of the entry on purpose: a name with nowhere to check it is how
+# guardduty sat in the tree for a year citing nothing but itself.
+DOCUMENTED = {
+ # "The AWSServiceRoleForAmazonGuardDuty service-linked role trusts the
+ # guardduty.amazonaws.com service to assume the role."
+ "guardduty.amazonaws.com": (
+ "AWSServiceRoleForAmazonGuardDuty",
+ "Amazon GuardDuty User Guide, Using service-linked roles: "
+ "https://docs.aws.amazon.com/guardduty/latest/ug/slr-permissions.html",
+ ),
+ # "AWS Cloud9 uses the service-linked role named AWSServiceRoleForAWSCloud9. This
+ # service-linked role trusts the service cloud9.amazonaws.com to assume the role."
+ # This one was in IamService's override map before the table existed, and dropping it
+ # regressed the name to the derived AWSServiceRoleForCloud9. The tests caught it; the
+ # entry carries the source the override map never did.
+ "cloud9.amazonaws.com": (
+ "AWSServiceRoleForAWSCloud9",
+ "AWS Cloud9 User Guide, Using service-linked roles: "
+ "https://docs.aws.amazon.com/cloud9/latest/user-guide/using-service-linked-roles.html",
+ ),
+ # Same guide, next section. The vendored policies hold this role only as a wildcard
+ # with no principal path, which is exactly the shape the extractor refuses to guess
+ # from, so the guide is what supplies the principal:
+ # "AWSServiceRoleForAmazonGuardDutyMalwareProtection service-linked role trusts the
+ # malware-protection.guardduty.amazonaws.com service to assume the role."
+ "malware-protection.guardduty.amazonaws.com": (
+ "AWSServiceRoleForAmazonGuardDutyMalwareProtection",
+ "Amazon GuardDuty User Guide, Service-linked role permissions for Malware "
+ "Protection for EC2: https://docs.aws.amazon.com/guardduty/latest/ug/"
+ "slr-permissions-malware-protection.html",
+ ),
+}
+
+
+def names_from_policy_documents(path: Path) -> dict[str, str]:
+ """Principal to role name, from the vendored AWS managed policy documents."""
+ raw = path.read_text()
+ names: dict[str, str] = {}
+ for match in ROLE_ARN_RE.finditer(raw):
+ if match.group("terminator") == "*":
+ # A prefix pattern. The real name is this and something, and nothing here says what.
+ continue
+ principal = match.group("principal")
+ # A policy matching suffixed roles writes the prefix as `...AmazonConnect_*`, so
+ # the captured name can carry a trailing separator. An underscore inside a name
+ # is real, though: ApplicationAutoScaling_CassandraTable is the whole name, and
+ # splitting on the separator would truncate it.
+ role = match.group("role").rstrip("_")
+ names.setdefault(principal, role)
+ return names
+
+
+def rows_from_snapshot(path: Path) -> dict[str, tuple[str | None, str]]:
+ """Principal to (role name, suffix support), from one AWS-validated snapshot."""
+ snapshot = json.loads(path.read_text())
+ names: dict[str, str] = {}
+ suffix: dict[str, str] = {}
+ for key, value in snapshot.items():
+ principal = re.search(r"\[([a-z0-9.\-]+\.amazonaws\.com)\]", key)
+ if not principal:
+ continue
+ service = principal.group(1)
+ if "custom_suffix_not_allowed[" in key:
+ suffix[service] = SUFFIX_REFUSED
+ elif "lifecycle_custom_suffix[" in key:
+ suffix[service] = SUFFIX_ALLOWED
+ for body in (value.get("recorded-content") or {}).values():
+ if not isinstance(body, dict) or not isinstance(body.get("Role"), dict):
+ continue
+ role = body["Role"].get("RoleName")
+ if role:
+ # Only the custom-suffix test appends the placeholder.
+ names.setdefault(service, re.sub(r"_<suffix>$", "", role))
+ return {
+ service: (names.get(service), suffix.get(service, SUFFIX_UNKNOWN))
+ for service in set(names) | set(suffix)
+ }
+
+
+def derived_name(principal: str) -> str:
+ """What CreateServiceLinkedRole falls back to when the table does not cover a service."""
+ core = principal
+ for suffix in (".amazonaws.com",):
+ if core.endswith(suffix):
+ core = core[: -len(suffix)]
+ return ROLE_PREFIX + "".join(
+ part[0].upper() + part[1:] for part in re.split(r"[.\-]", core) if part
+ )
+
+
+class Row:
+ """One service: its principal, the role name AWS mints, suffix support, and provenance."""
+
+ __slots__ = ("principal", "role", "suffix", "source")
+
+ def __init__(self, principal: str, role: str, suffix: str, source: str) -> None:
+ self.principal = principal
+ self.role = role
+ self.suffix = suffix
+ self.source = source
+
+ def as_tsv(self) -> str:
+ return "\t".join((self.principal, self.role, self.suffix, self.source))
+
+
+def build(policy_documents: Path, snapshot: Path | None,
+ conflicts: dict[str, tuple[str, str]] | None = None,
+ documented: dict[str, tuple[str, str]] | None = None) -> tuple[list[Row], list[str]]:
+ """The table, anything that needs a human, and anything worth saying out loud.
+
+ Both curated overlays are parameters rather than read off the module, so that a
+ caller working from a small fixture does not see every real conflict reported as
+ stale, or a seeded name appear in a table built from two synthetic sources.
+ """
+ if conflicts is None:
+ conflicts = KNOWN_SOURCE_CONFLICTS
+ if documented is None:
+ documented = DOCUMENTED
+ problems: list[str] = []
+ notes: list[str] = []
+ vendored = names_from_policy_documents(policy_documents)
+ recorded = rows_from_snapshot(snapshot) if snapshot else {}
+
+ rows: list[Row] = []
+ for principal in sorted(set(vendored) | set(recorded) | set(documented)):
+ recorded_name, suffix = recorded.get(principal, (None, SUFFIX_UNKNOWN))
+ vendored_name = vendored.get(principal)
+
+ if recorded_name and vendored_name and recorded_name != vendored_name:
+ expected = conflicts.get(principal)
+ if expected != (vendored_name, recorded_name):
+ problems.append(
+ f"{principal}: the sources disagree and the conflict is not recorded. "
+ f"policy documents say {vendored_name}, the recording says {recorded_name}. "
+ f"The recording is an actual create response, so it should win, but add the "
+ f"pair to KNOWN_SOURCE_CONFLICTS so the next disagreement still fails."
+ )
+
+ if recorded_name:
+ rows.append(Row(principal, recorded_name, suffix, "recording"))
+ elif vendored_name:
+ rows.append(Row(principal, vendored_name, suffix, "policy-documents"))
+ else:
+ rows.append(Row(principal, documented[principal][0], suffix, "docs"))
+
+ # A role name is unique within an account, and createServiceLinkedRole refuses a name
+ # already taken, so two principals cannot share one. The policy documents hand out
+ # collisions anyway: they reference the parent's role under a child principal path, as
+ # with maintenance.elasticbeanstalk pointing at AWSServiceRoleForElasticBeanstalk. Taken
+ # at face value that makes the sibling's create fail as a duplicate, so the weaker row is
+ # dropped back to the derived fallback rather than asserting a name that would collide.
+ AUTHORITY = {"recording": 0, "docs": 1, "policy-documents": 2}
+ by_name: dict[str, list[Row]] = {}
+ for row in rows:
+ by_name.setdefault(row.role, []).append(row)
+ dropped: set[str] = set()
+ for role, sharing in by_name.items():
+ if len(sharing) == 1:
+ continue
+ ranked = sorted(sharing, key=lambda row: AUTHORITY[row.source])
+ keep, rest = ranked[0], ranked[1:]
+ if AUTHORITY[rest[0].source] == AUTHORITY[keep.source]:
+ problems.append(
+ f"{role} is claimed by {', '.join(row.principal for row in sharing)}, all on "
+ f"{keep.source} evidence, and a role name cannot be shared. Settle which "
+ f"principal owns it and put the others in DOCUMENTED."
+ )
+ continue
+ for row in rest:
+ dropped.add(row.principal)
+ problems_note = (
+ f"{row.principal} dropped: its {row.source} evidence names {role}, which "
+ f"{keep.principal} already owns on {keep.source} evidence. The policy document "
+ f"references the parent's role under a child path, so the real name is unknown "
+ f"and the derived fallback applies. Add a DOCUMENTED entry to fix it properly."
+ )
+ notes.append(problems_note)
+ rows = [row for row in rows if row.principal not in dropped]
+
+ for principal in conflicts:
+ if principal not in {row.principal for row in rows}:
+ problems.append(
+ f"{principal} is listed in KNOWN_SOURCE_CONFLICTS but is in no source, so the "
+ f"entry is stale and should come out."
+ )
+ return rows, problems, notes
+
+
+HEADER = """\
+# Service-linked roles: the role name AWS mints for a principal, and whether the service
+# takes a CustomSuffix.
+#
+# Columns: principal, role name, suffix support, source.
+#
+# Generated by tools/slr/service_linked_roles.py. Do not hand-edit: run
+# `make slr-table` to regenerate, or `make slr-check` to see what drifted.
+#
+# Neither column can be derived from the principal. Capitalising the principal gives the
+# wrong name for {wrong} of these {total} services, and the API Reference says only that
+# "some services do not support the CustomSuffix parameter" without listing which.
+#
+# Suffix support is only ever known from a recorded create: `unknown` means no recording
+# covers it, and CreateServiceLinkedRole keeps taking a suffix there rather than refusing
+# on an inference. Source is the authority the row rests on, weakest last:
+#
+# recording an AWS-validated create response, and the only source for suffix
+# policy-documents a role ARN in vendored AWS managed policy documents, name only
+# docs AWS's own service-linked role page for that service, cited in
+# DOCUMENTED in the generator so the claim can be rechecked
+#
+# {counts}
+# {recordings}
+"""
+
+
+RECORDINGS_RE = re.compile(r"^#\s*recordings: (?P<digest>[0-9a-f]{64}|none) ")
+
+
+def snapshot_fingerprint(path: Path | None) -> str:
+ """sha256 of the snapshot the recording rows came from, so a refresh can say whether it moved.
+
+ The recording half of the table cannot be rechecked offline, which `--check` can only report
+ rather than fix. A digest in the header turns the next `--refresh` into a diff against a known
+ source instead of an act of faith: same digest means the recordings are unchanged and any
+ difference in the table came from the vendored policy documents.
+ """
+ if path is None:
+ return "none"
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for block in iter(lambda: handle.read(1 << 20), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def fingerprint_in(table: Path) -> str | None:
+ """The digest a table records, or None when it has none or does not exist."""
+ if not table.exists():
+ return None
+ for line in table.read_text().splitlines():
+ match = RECORDINGS_RE.match(line.strip())
+ if match:
+ return match.group("digest")
+ return None
+
+
+def render(rows: list[Row], recordings: str = "none") -> str:
+ wrong = sum(1 for row in rows if derived_name(row.principal) != row.role)
+ by_source: dict[str, int] = {}
+ by_suffix: dict[str, int] = {}
+ for row in rows:
+ by_source[row.source] = by_source.get(row.source, 0) + 1
+ by_suffix[row.suffix] = by_suffix.get(row.suffix, 0) + 1
+ counts = (
+ f"{len(rows)} services: "
+ + ", ".join(f"{count} {source}" for source, count in sorted(by_source.items()))
+ + " / suffix "
+ + ", ".join(f"{count} {state}" for state, count in sorted(by_suffix.items()))
+ )
+ recordings_line = (
+ f"recordings: {recordings} "
+ + ("(no snapshot was given, so no row here rests on a recording)"
+ if recordings == "none"
+ else "(sha256 of the LocalStack tests/aws/services/iam/test_iam.snapshot.json "
+ "the recording rows came from)")
+ )
+ header = HEADER.format(wrong=wrong, total=len(rows), counts=counts,
+ recordings=recordings_line)
+ return header + "\n".join(row.as_tsv() for row in rows) + "\n"
+
+
+def parse_table(path: Path) -> list[Row]:
+ rows = []
+ for line in path.read_text().splitlines():
+ stripped = line.strip()
+ if not stripped or stripped.startswith("#"):
+ continue
+ principal, role, suffix, source = stripped.split("\t")
+ rows.append(Row(principal, role, suffix, source))
+ return rows
+
+
+def check(table: Path, policy_documents: Path,
+ documented: dict[str, tuple[str, str]] | None = None) -> list[str]:
+ """What can be verified without the snapshot, which is what CI can run.
+
+ `documented` is a parameter for the same reason it is on build(): a caller checking a
+ two-row fixture should not see every real DOCUMENTED entry reported missing from it.
+ """
+ if documented is None:
+ documented = DOCUMENTED
+ if not table.exists():
+ return [f"{table} is missing; run `make slr-table`."]
+
+ rows = parse_table(table)
+ problems: list[str] = []
+
+ seen: dict[str, Row] = {}
+ for row in rows:
+ if row.principal in seen:
+ problems.append(f"{row.principal} appears twice in the table.")
+ seen[row.principal] = row
+ if not row.role.startswith(ROLE_PREFIX):
+ problems.append(f"{row.principal}: {row.role} does not start with {ROLE_PREFIX}.")
+ if row.suffix not in (SUFFIX_ALLOWED, SUFFIX_REFUSED, SUFFIX_UNKNOWN):
+ problems.append(f"{row.principal}: {row.suffix} is not a suffix state.")
+ if row.source not in ("recording", "policy-documents", "docs"):
+ problems.append(f"{row.principal}: {row.source} is not a source.")
+ if row.source != "recording" and row.suffix != SUFFIX_UNKNOWN:
+ problems.append(
+ f"{row.principal}: suffix support is {row.suffix} on a {row.source} row, but only "
+ f"a recording can establish it."
+ )
+
+ if sorted(seen) != [row.principal for row in rows]:
+ problems.append("the table is not sorted by principal; regenerate it.")
+
+ # docs rows name a role from a page nothing here can fetch, but the expected value is in
+ # DOCUMENTED, so the table and the generator can at least be held to each other.
+ for row in rows:
+ if row.source != "docs":
+ continue
+ documented_entry = documented.get(row.principal)
+ if documented_entry is None:
+ problems.append(
+ f"{row.principal} is a docs row but has no DOCUMENTED entry, so nothing records "
+ f"where {row.role} came from; add one or regenerate the table."
+ )
+ elif documented_entry[0] != row.role:
+ problems.append(
+ f"{row.principal}: the table says {row.role}, DOCUMENTED says {documented_entry[0]}; "
+ f"regenerate the table."
+ )
+ for principal, (role, _source) in documented.items():
+ if principal not in seen:
+ problems.append(
+ f"{principal} is in DOCUMENTED ({role}) but not in the table; regenerate it."
+ )
+
+ # The half that can be re-derived offline.
+ vendored = names_from_policy_documents(policy_documents)
+ for row in rows:
+ if row.source != "policy-documents":
+ continue
+ current = vendored.get(row.principal)
+ if current is None:
+ problems.append(
+ f"{row.principal} is a policy-documents row but no longer appears in "
+ f"{policy_documents.name}; regenerate the table."
+ )
+ elif current != row.role:
+ problems.append(
+ f"{row.principal}: the table says {row.role}, the vendored policy documents now "
+ f"say {current}; regenerate the table."
+ )
+ # The digest itself cannot be checked without the snapshot. Its absence can, and a table
+ # that has quietly lost it is a table whose recording rows have no stated source.
+ recorded_digest = fingerprint_in(table)
+ if recorded_digest is None:
+ problems.append(
+ f"{table.name} has no `recordings:` line, so nothing says which snapshot its "
+ f"recording rows came from; regenerate it."
+ )
+ elif recorded_digest == "none" and any(row.source == "recording" for row in rows):
+ problems.append(
+ f"{table.name} says it was built from no snapshot, yet carries recording rows; "
+ f"regenerate it from the snapshot those came from."
+ )
+
+ owners = {row.role: row.principal for row in rows}
+ for principal, role in vendored.items():
+ if principal in seen:
+ continue
+ if owners.get(role) not in (None, principal):
+ # Dropped by build()'s collision guard: the policy document points this principal
+ # at a role another one owns, so it falls back to the derived name rather than
+ # claiming a name that would make the sibling's create fail as a duplicate.
+ continue
+ problems.append(
+ f"{principal} is in the vendored policy documents ({role}) but not in the table; "
+ f"regenerate it so the new service is covered."
+ )
+ return problems
+
+
+def audit(rows: list[Row]) -> str:
+ lines = [f"{'principal':52} {'role name':58} {'suffix':8} source", "-" * 134]
+ for row in rows:
+ marker = "" if derived_name(row.principal) == row.role else " (not derivable)"
+ lines.append(f"{row.principal:52} {row.role:58} {row.suffix:8} {row.source}{marker}")
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
+ )
+ mode = parser.add_mutually_exclusive_group()
+ mode.add_argument("--check", action="store_true",
+ help="exit 1 when the table drifted from the vendored data (CI gate)")
+ mode.add_argument("--refresh", type=Path, metavar="SNAPSHOT",
+ help="regenerate from an AWS-validated LocalStack IAM snapshot")
+ mode.add_argument("--audit", action="store_true", help="print the table (the default)")
+ parser.add_argument("--table", type=Path, default=TABLE, help=argparse.SUPPRESS)
+ parser.add_argument("--policy-documents", type=Path, default=POLICY_DOCUMENTS,
+ help=argparse.SUPPRESS)
+ args = parser.parse_args(argv)
+
+ if args.refresh:
+ rows, problems, notes = build(args.policy_documents, args.refresh)
+ for note in notes:
+ print(f"note: {note}", file=sys.stderr)
+ if problems:
+ print("\n".join(f"error: {problem}" for problem in problems), file=sys.stderr)
+ return 1
+ previous = fingerprint_in(args.table)
+ current = snapshot_fingerprint(args.refresh)
+ args.table.write_text(render(rows, current))
+ if previous is None:
+ print(f"recordings: {current} (the table recorded none before this)")
+ elif previous == current:
+ print(f"recordings: {current} (unchanged, so any difference came from the "
+ f"vendored policy documents)")
+ else:
+ print(f"recordings: {previous} -> {current} (the snapshot moved; the recording rows "
+ f"may have changed with it)")
+ print(f"wrote {args.table.relative_to(REPO_ROOT)} with {len(rows)} services")
+ return 0
+
+ if args.check:
+ problems = check(args.table, args.policy_documents)
+ if problems:
+ print("\n".join(f"error: {problem}" for problem in problems), file=sys.stderr)
+ return 1
+ print(f"{args.table.relative_to(REPO_ROOT)} matches the vendored data")
+ return 0
+
+ print(audit(parse_table(args.table)))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/slr/test_service_linked_roles.py b/tools/slr/test_service_linked_roles.py
new file mode 100644
index 0000000000..d8256dec20
--- /dev/null
+++ b/tools/slr/test_service_linked_roles.py
@@ -0,0 +1,371 @@
+"""Tests for the service-linked role table generator.
+
+The traps here are all ones the real data walked into, so each has a case: an underscore
+that is part of a role name rather than a suffix separator, a policy that matches
+suffixed roles with a trailing separator, and a wildcard ARN that names a role without
+saying which principal mints it.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+import service_linked_roles as slr
+
+
+def write(tmp_path: Path, name: str, text: str) -> Path:
+ path = tmp_path / name
+ path.write_text(text)
+ return path
+
+
+def policy_documents(tmp_path: Path, *arns: str) -> Path:
+ statements = ",".join(f'{{"Resource":"{arn}"}}' for arn in arns)
+ return write(tmp_path, "documents.json", f'{{"P":[{statements}]}}')
+
+
+def snapshot(tmp_path: Path, entries: dict[str, dict]) -> Path:
+ return write(tmp_path, "snap.json", json.dumps(entries))
+
+
+def lifecycle(service: str, role: str) -> tuple[str, dict]:
+ key = f"tests/aws/services/iam/test_iam.py::T::test_service_role_lifecycle[{service}]"
+ return key, {"recorded-content": {"describe-response": {"Role": {"RoleName": role}}}}
+
+
+def with_suffix(service: str, role: str) -> tuple[str, dict]:
+ key = (f"tests/aws/services/iam/test_iam.py::T::"
+ f"test_service_role_lifecycle_custom_suffix[{service}]")
+ return key, {"recorded-content": {"describe-response": {"Role": {"RoleName": role}}}}
+
+
+def suffix_refused(service: str) -> tuple[str, dict]:
+ key = (f"tests/aws/services/iam/test_iam.py::T::"
+ f"test_service_role_lifecycle_custom_suffix_not_allowed[{service}]")
+ return key, {"recorded-content": {"custom-suffix-not-allowed": {"Error": {"Code": "InvalidInput"}}}}
+
+
+class TestPolicyDocumentExtraction:
+ def test_an_underscore_inside_a_role_name_survives(self, tmp_path):
+ path = policy_documents(tmp_path, "arn:aws:iam::*:role/aws-service-role/"
+ "cassandra.application-autoscaling.amazonaws.com/"
+ "AWSServiceRoleForApplicationAutoScaling_CassandraTable")
+ names = slr.names_from_policy_documents(path)
+ assert names["cassandra.application-autoscaling.amazonaws.com"] == (
+ "AWSServiceRoleForApplicationAutoScaling_CassandraTable")
+
+ def test_a_trailing_separator_from_a_wildcard_policy_is_dropped(self, tmp_path):
+ path = policy_documents(tmp_path, "arn:aws:iam::*:role/aws-service-role/"
+ "connect.amazonaws.com/AWSServiceRoleForAmazonConnect_")
+ assert slr.names_from_policy_documents(path) == {
+ "connect.amazonaws.com": "AWSServiceRoleForAmazonConnect"}
+
+ def test_a_wildcard_arn_with_no_principal_path_is_ignored(self, tmp_path):
+ """This one matters: guessing from it once gave GuardDuty another role's name."""
+ path = policy_documents(
+ tmp_path, "arn:aws:iam::*:role/*AWSServiceRoleForAmazonGuardDutyMalwareProtection")
+ assert slr.names_from_policy_documents(path) == {}
+
+
+class TestSnapshotExtraction:
+ def test_a_name_and_a_refusal_come_out_of_one_pass(self, tmp_path):
+ path = snapshot(tmp_path, dict([lifecycle("ecs.amazonaws.com", "AWSServiceRoleForECS"),
+ suffix_refused("ecs.amazonaws.com")]))
+ assert slr.rows_from_snapshot(path) == {
+ "ecs.amazonaws.com": ("AWSServiceRoleForECS", slr.SUFFIX_REFUSED)}
+
+ def test_the_suffix_placeholder_is_stripped_from_a_suffixed_create(self, tmp_path):
+ path = snapshot(tmp_path, dict([
+ with_suffix("autoscaling.amazonaws.com", "AWSServiceRoleForAutoScaling_<suffix>")]))
+ assert slr.rows_from_snapshot(path) == {
+ "autoscaling.amazonaws.com": ("AWSServiceRoleForAutoScaling", slr.SUFFIX_ALLOWED)}
+
+ def test_a_service_with_no_recording_is_unknown_rather_than_permitted_or_refused(self, tmp_path):
+ path = snapshot(tmp_path, dict([lifecycle("acm.amazonaws.com",
+ "AWSServiceRoleForCertificateManager")]))
+ assert slr.rows_from_snapshot(path)["acm.amazonaws.com"][1] == slr.SUFFIX_UNKNOWN
+
+
+class TestBuild:
+ def test_a_recording_outranks_a_policy_document(self, tmp_path):
+ documents = policy_documents(tmp_path, "arn:aws:iam::*:role/aws-service-role/"
+ "x.amazonaws.com/AWSServiceRoleForFromDocuments")
+ snap = snapshot(tmp_path, dict([lifecycle("x.amazonaws.com",
+ "AWSServiceRoleForFromRecording")]))
+ rows, problems, _notes = slr.build(documents, snap, documented={}, conflicts={
+ "x.amazonaws.com": ("AWSServiceRoleForFromDocuments",
+ "AWSServiceRoleForFromRecording")})
+ assert problems == []
+ assert [(r.role, r.source) for r in rows] == [("AWSServiceRoleForFromRecording", "recording")]
+
+ def test_an_unrecorded_disagreement_is_a_problem_rather_than_a_silent_preference(self, tmp_path):
+ documents = policy_documents(tmp_path, "arn:aws:iam::*:role/aws-service-role/"
+ "y.amazonaws.com/AWSServiceRoleForOne")
+ snap = snapshot(tmp_path, dict([lifecycle("y.amazonaws.com", "AWSServiceRoleForTwo")]))
+ rows, problems, _notes = slr.build(documents, snap, conflicts={}, documented={})
+ assert len(problems) == 1
+ assert "the sources disagree" in problems[0]
+
+ def test_a_stale_conflict_entry_is_reported(self, tmp_path):
+ _, problems, _notes = slr.build(policy_documents(tmp_path), None, documented={},
+ conflicts={"gone.amazonaws.com": ("a", "b")})
+ assert any("is in no source" in problem for problem in problems)
+
+
+class TestDerivedName:
+ @pytest.mark.parametrize("principal,expected", [
+ ("batch.amazonaws.com", "AWSServiceRoleForBatch"),
+ ("access-analyzer.amazonaws.com", "AWSServiceRoleForAccessAnalyzer"),
+ ("ops.apigateway.amazonaws.com", "AWSServiceRoleForOpsApigateway"),
+ ])
+ def test_the_fallback_matches_what_the_service_derives(self, principal, expected):
+ assert slr.derived_name(principal) == expected
+
+
+def table(tmp_path: Path, *rows: str, recordings: str = "none") -> Path:
+ header = ("# generated, do not hand-edit\n"
+ f"# recordings: {recordings} (fixture)\n")
+ return write(tmp_path, "table.tsv", header + "".join(row + "\n" for row in rows))
+
+
+ROW = "{}\t{}\t{}\t{}".format
+
+
+class TestCheck:
+ """The CI gate. These were probed by hand first; a gate nothing tests is not a gate."""
+
+ def clean(self, tmp_path: Path) -> tuple[Path, Path]:
+ documents = policy_documents(
+ tmp_path,
+ "arn:aws:iam::*:role/aws-service-role/aaa.amazonaws.com/AWSServiceRoleForAaa",
+ "arn:aws:iam::*:role/aws-service-role/bbb.amazonaws.com/AWSServiceRoleForBbb")
+ return table(
+ tmp_path,
+ ROW("aaa.amazonaws.com", "AWSServiceRoleForAaa", "unknown", "policy-documents"),
+ ROW("bbb.amazonaws.com", "AWSServiceRoleForBbb", "unknown", "policy-documents"),
+ ), documents
+
+ def test_a_table_matching_the_vendored_data_has_no_problems(self, tmp_path):
+ tsv, documents = self.clean(tmp_path)
+ assert slr.check(tsv, documents, documented={}) == []
+
+ def test_a_hand_edited_name_on_a_policy_documents_row_is_caught(self, tmp_path):
+ _, documents = self.clean(tmp_path)
+ tsv = table(tmp_path,
+ ROW("aaa.amazonaws.com", "AWSServiceRoleForEdited", "unknown", "policy-documents"),
+ ROW("bbb.amazonaws.com", "AWSServiceRoleForBbb", "unknown", "policy-documents"))
+ problems = slr.check(tsv, documents, documented={})
+ assert any("the vendored policy documents now say" in problem for problem in problems)
+
+ def test_a_vendored_service_missing_from_the_table_is_caught(self, tmp_path):
+ _, documents = self.clean(tmp_path)
+ tsv = table(tmp_path,
+ ROW("aaa.amazonaws.com", "AWSServiceRoleForAaa", "unknown", "policy-documents"))
+ problems = slr.check(tsv, documents, documented={})
+ assert any("but not in the table" in problem for problem in problems)
+
+ def test_suffix_support_claimed_without_a_recording_is_caught(self, tmp_path):
+ """Only a recorded create can establish it, so any other source must say unknown."""
+ _, documents = self.clean(tmp_path)
+ tsv = table(tmp_path,
+ ROW("aaa.amazonaws.com", "AWSServiceRoleForAaa", "refused", "policy-documents"),
+ ROW("bbb.amazonaws.com", "AWSServiceRoleForBbb", "unknown", "policy-documents"))
+ problems = slr.check(tsv, documents, documented={})
+ assert any("only" in problem and "recording" in problem for problem in problems)
+
+ def test_an_unsorted_table_is_caught(self, tmp_path):
+ _, documents = self.clean(tmp_path)
+ tsv = table(tmp_path,
+ ROW("bbb.amazonaws.com", "AWSServiceRoleForBbb", "unknown", "policy-documents"),
+ ROW("aaa.amazonaws.com", "AWSServiceRoleForAaa", "unknown", "policy-documents"))
+ assert any("not sorted" in problem for problem in slr.check(tsv, documents, documented={}))
+
+ def test_a_duplicated_principal_is_caught(self, tmp_path):
+ _, documents = self.clean(tmp_path)
+ tsv = table(tmp_path,
+ ROW("aaa.amazonaws.com", "AWSServiceRoleForAaa", "unknown", "policy-documents"),
+ ROW("aaa.amazonaws.com", "AWSServiceRoleForAaa", "unknown", "policy-documents"),
+ ROW("bbb.amazonaws.com", "AWSServiceRoleForBbb", "unknown", "policy-documents"))
+ assert any("appears twice" in problem for problem in slr.check(tsv, documents, documented={}))
+
+ def test_a_name_without_the_aws_prefix_is_caught(self, tmp_path):
+ _, documents = self.clean(tmp_path)
+ tsv = table(tmp_path,
+ ROW("aaa.amazonaws.com", "NotAServiceLinkedRole", "unknown", "policy-documents"),
+ ROW("bbb.amazonaws.com", "AWSServiceRoleForBbb", "unknown", "policy-documents"))
+ assert any("does not start with" in problem for problem in slr.check(tsv, documents, documented={}))
+
+ def test_an_unknown_source_or_suffix_state_is_caught(self, tmp_path):
+ _, documents = self.clean(tmp_path)
+ tsv = table(tmp_path,
+ ROW("aaa.amazonaws.com", "AWSServiceRoleForAaa", "maybe", "policy-documents"),
+ ROW("bbb.amazonaws.com", "AWSServiceRoleForBbb", "unknown", "hearsay"))
+ problems = slr.check(tsv, documents, documented={})
+ assert any("is not a suffix state" in problem for problem in problems)
+ assert any("is not a source" in problem for problem in problems)
+
+ def test_a_missing_table_says_how_to_make_one(self, tmp_path):
+ _, documents = self.clean(tmp_path)
+ problems = slr.check(tmp_path / "absent.tsv", documents, documented={})
+ assert len(problems) == 1
+ assert "slr-table" in problems[0]
+
+
+class TestRoundTrip:
+ def test_what_render_writes_parse_table_reads_back(self, tmp_path):
+ documents = policy_documents(
+ tmp_path, "arn:aws:iam::*:role/aws-service-role/aaa.amazonaws.com/AWSServiceRoleForAaa")
+ snap = snapshot(tmp_path, dict([lifecycle("zzz.amazonaws.com", "AWSServiceRoleForZzz"),
+ suffix_refused("zzz.amazonaws.com")]))
+ rows, problems, _notes = slr.build(documents, snap, conflicts={}, documented={})
+ assert problems == []
+
+ rendered = write(tmp_path, "rendered.tsv", slr.render(rows))
+ read_back = slr.parse_table(rendered)
+ assert [(r.principal, r.role, r.suffix, r.source) for r in read_back] == [
+ (r.principal, r.role, r.suffix, r.source) for r in rows]
+
+ def test_the_header_counts_what_it_wrote(self, tmp_path):
+ """The header states totals, and a header that counts wrong is how a table starts lying."""
+ documents = policy_documents(
+ tmp_path,
+ "arn:aws:iam::*:role/aws-service-role/aaa.amazonaws.com/AWSServiceRoleForAaa",
+ "arn:aws:iam::*:role/aws-service-role/bbb.amazonaws.com/AWSServiceRoleForBbb")
+ rows, _p, _n = slr.build(documents, None, conflicts={}, documented={})
+ rendered = slr.render(rows)
+ assert f"{len(rows)} services:" in rendered
+ assert f"{len(rows)} policy-documents" in rendered
+
+
+class TestWildcardSuffix:
+ """
+ A name followed by `*` is a prefix pattern, not a name. email.cognito-idp is the proof: the
+ policy writes AWSServiceRoleForAmazonCognitoIdpEmail* where the recorded create returns
+ AWSServiceRoleForAmazonCognitoIdpEmailService, so reading the prefix invents a role.
+ """
+
+ def test_a_wildcard_suffixed_arn_is_not_read_as_a_name(self, tmp_path):
+ path = policy_documents(
+ tmp_path, "arn:aws:iam::*:role/aws-service-role/email.cognito-idp.amazonaws.com/"
+ "AWSServiceRoleForAmazonCognitoIdpEmail*")
+ assert slr.names_from_policy_documents(path) == {}
+
+ def test_an_exact_arn_beside_a_wildcard_one_still_counts(self, tmp_path):
+ path = policy_documents(
+ tmp_path,
+ "arn:aws:iam::*:role/aws-service-role/aaa.amazonaws.com/AWSServiceRoleForAaa*",
+ "arn:aws:iam::*:role/aws-service-role/aaa.amazonaws.com/AWSServiceRoleForAaaExact")
+ assert slr.names_from_policy_documents(path) == {
+ "aaa.amazonaws.com": "AWSServiceRoleForAaaExact"}
+
+
+class TestNameCollisions:
+ """
+ A role name is unique per account and createServiceLinkedRole refuses one already taken, so
+ two principals sharing a name makes the second principal's create fail as a duplicate. The
+ policy documents produce exactly that, pointing maintenance.elasticbeanstalk at the parent's
+ AWSServiceRoleForElasticBeanstalk.
+ """
+
+ def test_the_weaker_row_is_dropped_rather_than_asserting_a_colliding_name(self, tmp_path):
+ documents = policy_documents(
+ tmp_path,
+ "arn:aws:iam::*:role/aws-service-role/parent.amazonaws.com/AWSServiceRoleForShared",
+ "arn:aws:iam::*:role/aws-service-role/child.parent.amazonaws.com/AWSServiceRoleForShared")
+ snap = snapshot(tmp_path, dict([lifecycle("parent.amazonaws.com", "AWSServiceRoleForShared")]))
+ rows, problems, notes = slr.build(documents, snap, conflicts={}, documented={})
+
+ assert problems == []
+ assert [r.principal for r in rows] == ["parent.amazonaws.com"]
+ assert any("child.parent.amazonaws.com dropped" in note for note in notes)
+
+ def test_a_collision_between_equal_sources_is_a_problem_for_a_human(self, tmp_path):
+ documents = policy_documents(
+ tmp_path,
+ "arn:aws:iam::*:role/aws-service-role/one.amazonaws.com/AWSServiceRoleForShared",
+ "arn:aws:iam::*:role/aws-service-role/two.amazonaws.com/AWSServiceRoleForShared")
+ _, problems, _ = slr.build(documents, None, conflicts={}, documented={})
+ assert any("cannot be shared" in problem for problem in problems)
+
+ def test_check_does_not_demand_a_principal_the_collision_guard_dropped(self, tmp_path):
+ """Otherwise the gate asks for a row build() deliberately refuses to emit, forever."""
+ documents = policy_documents(
+ tmp_path,
+ "arn:aws:iam::*:role/aws-service-role/parent.amazonaws.com/AWSServiceRoleForShared",
+ "arn:aws:iam::*:role/aws-service-role/child.parent.amazonaws.com/AWSServiceRoleForShared")
+ tsv = table(tmp_path,
+ ROW("parent.amazonaws.com", "AWSServiceRoleForShared", "unknown", "policy-documents"))
+ assert slr.check(tsv, documents, documented={}) == []
+
+
+class TestDocumentedRows:
+ """docs rows cite a page nothing here can fetch, but the generator holds the expected value."""
+
+ def test_a_docs_row_disagreeing_with_the_generator_is_caught(self, tmp_path):
+ documents = policy_documents(tmp_path)
+ tsv = table(tmp_path, ROW("x.amazonaws.com", "AWSServiceRoleForEdited", "unknown", "docs"))
+ problems = slr.check(tsv, documents,
+ documented={"x.amazonaws.com": ("AWSServiceRoleForReal", "a url")})
+ assert any("DOCUMENTED says AWSServiceRoleForReal" in problem for problem in problems)
+
+ def test_a_docs_row_with_no_generator_entry_is_caught(self, tmp_path):
+ documents = policy_documents(tmp_path)
+ tsv = table(tmp_path, ROW("x.amazonaws.com", "AWSServiceRoleForX", "unknown", "docs"))
+ problems = slr.check(tsv, documents, documented={})
+ assert any("no DOCUMENTED entry" in problem for problem in problems)
+
+ def test_a_documented_service_missing_from_the_table_is_caught(self, tmp_path):
+ documents = policy_documents(tmp_path)
+ tsv = table(tmp_path)
+ problems = slr.check(tsv, documents,
+ documented={"x.amazonaws.com": ("AWSServiceRoleForX", "a url")})
+ assert any("but not in the table" in problem for problem in problems)
+
+
+class TestSnapshotFingerprint:
+ """
+ The recording half of the table cannot be rechecked offline. A digest in the header turns the
+ next refresh into a diff against a known source rather than an act of faith.
+ """
+
+ def test_the_header_records_the_digest_of_the_snapshot_it_was_built_from(self, tmp_path):
+ snap = snapshot(tmp_path, dict([lifecycle("x.amazonaws.com", "AWSServiceRoleForX")]))
+ rows, _, _ = slr.build(policy_documents(tmp_path), snap, conflicts={}, documented={})
+ digest = slr.snapshot_fingerprint(snap)
+ assert len(digest) == 64
+ assert f"recordings: {digest} " in slr.render(rows, digest)
+
+ def test_a_different_snapshot_gives_a_different_digest(self, tmp_path):
+ one = snapshot(tmp_path, dict([lifecycle("x.amazonaws.com", "AWSServiceRoleForX")]))
+ two = write(tmp_path, "other.json", one.read_text() + " ")
+ assert slr.snapshot_fingerprint(one) != slr.snapshot_fingerprint(two)
+
+ def test_no_snapshot_is_recorded_as_none_rather_than_a_made_up_digest(self):
+ assert slr.snapshot_fingerprint(None) == "none"
+
+ def test_the_digest_is_read_back_out_of_a_table(self, tmp_path):
+ digest = "a" * 64
+ tsv = table(tmp_path, ROW("a.amazonaws.com", "AWSServiceRoleForA", "unknown", "docs"),
+ recordings=digest)
+ assert slr.fingerprint_in(tsv) == digest
+
+ def test_a_table_that_lost_its_recordings_line_is_caught(self, tmp_path):
+ tsv = write(tmp_path, "nodigest.tsv",
+ "# generated\n"
+ + ROW("a.amazonaws.com", "AWSServiceRoleForA", "unknown", "policy-documents")
+ + "\n")
+ documents = policy_documents(
+ tmp_path, "arn:aws:iam::*:role/aws-service-role/a.amazonaws.com/AWSServiceRoleForA")
+ problems = slr.check(tsv, documents, documented={})
+ assert any("no `recordings:` line" in problem for problem in problems)
+
+ def test_recording_rows_with_no_snapshot_recorded_is_caught(self, tmp_path):
+ """Otherwise the suffix column rests on a source the table does not name."""
+ tsv = table(tmp_path,
+ ROW("a.amazonaws.com", "AWSServiceRoleForA", "refused", "recording"),
+ recordings="none")
+ problems = slr.check(tsv, policy_documents(tmp_path), documented={})
+ assert any("built from no snapshot" in problem for problem in problems)