fix(budgets): give resource-tag conditions the tags of the budget or budget action a request names (#8823)

The generated request resources give Budgets' budget and budgetAction
types the aws:ResourceTag/ key, but no service answered the budgets
namespace's stored tags, so a condition on a budget's or an action's
tags saw none. BudgetsService now answers it: a budget records no ARN,
so storedTags takes the ARN only when it is the one the budget's account
and name give in the request's partition, an action's adding its id,
then reads the record under the key the handlers read, in the request's
account, in place. Tag calls already run one at a time and give the
record a new tag list; the tag fields are now volatile.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 01:43:59 -04:00
1 parent 72055e2690
commit bb8a92b8fd
8 files changed
+166 -25

No files matched your search

+2 -2
View File
@@ -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
@@ -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<StoredResourceArns>} for the namespace a request or an ARN is of, so IAM never depends on that
* service directly.</p>
* 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<StoredResourceArns>} for the namespace a request or an
* ARN is of, so IAM never depends on that service directly.</p>
*
* <p>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
@@ -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<BudgetRecord> budgets;
private final AccountAwareStorageBackend<BudgetActionRecord> 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<Map<String, BudgetRecord>>() {}),
storageFactory.create("budget-actions", "budget-actions.json", new TypeReference<Map<String, BudgetActionRecord>>() {}),
objectMapper);
objectMapper, regionResolver);
}
BudgetsService(AccountAwareStorageBackend<BudgetRecord> budgets,
AccountAwareStorageBackend<BudgetActionRecord> 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<String> find(String type, List<String> 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/<id>}; 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<String, String> 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<JsonNode> 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<String, String> 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.");
}
@@ -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<JsonNode> histories = new ArrayList<>();
public BudgetActionRecord() {}
@@ -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<BudgetNotification> notifications = new ArrayList<>();
public BudgetRecord() {}
@@ -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.<BudgetActionRecord>inMemory(ACCOUNT), mapper);
AccountAwareStorageBackend.<BudgetActionRecord>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<String, BudgetRecord> raw = new InMemoryStorage<>();
BudgetsService legacyState = new BudgetsService(new AccountAwareStorageBackend<>(raw, null, ACCOUNT),
AccountAwareStorageBackend.<BudgetActionRecord>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");
@@ -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/<name>}, a put on the one its
* {@code ReportDefinition.ReportName} names and a modify on the one its {@code ReportName} names, neither on one
@@ -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)
1 # Service packages that mint ARNs or hosts but are not in PartitionCrossServiceSmokeIntegrationTest.
5 account
6 appintegrations
7 athena
8 budgets
9 cloudformation
10 cloudhsmv2
11 cloudtrail