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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

@@ -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";
@@ -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) {
@@ -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();
}
@@ -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",
@@ -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);
}
}
}
@@ -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();
}
@@ -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.");
}