From 368488cd5b367645aa4b38f6a5bac9bbcd036bc7 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:07:38 -0400 Subject: [PATCH] fix(iam): read the stored tags of SageMaker and BCM Data Exports resources (#9872) The request-resources table gives resource-tag keys to SageMaker's model, endpoint configuration, endpoint and training job types and to BCM Data Exports' export type, but neither namespace gave IAM the tags it stores, so an aws:ResourceTag condition on one of their actions never matched. SageMakerStoredResourceArns reads SageMakerService.storedTags: the tags of the caller's model, endpoint configuration, endpoint or training job the ARN names, in its Region, by the resource part the ARN starts with, read in place and copied under the monitor AddTags and DeleteTags change them under. BcmDataExportsStoredResourceArns reads BcmDataExportsService.storedTags: the ResourceTags an export's create gave it, read in place under its ARN. StoredResourceTagIamIntegrationTest checks a caller allowed sagemaker:DescribeModel and bcm-data-exports:GetExport only on resources tagged team=blue reaches the blue one and is refused the red one; both fail without the readers. SageMakerServiceTest checks the read, its copy, the ARNs that name nothing, and that a model, an endpoint configuration, an endpoint and a training job of one name answer their own tags by their own ARNs. --- docs/services/iam.md | 5 +- .../bcmdataexports/BcmDataExportsService.java | 17 ++++++ .../BcmDataExportsStoredResourceArns.java | 44 ++++++++++++++++ .../services/sagemaker/SageMakerService.java | 35 +++++++++++++ .../SageMakerStoredResourceArns.java | 45 ++++++++++++++++ .../StoredResourceTagIamIntegrationTest.java | 50 +++++++++++++++++- .../sagemaker/SageMakerServiceTest.java | 52 +++++++++++++++++++ 7 files changed, 244 insertions(+), 4 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/bcmdataexports/BcmDataExportsStoredResourceArns.java create mode 100644 src/main/java/io/floci/aws/services/sagemaker/SageMakerStoredResourceArns.java diff --git a/docs/services/iam.md b/docs/services/iam.md index 6bbdabf3bf..fe2f967525 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -4049,8 +4049,9 @@ floci populates: for its servers and users, SES for its identities, configuration sets, templates, contact lists, custom verification email templates, dedicated IP pools and tenants, ElastiCache for its users, user groups, replication groups, cache clusters, snapshots, subnet groups, parameter groups and serverless caches, DMS for its endpoints, - replication instances, replication tasks and replication subnet groups, and Amazon Managed Service for Prometheus - for its workspaces and rule groups namespaces. Tag keys + replication instances, replication tasks and replication subnet groups, SageMaker for its models, endpoint + configurations, endpoints and training jobs, BCM Data Exports for its exports, and Amazon Managed Service for + Prometheus for its workspaces and rule groups namespaces. Tag keys differing only in case are one condition key holding every value. - EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and `ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the diff --git a/src/main/java/io/floci/aws/services/bcmdataexports/BcmDataExportsService.java b/src/main/java/io/floci/aws/services/bcmdataexports/BcmDataExportsService.java index 8705796902..d10a8d432e 100644 --- a/src/main/java/io/floci/aws/services/bcmdataexports/BcmDataExportsService.java +++ b/src/main/java/io/floci/aws/services/bcmdataexports/BcmDataExportsService.java @@ -109,6 +109,23 @@ public class BcmDataExportsService { return incoming; } + /** + * The tags of the caller's export the ARN names, the {@code ResourceTags} its create gave it, read in place; empty + * for an ARN of another account or naming no export this service holds. Every change stores a new export record, + * so the copy read is of one whole set. + */ + public Map storedTags(String exportArn) { + String account = regionResolver.getAccountId(); + if (!AwsArnUtils.isArnFor(exportArn, "bcm-data-exports") + || !account.equals(AwsArnUtils.parse(exportArn).accountId())) { + return Map.of(); + } + return AccountAwareStorageBackend.readInAccount(exportStore, account, exportKey(exportArn)) + .map(Export::getResourceTags) + .>map(LinkedHashMap::new) + .orElse(Map.of()); + } + /** {@code GetExport} — returns the {@link Export} matching {@code exportArn}. */ public Export getExport(String exportArn) { requireNonEmpty(exportArn, "ExportArn"); diff --git a/src/main/java/io/floci/aws/services/bcmdataexports/BcmDataExportsStoredResourceArns.java b/src/main/java/io/floci/aws/services/bcmdataexports/BcmDataExportsStoredResourceArns.java new file mode 100644 index 0000000000..422b3c2281 --- /dev/null +++ b/src/main/java/io/floci/aws/services/bcmdataexports/BcmDataExportsStoredResourceArns.java @@ -0,0 +1,44 @@ +package io.floci.aws.services.bcmdataexports; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.StoredResourceArns; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * What IAM asks BCM Data Exports of the resources a request names: the tags it keeps on an export, which the + * request-resources table's resource-tag keys for that type take as their values ({@code aws:ResourceTag/}). + */ +@ApplicationScoped +public class BcmDataExportsStoredResourceArns implements StoredResourceArns { + + private final BcmDataExportsService exports; + + @Inject + public BcmDataExportsStoredResourceArns(BcmDataExportsService exports) { + this.exports = exports; + } + + @Override + public String namespace() { + return "bcm-data-exports"; + } + + /** A request names an export by its ARN: nothing to find. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "bcm-data-exports")) { + return Map.of(); + } + return StoredResourceArns.withEmptyValues(exports.storedTags(arn)); + } +} diff --git a/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java b/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java index a329efd6cc..24eafe19eb 100644 --- a/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java +++ b/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java @@ -462,6 +462,41 @@ public class SageMakerService { return mapper.createObjectNode(); } + /** + * The tags of the caller's model, endpoint configuration, endpoint or training job the ARN names, in the ARN's + * Region, the ones {@code ListTags} reads, read in place and copied under the monitor {@code AddTags} and + * {@code DeleteTags} change them under; empty for an ARN of another kind, account or Region, or naming nothing + * this service holds. The kind is the resource part the ARN starts with, as its format names it. + */ + public synchronized Map storedTags(String arn) { + AwsArnUtils.Arn parsed; + try { + parsed = AwsArnUtils.parse(arn); + } catch (IllegalArgumentException expected) { + // Not an ARN: it names no SageMaker resource. + return Map.of(); + } + String account = regionResolver.getAccountId(); + String resource = parsed.resource(); + int slash = resource.indexOf('/'); + if (!"sagemaker".equals(parsed.service()) || !account.equals(parsed.accountId()) || parsed.region().isBlank() + || slash < 0) { + return Map.of(); + } + String key = regionKey(parsed.region(), resource.substring(slash + 1)); + Optional> tags = switch (resource.substring(0, slash)) { + case "model" -> AccountAwareStorageBackend.readInAccount(modelStore, account, key).map(model -> model.tags); + case "endpoint-config" -> AccountAwareStorageBackend.readInAccount(endpointConfigStore, account, key) + .map(config -> config.tags); + case "endpoint" -> AccountAwareStorageBackend.readInAccount(endpointStore, account, key) + .map(endpoint -> endpoint.tags); + case "training-job" -> AccountAwareStorageBackend.readInAccount(trainingJobStore, account, key) + .map(job -> job.tags); + default -> Optional.empty(); + }; + return tags.>map(LinkedHashMap::new).orElse(Map.of()); + } + public synchronized ObjectNode addTags(JsonNode request) { String arn = required(request, "ResourceArn"); Map tags = tagsFromList(request.path("Tags")); diff --git a/src/main/java/io/floci/aws/services/sagemaker/SageMakerStoredResourceArns.java b/src/main/java/io/floci/aws/services/sagemaker/SageMakerStoredResourceArns.java new file mode 100644 index 0000000000..08083f449f --- /dev/null +++ b/src/main/java/io/floci/aws/services/sagemaker/SageMakerStoredResourceArns.java @@ -0,0 +1,45 @@ +package io.floci.aws.services.sagemaker; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.StoredResourceArns; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * What IAM asks SageMaker of the resources a request names: the tags it keeps on a model, an endpoint + * configuration, an endpoint or a training job, which the request-resources table's resource-tag keys for those types + * take as their values ({@code aws:ResourceTag/}). + */ +@ApplicationScoped +public class SageMakerStoredResourceArns implements StoredResourceArns { + + private final SageMakerService sageMaker; + + @Inject + public SageMakerStoredResourceArns(SageMakerService sageMaker) { + this.sageMaker = sageMaker; + } + + @Override + public String namespace() { + return "sagemaker"; + } + + /** A request names a SageMaker resource by the name its ARN ends in: nothing to find. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "sagemaker")) { + return Map.of(); + } + return StoredResourceArns.withEmptyValues(sageMaker.storedTags(arn)); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/StoredResourceTagIamIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StoredResourceTagIamIntegrationTest.java index e996d70e8e..075632b633 100644 --- a/src/test/java/io/floci/aws/services/iam/StoredResourceTagIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/StoredResourceTagIamIntegrationTest.java @@ -36,8 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** * A condition on {@code aws:ResourceTag} reads the tags a service keeps on the resource a request names, for the types * the request-resources table gives resource-tag keys: a Config rule, an EFS file system, a Route 53 Resolver rule, a - * Transfer Family server, an SES configuration set, an SES tenant, a DMS endpoint and a DMS subnet group. A caller - * allowed an action only on resources tagged {@code team=blue} may act on the blue one and is refused the red one. + * Transfer Family server, an SES configuration set, an SES tenant, a DMS endpoint, a DMS subnet group, a SageMaker + * model and a BCM Data Exports export. A caller allowed an action only on resources tagged {@code team=blue} may act + * on the blue one and is refused the red one. */ @QuarkusTest @TestProfile(IamEnforcementProfile.class) @@ -257,6 +258,51 @@ class StoredResourceTagIamIntegrationTest { .statusCode(200); } + @Test + void aSageMakerModelIsCheckedWithItsTags() { + String admin = auth(ACCOUNT, REGION.id(), "sagemaker"); + String[] names = new String[2]; + for (int i = 0; i < 2; i++) { + String team = i == 0 ? "blue" : "red"; + String name = team + "-" + suffix(); + json("SageMaker.CreateModel", """ + {"ModelName":"%s","PrimaryContainer":{"Image":"busybox:stable"}, + "Tags":[{"Key":"team","Value":"%s"}]}""".formatted(name, team), admin).statusCode(200); + cleanup.register(() -> json("SageMaker.DeleteModel", "{\"ModelName\":\"" + name + "\"}", admin)); + names[i] = name; + } + String caller = auth(user("sagemaker:DescribeModel").accessKeyId(), REGION.id(), "sagemaker"); + json("SageMaker.DescribeModel", "{\"ModelName\":\"" + names[1] + "\"}", caller) + .statusCode(400).body(containsString("not authorized to perform: sagemaker:DescribeModel")); + json("SageMaker.DescribeModel", "{\"ModelName\":\"" + names[0] + "\"}", caller) + .statusCode(200).body("ModelName", equalTo(names[0])); + } + + @Test + void aBcmDataExportIsCheckedWithItsTags() { + String admin = auth(ACCOUNT, REGION.id(), "bcm-data-exports"); + String[] arns = new String[2]; + for (int i = 0; i < 2; i++) { + String team = i == 0 ? "blue" : "red"; + String arn = json("AWSBillingAndCostManagementDataExports.CreateExport", """ + {"Export":{"Name":"%s","DataQuery":{"QueryStatement":"SELECT * FROM COST_AND_USAGE_REPORT"}, + "DestinationConfigurations":{"S3Destination":{"S3Bucket":"tags-bucket","S3Prefix":"out/", + "S3Region":"us-east-1","S3OutputConfigurations":{"Format":"PARQUET","Compression":"PARQUET", + "OutputType":"CUSTOM","Overwrite":"OVERWRITE_REPORT"}}}, + "RefreshCadence":{"Frequency":"SYNCHRONOUS"}}, + "ResourceTags":[{"Key":"team","Value":"%s"}]}""".formatted(team + "-" + suffix(), team), admin) + .statusCode(200).extract().path("ExportArn"); + cleanup.register(() -> json("AWSBillingAndCostManagementDataExports.DeleteExport", + "{\"ExportArn\":\"" + arn + "\"}", admin)); + arns[i] = arn; + } + String caller = auth(user("bcm-data-exports:GetExport").accessKeyId(), REGION.id(), "bcm-data-exports"); + json("AWSBillingAndCostManagementDataExports.GetExport", "{\"ExportArn\":\"" + arns[1] + "\"}", caller) + .statusCode(400).body(containsString("not authorized to perform: bcm-data-exports:GetExport")); + json("AWSBillingAndCostManagementDataExports.GetExport", "{\"ExportArn\":\"" + arns[0] + "\"}", caller) + .statusCode(200); + } + /** * A JSON 1.1 call on the test's port: a cleanup runs after the test method, once Quarkus has reset RestAssured's * port, so every call names it. diff --git a/src/test/java/io/floci/aws/services/sagemaker/SageMakerServiceTest.java b/src/test/java/io/floci/aws/services/sagemaker/SageMakerServiceTest.java index 1bc6ac2aa3..48a9d59920 100644 --- a/src/test/java/io/floci/aws/services/sagemaker/SageMakerServiceTest.java +++ b/src/test/java/io/floci/aws/services/sagemaker/SageMakerServiceTest.java @@ -42,6 +42,58 @@ class SageMakerServiceTest { private final ObjectMapper mapper = new ObjectMapper(); + /** + * IAM reads the tags SageMaker keeps on a resource by its ARN, in the ARN's Region, as a copy; an ARN of another + * kind, Region or account, or naming nothing it holds, has none, and a name holding another kind's word is read as + * its own kind. + */ + @Test + void storedTagsReadTheResourceTheArnNames() throws Exception { + SageMakerService service = service(); + String arn = service.createModel(mapper.readTree(""" + {"ModelName":"endpoint-like","PrimaryContainer":{"Image":"busybox:stable"}, + "Tags":[{"Key":"team","Value":"blue"}]} + """), "us-east-1").path("ModelArn").asText(); + + assertEquals(Map.of("team", "blue"), service.storedTags(arn)); + service.storedTags(arn).put("forged", "yes"); + assertEquals(Map.of("team", "blue"), service.storedTags(arn)); + assertEquals(Map.of(), service.storedTags(arn.replace(":us-east-1:", ":eu-west-1:"))); + assertEquals(Map.of(), service.storedTags(arn.replace(":" + DEFAULT_ACCOUNT + ":", ":" + OTHER_ACCOUNT + ":"))); + assertEquals(Map.of(), service.storedTags(arn.replace(":model/", ":endpoint/"))); + assertEquals(Map.of(), service.storedTags(arn + "-missing")); + assertEquals(Map.of(), service.storedTags("not-an-arn")); + } + + /** + * Each kind of SageMaker resource is read from its own store: a model, an endpoint configuration, an endpoint and a + * training job of one name, each tagged apart, answer their own tags by their own ARNs. + */ + @Test + void storedTagsReadEachKindFromItsOwnStore() throws Exception { + SageMakerService service = service(); + String model = service.createModel(mapper.readTree(""" + {"ModelName":"same","PrimaryContainer":{"Image":"busybox:stable"}, + "Tags":[{"Key":"kind","Value":"model"}]} + """), "us-east-1").path("ModelArn").asText(); + String config = service.createEndpointConfig(mapper.readTree(""" + {"EndpointConfigName":"same","ProductionVariants":[{"VariantName":"AllTraffic","ModelName":"same", + "InitialInstanceCount":1,"InstanceType":"ml.t2.medium"}],"Tags":[{"Key":"kind","Value":"config"}]} + """), "us-east-1").path("EndpointConfigArn").asText(); + String endpoint = service.createEndpoint(mapper.readTree(""" + {"EndpointName":"same","EndpointConfigName":"same","Tags":[{"Key":"kind","Value":"endpoint"}]} + """), "us-east-1").path("EndpointArn").asText(); + String job = service.createTrainingJob(mapper.readTree(""" + {"TrainingJobName":"same","AlgorithmSpecification":{"TrainingImage":"busybox:stable"}, + "OutputDataConfig":{"S3OutputPath":"s3://bucket/out"},"Tags":[{"Key":"kind","Value":"job"}]} + """), "us-east-1").path("TrainingJobArn").asText(); + + assertEquals(Map.of("kind", "model"), service.storedTags(model)); + assertEquals(Map.of("kind", "config"), service.storedTags(config)); + assertEquals(Map.of("kind", "endpoint"), service.storedTags(endpoint)); + assertEquals(Map.of("kind", "job"), service.storedTags(job)); + } + @Test void modelCrudAndDuplicateValidation() throws Exception { SageMakerService service = service();