Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(budgets): add full service emulation (#3165)

Franklin G. Mendoza7a5ae965e52d
diff --git a/README.md b/README.md
index 17c4aefd79..bb3a61122e 100644
--- a/README.md
+++ b/README.md
@@ -239,7 +239,7 @@ Floci supports local emulation for application services, data services, eventing
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core, Amazon Connect |
| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin), Identity Store, Amazon Macie, Control Tower, Service Catalog |
-| Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
+| Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
For operation-level compatibility, see the [Services Overview](https://floci.io/floci/services/).
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index a3b71d50b9..10aef8febb 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -244,6 +244,10 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>identitystore</artifactId>
</dependency>
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>budgets</artifactId>
+ </dependency>
<!-- Amazon Macie client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 7f3820d2f0..36184b46cc 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -34,6 +34,7 @@ import software.amazon.awssdk.services.fis.FisClient;
import software.amazon.awssdk.services.organizations.OrganizationsClient;
import software.amazon.awssdk.services.ssoadmin.SsoAdminClient;
import software.amazon.awssdk.services.identitystore.IdentitystoreClient;
+import software.amazon.awssdk.services.budgets.BudgetsClient;
import software.amazon.awssdk.services.macie2.Macie2Client;
import software.amazon.awssdk.services.rum.RumClient;
import software.amazon.awssdk.services.resourceexplorer2.ResourceExplorer2Client;
@@ -312,6 +313,22 @@ public final class TestFixtures {
.build();
}
+ public static BudgetsClient budgetsClient() {
+ return BudgetsClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
+ public static BudgetsClient budgetsClient(String accountId) {
+ return BudgetsClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accountId, "test")))
+ .build();
+ }
+
public static Macie2Client macie2Client() {
return macie2Client("test");
}
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BudgetsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BudgetsTest.java
new file mode 100644
index 0000000000..f55527838d
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BudgetsTest.java
@@ -0,0 +1,138 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.budgets.BudgetsClient;
+import software.amazon.awssdk.services.budgets.model.*;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class BudgetsTest {
+ private static final String ACCOUNT_ID = "000000000000";
+
+ @Test
+ void completeBudgetLifecycle() {
+ String budgetName = TestFixtures.uniqueName("budget");
+ Notification notification = Notification.builder()
+ .notificationType(NotificationType.ACTUAL)
+ .comparisonOperator(ComparisonOperator.GREATER_THAN)
+ .threshold(80d)
+ .thresholdType(ThresholdType.PERCENTAGE)
+ .build();
+ Subscriber firstSubscriber = Subscriber.builder()
+ .subscriptionType(SubscriptionType.EMAIL)
+ .address("[email protected]")
+ .build();
+
+ try (BudgetsClient client = TestFixtures.budgetsClient()) {
+ client.createBudget(CreateBudgetRequest.builder()
+ .accountId(ACCOUNT_ID)
+ .budget(Budget.builder()
+ .budgetName(budgetName)
+ .budgetType(BudgetType.COST)
+ .timeUnit(TimeUnit.MONTHLY)
+ .budgetLimit(Spend.builder().amount(new java.math.BigDecimal("100.00")).unit("USD").build())
+ .build())
+ .notificationsWithSubscribers(NotificationWithSubscribers.builder()
+ .notification(notification)
+ .subscribers(firstSubscriber)
+ .build())
+ .resourceTags(ResourceTag.builder().key("managed_by").value("floci-test").build())
+ .build());
+
+ assertThat(client.describeBudget(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName)).budget().budgetName())
+ .isEqualTo(budgetName);
+ assertThat(client.describeBudgets(b -> b.accountId(ACCOUNT_ID).maxResults(1000)).budgets())
+ .extracting(Budget::budgetName).contains(budgetName);
+ assertThat(client.describeNotificationsForBudget(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName)).notifications())
+ .hasSize(1);
+ assertThat(client.describeSubscribersForNotification(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).notification(notification)).subscribers())
+ .hasSize(1);
+ assertThat(client.describeBudgetNotificationsForAccount(b -> b.accountId(ACCOUNT_ID)).budgetNotificationsForAccount())
+ .anyMatch(item -> budgetName.equals(item.budgetName()));
+
+ Subscriber second = Subscriber.builder().subscriptionType(SubscriptionType.EMAIL).address("[email protected]").build();
+ client.createSubscriber(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).notification(notification).subscriber(second));
+ Subscriber replacement = Subscriber.builder().subscriptionType(SubscriptionType.EMAIL).address("[email protected]").build();
+ client.updateSubscriber(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).notification(notification)
+ .oldSubscriber(second).newSubscriber(replacement));
+ client.deleteSubscriber(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).notification(notification).subscriber(replacement));
+
+ Notification updatedNotification = notification.toBuilder().threshold(90d).build();
+ client.updateNotification(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName)
+ .oldNotification(notification).newNotification(updatedNotification));
+
+ String budgetArn = "arn:aws:budgets::" + ACCOUNT_ID + ":budget/" + budgetName;
+ client.tagResource(b -> b.resourceARN(budgetArn).resourceTags(ResourceTag.builder().key("team").value("platform").build()));
+ assertThat(client.listTagsForResource(b -> b.resourceARN(budgetArn)).resourceTags())
+ .anyMatch(tag -> "team".equals(tag.key()));
+ client.untagResource(b -> b.resourceARN(budgetArn).resourceTagKeys("team"));
+
+ client.updateBudget(b -> b.accountId(ACCOUNT_ID).newBudget(Budget.builder()
+ .budgetName(budgetName).budgetType(BudgetType.COST).timeUnit(TimeUnit.MONTHLY)
+ .budgetLimit(Spend.builder().amount(new java.math.BigDecimal("150.00")).unit("USD").build()).build()));
+ assertThat(client.describeBudgetPerformanceHistory(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName)).budgetPerformanceHistory())
+ .isNotNull();
+
+ CreateBudgetActionResponse createdAction = client.createBudgetAction(CreateBudgetActionRequest.builder()
+ .accountId(ACCOUNT_ID)
+ .budgetName(budgetName)
+ .notificationType(NotificationType.ACTUAL)
+ .actionType(ActionType.APPLY_IAM_POLICY)
+ .actionThreshold(ActionThreshold.builder().actionThresholdType(ThresholdType.PERCENTAGE).actionThresholdValue(100d).build())
+ .definition(Definition.builder().iamActionDefinition(IamActionDefinition.builder()
+ .policyArn("arn:aws:iam::aws:policy/ReadOnlyAccess").users("alice").build()).build())
+ .executionRoleArn("arn:aws:iam::" + ACCOUNT_ID + ":role/BudgetExecutionRole")
+ .approvalModel(ApprovalModel.MANUAL)
+ .subscribers(firstSubscriber)
+ .resourceTags(ResourceTag.builder().key("kind").value("guardrail").build())
+ .build());
+ String actionId = createdAction.actionId();
+ assertThat(actionId).isNotBlank();
+ assertThat(client.describeBudgetAction(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).actionId(actionId)).action().actionId())
+ .isEqualTo(actionId);
+ assertThat(client.describeBudgetActionsForAccount(b -> b.accountId(ACCOUNT_ID)).actions())
+ .extracting(Action::actionId).contains(actionId);
+ assertThat(client.describeBudgetActionsForBudget(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName)).actions())
+ .extracting(Action::actionId).contains(actionId);
+
+ client.updateBudgetAction(UpdateBudgetActionRequest.builder()
+ .accountId(ACCOUNT_ID).budgetName(budgetName).actionId(actionId)
+ .approvalModel(ApprovalModel.AUTOMATIC).build());
+ client.executeBudgetAction(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).actionId(actionId)
+ .executionType(ExecutionType.APPROVE_BUDGET_ACTION));
+ Action executed = client.describeBudgetAction(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).actionId(actionId)).action();
+ assertThat(executed.status()).isEqualTo(ActionStatus.EXECUTION_SUCCESS);
+ List<ActionHistory> histories = client.describeBudgetActionHistories(
+ b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).actionId(actionId)).actionHistories();
+ assertThat(histories).isNotEmpty();
+ assertThat(histories).anySatisfy(history -> {
+ assertThat(history.eventType()).isEqualTo(EventType.EXECUTE_ACTION);
+ assertThat(history.status()).isEqualTo(ActionStatus.EXECUTION_SUCCESS);
+ });
+
+ String actionArn = budgetArn + "/action/" + actionId;
+ client.tagResource(b -> b.resourceARN(actionArn).resourceTags(ResourceTag.builder().key("action").value("yes").build()));
+ assertThat(client.listTagsForResource(b -> b.resourceARN(actionArn)).resourceTags()).isNotEmpty();
+
+ client.deleteBudgetAction(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).actionId(actionId));
+ client.deleteNotification(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName).notification(updatedNotification));
+ client.deleteBudget(b -> b.accountId(ACCOUNT_ID).budgetName(budgetName));
+ }
+ }
+ @Test
+ void crossAccountBudgetAccessIsDenied() {
+ String caller = "123456789012";
+ String foreign = "210987654321";
+ try (BudgetsClient client = TestFixtures.budgetsClient(caller)) {
+ assertThatThrownBy(() -> client.describeBudget(b -> b.accountId(foreign).budgetName("foreign")))
+ .isInstanceOf(AccessDeniedException.class);
+ assertThatThrownBy(() -> client.listTagsForResource(b ->
+ b.resourceARN("arn:aws:budgets::" + foreign + ":budget/foreign")))
+ .isInstanceOf(AccessDeniedException.class);
+ }
+ }
+
+}
diff --git a/docs/services/budgets.md b/docs/services/budgets.md
new file mode 100644
index 0000000000..212f38f641
--- /dev/null
+++ b/docs/services/budgets.md
@@ -0,0 +1,60 @@
+# AWS Budgets
+
+**Protocol:** JSON 1.1 (`X-Amz-Target: AWSBudgetServiceGateway.*`)
+
+**Signing name:** `budgets`
+
+Floci emulates the complete AWS Budgets management API surface, including budgets, notifications, subscribers, budget actions, action history, performance history, and resource tags. State is persisted locally and isolated by AWS account.
+
+## Supported Actions
+
+<!-- floci:actions:start -->
+| Action | Description |
+| --- | --- |
+| `CreateBudget` | - |
+| `CreateBudgetAction` | - |
+| `CreateNotification` | - |
+| `CreateSubscriber` | - |
+| `DeleteBudget` | - |
+| `DeleteBudgetAction` | - |
+| `DeleteNotification` | - |
+| `DeleteSubscriber` | - |
+| `DescribeBudget` | - |
+| `DescribeBudgetAction` | - |
+| `DescribeBudgetActionHistories` | - |
+| `DescribeBudgetActionsForAccount` | - |
+| `DescribeBudgetActionsForBudget` | - |
+| `DescribeBudgetNotificationsForAccount` | - |
+| `DescribeBudgetPerformanceHistory` | - |
+| `DescribeBudgets` | - |
+| `DescribeNotificationsForBudget` | - |
+| `DescribeSubscribersForNotification` | - |
+| `ExecuteBudgetAction` | - |
+| `ListTagsForResource` | - |
+| `TagResource` | - |
+| `UntagResource` | - |
+| `UpdateBudget` | - |
+| `UpdateBudgetAction` | - |
+| `UpdateNotification` | - |
+| `UpdateSubscriber` | - |
+<!-- floci:actions:end -->
+
+## Behavior
+
+Budgets support the AWS budget types and time units, fixed or planned limits, legacy or expression-based filters, notifications and subscribers, and account-scoped listing. Budget actions support IAM, SCP, and SSM definition shapes, approval models, execution status transitions, history, and tags.
+
+Pagination uses the operation-specific AWS limits. `DescribeBudgets` and `DescribeBudgetNotificationsForAccount` allow up to 1000 results, while notification, subscriber, action, action-history, and performance-history listings use their documented lower limits.
+
+`DescribeBudgetPerformanceHistory` returns deterministic local history metadata. Floci does not manufacture provider billing usage, forecasts, or provider-side failures that do not arise from local state.
+
+## AWS-compatible failures
+
+Floci validates account IDs, budget names, budget/filter unions, tags, notification thresholds, subscriber quotas, action definitions, role ownership, action identifiers, and pagination. Deterministic failures use modeled AWS errors such as `InvalidParameterException`, `NotFoundException`, `DuplicateRecordException`, `CreationLimitExceededException`, `ServiceQuotaExceededException`, and `InvalidNextTokenException`.
+
+See the [AWS Budgets API Reference](https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Operations_AWS_Budgets.html).
+
+## Configuration
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_BUDGETS_ENABLED` | `true` | Enable or disable AWS Budgets |
diff --git a/docs/services/index.md b/docs/services/index.md
index 3004a12e34..a33e7e7e25 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -97,6 +97,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [AWS Network Firewall](network-firewall.md) | `POST /` + `X-Amz-Target: NetworkFirewall_20201112.*` | JSON 1.0 | 27 |
| [AWS Service Catalog](service-catalog.md) | `POST /` + `X-Amz-Target: AWS242ServiceCatalogService.*` | JSON 1.1 | 89 |
| [Service Quotas](servicequotas.md) | `POST /` + `X-Amz-Target: ServiceQuotasV20190624.*` | JSON 1.1 | 5 |
+| [AWS Budgets](budgets.md) | `POST /` + `X-Amz-Target: AWSBudgetServiceGateway.*` | JSON 1.1 | 26 |
| [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 12 |
| [Control Tower](controltower.md) | `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/*-baseline*` | REST JSON | 15 |
| [Managed Prometheus (AMP)](managed-prometheus.md) | `/workspaces/*`, `/tags/*` | REST JSON | 8 |
diff --git a/mkdocs.yml b/mkdocs.yml
index 59358e157b..536fc45a67 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -123,6 +123,7 @@ nav:
- IAM Access Analyzer: services/access-analyzer.md
- IAM Identity Center (SSO Admin): services/ssoadmin.md
- Identity Store: services/identitystore.md
+ - AWS Budgets: services/budgets.md
- Amazon Macie: services/macie2.md
- Control Tower: services/controltower.md
- AWS Service Catalog: services/service-catalog.md
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index ee11ef6cd0..eee5ceddd6 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -714,6 +714,7 @@ public interface EmulatorConfig {
AccountServiceConfig account();
AccessAnalyzerServiceConfig accessanalyzer();
IdentityStoreServiceConfig identitystore();
+ BudgetsServiceConfig budgets();
ServiceQuotasServiceConfig servicequotas();
RamServiceConfig ram();
ControlTowerServiceConfig controltower();
@@ -762,6 +763,11 @@ public interface EmulatorConfig {
boolean enabled();
}
+ interface BudgetsServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface ApsServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
index c25a2abf75..e9515df300 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
@@ -25,6 +25,7 @@ import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAut
import io.github.hectorvent.floci.services.cloudcontrol.CloudControlJsonHandler;
import io.github.hectorvent.floci.services.ssoadmin.SsoAdminJsonHandler;
import io.github.hectorvent.floci.services.identitystore.IdentityStoreJsonHandler;
+import io.github.hectorvent.floci.services.budgets.BudgetsJsonHandler;
import io.github.hectorvent.floci.services.configservice.ConfigServiceJsonHandler;
import io.github.hectorvent.floci.services.cur.CurJsonHandler;
import io.github.hectorvent.floci.services.pricing.PricingJsonHandler;
@@ -126,6 +127,7 @@ public class AwsJson11Controller {
private final OrganizationsJsonHandler organizationsJsonHandler;
private final SsoAdminJsonHandler ssoAdminJsonHandler;
private final IdentityStoreJsonHandler identityStoreJsonHandler;
+ private final BudgetsJsonHandler budgetsJsonHandler;
private final ServiceQuotasJsonHandler serviceQuotasJsonHandler;
@Inject
@@ -174,6 +176,7 @@ public class AwsJson11Controller {
OrganizationsJsonHandler organizationsJsonHandler,
SsoAdminJsonHandler ssoAdminJsonHandler,
IdentityStoreJsonHandler identityStoreJsonHandler,
+ BudgetsJsonHandler budgetsJsonHandler,
ServiceQuotasJsonHandler serviceQuotasJsonHandler) {
this.objectMapper = objectMapper;
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
@@ -226,6 +229,7 @@ public class AwsJson11Controller {
this.organizationsJsonHandler = organizationsJsonHandler;
this.ssoAdminJsonHandler = ssoAdminJsonHandler;
this.identityStoreJsonHandler = identityStoreJsonHandler;
+ this.budgetsJsonHandler = budgetsJsonHandler;
this.serviceQuotasJsonHandler = serviceQuotasJsonHandler;
}
@@ -314,6 +318,7 @@ public class AwsJson11Controller {
organizationsJsonHandler.handle(action, request, regionResolver.getAccountId());
case "sso" -> ssoAdminJsonHandler.handle(action, request, regionResolver.getAccountId());
case "identitystore" -> identityStoreJsonHandler.handle(action, request);
+ case "budgets" -> budgetsJsonHandler.handle(action, request, regionResolver.getAccountId());
case "servicequotas" -> serviceQuotasJsonHandler.handle(
action, request, region, regionResolver.getAccountId());
default -> null;
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 37b44de05e..fd1a980dab 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -423,6 +423,9 @@ public class ResolvedServiceCatalog {
descriptor("identitystore", "identitystore", config.services().identitystore().enabled(), true,
"identitystore", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON), Set.of("AWSIdentityStore."), Set.of("identitystore"), Set.of(), Set.of()),
+ descriptor("budgets", "budgets", config.services().budgets().enabled(), true,
+ "budgets", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
+ protocols(ServiceProtocol.JSON), Set.of("AWSBudgetServiceGateway."), Set.of("budgets"), Set.of(), Set.of()),
descriptor("autoscaling", "autoscaling", config.services().autoscaling().enabled(), true,
"autoscaling", config.storage().mode(), 5000L, AwsNamespaces.AUTOSCALING, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
diff --git a/src/main/java/io/github/hectorvent/floci/services/budgets/BudgetsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/budgets/BudgetsJsonHandler.java
new file mode 100644
index 0000000000..e209dc652e
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/budgets/BudgetsJsonHandler.java
@@ -0,0 +1,130 @@
+package io.github.hectorvent.floci.services.budgets;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.services.budgets.model.BudgetActionRecord;
+import io.github.hectorvent.floci.services.budgets.model.BudgetRecord;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+
+@ApplicationScoped
+public class BudgetsJsonHandler {
+ private final BudgetsService budgetsService;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public BudgetsJsonHandler(BudgetsService budgetsService, ObjectMapper objectMapper) {
+ this.budgetsService = budgetsService;
+ this.objectMapper = objectMapper;
+ }
+
+ public Response handle(String action, JsonNode request, String callerAccountId) {
+ budgetsService.validateCallerScope(request, callerAccountId);
+ return switch (action) {
+ case "CreateBudget" -> emptyAfter(() -> budgetsService.createBudget(request));
+ case "CreateBudgetAction" -> createBudgetAction(request);
+ case "CreateNotification" -> emptyAfter(() -> budgetsService.createNotification(request));
+ case "CreateSubscriber" -> emptyAfter(() -> budgetsService.createSubscriber(request));
+ case "DeleteBudget" -> emptyAfter(() -> budgetsService.deleteBudget(request));
+ case "DeleteBudgetAction" -> deleteBudgetAction(request);
+ case "DeleteNotification" -> emptyAfter(() -> budgetsService.deleteNotification(request));
+ case "DeleteSubscriber" -> emptyAfter(() -> budgetsService.deleteSubscriber(request));
+ case "DescribeBudget" -> describeBudget(request);
+ case "DescribeBudgetAction" -> describeBudgetAction(request);
+ case "DescribeBudgetActionHistories" -> page("ActionHistories", budgetsService.describeBudgetActionHistories(request));
+ case "DescribeBudgetActionsForAccount" -> page("Actions", budgetsService.describeBudgetActionsForAccount(request));
+ case "DescribeBudgetActionsForBudget" -> page("Actions", budgetsService.describeBudgetActionsForBudget(request));
+ case "DescribeBudgetNotificationsForAccount" -> page("BudgetNotificationsForAccount", budgetsService.describeBudgetNotificationsForAccount(request));
+ case "DescribeBudgetPerformanceHistory" -> describeBudgetPerformanceHistory(request);
+ case "DescribeBudgets" -> page("Budgets", budgetsService.describeBudgets(request));
+ case "DescribeNotificationsForBudget" -> page("Notifications", budgetsService.describeNotifications(request));
+ case "DescribeSubscribersForNotification" -> page("Subscribers", budgetsService.describeSubscribers(request));
+ case "ExecuteBudgetAction" -> executeBudgetAction(request);
+ case "ListTagsForResource" -> listTagsForResource(request);
+ case "TagResource" -> emptyAfter(() -> budgetsService.tagResource(request));
+ case "UntagResource" -> emptyAfter(() -> budgetsService.untagResource(request));
+ case "UpdateBudget" -> emptyAfter(() -> budgetsService.updateBudget(request));
+ case "UpdateBudgetAction" -> Response.ok(budgetsService.updateBudgetAction(request)).build();
+ case "UpdateNotification" -> emptyAfter(() -> budgetsService.updateNotification(request));
+ case "UpdateSubscriber" -> emptyAfter(() -> budgetsService.updateSubscriber(request));
+ default -> throw new AwsException("UnknownOperationException", "Operation " + action + " is not supported.", 400);
+ };
+ }
+
+ private Response describeBudget(JsonNode request) {
+ BudgetRecord record = budgetsService.describeBudget(request);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Budget", record.getBudget());
+ return Response.ok(response).build();
+ }
+
+ private Response createBudgetAction(JsonNode request) {
+ BudgetActionRecord record = budgetsService.createBudgetAction(request);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("AccountId", record.getAccountId());
+ response.put("BudgetName", record.getBudgetName());
+ response.put("ActionId", record.getActionId());
+ return Response.ok(response).build();
+ }
+
+
+ private Response deleteBudgetAction(JsonNode request) {
+ BudgetActionRecord record = budgetsService.deleteBudgetAction(request);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("AccountId", record.getAccountId());
+ response.put("BudgetName", record.getBudgetName());
+ response.set("Action", record.getAction());
+ return Response.ok(response).build();
+ }
+
+ private Response describeBudgetAction(JsonNode request) {
+ BudgetActionRecord record = budgetsService.describeBudgetAction(request);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("AccountId", record.getAccountId());
+ response.put("BudgetName", record.getBudgetName());
+ response.set("Action", record.getAction());
+ return Response.ok(response).build();
+ }
+
+ private Response executeBudgetAction(JsonNode request) {
+ BudgetActionRecord record = budgetsService.executeBudgetAction(request);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("AccountId", record.getAccountId());
+ response.put("BudgetName", record.getBudgetName());
+ response.put("ActionId", record.getActionId());
+ response.put("ExecutionType", request.path("ExecutionType").asText());
+ return Response.ok(response).build();
+ }
+
+ private Response describeBudgetPerformanceHistory(JsonNode request) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("BudgetPerformanceHistory", budgetsService.describeBudgetPerformanceHistory(request));
+ return Response.ok(response).build();
+ }
+
+ private Response listTagsForResource(JsonNode request) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("ResourceTags", budgetsService.listTagsForResource(request));
+ return Response.ok(response).build();
+ }
+
+ private Response page(String field, PaginatedResult<JsonNode> page) {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode items = response.putArray(field);
+ page.items().forEach(items::add);
+ if (page.nextToken() != null) {
+ response.put("NextToken", page.nextToken());
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response emptyAfter(Runnable action) {
+ action.run();
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/budgets/BudgetsService.java b/src/main/java/io/github/hectorvent/floci/services/budgets/BudgetsService.java
new file mode 100644
index 0000000000..64d89e5626
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/budgets/BudgetsService.java
@@ -0,0 +1,944 @@
+package io.github.hectorvent.floci.services.budgets;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.common.Pagination;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.budgets.model.BudgetActionRecord;
+import io.github.hectorvent.floci.services.budgets.model.BudgetNotification;
+import io.github.hectorvent.floci.services.budgets.model.BudgetRecord;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+@ApplicationScoped
+public class BudgetsService implements Resettable {
+ private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
+ private static final Pattern ACTION_ID = Pattern.compile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$");
+ private static final Pattern IAM_POLICY_ARN = Pattern.compile("^arn:aws(?:-eusc|-cn|-us-gov|-iso|-iso-[a-z])?:iam::(?:\\d{12}|aws):policy/.+$");
+ private static final Pattern SCP_POLICY_ID = Pattern.compile("^p-[0-9a-zA-Z_]{8,128}$");
+ private static final Pattern SCP_TARGET_ID = Pattern.compile("^(?:ou-[0-9a-z]{4,32}-[a-z0-9]{8,32}|\\d{12})$");
+ private static final Pattern SSM_INSTANCE_ID = Pattern.compile("^(?:i-(?:\\w{8}|\\w{17})|[a-zA-Z](?:[\\w-]{0,61}\\w)?)$");
+ private static final Pattern AWS_REGION = Pattern.compile("^\\w{2,4}-\\w+(?:-\\w+)?-\\d$");
+ private static final Pattern BUDGET_NAME = Pattern.compile("^(?![^:\\\\]*/action/|(?i).*<script>.*</script>.*)[^:\\\\]+$");
+ private static final Set<String> BUDGET_TYPES = Set.of("USAGE", "COST", "RI_UTILIZATION", "RI_COVERAGE",
+ "SAVINGS_PLANS_UTILIZATION", "SAVINGS_PLANS_COVERAGE");
+ private static final Set<String> TIME_UNITS = Set.of("DAILY", "MONTHLY", "QUARTERLY", "ANNUALLY", "CUSTOM");
+ private static final Set<String> COMPARISONS = Set.of("GREATER_THAN", "LESS_THAN", "EQUAL_TO");
+ private static final Set<String> NOTIFICATION_TYPES = Set.of("ACTUAL", "FORECASTED");
+ private static final Set<String> THRESHOLD_TYPES = Set.of("PERCENTAGE", "ABSOLUTE_VALUE");
+ private static final Set<String> ACTION_TYPES = Set.of("APPLY_IAM_POLICY", "APPLY_SCP_POLICY", "RUN_SSM_DOCUMENTS");
+ private static final Set<String> APPROVAL_MODELS = Set.of("AUTOMATIC", "MANUAL");
+ private static final Set<String> ACTION_THRESHOLD_TYPES = Set.of("PERCENTAGE", "ABSOLUTE_VALUE");
+ private static final int MAX_NOTIFICATIONS = 10;
+ private static final int MAX_EMAIL_SUBSCRIBERS = 10;
+
+ private final AccountAwareStorageBackend<BudgetRecord> budgets;
+ private final AccountAwareStorageBackend<BudgetActionRecord> actions;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public BudgetsService(StorageFactory storageFactory, ObjectMapper objectMapper) {
+ this(
+ storageFactory.create("budgets", "budgets.json", new TypeReference<Map<String, BudgetRecord>>() {}),
+ storageFactory.create("budget-actions", "budget-actions.json", new TypeReference<Map<String, BudgetActionRecord>>() {}),
+ objectMapper);
+ }
+
+ BudgetsService(AccountAwareStorageBackend<BudgetRecord> budgets,
+ AccountAwareStorageBackend<BudgetActionRecord> actions,
+ ObjectMapper objectMapper) {
+ this.budgets = budgets;
+ this.actions = actions;
+ this.objectMapper = objectMapper;
+ }
+
+
+ public void validateCallerScope(JsonNode request, String callerAccountId) {
+ if (callerAccountId == null || !ACCOUNT_ID.matcher(callerAccountId).matches()) {
+ throw new AwsException("AccessDeniedException",
+ "You are not authorized to use this operation with the given parameters.", 400);
+ }
+ if (request != null && request.has("AccountId")) {
+ String requestedAccountId = requireAccount(request);
+ if (!callerAccountId.equals(requestedAccountId)) {
+ throw new AwsException("AccessDeniedException",
+ "You are not authorized to use this operation with the given parameters.", 400);
+ }
+ }
+ if (request != null && request.has("ResourceARN")) {
+ String arn = text(request, "ResourceARN");
+ if (arn == null) {
+ throw invalid("ResourceARN is required.");
+ }
+ ResourceRef ref = parseResourceArn(arn);
+ if (!callerAccountId.equals(ref.accountId())) {
+ throw new AwsException("AccessDeniedException",
+ "You are not authorized to use this operation with the given parameters.", 400);
+ }
+ }
+ }
+
+ public BudgetRecord describeBudget(JsonNode request) {
+ return requireBudget(requireAccount(request), requireBudgetName(request));
+ }
+
+ public PaginatedResult<JsonNode> describeBudgets(JsonNode request) {
+ String accountId = requireAccount(request);
+ List<JsonNode> items = budgets.scanForAccount(accountId, key -> true).stream()
+ .map(BudgetRecord::getBudget)
+ .filter(node -> node != null)
+ .sorted(Comparator.comparing(node -> node.path("BudgetName").asText()))
+ .toList();
+ return Pagination.paginate(items, node -> node.path("BudgetName").asText(), readMaxResults(request, 1000, 1000),
+ text(request, "NextToken"), 1000, "InvalidNextTokenException");
+ }
+
+ public synchronized void createBudget(JsonNode request) {
+ String accountId = requireAccount(request);
+ JsonNode budget = request.get("Budget");
+ if (budget == null || !budget.isObject()) {
+ throw invalid("Budget is required.");
+ }
+ String name = requireBudgetName(budget, "BudgetName");
+ validateBudget(budget);
+ String key = key(accountId, name);
+ if (budgets.getForAccount(accountId, key).isPresent()) {
+ throw new AwsException("DuplicateRecordException", "A budget with this name already exists.", 400);
+ }
+ JsonNode resourceTags = request.get("ResourceTags");
+ validateTags(resourceTags);
+ List<BudgetNotification> notifications = parseNotifications(request.get("NotificationsWithSubscribers"));
+ BudgetRecord record = new BudgetRecord();
+ record.setAccountId(accountId);
+ record.setBudget(withBudgetResponseDefaults(budget));
+ record.setResourceTags(resourceTags == null ? null : resourceTags.deepCopy());
+ record.setNotifications(notifications);
+ budgets.putForAccount(accountId, key, record);
+ }
+
+ public synchronized void updateBudget(JsonNode request) {
+ String accountId = requireAccount(request);
+ JsonNode newBudget = request.get("NewBudget");
+ if (newBudget == null || !newBudget.isObject()) {
+ throw invalid("NewBudget is required.");
+ }
+ String name = requireBudgetName(newBudget, "BudgetName");
+ validateBudget(newBudget);
+ BudgetRecord record = requireBudget(accountId, name);
+ record.setBudget(withBudgetResponseDefaults(newBudget));
+ budgets.putForAccount(accountId, key(accountId, name), record);
+ }
+
+ public synchronized void deleteBudget(JsonNode request) {
+ String accountId = requireAccount(request);
+ String name = requireBudgetName(request);
+ requireBudget(accountId, name);
+ budgets.deleteForAccount(accountId, key(accountId, name));
+ actions.keysForAccount(accountId).stream()
+ .filter(actionKey -> actionKey.startsWith(name + "::"))
+ .toList()
+ .forEach(actionKey -> actions.deleteForAccount(accountId, actionKey));
+ }
+
+ public PaginatedResult<JsonNode> describeNotifications(JsonNode request) {
+ BudgetRecord record = requireBudget(requireAccount(request), requireBudgetName(request));
+ List<JsonNode> notifications = record.getNotifications().stream().map(BudgetNotification::getNotification).toList();
+ return Pagination.paginate(notifications, this::notificationCursor, readMaxResults(request, 100, 100),
+ text(request, "NextToken"), 100, "InvalidNextTokenException");
+ }
+
+ public PaginatedResult<JsonNode> describeSubscribers(JsonNode request) {
+ BudgetRecord record = requireBudget(requireAccount(request), requireBudgetName(request));
+ JsonNode notification = requireNotification(request.get("Notification"));
+ BudgetNotification found = findNotification(record, notification);
+ if (found == null) {
+ throw notFound("The specified notification was not found.");
+ }
+ return Pagination.paginate(found.getSubscribers(), this::subscriberCursor, readMaxResults(request, 100, 100),
+ text(request, "NextToken"), 100, "InvalidNextTokenException");
+ }
+
+ public PaginatedResult<JsonNode> describeBudgetNotificationsForAccount(JsonNode request) {
+ String accountId = requireAccount(request);
+ List<JsonNode> items = new ArrayList<>();
+ for (BudgetRecord record : budgets.scanForAccount(accountId, key -> true)) {
+ String budgetName = record.getBudget().path("BudgetName").asText();
+ for (BudgetNotification notification : record.getNotifications()) {
+ ObjectNode item = objectMapper.createObjectNode();
+ item.put("BudgetName", budgetName);
+ item.set("Notification", notification.getNotification());
+ items.add(item);
+ }
+ }
+ items.sort(Comparator.comparing(node -> node.path("BudgetName").asText() + "::" + notificationCursor(node.path("Notification"))));
+ return Pagination.paginate(items,
+ node -> node.path("BudgetName").asText() + "::" + notificationCursor(node.path("Notification")),
+ readMaxResults(request, 50, 1000), text(request, "NextToken"), 1000, "InvalidNextTokenException");
+ }
+
+ public synchronized void createNotification(JsonNode request) {
+ String accountId = requireAccount(request);
+ String name = requireBudgetName(request);
+ BudgetRecord record = requireBudget(accountId, name);
+ JsonNode notification = requireNotification(request.get("Notification"));
+ if (findNotification(record, notification) != null) {
+ throw new AwsException("DuplicateRecordException", "The notification already exists.", 400);
+ }
+ if (record.getNotifications().size() >= MAX_NOTIFICATIONS) {
+ throw new AwsException("CreationLimitExceededException", "A budget can have at most 10 notifications.", 400);
+ }
+ List<JsonNode> subscribers = parseSubscribers(request.get("Subscribers"));
+ record.getNotifications().add(new BudgetNotification(notification.deepCopy(), subscribers));
+ budgets.putForAccount(accountId, key(accountId, name), record);
+ }
+
+ public synchronized void updateNotification(JsonNode request) {
+ String accountId = requireAccount(request);
+ String name = requireBudgetName(request);
+ BudgetRecord record = requireBudget(accountId, name);
+ JsonNode oldNotification = requireNotification(request.get("OldNotification"));
+ JsonNode newNotification = requireNotification(request.get("NewNotification"));
+ BudgetNotification found = findNotification(record, oldNotification);
+ if (found == null) {
+ throw notFound("The specified notification was not found.");
+ }
+ BudgetNotification duplicate = findNotification(record, newNotification);
+ if (duplicate != null && duplicate != found) {
+ throw new AwsException("DuplicateRecordException", "The notification already exists.", 400);
+ }
+ found.setNotification(newNotification.deepCopy());
+ budgets.putForAccount(accountId, key(accountId, name), record);
+ }
+
+ public synchronized void deleteNotification(JsonNode request) {
+ String accountId = requireAccount(request);
+ String name = requireBudgetName(request);
+ BudgetRecord record = requireBudget(accountId, name);
+ JsonNode notification = requireNotification(request.get("Notification"));
+ BudgetNotification found = findNotification(record, notification);
+ if (found == null) {
+ throw notFound("The specified notification was not found.");
+ }
+ record.getNotifications().remove(found);
+ budgets.putForAccount(accountId, key(accountId, name), record);
+ }
+
+ public synchronized void createSubscriber(JsonNode request) {
+ mutateSubscriber(request, null, request.get("Subscriber"), SubscriberMutation.CREATE);
+ }
+
+ public synchronized void updateSubscriber(JsonNode request) {
+ mutateSubscriber(request, request.get("OldSubscriber"), request.get("NewSubscriber"), SubscriberMutation.UPDATE);
+ }
+
+ public synchronized void deleteSubscriber(JsonNode request) {
+ mutateSubscriber(request, request.get("Subscriber"), null, SubscriberMutation.DELETE);
+ }
+
+ public JsonNode listTagsForResource(JsonNode request) {
+ ResourceRef ref = parseResourceArn(requireText(request, "ResourceARN"));
+ JsonNode tags = tagsFor(ref);
+ return tags == null ? objectMapper.createArrayNode() : tags.deepCopy();
+ }
+
+ public synchronized void tagResource(JsonNode request) {
+ ResourceRef ref = parseResourceArn(requireText(request, "ResourceARN"));
+ JsonNode incoming = request.get("ResourceTags");
+ validateTags(incoming);
+ ArrayNode merged = objectMapper.createArrayNode();
+ Map<String, String> tags = new java.util.LinkedHashMap<>();
+ JsonNode current = tagsFor(ref);
+ if (current != null && current.isArray()) {
+ current.forEach(tag -> tags.put(text(tag, "Key"), text(tag, "Value")));
+ }
+ if (incoming != null && incoming.isArray()) {
+ incoming.forEach(tag -> tags.put(text(tag, "Key"), text(tag, "Value")));
+ }
+ if (tags.size() > 200) {
+ throw new AwsException("ServiceQuotaExceededException", "Tag limit exceeded.", 400);
+ }
+ tags.forEach((key, value) -> {
+ ObjectNode tag = merged.addObject();
+ tag.put("Key", key);
+ tag.put("Value", value);
+ });
+ setTags(ref, merged);
+ }
+
+ public synchronized void untagResource(JsonNode request) {
+ ResourceRef ref = parseResourceArn(requireText(request, "ResourceARN"));
+ JsonNode keys = request.get("ResourceTagKeys");
+ if (keys == null || !keys.isArray() || keys.isEmpty()) {
+ throw invalid("ResourceTagKeys must contain at least one key.");
+ }
+ Set<String> remove = new HashSet<>();
+ keys.forEach(node -> {
+ if (!node.isTextual() || node.textValue().isBlank()) {
+ throw invalid("ResourceTagKeys contains an invalid key.");
+ }
+ remove.add(node.textValue());
+ });
+ ArrayNode remaining = objectMapper.createArrayNode();
+ JsonNode current = tagsFor(ref);
+ if (current != null && current.isArray()) {
+ current.forEach(tag -> {
+ if (!remove.contains(text(tag, "Key"))) {
+ remaining.add(tag.deepCopy());
+ }
+ });
+ }
+ setTags(ref, remaining);
+ }
+
+ public ObjectNode describeBudgetPerformanceHistory(JsonNode request) {
+ BudgetRecord record = requireBudget(requireAccount(request), requireBudgetName(request));
+ JsonNode budget = record.getBudget();
+ String timeUnit = text(budget, "TimeUnit");
+ if ("ANNUALLY".equals(timeUnit)) {
+ throw invalid("Budget performance history is not available for annual budgets.");
+ }
+ readMaxResults(request, 100, 100);
+ if (text(request, "NextToken") != null) {
+ throw new AwsException("InvalidNextTokenException", "The pagination token is invalid.", 400);
+ }
+ ObjectNode history = objectMapper.createObjectNode();
+ copyIfPresent(budget, history, "BudgetName", "BudgetType", "CostFilters", "CostTypes", "FilterExpression", "Metrics", "TimeUnit", "BillingViewArn");
+ history.putArray("BudgetedAndActualAmountsList");
+ return history;
+ }
+
+ public synchronized BudgetActionRecord createBudgetAction(JsonNode request) {
+ String accountId = requireAccount(request);
+ String budgetName = requireBudgetName(request);
+ requireBudget(accountId, budgetName);
+ validateActionRequest(request, true, text(request, "ActionType"));
+ String actionId = UUID.randomUUID().toString();
+ ObjectNode action = actionFromRequest(request, actionId, "STANDBY");
+ BudgetActionRecord record = new BudgetActionRecord();
+ record.setAccountId(accountId);
+ record.setBudgetName(budgetName);
+ record.setActionId(actionId);
+ record.setAction(action);
+ JsonNode tags = request.get("ResourceTags");
+ validateTags(tags);
+ record.setResourceTags(tags == null ? null : tags.deepCopy());
+ actions.putForAccount(accountId, actionKey(budgetName, actionId), record);
+ return record;
+ }
+
+ public BudgetActionRecord describeBudgetAction(JsonNode request) {
+ return requireAction(requireAccount(request), requireBudgetName(request), requireActionId(request));
+ }
+
+ public PaginatedResult<JsonNode> describeBudgetActionsForAccount(JsonNode request) {
+ String accountId = requireAccount(request);
+ List<JsonNode> items = actions.scanForAccount(accountId, key -> true).stream()
+ .map(BudgetActionRecord::getAction)
+ .sorted(Comparator.comparing(node -> node.path("ActionId").asText()))
+ .toList();
+ return Pagination.paginate(items, node -> node.path("ActionId").asText(), readMaxResults(request, 100, 100),
+ text(request, "NextToken"), 100, "InvalidNextTokenException");
+ }
+
+ public PaginatedResult<JsonNode> describeBudgetActionsForBudget(JsonNode request) {
+ String accountId = requireAccount(request);
+ String budgetName = requireBudgetName(request);
+ requireBudget(accountId, budgetName);
+ List<JsonNode> items = actions.scanForAccount(accountId, key -> key.startsWith(budgetName + "::")).stream()
+ .map(BudgetActionRecord::getAction)
+ .sorted(Comparator.comparing(node -> node.path("ActionId").asText()))
+ .toList();
+ return Pagination.paginate(items, node -> node.path("ActionId").asText(), readMaxResults(request, 100, 100),
+ text(request, "NextToken"), 100, "InvalidNextTokenException");
+ }
+
+ public PaginatedResult<JsonNode> describeBudgetActionHistories(JsonNode request) {
+ BudgetActionRecord record = requireAction(requireAccount(request), requireBudgetName(request), requireActionId(request));
+ List<JsonNode> histories = record.getHistories();
+ return Pagination.paginate(histories, JsonNode::toString, readMaxResults(request, 100, 100),
+ text(request, "NextToken"), 100, "InvalidNextTokenException");
+ }
+
+ public synchronized ObjectNode updateBudgetAction(JsonNode request) {
+ String accountId = requireAccount(request);
+ String budgetName = requireBudgetName(request);
+ String actionId = requireActionId(request);
+ BudgetActionRecord record = requireAction(accountId, budgetName, actionId);
+ validateActionRequest(request, false, record.getAction().path("ActionType").asText());
+ ObjectNode oldAction = record.getAction().deepCopy();
+ ObjectNode updated = oldAction.deepCopy();
+ for (String field : List.of("ActionThreshold", "ApprovalModel", "Definition", "ExecutionRoleArn", "NotificationType", "Subscribers")) {
+ if (request.has(field)) {
+ updated.set(field, request.get(field).deepCopy());
+ }
+ }
+ record.setAction(updated);
+ addActionHistory(record, "UPDATE_ACTION", updated.path("Status").asText(), "Budget action updated.", updated);
+ actions.putForAccount(accountId, actionKey(budgetName, actionId), record);
+ ObjectNode result = objectMapper.createObjectNode();
+ result.put("AccountId", accountId);
+ result.put("BudgetName", budgetName);
+ result.set("OldAction", oldAction);
+ result.set("NewAction", updated);
+ return result;
+ }
+
+ public synchronized BudgetActionRecord deleteBudgetAction(JsonNode request) {
+ String accountId = requireAccount(request);
+ String budgetName = requireBudgetName(request);
+ String actionId = requireActionId(request);
+ BudgetActionRecord record = requireAction(accountId, budgetName, actionId);
+ actions.deleteForAccount(accountId, actionKey(budgetName, actionId));
+ return record;
+ }
+
+ public synchronized BudgetActionRecord executeBudgetAction(JsonNode request) {
+ String accountId = requireAccount(request);
+ String budgetName = requireBudgetName(request);
+ String actionId = requireActionId(request);
+ BudgetActionRecord record = requireAction(accountId, budgetName, actionId);
+ String executionType = requireText(request, "ExecutionType");
+ if (!Set.of("APPROVE_BUDGET_ACTION", "RETRY_BUDGET_ACTION", "REVERSE_BUDGET_ACTION", "RESET_BUDGET_ACTION").contains(executionType)) {
+ throw invalid("ExecutionType is invalid.");
+ }
+ ObjectNode action = record.getAction().deepCopy();
+ String status = switch (executionType) {
+ case "REVERSE_BUDGET_ACTION" -> "REVERSE_SUCCESS";
+ case "RESET_BUDGET_ACTION" -> "STANDBY";
+ default -> "EXECUTION_SUCCESS";
+ };
+ action.put("Status", status);
+ record.setAction(action);
+ addActionHistory(record, "EXECUTE_ACTION", status, "Budget action execution completed.", action);
+ actions.putForAccount(accountId, actionKey(budgetName, actionId), record);
+ return record;
+ }
+
+ @Override
+ public synchronized void clear() {
+ budgets.clear();
+ actions.clear();
+ }
+
+ private void mutateSubscriber(JsonNode request, JsonNode oldNode, JsonNode newNode, SubscriberMutation mutation) {
+ String accountId = requireAccount(request);
+ String budgetName = requireBudgetName(request);
+ BudgetRecord record = requireBudget(accountId, budgetName);
+ JsonNode notification = requireNotification(request.get("Notification"));
+ BudgetNotification found = findNotification(record, notification);
+ if (found == null) {
+ throw notFound("The specified notification was not found.");
+ }
+ JsonNode oldSubscriber = oldNode == null ? null : requireSubscriber(oldNode);
+ JsonNode newSubscriber = newNode == null ? null : requireSubscriber(newNode);
+ if (mutation == SubscriberMutation.CREATE) {
+ if (findSubscriber(found, newSubscriber) != null) {
+ throw new AwsException("DuplicateRecordException", "The subscriber already exists.", 400);
+ }
+ List<JsonNode> copy = new ArrayList<>(found.getSubscribers());
+ copy.add(newSubscriber);
+ found.setSubscribers(parseSubscribers(objectMapper.valueToTree(copy)));
+ } else {
+ JsonNode existing = findSubscriber(found, oldSubscriber);
+ if (existing == null) {
+ throw notFound("The specified subscriber was not found.");
+ }
+ if (mutation == SubscriberMutation.DELETE) {
+ found.getSubscribers().remove(existing);
+ } else {
+ JsonNode duplicate = findSubscriber(found, newSubscriber);
+ if (duplicate != null && duplicate != existing) {
+ throw new AwsException("DuplicateRecordException", "The subscriber already exists.", 400);
+ }
+ int index = found.getSubscribers().indexOf(existing);
+ found.getSubscribers().set(index, newSubscriber.deepCopy());
+ found.setSubscribers(parseSubscribers(objectMapper.valueToTree(found.getSubscribers())));
+ }
+ }
+ budgets.putForAccount(accountId, key(accountId, budgetName), record);
+ }
+
+ private BudgetRecord requireBudget(String accountId, String name) {
+ return budgets.getForAccount(accountId, key(accountId, name))
+ .orElseThrow(() -> notFound("The specified budget was not found."));
+ }
+
+ private BudgetActionRecord requireAction(String accountId, String budgetName, String actionId) {
+ return actions.getForAccount(accountId, actionKey(budgetName, actionId))
+ .orElseThrow(() -> notFound("The specified budget action was not found."));
+ }
+
+ private List<BudgetNotification> parseNotifications(JsonNode node) {
+ if (node == null || node.isNull()) {
+ return new ArrayList<>();
+ }
+ if (!node.isArray() || node.size() > MAX_NOTIFICATIONS) {
+ throw new AwsException("CreationLimitExceededException", "A budget can have at most 10 notifications.", 400);
+ }
+ List<BudgetNotification> result = new ArrayList<>();
+ for (JsonNode item : node) {
+ if (!item.isObject()) {
+ throw invalid("NotificationsWithSubscribers contains an invalid entry.");
+ }
+ JsonNode notification = requireNotification(item.get("Notification"));
+ if (result.stream().anyMatch(existing -> existing.getNotification().equals(notification))) {
+ throw new AwsException("DuplicateRecordException", "Duplicate notification.", 400);
+ }
+ result.add(new BudgetNotification(notification.deepCopy(), parseSubscribers(item.get("Subscribers"))));
+ }
+ return result;
+ }
+
+ private List<JsonNode> parseSubscribers(JsonNode node) {
+ if (node == null || !node.isArray() || node.isEmpty()) {
+ throw invalid("Subscribers must contain at least one subscriber.");
+ }
+ if (node.size() > 11) {
+ throw new AwsException("CreationLimitExceededException", "A notification can have at most 11 subscribers.", 400);
+ }
+ int sns = 0;
+ int email = 0;
+ Set<String> unique = new HashSet<>();
+ List<JsonNode> result = new ArrayList<>();
+ for (JsonNode subscriber : node) {
+ JsonNode validated = requireSubscriber(subscriber);
+ String type = text(validated, "SubscriptionType");
+ String address = text(validated, "Address");
+ if ("SNS".equals(type)) {
+ sns++;
+ } else {
+ email++;
+ }
+ if (sns > 1 || email > MAX_EMAIL_SUBSCRIBERS) {
+ throw new AwsException("CreationLimitExceededException", "Subscriber limit exceeded.", 400);
+ }
+ if (!unique.add(type + "::" + address)) {
+ throw new AwsException("DuplicateRecordException", "Duplicate subscriber.", 400);
+ }
+ result.add(validated.deepCopy());
+ }
+ return result;
+ }
+
+ private JsonNode requireSubscriber(JsonNode node) {
+ if (node == null || !node.isObject()) {
+ throw invalid("Subscriber is required.");
+ }
+ String type = text(node, "SubscriptionType");
+ String address = text(node, "Address");
+ if (!Set.of("SNS", "EMAIL").contains(type) || address == null || address.isBlank()
+ || address.contains("\n") || address.contains("\r")) {
+ throw invalid("Subscriber is invalid.");
+ }
+ return node;
+ }
+
+ private JsonNode requireNotification(JsonNode node) {
+ if (node == null || !node.isObject()) {
+ throw invalid("Notification is required.");
+ }
+ String comparison = text(node, "ComparisonOperator");
+ String type = text(node, "NotificationType");
+ String thresholdType = text(node, "ThresholdType");
+ JsonNode threshold = node.get("Threshold");
+ if (!COMPARISONS.contains(comparison) || !NOTIFICATION_TYPES.contains(type)
+ || (thresholdType != null && !THRESHOLD_TYPES.contains(thresholdType))
+ || threshold == null || !threshold.isNumber() || !Double.isFinite(threshold.asDouble())
+ || threshold.asDouble() < 0 || threshold.asDouble() > 10_000_000) {
+ throw invalid("Notification contains invalid values.");
+ }
+ return node;
+ }
+
+ private void validateBudget(JsonNode budget) {
+ String type = text(budget, "BudgetType");
+ String unit = text(budget, "TimeUnit");
+ if (type == null || !BUDGET_TYPES.contains(type)) {
+ throw invalid("BudgetType is invalid.");
+ }
+ if (unit == null || !TIME_UNITS.contains(unit)) {
+ throw invalid("TimeUnit is invalid.");
+ }
+ if (budget.has("BudgetLimit") && budget.has("PlannedBudgetLimits")) {
+ throw invalid("Only one of BudgetLimit or PlannedBudgetLimits may be specified.");
+ }
+ boolean newFilters = budget.has("FilterExpression") || budget.has("Metrics");
+ boolean legacyFilters = budget.has("CostFilters") || budget.has("CostTypes");
+ if (newFilters && legacyFilters) {
+ throw invalid("FilterExpression/Metrics and CostFilters/CostTypes cannot be combined.");
+ }
+ JsonNode period = budget.get("TimePeriod");
+ if (period != null && period.isObject() && period.has("Start") && period.has("End")
+ && period.path("Start").asDouble() >= period.path("End").asDouble()) {
+ throw invalid("TimePeriod Start must be before End.");
+ }
+ }
+
+ private ObjectNode withBudgetResponseDefaults(JsonNode input) {
+ ObjectNode result = input.deepCopy();
+ result.put("LastUpdatedTime", Instant.now().getEpochSecond());
+ if (!result.has("CalculatedSpend")) {
+ ObjectNode spend = result.putObject("CalculatedSpend");
+ ObjectNode actual = spend.putObject("ActualSpend");
+ actual.put("Amount", "0");
+ actual.put("Unit", budgetUnit(result));
+ }
+ return result;
+ }
+
+ private String budgetUnit(JsonNode budget) {
+ JsonNode limit = budget.get("BudgetLimit");
+ if (limit != null && limit.isObject() && text(limit, "Unit") != null) {
+ return text(limit, "Unit");
+ }
+ return "USD";
+ }
+
+ private void validateTags(JsonNode tags) {
+ if (tags == null || tags.isNull()) {
+ return;
+ }
+ if (!tags.isArray() || tags.size() > 200) {
+ throw invalid("ResourceTags must contain at most 200 tags.");
+ }
+ Set<String> keys = new HashSet<>();
+ for (JsonNode tag : tags) {
+ String key = text(tag, "Key");
+ String value = text(tag, "Value");
+ if (key == null || key.isBlank() || key.length() > 128 || key.startsWith("aws:")
+ || value == null || value.length() > 256) {
+ throw invalid("ResourceTags contains an invalid tag.");
+ }
+ if (!keys.add(key)) {
+ throw invalid("ResourceTags contains duplicate keys.");
+ }
+ }
+ }
+
+ private void validateActionRequest(JsonNode request, boolean create, String effectiveActionType) {
+ if (create || request.has("NotificationType")) {
+ if (!NOTIFICATION_TYPES.contains(text(request, "NotificationType"))) {
+ throw invalid("NotificationType is invalid.");
+ }
+ }
+ if (create || request.has("ActionType")) {
+ if (!ACTION_TYPES.contains(text(request, "ActionType"))) {
+ throw invalid("ActionType is invalid.");
+ }
+ }
+ if (effectiveActionType == null || !ACTION_TYPES.contains(effectiveActionType)) {
+ throw invalid("ActionType is invalid.");
+ }
+ if (create || request.has("ApprovalModel")) {
+ if (!APPROVAL_MODELS.contains(text(request, "ApprovalModel"))) {
+ throw invalid("ApprovalModel is invalid.");
+ }
+ }
+ if (create || request.has("ActionThreshold")) {
+ JsonNode threshold = request.get("ActionThreshold");
+ double value = threshold == null ? Double.NaN : threshold.path("ActionThresholdValue").asDouble(Double.NaN);
+ if (threshold == null || !threshold.isObject()
+ || !ACTION_THRESHOLD_TYPES.contains(text(threshold, "ActionThresholdType"))
+ || !threshold.path("ActionThresholdValue").isNumber()
+ || !Double.isFinite(value) || value < 0 || value > 15_000_000_000_000D) {
+ throw invalid("ActionThreshold is invalid.");
+ }
+ }
+ if (create || request.has("Definition")) {
+ validateActionDefinition(request.get("Definition"), effectiveActionType);
+ }
+ if (create || request.has("ExecutionRoleArn")) {
+ String arn = text(request, "ExecutionRoleArn");
+ String account = requireAccount(request);
+ if (arn == null || !arn.matches("^arn:aws(?:-eusc|-cn|-us-gov|-iso|-iso-[a-z])?:iam::" + account + ":role/.+$")) {
+ throw invalid("ExecutionRoleArn is invalid or belongs to another account.");
+ }
+ }
+ if (create || request.has("Subscribers")) {
+ parseSubscribers(request.get("Subscribers"));
+ }
+ }
+
+ private void validateActionDefinition(JsonNode definition, String actionType) {
+ if (definition == null || !definition.isObject()) {
+ throw invalid("Definition is required.");
+ }
+ int variants = (definition.has("IamActionDefinition") ? 1 : 0)
+ + (definition.has("ScpActionDefinition") ? 1 : 0)
+ + (definition.has("SsmActionDefinition") ? 1 : 0);
+ if (variants != 1) {
+ throw invalid("Definition must contain exactly one action definition.");
+ }
+ switch (actionType) {
+ case "APPLY_IAM_POLICY" -> validateIamActionDefinition(definition.get("IamActionDefinition"));
+ case "APPLY_SCP_POLICY" -> validateScpActionDefinition(definition.get("ScpActionDefinition"));
+ case "RUN_SSM_DOCUMENTS" -> validateSsmActionDefinition(definition.get("SsmActionDefinition"));
+ default -> throw invalid("ActionType is invalid.");
+ }
+ }
+
+ private void validateIamActionDefinition(JsonNode iam) {
+ if (iam == null || !iam.isObject()) {
+ throw invalid("Definition does not match ActionType.");
+ }
+ String policyArn = text(iam, "PolicyArn");
+ if (policyArn == null || policyArn.length() < 25 || policyArn.length() > 684
+ || !IAM_POLICY_ARN.matcher(policyArn).matches()) {
+ throw invalid("IamActionDefinition.PolicyArn is invalid.");
+ }
+ int targets = validateStringArray(iam, "Groups", 100, 640)
+ + validateStringArray(iam, "Roles", 100, 576)
+ + validateStringArray(iam, "Users", 100, 576);
+ if (targets == 0) {
+ throw invalid("IamActionDefinition must target at least one group, role, or user.");
+ }
+ }
+
+ private void validateScpActionDefinition(JsonNode scp) {
+ if (scp == null || !scp.isObject()) {
+ throw invalid("Definition does not match ActionType.");
+ }
+ String policyId = text(scp, "PolicyId");
+ if (policyId == null || !SCP_POLICY_ID.matcher(policyId).matches()) {
+ throw invalid("ScpActionDefinition.PolicyId is invalid.");
+ }
+ JsonNode targets = scp.get("TargetIds");
+ if (targets == null || !targets.isArray() || targets.isEmpty() || targets.size() > 100) {
+ throw invalid("ScpActionDefinition.TargetIds is invalid.");
+ }
+ for (JsonNode target : targets) {
+ if (!target.isTextual() || !SCP_TARGET_ID.matcher(target.textValue()).matches()) {
+ throw invalid("ScpActionDefinition.TargetIds is invalid.");
+ }
+ }
+ }
+
+ private void validateSsmActionDefinition(JsonNode ssm) {
+ if (ssm == null || !ssm.isObject()) {
+ throw invalid("Definition does not match ActionType.");
+ }
+ if (!Set.of("STOP_EC2_INSTANCES", "STOP_RDS_INSTANCES").contains(text(ssm, "ActionSubType"))) {
+ throw invalid("SsmActionDefinition.ActionSubType is invalid.");
+ }
+ String region = text(ssm, "Region");
+ if (region == null || !AWS_REGION.matcher(region).matches()) {
+ throw invalid("SsmActionDefinition.Region is invalid.");
+ }
+ JsonNode instances = ssm.get("InstanceIds");
+ if (instances == null || !instances.isArray() || instances.isEmpty() || instances.size() > 100) {
+ throw invalid("SsmActionDefinition.InstanceIds is invalid.");
+ }
+ for (JsonNode instance : instances) {
+ if (!instance.isTextual() || !SSM_INSTANCE_ID.matcher(instance.textValue()).matches()) {
+ throw invalid("SsmActionDefinition.InstanceIds is invalid.");
+ }
+ }
+ }
+
+ private int validateStringArray(JsonNode node, String field, int maximumItems, int maximumLength) {
+ JsonNode values = node.get(field);
+ if (values == null || values.isNull()) {
+ return 0;
+ }
+ if (!values.isArray() || values.isEmpty() || values.size() > maximumItems) {
+ throw invalid(field + " is invalid.");
+ }
+ for (JsonNode value : values) {
+ if (!value.isTextual() || value.textValue().isBlank() || value.textValue().length() > maximumLength) {
+ throw invalid(field + " is invalid.");
+ }
+ }
+ return values.size();
+ }
+
+ private ObjectNode actionFromRequest(JsonNode request, String actionId, String status) {
+ ObjectNode action = objectMapper.createObjectNode();
+ action.put("ActionId", actionId);
+ action.put("BudgetName", requireBudgetName(request));
+ for (String field : List.of("NotificationType", "ActionType", "ActionThreshold", "Definition", "ExecutionRoleArn", "ApprovalModel", "Subscribers")) {
+ action.set(field, request.get(field).deepCopy());
+ }
+ action.put("Status", status);
+ return action;
+ }
+
+ private void addActionHistory(BudgetActionRecord record, String eventType, String status, String message, JsonNode action) {
+ ObjectNode history = objectMapper.createObjectNode();
+ history.put("Timestamp", Instant.now().getEpochSecond());
+ history.put("Status", status);
+ history.put("EventType", eventType);
+ ObjectNode details = history.putObject("ActionHistoryDetails");
+ details.set("Action", action.deepCopy());
+ details.put("Message", message);
+ record.getHistories().add(history);
+ }
+
+ private JsonNode tagsFor(ResourceRef ref) {
+ if (ref.actionId() == null) {
+ return requireBudget(ref.accountId(), ref.budgetName()).getResourceTags();
+ }
+ return requireAction(ref.accountId(), ref.budgetName(), ref.actionId()).getResourceTags();
+ }
+
+ private void setTags(ResourceRef ref, JsonNode tags) {
+ if (ref.actionId() == null) {
+ BudgetRecord record = requireBudget(ref.accountId(), ref.budgetName());
+ record.setResourceTags(tags.deepCopy());
+ budgets.putForAccount(ref.accountId(), key(ref.accountId(), ref.budgetName()), record);
+ } else {
+ BudgetActionRecord record = requireAction(ref.accountId(), ref.budgetName(), ref.actionId());
+ record.setResourceTags(tags.deepCopy());
+ actions.putForAccount(ref.accountId(), actionKey(ref.budgetName(), ref.actionId()), record);
+ }
+ }
+
+ private ResourceRef parseResourceArn(String arn) {
+ String marker = ":budgets::";
+ int service = arn.indexOf(marker);
+ if (!arn.startsWith("arn:") || service < 0) {
+ throw invalid("ResourceARN is not a valid Budgets ARN.");
+ }
+ int resourceStart = service + marker.length();
+ int separator = arn.indexOf(':', resourceStart);
+ if (separator < 0) {
+ throw invalid("ResourceARN is not a valid Budgets ARN.");
+ }
+ String account = arn.substring(resourceStart, separator);
+ String resource = arn.substring(separator + 1);
+ if (!ACCOUNT_ID.matcher(account).matches() || !resource.startsWith("budget/")) {
+ throw invalid("ResourceARN is not a valid Budgets ARN.");
+ }
+ String value = resource.substring("budget/".length());
+ int actionMarker = value.indexOf("/action/");
+ if (actionMarker < 0) {
+ return new ResourceRef(account, requireBudgetNameValue(value), null);
+ }
+ String budgetName = requireBudgetNameValue(value.substring(0, actionMarker));
+ String actionId = value.substring(actionMarker + "/action/".length());
+ if (!ACTION_ID.matcher(actionId).matches()) {
+ throw invalid("ResourceARN contains an invalid action ID.");
+ }
+ return new ResourceRef(account, budgetName, actionId);
+ }
+
+ private static int readMaxResults(JsonNode request, int defaultValue, int maximum) {
+ JsonNode node = request == null ? null : request.get("MaxResults");
+ if (node == null || node.isNull()) {
+ return defaultValue;
+ }
+ if (!node.canConvertToInt() || node.asInt() < 1 || node.asInt() > maximum) {
+ throw invalid("MaxResults must be between 1 and " + maximum + ".");
+ }
+ return node.asInt();
+ }
+
+ private static String requireAccount(JsonNode request) {
+ String account = text(request, "AccountId");
+ if (account == null || !ACCOUNT_ID.matcher(account).matches()) {
+ throw invalid("AccountId must be a 12 digit account ID.");
+ }
+ return account;
+ }
+
+ private static String requireActionId(JsonNode request) {
+ String actionId = text(request, "ActionId");
+ if (actionId == null || !ACTION_ID.matcher(actionId).matches()) {
+ throw invalid("ActionId is invalid.");
+ }
+ return actionId;
+ }
+
+ private static String requireBudgetName(JsonNode request) {
+ return requireBudgetName(request, "BudgetName");
+ }
+
+ private static String requireBudgetName(JsonNode request, String field) {
+ return requireBudgetNameValue(text(request, field));
+ }
+
+ private static String requireBudgetNameValue(String name) {
+ if (name == null || name.length() < 1 || name.length() > 100 || !BUDGET_NAME.matcher(name).matches()) {
+ throw invalid("BudgetName is invalid.");
+ }
+ return name;
+ }
+
+ private static String requireText(JsonNode node, String field) {
+ String value = text(node, field);
+ if (value == null || value.isBlank()) {
+ throw invalid(field + " is required.");
+ }
+ return value;
+ }
+
+ private static String text(JsonNode node, String field) {
+ JsonNode value = node == null ? null : node.get(field);
+ return value != null && value.isTextual() ? value.textValue() : null;
+ }
+
+ private static String key(String accountId, String name) {
+ return accountId + "::" + name;
+ }
+
+ private static String actionKey(String budgetName, String actionId) {
+ return budgetName + "::" + actionId;
+ }
+
+ private String notificationCursor(JsonNode node) {
+ return node.toString();
+ }
+
+ private String subscriberCursor(JsonNode node) {
+ return node.path("SubscriptionType").asText() + "::" + node.path("Address").asText();
+ }
+
+ private static BudgetNotification findNotification(BudgetRecord record, JsonNode notification) {
+ return record.getNotifications().stream()
+ .filter(candidate -> candidate.getNotification().equals(notification))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private static JsonNode findSubscriber(BudgetNotification notification, JsonNode subscriber) {
+ if (subscriber == null) {
+ return null;
+ }
+ return notification.getSubscribers().stream().filter(subscriber::equals).findFirst().orElse(null);
+ }
+
+ private static void copyIfPresent(JsonNode source, ObjectNode target, String... fields) {
+ for (String field : fields) {
+ if (source.has(field)) {
+ target.set(field, source.get(field).deepCopy());
+ }
+ }
+ }
+
+ private static AwsException invalid(String message) {
+ return new AwsException("InvalidParameterException", message, 400);
+ }
+
+ private static AwsException notFound(String message) {
+ return new AwsException("NotFoundException", message, 400);
+ }
+
+ private enum SubscriberMutation { CREATE, UPDATE, DELETE }
+ private record ResourceRef(String accountId, String budgetName, String actionId) {}
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetActionRecord.java b/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetActionRecord.java
new file mode 100644
index 0000000000..428e591a85
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetActionRecord.java
@@ -0,0 +1,34 @@
+package io.github.hectorvent.floci.services.budgets.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.databind.JsonNode;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class BudgetActionRecord {
+ private String accountId;
+ private String budgetName;
+ private String actionId;
+ private JsonNode action;
+ private JsonNode resourceTags;
+ private List<JsonNode> histories = new ArrayList<>();
+
+ public BudgetActionRecord() {}
+
+ public String getAccountId() { return accountId; }
+ public void setAccountId(String accountId) { this.accountId = accountId; }
+ public String getBudgetName() { return budgetName; }
+ public void setBudgetName(String budgetName) { this.budgetName = budgetName; }
+ public String getActionId() { return actionId; }
+ public void setActionId(String actionId) { this.actionId = actionId; }
+ public JsonNode getAction() { return action; }
+ public void setAction(JsonNode action) { this.action = action; }
+ public JsonNode getResourceTags() { return resourceTags; }
+ public void setResourceTags(JsonNode resourceTags) { this.resourceTags = resourceTags; }
+ public List<JsonNode> getHistories() { return histories; }
+ public void setHistories(List<JsonNode> histories) { this.histories = histories; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetNotification.java b/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetNotification.java
new file mode 100644
index 0000000000..ba72e89c68
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetNotification.java
@@ -0,0 +1,25 @@
+package io.github.hectorvent.floci.services.budgets.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.databind.JsonNode;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class BudgetNotification {
+ private JsonNode notification;
+ private List<JsonNode> subscribers = new ArrayList<>();
+
+ public BudgetNotification() {}
+ public BudgetNotification(JsonNode notification, List<JsonNode> subscribers) {
+ this.notification = notification;
+ this.subscribers = subscribers;
+ }
+ public JsonNode getNotification() { return notification; }
+ public void setNotification(JsonNode notification) { this.notification = notification; }
+ public List<JsonNode> getSubscribers() { return subscribers; }
+ public void setSubscribers(List<JsonNode> subscribers) { this.subscribers = subscribers; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetRecord.java b/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetRecord.java
new file mode 100644
index 0000000000..feba1024ff
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/budgets/model/BudgetRecord.java
@@ -0,0 +1,28 @@
+package io.github.hectorvent.floci.services.budgets.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.databind.JsonNode;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class BudgetRecord {
+ private String accountId;
+ private JsonNode budget;
+ private JsonNode resourceTags;
+ private List<BudgetNotification> notifications = new ArrayList<>();
+
+ public BudgetRecord() {}
+
+ public String getAccountId() { return accountId; }
+ public void setAccountId(String accountId) { this.accountId = accountId; }
+ public JsonNode getBudget() { return budget; }
+ public void setBudget(JsonNode budget) { this.budget = budget; }
+ public JsonNode getResourceTags() { return resourceTags; }
+ public void setResourceTags(JsonNode resourceTags) { this.resourceTags = resourceTags; }
+ public List<BudgetNotification> getNotifications() { return notifications; }
+ public void setNotifications(List<BudgetNotification> notifications) { this.notifications = notifications; }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index efa358b2f3..555c15ef81 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -621,6 +621,8 @@ floci:
enabled: true
identitystore:
enabled: true
+ budgets:
+ enabled: true
controltower:
enabled: true
seed-landing-zone: false
diff --git a/src/test/java/io/github/hectorvent/floci/services/budgets/BudgetsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/budgets/BudgetsIntegrationTest.java
new file mode 100644
index 0000000000..63dd08bd8c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/budgets/BudgetsIntegrationTest.java
@@ -0,0 +1,58 @@
+package io.github.hectorvent.floci.services.budgets;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+@QuarkusTest
+class BudgetsIntegrationTest {
+ private static final String TYPE = "application/x-amz-json-1.1";
+ private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/budgets/aws4_request";
+
+ @BeforeAll
+ static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); }
+
+ @Test
+ void budgetLifecycle() {
+ json("AWSBudgetServiceGateway.CreateBudget", "{\"AccountId\":\"000000000000\",\"Budget\":{\"BudgetName\":\"platform\",\"BudgetType\":\"COST\",\"TimeUnit\":\"MONTHLY\",\"BudgetLimit\":{\"Amount\":\"100\",\"Unit\":\"USD\"}}}")
+ .statusCode(200);
+ json("AWSBudgetServiceGateway.DescribeBudget", "{\"AccountId\":\"000000000000\",\"BudgetName\":\"platform\"}")
+ .statusCode(200).body("Budget.BudgetName", equalTo("platform"));
+ json("AWSBudgetServiceGateway.CreateNotification", "{\"AccountId\":\"000000000000\",\"BudgetName\":\"platform\",\"Notification\":{\"NotificationType\":\"ACTUAL\",\"ComparisonOperator\":\"GREATER_THAN\",\"Threshold\":80},\"Subscribers\":[{\"SubscriptionType\":\"EMAIL\",\"Address\":\"[email protected]\"}]}")
+ .statusCode(200);
+ json("AWSBudgetServiceGateway.DescribeSubscribersForNotification", "{\"AccountId\":\"000000000000\",\"BudgetName\":\"platform\",\"Notification\":{\"NotificationType\":\"ACTUAL\",\"ComparisonOperator\":\"GREATER_THAN\",\"Threshold\":80}}")
+ .statusCode(200).body("Subscribers[0].Address", equalTo("[email protected]"));
+ }
+
+
+ @Test
+ void crossAccountRequestsReturnAccessDenied() {
+ String foreign = "210987654321";
+ String caller = "123456789012";
+ jsonAs(caller, "AWSBudgetServiceGateway.DescribeBudget",
+ "{\"AccountId\":\"" + foreign + "\",\"BudgetName\":\"foreign\"}")
+ .statusCode(400).body("__type", equalTo("AccessDeniedException"));
+ jsonAs(caller, "AWSBudgetServiceGateway.ListTagsForResource",
+ "{\"ResourceARN\":\"arn:aws:budgets::" + foreign + ":budget/foreign\"}")
+ .statusCode(400).body("__type", equalTo("AccessDeniedException"));
+ }
+
+ @Test
+ void missingBudgetReturnsNotFound() {
+ json("AWSBudgetServiceGateway.DescribeBudget", "{\"AccountId\":\"000000000000\",\"BudgetName\":\"missing\"}")
+ .statusCode(400).body("__type", equalTo("NotFoundException"));
+ }
+
+ private static io.restassured.response.ValidatableResponse json(String target, String body) {
+ return given().contentType(TYPE).header("Authorization", AUTH).header("X-Amz-Target", target).body(body).post("/").then();
+ }
+
+ private static io.restassured.response.ValidatableResponse jsonAs(String accountId, String target, String body) {
+ String auth = "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260904/us-east-1/budgets/aws4_request";
+ return given().contentType(TYPE).header("Authorization", auth).header("X-Amz-Target", target).body(body).post("/").then();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/budgets/BudgetsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/budgets/BudgetsServiceTest.java
new file mode 100644
index 0000000000..784bb11b85
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/budgets/BudgetsServiceTest.java
@@ -0,0 +1,147 @@
+package io.github.hectorvent.floci.services.budgets;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.services.budgets.model.BudgetActionRecord;
+import io.github.hectorvent.floci.services.budgets.model.BudgetRecord;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class BudgetsServiceTest {
+ private static final String ACCOUNT = "123456789012";
+ private final ObjectMapper mapper = new ObjectMapper();
+ private BudgetsService service;
+
+ @BeforeEach
+ void setUp() {
+ service = new BudgetsService(AccountAwareStorageBackend.inMemory(ACCOUNT),
+ AccountAwareStorageBackend.<BudgetActionRecord>inMemory(ACCOUNT), mapper);
+ }
+
+ @Test
+ void describeBudgetsUsesAwsThousandItemLimitAndResetClearsState() {
+ service.createBudget(createBudget("platform"));
+ ObjectNode list = mapper.createObjectNode().put("AccountId", ACCOUNT).put("MaxResults", 1000);
+ assertEquals(1, service.describeBudgets(list).items().size());
+ list.put("MaxResults", 1001);
+ assertError("InvalidParameterException", () -> service.describeBudgets(list));
+ service.clear();
+ list.put("MaxResults", 1000);
+ assertTrue(service.describeBudgets(list).items().isEmpty());
+ }
+
+ @Test
+ void subscriberAndNotificationUpdatesPreserveAwsLifecycle() {
+ service.createBudget(createBudget("notify"));
+ ObjectNode create = notificationRequest("notify", 80);
+ create.putArray("Subscribers").addObject().put("SubscriptionType", "EMAIL").put("Address", "[email protected]");
+ service.createNotification(create);
+
+ ObjectNode subscriber = notificationRequest("notify", 80);
+ subscriber.set("Subscriber", mapper.createObjectNode().put("SubscriptionType", "EMAIL").put("Address", "[email protected]"));
+ service.createSubscriber(subscriber);
+ assertEquals(2, service.describeSubscribers(notificationRequest("notify", 80)).items().size());
+
+ ObjectNode update = mapper.createObjectNode().put("AccountId", ACCOUNT).put("BudgetName", "notify");
+ update.set("OldNotification", notification(80));
+ update.set("NewNotification", notification(90));
+ service.updateNotification(update);
+ assertEquals(1, service.describeNotifications(update).items().size());
+ }
+
+
+ @Test
+ void callerScopeRejectsCrossAccountIdsAndArns() {
+ ObjectNode request = mapper.createObjectNode().put("AccountId", "210987654321");
+ assertError("AccessDeniedException", () -> service.validateCallerScope(request, ACCOUNT));
+
+ ObjectNode arnRequest = mapper.createObjectNode()
+ .put("ResourceARN", "arn:aws:budgets::210987654321:budget/foreign");
+ assertError("AccessDeniedException", () -> service.validateCallerScope(arnRequest, ACCOUNT));
+ }
+
+ @Test
+ void budgetActionDefinitionsMustMatchTypeAndContainRequiredFields() {
+ service.createBudget(createBudget("actions"));
+
+ ObjectNode emptyIam = actionRequest("actions", "APPLY_IAM_POLICY");
+ emptyIam.set("Definition", mapper.createObjectNode().set("IamActionDefinition", mapper.createObjectNode()));
+ assertError("InvalidParameterException", () -> service.createBudgetAction(emptyIam));
+
+ ObjectNode noIamTarget = actionRequest("actions", "APPLY_IAM_POLICY");
+ noIamTarget.set("Definition", mapper.createObjectNode().set("IamActionDefinition",
+ mapper.createObjectNode().put("PolicyArn", "arn:aws:iam::aws:policy/ReadOnlyAccess")));
+ assertError("InvalidParameterException", () -> service.createBudgetAction(noIamTarget));
+
+ ObjectNode wrongVariant = actionRequest("actions", "APPLY_IAM_POLICY");
+ ObjectNode ssm = mapper.createObjectNode().put("ActionSubType", "STOP_EC2_INSTANCES").put("Region", "us-east-1");
+ ssm.putArray("InstanceIds").add("i-12345678");
+ wrongVariant.set("Definition", mapper.createObjectNode().set("SsmActionDefinition", ssm));
+ assertError("InvalidParameterException", () -> service.createBudgetAction(wrongVariant));
+
+ BudgetActionRecord record = service.createBudgetAction(actionRequest("actions", "APPLY_IAM_POLICY"));
+ ObjectNode update = mapper.createObjectNode().put("AccountId", ACCOUNT).put("BudgetName", "actions")
+ .put("ActionId", record.getActionId());
+ update.set("Definition", mapper.createObjectNode().set("SsmActionDefinition", ssm));
+ assertError("InvalidParameterException", () -> service.updateBudgetAction(update));
+ }
+
+ @Test
+ void actionExecutionUsesAwsStatusAndHistoryEnums() {
+ service.createBudget(createBudget("execute"));
+ BudgetActionRecord record = service.createBudgetAction(actionRequest("execute", "APPLY_IAM_POLICY"));
+
+ ObjectNode execute = mapper.createObjectNode().put("AccountId", ACCOUNT).put("BudgetName", "execute")
+ .put("ActionId", record.getActionId()).put("ExecutionType", "APPROVE_BUDGET_ACTION");
+ BudgetActionRecord executed = service.executeBudgetAction(execute);
+
+ assertEquals("EXECUTION_SUCCESS", executed.getAction().path("Status").asText());
+ JsonNode history = executed.getHistories().get(executed.getHistories().size() - 1);
+ assertEquals("EXECUTE_ACTION", history.path("EventType").asText());
+ assertEquals("EXECUTION_SUCCESS", history.path("Status").asText());
+ }
+
+ private ObjectNode createBudget(String name) {
+ ObjectNode request = mapper.createObjectNode().put("AccountId", ACCOUNT);
+ ObjectNode budget = request.putObject("Budget");
+ budget.put("BudgetName", name).put("BudgetType", "COST").put("TimeUnit", "MONTHLY");
+ budget.putObject("BudgetLimit").put("Amount", "100").put("Unit", "USD");
+ return request;
+ }
+
+
+ private ObjectNode actionRequest(String budgetName, String actionType) {
+ ObjectNode request = mapper.createObjectNode().put("AccountId", ACCOUNT).put("BudgetName", budgetName)
+ .put("NotificationType", "ACTUAL").put("ActionType", actionType).put("ApprovalModel", "MANUAL")
+ .put("ExecutionRoleArn", "arn:aws:iam::" + ACCOUNT + ":role/BudgetExecutionRole");
+ request.putObject("ActionThreshold").put("ActionThresholdType", "PERCENTAGE").put("ActionThresholdValue", 100);
+ ObjectNode iam = mapper.createObjectNode().put("PolicyArn", "arn:aws:iam::aws:policy/ReadOnlyAccess");
+ iam.putArray("Users").add("alice");
+ request.set("Definition", mapper.createObjectNode().set("IamActionDefinition", iam));
+ request.putArray("Subscribers").addObject().put("SubscriptionType", "EMAIL").put("Address", "[email protected]");
+ return request;
+ }
+
+ private ObjectNode notificationRequest(String name, double threshold) {
+ ObjectNode request = mapper.createObjectNode().put("AccountId", ACCOUNT).put("BudgetName", name);
+ request.set("Notification", notification(threshold));
+ return request;
+ }
+
+ private ObjectNode notification(double threshold) {
+ return mapper.createObjectNode().put("NotificationType", "ACTUAL")
+ .put("ComparisonOperator", "GREATER_THAN").put("Threshold", threshold).put("ThresholdType", "PERCENTAGE");
+ }
+
+ private static void assertError(String code, Runnable operation) {
+ AwsException error = assertThrows(AwsException.class, operation::run);
+ assertEquals(code, error.getErrorCode());
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 4fb11a1f26..4bd880d0e5 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -383,6 +383,8 @@ floci:
enabled: true
identitystore:
enabled: true
+ budgets:
+ enabled: true
controltower:
enabled: true
seed-landing-zone: true
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index 82dd71fd4d..9bc8e2373e 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -222,6 +222,10 @@ services:
doc: docs/services/identitystore.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/identitystore/IdentityStoreJsonHandler.java, mode: switch }
+ - service: budgets
+ doc: docs/services/budgets.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/budgets/BudgetsJsonHandler.java, mode: switch }
- service: sqs
doc: docs/services/sqs.md
sources: