diff --git a/docs/services/iam.md b/docs/services/iam.md index 7321ba3188..760983b01b 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3355,8 +3355,8 @@ floci populates: instances, ACM for its certificates, Firehose for its delivery streams, Cognito for its user pools and identity pools, OpenSearch for its domains, Signer for its signing profiles, Access Analyzer for its analyzers, Managed Service for Apache Flink for its applications, S3 Vectors for its vector buckets and indexes, Timestream for InfluxDB for its - DB instances, DB clusters, parameter groups and backups, and CloudTrail for its trails. Tag keys differing only in - case are one condition key holding every value. + DB instances, DB clusters, parameter groups and backups, CloudTrail for its trails, and Budgets for its budgets and + budget actions. 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 key names, an ARN for a key the Service Reference types as one. `resourceKeys` in diff --git a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java index 63abf34f08..ca23f387d2 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -48,10 +48,10 @@ import java.util.Optional; * stream; Cognito, for the tags of a user pool or an identity pool; OpenSearch, for the tags of a domain; Signer, for * the tags of a signing profile; Access Analyzer, for the tags of an analyzer; Managed Service for Apache Flink, for * the tags of an application; S3 Vectors, for the tags of a vector bucket or an index; Timestream for InfluxDB, for the - * tags of a DB instance, a DB cluster, a parameter group or a backup; CloudTrail, for the tags of a trail); looked up - * lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through - * {@code Instance} for the namespace a request or an ARN is of, so IAM never depends on that - * service directly.

+ * tags of a DB instance, a DB cluster, a parameter group or a backup; CloudTrail, for the tags of a trail; Budgets, for + * the tags of a budget or a budget action); looked up lazily by {@code ResourceArnBuilder} and + * {@code IamConditionContextResolver} through {@code Instance} for the namespace a request or an + * ARN is of, so IAM never depends on that service directly.

* *

Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find}, * {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone diff --git a/src/main/java/io/floci/aws/services/budgets/BudgetsService.java b/src/main/java/io/floci/aws/services/budgets/BudgetsService.java index b530afbdd7..e794afbdbb 100644 --- a/src/main/java/io/floci/aws/services/budgets/BudgetsService.java +++ b/src/main/java/io/floci/aws/services/budgets/BudgetsService.java @@ -9,7 +9,9 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; +import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.Resettable; +import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.common.UuidShapes; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -26,12 +28,13 @@ import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; @ApplicationScoped -public class BudgetsService implements Resettable { +public class BudgetsService implements Resettable, StoredResourceArns { private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}"); private static final Pattern IAM_POLICY_ARN = Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::(?:\\d{12}|aws):policy/.+$"); private static final Pattern SCP_POLICY_ID = Pattern.compile("^p-[0-9a-zA-Z_]{8,128}$"); @@ -51,24 +54,78 @@ public class BudgetsService implements Resettable { private static final int MAX_NOTIFICATIONS = 10; private static final int MAX_EMAIL_SUBSCRIBERS = 10; + /** What a budget's ARN resource starts with, its name following. */ + private static final String BUDGET_RESOURCE = "budget/"; + /** What follows a budget's ARN in the ARN of one of its actions, the action's id following. */ + private static final String ACTION_SEGMENT = "/action/"; + private final AccountAwareStorageBackend budgets; private final AccountAwareStorageBackend actions; private final ObjectMapper objectMapper; + private final RegionResolver regionResolver; @Inject - public BudgetsService(StorageFactory storageFactory, ObjectMapper objectMapper) { + public BudgetsService(StorageFactory storageFactory, ObjectMapper objectMapper, RegionResolver regionResolver) { this( storageFactory.create("budgets", "budgets.json", new TypeReference>() {}), storageFactory.create("budget-actions", "budget-actions.json", new TypeReference>() {}), - objectMapper); + objectMapper, regionResolver); } BudgetsService(AccountAwareStorageBackend budgets, AccountAwareStorageBackend actions, - ObjectMapper objectMapper) { + ObjectMapper objectMapper, RegionResolver regionResolver) { this.budgets = budgets; this.actions = actions; this.objectMapper = objectMapper; + this.regionResolver = regionResolver; + } + + @Override + public String namespace() { + return "budgets"; + } + + /** A request names a budget by its account and name, and an action by its id, all in its ARN: nothing to find. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + /** + * The tags of the budget or the budget action whose ARN is {@code arn}, in the request's account, where the + * handlers read: an ARN of another account names none. A budget records no ARN, so the ARN must be the one its + * account and name give in the request's partition, an action's adding {@code /action/}; the record is then + * read in place under the key the handlers read it by, one stored before storage was account-aware included. Tag + * calls run one at a time and give the record a new tag list, so the read is of one whole set. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "budgets")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String account = budgets.accountId(); + if (!parsed.accountId().equals(account) || !parsed.resource().startsWith(BUDGET_RESOURCE) + || !arn.equals(regionResolver.buildGlobalArn("budgets", account, parsed.resource()))) { + return Map.of(); + } + String value = parsed.resource().substring(BUDGET_RESOURCE.length()); + int action = value.indexOf(ACTION_SEGMENT); + Optional tags = action < 0 + ? AccountAwareStorageBackend.readInAccount(budgets, account, key(account, value)) + .map(BudgetRecord::getResourceTags) + : AccountAwareStorageBackend.readInAccount(actions, account, actionKey(value.substring(0, action), + value.substring(action + ACTION_SEGMENT.length()))) + .map(BudgetActionRecord::getResourceTags); + Map held = new LinkedHashMap<>(); + tags.filter(JsonNode::isArray).ifPresent(list -> list.forEach(tag -> { + String key = text(tag, "Key"); + if (key != null) { + held.put(key, tag.path("Value").asText("")); + } + })); + return held; } @@ -824,16 +881,16 @@ public class BudgetsService implements Resettable { } String account = arn.substring(resourceStart, separator); String resource = arn.substring(separator + 1); - if (!ACCOUNT_ID.matcher(account).matches() || !resource.startsWith("budget/")) { + if (!ACCOUNT_ID.matcher(account).matches() || !resource.startsWith(BUDGET_RESOURCE)) { throw invalid("ResourceARN is not a valid Budgets ARN."); } - String value = resource.substring("budget/".length()); - int actionMarker = value.indexOf("/action/"); + String value = resource.substring(BUDGET_RESOURCE.length()); + int actionMarker = value.indexOf(ACTION_SEGMENT); if (actionMarker < 0) { return new ResourceRef(account, requireBudgetNameValue(value), null); } String budgetName = requireBudgetNameValue(value.substring(0, actionMarker)); - String actionId = value.substring(actionMarker + "/action/".length()); + String actionId = value.substring(actionMarker + ACTION_SEGMENT.length()); if (!UuidShapes.matchesEitherCase(actionId)) { throw invalid("ResourceARN contains an invalid action ID."); } diff --git a/src/main/java/io/floci/aws/services/budgets/model/BudgetActionRecord.java b/src/main/java/io/floci/aws/services/budgets/model/BudgetActionRecord.java index 48d691dca8..d4fd3e7624 100644 --- a/src/main/java/io/floci/aws/services/budgets/model/BudgetActionRecord.java +++ b/src/main/java/io/floci/aws/services/budgets/model/BudgetActionRecord.java @@ -14,7 +14,7 @@ public class BudgetActionRecord { private String budgetName; private String actionId; private JsonNode action; - private JsonNode resourceTags; + private volatile JsonNode resourceTags; private List histories = new ArrayList<>(); public BudgetActionRecord() {} diff --git a/src/main/java/io/floci/aws/services/budgets/model/BudgetRecord.java b/src/main/java/io/floci/aws/services/budgets/model/BudgetRecord.java index dfe6ba9cfb..ff2b8016de 100644 --- a/src/main/java/io/floci/aws/services/budgets/model/BudgetRecord.java +++ b/src/main/java/io/floci/aws/services/budgets/model/BudgetRecord.java @@ -12,7 +12,7 @@ import java.util.List; public class BudgetRecord { private String accountId; private JsonNode budget; - private JsonNode resourceTags; + private volatile JsonNode resourceTags; private List notifications = new ArrayList<>(); public BudgetRecord() {} diff --git a/src/test/java/io/floci/aws/services/budgets/BudgetsServiceTest.java b/src/test/java/io/floci/aws/services/budgets/BudgetsServiceTest.java index 185312e452..0bda77acfd 100644 --- a/src/test/java/io/floci/aws/services/budgets/BudgetsServiceTest.java +++ b/src/test/java/io/floci/aws/services/budgets/BudgetsServiceTest.java @@ -4,12 +4,17 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.budgets.model.BudgetActionRecord; import io.floci.aws.services.budgets.model.BudgetRecord; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.Map; +import java.util.Set; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -22,7 +27,8 @@ class BudgetsServiceTest { @BeforeEach void setUp() { service = new BudgetsService(AccountAwareStorageBackend.inMemory(ACCOUNT), - AccountAwareStorageBackend.inMemory(ACCOUNT), mapper); + AccountAwareStorageBackend.inMemory(ACCOUNT), mapper, + new RegionResolver("us-east-1", ACCOUNT)); } @Test @@ -108,6 +114,55 @@ class BudgetsServiceTest { assertEquals("EXECUTION_SUCCESS", history.path("Status").asText()); } + /** + * IAM's lookup reads the tags of the budget or the action the ARN names, as the tag calls leave them, and nothing + * for another account's, another partition's, a Regional or an unknown ARN. + */ + @Test + void storedTagsAreTheTagsOfTheBudgetOrTheActionTheArnNames() { + ObjectNode create = createBudget("tagged"); + create.putArray("ResourceTags").addObject().put("Key", "team").put("Value", "web"); + service.createBudget(create); + String arn = "arn:aws:budgets::" + ACCOUNT + ":budget/tagged"; + ObjectNode tag = mapper.createObjectNode().put("ResourceARN", arn); + tag.putArray("ResourceTags").add(mapper.createObjectNode().put("Key", "team").put("Value", "data")) + .add(mapper.createObjectNode().put("Key", "env").put("Value", "dev")); + service.tagResource(tag); + ObjectNode untag = mapper.createObjectNode().put("ResourceARN", arn); + untag.putArray("ResourceTagKeys").add("env"); + service.untagResource(untag); + ObjectNode action = actionRequest("tagged", "APPLY_IAM_POLICY"); + action.putArray("ResourceTags").addObject().put("Key", "team").put("Value", "ops"); + String actionArn = arn + "/action/" + service.createBudgetAction(action).getActionId(); + + assertEquals("budgets", service.namespace()); + assertEquals(Map.of("team", "data"), service.storedTags(arn)); + assertEquals(Map.of("team", "ops"), service.storedTags(actionArn)); + assertTrue(service.storedTags(arn.replace(ACCOUNT, "210987654321")).isEmpty()); + assertTrue(service.storedTags(arn.replace("arn:aws:", "arn:aws-cn:")).isEmpty()); + assertTrue(service.storedTags(arn.replace("budgets::", "budgets:us-east-1:")).isEmpty()); + assertTrue(service.storedTags(arn.replace("budget/tagged", "budget/missing")).isEmpty()); + assertTrue(service.storedTags("arn:aws:ce::" + ACCOUNT + ":anomalymonitor/tagged").isEmpty()); + } + + /** A budget stored before storage was account-aware is read in place: the lookup migrates nothing. */ + @Test + void storedTagsReadAPreAccountAwareBudgetInPlace() { + InMemoryStorage raw = new InMemoryStorage<>(); + BudgetsService legacyState = new BudgetsService(new AccountAwareStorageBackend<>(raw, null, ACCOUNT), + AccountAwareStorageBackend.inMemory(ACCOUNT), mapper, + new RegionResolver("us-east-1", ACCOUNT)); + BudgetRecord legacy = new BudgetRecord(); + legacy.setAccountId(ACCOUNT); + legacy.setBudget(createBudget("legacy").get("Budget")); + legacy.setResourceTags(mapper.createArrayNode().add(mapper.createObjectNode().put("Key", "team") + .put("Value", "data"))); + raw.put(ACCOUNT + "::legacy", legacy); + + assertEquals(Map.of("team", "data"), legacyState.storedTags("arn:aws:budgets::" + ACCOUNT + ":budget/legacy")); + assertEquals(Set.of(ACCOUNT + "::legacy"), raw.keys()); + } + private ObjectNode createBudget(String name) { ObjectNode request = mapper.createObjectNode().put("AccountId", ACCOUNT); ObjectNode budget = request.putObject("Budget"); diff --git a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java index a8971da4ac..e1c93a0a65 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -1680,14 +1680,8 @@ class IamRequestResourceEnforcementIntegrationTest { void aBudgetIsCheckedOnTheArnItsNameGives() { String name = "res-budget-" + suffix(); String other = name + "-other"; - for (String budget : List.of(name, other)) { - adminJson("budgets", "AWSBudgetServiceGateway.CreateBudget") - .body("{\"AccountId\":\"" + ACCOUNT + "\",\"Budget\":" + budget(budget, null) + "}").post("/") - .then().statusCode(200); - cleanup.register(() -> adminJson("budgets", "AWSBudgetServiceGateway.DeleteBudget") - .body("{\"AccountId\":\"" + ACCOUNT + "\",\"BudgetName\":\"" + budget + "\"}").post("/")); - } - String arn = "arn:aws:budgets::" + ACCOUNT + ":budget/" + name; + String arn = createdBudget(name, null); + createdBudget(other, null); adminJson("budgets", "AWSBudgetServiceGateway.TagResource").body("{\"ResourceARN\":\"" + arn + "\",\"ResourceTags\":[{\"Key\":\"a\",\"Value\":\"b\"}]}").post("/").then().statusCode(200); @@ -1703,6 +1697,40 @@ class IamRequestResourceEnforcementIntegrationTest { .statusCode(200); } + /** + * An {@code aws:ResourceTag} condition reads the tags Budgets holds on the budget a request names, as TagResource + * leaves them, so an allow on one team's tag lets the caller read that team's budget and not another's. + */ + @Test + void aBudgetsResourceTagConditionReadsTheTagsOfTheBudget() { + String web = "[{\"Key\":\"team\",\"Value\":\"web\"}]"; + String tagged = "res-budget-tagged-" + suffix(); + String other = "res-budget-untagged-" + suffix(); + String taggedArn = createdBudget(tagged, web); + createdBudget(other, web); + adminJson("budgets", "AWSBudgetServiceGateway.TagResource").body("{\"ResourceARN\":\"" + taggedArn + + "\",\"ResourceTags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}").post("/").then().statusCode(200); + + User user = user("res-budget-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":\"budgets:ViewBudget\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + budgets(user, "DescribeBudget", "{\"AccountId\":\"" + ACCOUNT + "\",\"BudgetName\":\"" + tagged + "\"}") + .statusCode(200); + refusedJson(budgets(user, "DescribeBudget", "{\"AccountId\":\"" + ACCOUNT + "\",\"BudgetName\":\"" + other + + "\"}"), "budgets:ViewBudget"); + } + + /** The ARN of the budget {@code name} an administrator creates, with the {@code tags} list if any. */ + private String createdBudget(String name, String tags) { + adminJson("budgets", "AWSBudgetServiceGateway.CreateBudget") + .body("{\"AccountId\":\"" + ACCOUNT + "\",\"Budget\":" + budget(name, null) + + (tags == null ? "" : ",\"ResourceTags\":" + tags) + "}") + .post("/").then().statusCode(200); + cleanup.register(() -> adminJson("budgets", "AWSBudgetServiceGateway.DeleteBudget") + .body("{\"AccountId\":\"" + ACCOUNT + "\",\"BudgetName\":\"" + name + "\"}").post("/")); + return "arn:aws:budgets::" + ACCOUNT + ":budget/" + name; + } + /** * A Cost and Usage Report definition is checked on {@code definition/}, a put on the one its * {@code ReportDefinition.ReportName} names and a modify on the one its {@code ReportName} names, neither on one diff --git a/src/test/resources/partition/smoke-exemptions.tsv b/src/test/resources/partition/smoke-exemptions.tsv index 9fded9d442..8621d15d81 100644 --- a/src/test/resources/partition/smoke-exemptions.tsv +++ b/src/test/resources/partition/smoke-exemptions.tsv @@ -5,6 +5,7 @@ account the one ARN it builds is the member account an IAM check names, in the partition of the caller's organization's own ARN, and it never reaches the wire, so a case has nothing to assert appintegrations no non-commercial partition publishes the service, so a case would be skipped in every partition athena the only ARNs it builds are the default workgroup and data catalog an IAM check names for a request naming none, in the request Region's partition, and they never reach the wire, so a case has nothing to assert +budgets the only ARN it builds is the budget's or budget action's own, in the request's partition, which an IAM tag lookup compares against the ARN a request names, and it never reaches the wire, so a case has nothing to assert cloudformation covered by PartitionArnMintingIntegrationTest (all partitions) cloudhsmv2 the only ARN on the wire is the automatic backup's, and a backup is never removed (DeleteBackup only marks it), so a case would leak state into the shared emulator cloudtrail covered by CloudTrailSelfDeliveryTest (one partition)