feat(ce): manage anomaly monitors and subscriptions (#4221)

* feat(ce): manage anomaly monitors and subscriptions

* fix(ce): return JSON objects for empty responses
This commit is contained in:
XuJian authored and GitHub committed 2026-09-24 08:20:17 -04:00
1 parent db73026a35
commit 7cf8ab7d85
9 files changed
+1293 -11

No files matched your search

@@ -0,0 +1,82 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
variable "endpoint" {
type = string
default = "http://localhost:4566"
}
variable "monitor_name" {
type = string
default = "floci-compat-cost-monitor"
}
variable "absolute_threshold" {
type = number
default = 100
}
variable "resource_tags" {
type = map(string)
default = {
Fixture = "cost-anomaly"
Stage = "initial"
RemoveOnUpdate = "yes"
}
}
provider "aws" {
region = "us-east-1"
access_key = "941000000010"
secret_key = "floci-compat-cost-anomaly"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
skip_region_validation = true
endpoints {
ce = var.endpoint
}
}
resource "aws_ce_anomaly_monitor" "service" {
name = var.monitor_name
monitor_type = "DIMENSIONAL"
monitor_dimension = "SERVICE"
tags = var.resource_tags
}
resource "aws_ce_anomaly_subscription" "daily" {
name = "floci-compat-cost-alerts"
frequency = "DAILY"
monitor_arn_list = [aws_ce_anomaly_monitor.service.arn]
tags = var.resource_tags
subscriber {
type = "EMAIL"
address = "floci-compat@example.invalid"
}
threshold_expression {
dimension {
key = "ANOMALY_TOTAL_IMPACT_ABSOLUTE"
match_options = ["GREATER_THAN_OR_EQUAL"]
values = [tostring(var.absolute_threshold)]
}
}
}
output "monitor_arn" {
value = aws_ce_anomaly_monitor.service.arn
}
output "subscription_arn" {
value = aws_ce_anomaly_subscription.daily.arn
}
@@ -0,0 +1,7 @@
monitor_name = "floci-compat-cost-monitor-updated"
absolute_threshold = 250
resource_tags = {
Fixture = "cost-anomaly"
Stage = "updated"
AddOnUpdate = "yes"
}
@@ -0,0 +1,79 @@
#!/usr/bin/env bats
# Cost anomaly resources must survive provider readback and converge after updates.
# Reproduces https://github.com/floci-io/floci/issues/4106.
ce_terraform() {
"${IAC_BIN:-terraform}" -chdir="${BATS_FILE_TMPDIR}/cost-anomaly-tf" "$@"
}
setup_file() {
load 'test_helper/common-setup'
local fixture_source
fixture_source="$(dirname "$BATS_TEST_FILENAME")/cost-anomaly-tf"
mkdir -p "${BATS_FILE_TMPDIR}/cost-anomaly-tf"
cp "$fixture_source/main.tf" "$fixture_source/updated.tfvars" \
"${BATS_FILE_TMPDIR}/cost-anomaly-tf/"
run ce_terraform init -input=false -no-color
assert_success
}
setup() {
load 'test_helper/common-setup'
}
teardown_file() {
load 'test_helper/common-setup'
if [ -f "${BATS_FILE_TMPDIR}/cost-anomaly-tf/terraform.tfstate" ]; then
if ! ce_terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" \
-input=false -auto-approve -no-color; then
echo "# Cost anomaly fixture cleanup failed; see the destroy output above." >&3
fi
fi
}
@test "Cost anomaly monitor and subscription: create, update without drift, and destroy" {
local monitor_arn subscription_arn
run ce_terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color
assert_success
assert_output --partial "2 added, 0 changed, 0 destroyed"
run ce_terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode
assert_success
run ce_terraform output -raw monitor_arn
assert_success
assert_output --regexp '^arn:aws:ce::941000000010:anomalymonitor/[a-zA-Z0-9-]+$'
monitor_arn="$output"
run ce_terraform output -raw subscription_arn
assert_success
assert_output --regexp '^arn:aws:ce::941000000010:anomalysubscription/[a-zA-Z0-9-]+$'
subscription_arn="$output"
run ce_terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -var-file=updated.tfvars \
-input=false -auto-approve -no-color
assert_success
assert_output --partial "0 added, 2 changed, 0 destroyed"
run ce_terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -var-file=updated.tfvars \
-input=false -no-color -detailed-exitcode
assert_success
run ce_terraform output -raw monitor_arn
assert_success
assert_output "$monitor_arn"
run ce_terraform output -raw subscription_arn
assert_success
assert_output "$subscription_arn"
run ce_terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -var-file=updated.tfvars \
-input=false -auto-approve -no-color
assert_success
assert_output --partial "2 destroyed"
run ce_terraform state list
assert_success
assert_output ''
}
+62 -9
View File
@@ -10,19 +10,72 @@ multiplied by the bundled AWS Pricing snapshot served by the
so any test that mutates resources (e.g. creates a bucket, runs an instance)
sees those changes in the next `GetCostAndUsage` call.
## Supported Operations
## Supported Actions
| Operation | Notes |
|-----------|-------|
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `GetCostAndUsage` | Full `TimePeriod` / `Granularity` / `Filter` / `GroupBy` / `Metrics` support |
| `GetCostAndUsageWithResources` | Same shape as `GetCostAndUsage`; for resource-level breakdown, group by `Type=DIMENSION,Key=RESOURCE_ID` |
| `GetDimensionValues` | Returns dimension values present in the synthesized data set |
| `GetTags` | Returns tag keys / values across enumerated resources |
| `GetReservationCoverage` | Stub — returns zeroed totals; full RI math lands in a follow-up PR |
| `GetReservationUtilization` | Stub — returns zeroed totals |
| `GetSavingsPlansCoverage` | Stub — returns empty list |
| `GetSavingsPlansUtilization` | Stub — returns zeroed totals |
| `GetCostCategories` | Stub — returns empty list (cost-category management not yet emulated) |
| `GetReservationCoverage` | Stub; returns zeroed totals; full RI math lands in a follow-up PR |
| `GetReservationUtilization` | Stub; returns zeroed totals |
| `GetSavingsPlansCoverage` | Stub; returns empty list |
| `GetSavingsPlansUtilization` | Stub; returns zeroed totals |
| `GetCostCategories` | Stub; returns empty list (cost-category management not yet emulated) |
| `CreateAnomalyMonitor` | Store a dimensional or custom monitor with optional resource tags |
| `GetAnomalyMonitors` | List account-scoped monitors with ARN filters and pagination |
| `UpdateAnomalyMonitor` | Update a monitor's name |
| `DeleteAnomalyMonitor` | Delete a monitor without deleting subscriptions |
| `CreateAnomalySubscription` | Store subscriber, frequency, monitor, and threshold configuration |
| `GetAnomalySubscriptions` | List subscriptions with ARN or monitor filters and pagination |
| `UpdateAnomalySubscription` | Update supplied settings while preserving omitted fields |
| `DeleteAnomalySubscription` | Delete a subscription |
| `ListTagsForResource` | Read monitor or subscription tags |
| `TagResource` | Add or replace monitor or subscription tags |
| `UntagResource` | Remove monitor or subscription tag keys |
<!-- floci:actions:end -->
## Cost anomaly configuration
Monitors and subscriptions support creation, listing, updates, deletion, and resource tags.
They are global within the calling account: requests signed for different regions see the same
resources, while another account cannot read or modify them. Definitions and tags use Floci's
configured storage and survive restarts in persistent storage modes.
`DIMENSIONAL` monitors support `SERVICE`, `LINKED_ACCOUNT`, `TAG`, and `COST_CATEGORY`.
Tag and cost-category monitors provide a key in `MonitorSpecification`; `CUSTOM` monitors
provide linked-account, tag, or cost-category values. `MonitorSpecification` is a JSON object,
including when the caller's configuration tool represents it internally as a JSON string.
Subscriptions support `DAILY` or `WEEKLY` email configuration and `IMMEDIATE` SNS configuration.
Updates preserve omitted fields and reject invalid changes before writing. The deprecated
`Threshold` input is accepted as an absolute-cost shorthand; reads return its normalized
`ThresholdExpression`. Monitor names are labels, not idempotency keys.
`GetAnomalyMonitors` and `GetAnomalySubscriptions` accept their ARN-list filters, `MaxResults`,
and `NextPageToken`; subscriptions also support a `MonitorArn` filter. Tags are managed through
`ResourceArn`, `ResourceTags`, and `ResourceTagKeys`, and are not embedded in the resource
definitions returned by the list APIs.
Deleting a monitor leaves subscriptions intact and editable. In this emulator, their saved
monitor ARN lists remain unchanged until explicitly updated. Monitor evaluation, anomaly
generation, email confirmation, and email/SNS notification delivery are not emulated. Floci
does not synthesize subscriber confirmation status or a monitor's last evaluation date.
Organizations management-account eligibility is not enforced for the additional dimensional
monitor types.
For example, create a monitor and a daily subscription against the local endpoint:
```bash
MONITOR_ARN=$(aws ce create-anomaly-monitor --endpoint-url http://localhost:4566 \
--anomaly-monitor '{"MonitorName":"services","MonitorType":"DIMENSIONAL","MonitorDimension":"SERVICE"}' \
--resource-tags Key=Environment,Value=development --query MonitorArn --output text)
aws ce create-anomaly-subscription --endpoint-url http://localhost:4566 \
--anomaly-subscription "{\"SubscriptionName\":\"daily-alerts\",\"Frequency\":\"DAILY\",\"MonitorArnList\":[\"$MONITOR_ARN\"],\"Subscribers\":[{\"Address\":\"alerts@example.com\",\"Type\":\"EMAIL\"}],\"ThresholdExpression\":{\"Dimensions\":{\"Key\":\"ANOMALY_TOTAL_IMPACT_ABSOLUTE\",\"Values\":[\"100\"],\"MatchOptions\":[\"GREATER_THAN_OR_EQUAL\"]}}}"
```
## Cost synthesis model
@@ -120,7 +173,7 @@ for result in resp["ResultsByTime"]:
- Forecasting (`GetCostForecast`, `GetUsageForecast`).
- Right-sizing recommendations (`GetRightsizingRecommendation`).
- Anomaly detection management (`GetAnomalies`, `*AnomalyMonitor`, `*AnomalySubscription`) — separate PR planned per #791.
- Anomaly evaluation and results (`GetAnomalies`), email confirmation, and email/SNS delivery.
- Real Reservation / Savings Plan utilization math — currently zeroed stubs.
- Cost category management (`CreateCostCategoryDefinition` / `*Definition` / `ListCostCategoryDefinitions`).
- Resource-level granularity beyond what `GetCostAndUsageWithResources` exposes today.
@@ -0,0 +1,530 @@
package io.github.hectorvent.floci.services.ce;
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.AwsArnUtils;
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 jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
/** Stores Cost Anomaly Detection configuration without generating anomalies or notifications. */
@ApplicationScoped
public class CostAnomalyService implements Resettable {
private static final BigDecimal MAX_THRESHOLD = new BigDecimal("10000000000");
private static final Pattern TAG_TEXT = Pattern.compile("[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*");
private static final Pattern EMAIL = Pattern.compile(
"^[a-zA-Z0-9.!#$%&'*+=?^_`{|}~-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
private static final Pattern SNS = Pattern.compile(
"^arn:aws[a-zA-Z-]*:sns:[a-zA-Z0-9-]+:[0-9]{12}:[a-zA-Z0-9_-]+(\\.fifo)?$");
private final AccountAwareStorageBackend<ObjectNode> monitors;
private final AccountAwareStorageBackend<ObjectNode> subscriptions;
private final ObjectMapper mapper;
@Inject
public CostAnomalyService(StorageFactory storageFactory, ObjectMapper mapper) {
this(storageFactory.create("ce", "anomaly-monitors.json", new TypeReference<Map<String, ObjectNode>>() {}),
storageFactory.create("ce", "anomaly-subscriptions.json", new TypeReference<Map<String, ObjectNode>>() {}),
mapper);
}
CostAnomalyService(AccountAwareStorageBackend<ObjectNode> monitors,
AccountAwareStorageBackend<ObjectNode> subscriptions, ObjectMapper mapper) {
this.monitors = monitors;
this.subscriptions = subscriptions;
this.mapper = mapper;
}
public synchronized ObjectNode createMonitor(JsonNode request) {
ObjectNode input = object(request, "AnomalyMonitor");
validateMonitor(input);
ObjectNode tags = tags(request, false);
String account = monitors.accountId();
String type = input.path("MonitorType").textValue();
String dimension = input.path("MonitorDimension").asText();
long count = monitors.scanForAccount(account, key -> true).stream()
.map(value -> value.path("definition"))
.filter(value -> type.equals(value.path("MonitorType").asText()))
.filter(value -> !"DIMENSIONAL".equals(type)
|| "SERVICE".equals(dimension) == "SERVICE".equals(value.path("MonitorDimension").asText()))
.count();
if (count >= ("CUSTOM".equals(type) ? 500 : 1)) {
throw new AwsException("LimitExceededException", "The account's monitor limit has been reached.", 400);
}
ObjectNode definition = fields(input, "MonitorName", "MonitorType", "MonitorDimension", "MonitorSpecification");
String arn = arn(account, "anomalymonitor");
String now = Instant.now().truncatedTo(ChronoUnit.SECONDS).toString();
definition.put("MonitorArn", arn).put("CreationDate", now).put("LastUpdatedDate", now);
monitors.putForAccount(account, arn, resource(definition, tags));
return mapper.createObjectNode().put("MonitorArn", arn);
}
public synchronized ObjectNode getMonitors(JsonNode request) {
List<ObjectNode> definitions = definitions(monitors, request, "MonitorArnList", "UnknownMonitorException");
return page(definitions, request, "AnomalyMonitors", "MonitorArn");
}
public synchronized ObjectNode updateMonitor(JsonNode request) {
String arn = text(request, "MonitorArn", 1024);
String account = monitors.accountId();
ObjectNode resource = existing(monitors, account, arn, "UnknownMonitorException").deepCopy();
ObjectNode definition = (ObjectNode) resource.get("definition");
if (present(request, "MonitorName")) {
definition.put("MonitorName", text(request, "MonitorName", 1024));
}
definition.put("LastUpdatedDate", Instant.now().truncatedTo(ChronoUnit.SECONDS).toString());
monitors.putForAccount(account, arn, resource);
return mapper.createObjectNode().put("MonitorArn", arn);
}
public synchronized void deleteMonitor(JsonNode request) {
String arn = text(request, "MonitorArn", 1024);
String account = monitors.accountId();
existing(monitors, account, arn, "UnknownMonitorException");
monitors.deleteForAccount(account, arn);
}
public synchronized ObjectNode createSubscription(JsonNode request) {
ObjectNode input = object(request, "AnomalySubscription");
String account = monitors.accountId();
text(input, "SubscriptionName", 1024);
validateMonitorReferences(input, account);
validateSubscribers(input);
ObjectNode definition = fields(input, "SubscriptionName", "Frequency", "MonitorArnList", "Subscribers");
definition.set("ThresholdExpression", threshold(input));
ObjectNode tags = tags(request, false);
if (subscriptions.scanForAccount(account, key -> true).size() >= 100) {
throw new AwsException("LimitExceededException", "The account's subscription limit has been reached.", 400);
}
String arn = arn(account, "anomalysubscription");
definition.put("SubscriptionArn", arn).put("AccountId", account);
subscriptions.putForAccount(account, arn, resource(definition, tags));
return mapper.createObjectNode().put("SubscriptionArn", arn);
}
public synchronized ObjectNode getSubscriptions(JsonNode request) {
List<ObjectNode> definitions = definitions(subscriptions, request,
"SubscriptionArnList", "UnknownSubscriptionException");
if (present(request, "MonitorArn")) {
String monitorArn = text(request, "MonitorArn", 1024);
definitions = definitions.stream()
.filter(value -> contains(value.path("MonitorArnList"), monitorArn)).toList();
}
return page(definitions, request, "AnomalySubscriptions", "SubscriptionArn");
}
public synchronized ObjectNode updateSubscription(JsonNode request) {
String arn = text(request, "SubscriptionArn", 1024);
String account = monitors.accountId();
ObjectNode resource = existing(subscriptions, account, arn, "UnknownSubscriptionException").deepCopy();
ObjectNode definition = (ObjectNode) resource.get("definition");
if (present(request, "SubscriptionName")) {
definition.put("SubscriptionName", text(request, "SubscriptionName", 1024));
}
if (present(request, "MonitorArnList")) {
validateMonitorReferences(request, account);
definition.set("MonitorArnList", request.get("MonitorArnList").deepCopy());
}
for (String field : List.of("Frequency", "Subscribers")) {
if (present(request, field)) {
definition.set(field, request.get(field).deepCopy());
}
}
validateSubscribers(definition);
if (present(request, "Threshold") || present(request, "ThresholdExpression")) {
definition.set("ThresholdExpression", threshold(request));
definition.remove("Threshold");
}
subscriptions.putForAccount(account, arn, resource);
return mapper.createObjectNode().put("SubscriptionArn", arn);
}
public synchronized void deleteSubscription(JsonNode request) {
String arn = text(request, "SubscriptionArn", 1024);
String account = monitors.accountId();
existing(subscriptions, account, arn, "UnknownSubscriptionException");
subscriptions.deleteForAccount(account, arn);
}
public synchronized ObjectNode listTags(JsonNode request) {
String arn = text(request, "ResourceArn", 2048);
AccountAwareStorageBackend<ObjectNode> storage = taggedStorage(arn);
JsonNode resourceTags = existing(storage, monitors.accountId(), arn, "ResourceNotFoundException").path("tags");
ObjectNode response = mapper.createObjectNode();
ArrayNode output = response.putArray("ResourceTags");
resourceTags.properties().forEach(entry -> output.addObject()
.put("Key", entry.getKey()).put("Value", entry.getValue().textValue()));
return response;
}
public synchronized void tagResource(JsonNode request) {
String arn = text(request, "ResourceArn", 2048);
AccountAwareStorageBackend<ObjectNode> storage = taggedStorage(arn);
String account = monitors.accountId();
ObjectNode resource = existing(storage, account, arn, "ResourceNotFoundException").deepCopy();
ObjectNode updatedTags = (ObjectNode) resource.get("tags");
updatedTags.setAll(tags(request, true));
checkTagCount(updatedTags);
storage.putForAccount(account, arn, resource);
}
public synchronized void untagResource(JsonNode request) {
String arn = text(request, "ResourceArn", 2048);
AccountAwareStorageBackend<ObjectNode> storage = taggedStorage(arn);
String account = monitors.accountId();
ObjectNode resource = existing(storage, account, arn, "ResourceNotFoundException").deepCopy();
ObjectNode updatedTags = (ObjectNode) resource.get("tags");
for (String key : strings(request, "ResourceTagKeys", 200, 128)) {
updatedTags.remove(tagText(key, true));
}
storage.putForAccount(account, arn, resource);
}
@Override
public synchronized void clear() {
monitors.clear();
subscriptions.clear();
}
private List<ObjectNode> definitions(AccountAwareStorageBackend<ObjectNode> storage, JsonNode request,
String filter, String errorCode) {
String account = monitors.accountId();
Set<String> arns = present(request, filter)
? new LinkedHashSet<>(strings(request, filter, Integer.MAX_VALUE, 1024)) : Set.of();
List<ObjectNode> result = new ArrayList<>();
if (arns.isEmpty()) {
for (ObjectNode resource : storage.scanForAccount(account, key -> true)) {
result.add(object(resource, "definition").deepCopy());
}
} else {
for (String arn : arns) {
result.add(object(existing(storage, account, arn, errorCode), "definition").deepCopy());
}
}
return result;
}
private ObjectNode page(List<ObjectNode> definitions, JsonNode request, String responseKey, String arnKey) {
int maxResults = 100;
if (present(request, "MaxResults")) {
JsonNode value = request.get("MaxResults");
if (!value.isIntegralNumber() || !value.canConvertToInt() || value.intValue() < 1) {
throw invalid("MaxResults must be a positive integer.");
}
maxResults = value.intValue();
}
String token = present(request, "NextPageToken") ? text(request, "NextPageToken", 8192) : null;
int pageSize = Math.min(maxResults, Math.max(definitions.size(), 1));
PaginatedResult<ObjectNode> page = Pagination.paginate(definitions,
value -> value.path(arnKey).asText(), pageSize, token, Integer.MAX_VALUE, "InvalidNextTokenException");
ObjectNode response = mapper.createObjectNode();
response.putArray(responseKey).addAll(page.items());
if (page.nextToken() != null) {
response.put("NextPageToken", page.nextToken());
}
return response;
}
private void validateMonitor(JsonNode input) {
text(input, "MonitorName", 1024);
String type = text(input, "MonitorType", 1024);
if ("CUSTOM".equals(type)) {
if (present(input, "MonitorDimension")) {
throw invalid("CUSTOM monitors must not specify MonitorDimension.");
}
validateSpecification(object(input, "MonitorSpecification"), null);
return;
}
if (!"DIMENSIONAL".equals(type)) {
throw invalid("MonitorType must be DIMENSIONAL or CUSTOM.");
}
String dimension = text(input, "MonitorDimension", 1024);
switch (dimension) {
case "SERVICE", "LINKED_ACCOUNT" -> {
if (present(input, "MonitorSpecification")) {
throw invalid("MonitorSpecification is not supported for this monitor dimension.");
}
}
case "TAG", "COST_CATEGORY" -> validateSpecification(object(input, "MonitorSpecification"), dimension);
default -> throw invalid("MonitorDimension must be SERVICE, LINKED_ACCOUNT, TAG, or COST_CATEGORY.");
}
}
private void validateSpecification(ObjectNode specification, String dimension) {
String root = singleRoot(specification, Set.of("Dimensions", "Tags", "CostCategories"));
if (dimension != null && !("TAG".equals(dimension) ? "Tags" : "CostCategories").equals(root)) {
throw invalid("MonitorSpecification must match MonitorDimension.");
}
ObjectNode values = object(specification, root);
String key = text(values, "Key", "CostCategories".equals(root) ? 50 : 1024);
if (key.isEmpty() || ("Dimensions".equals(root) && !"LINKED_ACCOUNT".equals(key))) {
throw invalid("MonitorSpecification must specify a linked account, tag key, or cost category key.");
}
if (dimension != null) {
if (present(values, "Values")) {
throw invalid("AWS managed tag and cost category monitors specify a key without values.");
}
} else {
List<String> selected = strings(values, "Values", "CostCategories".equals(root) ? 1 : 10, 1024);
if (selected.isEmpty()) {
throw invalid("CUSTOM monitors must specify at least one value.");
}
}
}
private void validateMonitorReferences(JsonNode input, String account) {
for (String monitorArn : strings(input, "MonitorArnList", 502, 2048)) {
existing(monitors, account, monitorArn, "UnknownMonitorException");
}
}
private void validateSubscribers(JsonNode input) {
String frequency = text(input, "Frequency", 1024);
if (!Set.of("DAILY", "WEEKLY", "IMMEDIATE").contains(frequency)) {
throw invalid("Frequency must be DAILY, WEEKLY, or IMMEDIATE.");
}
JsonNode recipients = input.path("Subscribers");
int limit = "IMMEDIATE".equals(frequency) ? 1 : 10;
if (!recipients.isArray() || recipients.isEmpty() || recipients.size() > limit) {
throw invalid("Subscribers must contain between 1 and " + limit + " recipients for this frequency.");
}
for (JsonNode recipient : recipients) {
String type = text(recipient, "Type", 1024);
String expected = "IMMEDIATE".equals(frequency) ? "SNS" : "EMAIL";
if (!expected.equals(type)) {
throw invalid("Subscribers must use " + expected + " for this frequency.");
}
String address = text(recipient, "Address", 302);
if (address.length() < 6 || !("SNS".equals(type) ? SNS : EMAIL).matcher(address).matches()) {
throw invalid("Subscriber Address must be an email address or SNS topic ARN matching its Type.");
}
if (present(recipient, "Status")
&& !Set.of("CONFIRMED", "DECLINED").contains(text(recipient, "Status", 1024))) {
throw invalid("Subscriber Status must be CONFIRMED or DECLINED.");
}
}
}
private ObjectNode threshold(JsonNode input) {
boolean legacy = present(input, "Threshold");
boolean expression = present(input, "ThresholdExpression");
if (legacy == expression) {
throw invalid("Specify exactly one of Threshold or ThresholdExpression.");
}
if (expression) {
ObjectNode value = object(input, "ThresholdExpression");
validateThresholdExpression(value);
return value.deepCopy();
}
JsonNode value = input.get("Threshold");
if (!value.isNumber()) {
throw invalid("Threshold must be a nonnegative number.");
}
BigDecimal amount = thresholdValue(value.asText());
ObjectNode result = mapper.createObjectNode();
ObjectNode dimensions = result.putObject("Dimensions");
dimensions.put("Key", "ANOMALY_TOTAL_IMPACT_ABSOLUTE");
dimensions.putArray("MatchOptions").add("GREATER_THAN_OR_EQUAL");
dimensions.putArray("Values").add(amount.stripTrailingZeros().toPlainString());
return result;
}
private void validateThresholdExpression(ObjectNode expression) {
String root = singleRoot(expression, Set.of("And", "Or", "Dimensions"));
if (!"Dimensions".equals(root)) {
JsonNode children = expression.get(root);
if (!children.isArray() || children.isEmpty()) {
throw invalid(root + " must contain at least one expression.");
}
for (JsonNode child : children) {
if (!(child instanceof ObjectNode object)) {
throw invalid("ThresholdExpression must contain expression objects.");
}
validateThresholdExpression(object);
}
return;
}
ObjectNode dimensions = object(expression, "Dimensions");
if (!Set.of("ANOMALY_TOTAL_IMPACT_ABSOLUTE", "ANOMALY_TOTAL_IMPACT_PERCENTAGE")
.contains(text(dimensions, "Key", 1024))) {
throw invalid("ThresholdExpression must use an anomaly impact dimension.");
}
List<String> matchOptions = strings(dimensions, "MatchOptions", 1, 1024);
if (!matchOptions.equals(List.of("GREATER_THAN_OR_EQUAL"))) {
throw invalid("ThresholdExpression requires GREATER_THAN_OR_EQUAL.");
}
List<String> values = strings(dimensions, "Values", Integer.MAX_VALUE, 1024);
if (values.isEmpty()) {
throw invalid("ThresholdExpression requires a numeric value.");
}
for (String value : values) {
thresholdValue(value);
}
}
private BigDecimal thresholdValue(String value) {
try {
BigDecimal amount = new BigDecimal(value);
if (amount.signum() < 0 || amount.compareTo(MAX_THRESHOLD) > 0) {
throw invalid("Threshold values must be between 0 and 10000000000.");
}
return amount;
} catch (NumberFormatException e) {
throw invalid("Threshold values must be numeric.");
}
}
private ObjectNode tags(JsonNode request, boolean required) {
ObjectNode tags = mapper.createObjectNode();
if (!required && !present(request, "ResourceTags")) {
return tags;
}
JsonNode input = request.path("ResourceTags");
if (!input.isArray() || input.size() > 200) {
throw invalid("ResourceTags must be an array of at most 200 tags.");
}
for (JsonNode tag : input) {
String key = tagText(text(tag, "Key", 128), true);
String value = tagText(text(tag, "Value", 256), false);
if (tags.has(key)) {
throw invalid("Each resource tag key must be unique.");
}
tags.put(key, value);
}
checkTagCount(tags);
return tags;
}
private String tagText(String value, boolean key) {
String trimmed = value.strip();
if (!TAG_TEXT.matcher(trimmed).matches()
|| (key && (trimmed.isEmpty() || trimmed.regionMatches(true, 0, "aws:", 0, 4)))) {
throw invalid("Resource tags must use valid characters and must not use reserved AWS keys.");
}
return trimmed;
}
private void checkTagCount(ObjectNode tags) {
if (tags.size() > 50) {
throw new AwsException("TooManyTagsException", "A resource may have at most 50 user tags.", 400);
}
}
private AccountAwareStorageBackend<ObjectNode> taggedStorage(String arn) {
String account = monitors.accountId();
if (monitors.getForAccount(account, arn).isPresent()) {
return monitors;
}
if (subscriptions.getForAccount(account, arn).isPresent()) {
return subscriptions;
}
throw new AwsException("ResourceNotFoundException", "The specified resource does not exist for this account.", 400);
}
private ObjectNode existing(AccountAwareStorageBackend<ObjectNode> storage, String account,
String arn, String errorCode) {
return storage.getForAccount(account, arn)
.orElseThrow(() -> new AwsException(errorCode, "The specified resource does not exist for this account.", 400));
}
private ObjectNode resource(ObjectNode definition, ObjectNode tags) {
ObjectNode resource = mapper.createObjectNode();
resource.set("definition", definition);
resource.set("tags", tags);
return resource;
}
private ObjectNode fields(ObjectNode input, String... fields) {
ObjectNode result = mapper.createObjectNode();
for (String field : fields) {
if (present(input, field)) {
result.set(field, input.get(field).deepCopy());
}
}
return result;
}
private String arn(String account, String type) {
return AwsArnUtils.Arn.of("ce", "", account, type + "/" + UUID.randomUUID()).toString();
}
private boolean contains(JsonNode values, String value) {
for (JsonNode item : values) {
if (value.equals(item.textValue())) {
return true;
}
}
return false;
}
private static ObjectNode object(JsonNode parent, String name) {
if (parent != null && parent.get(name) instanceof ObjectNode object) {
return object;
}
throw invalid(name + " must be an object.");
}
private static String text(JsonNode parent, String name, int maximum) {
JsonNode value = parent == null ? null : parent.get(name);
if (value == null || !value.isTextual() || value.textValue().length() > maximum) {
throw invalid(name + " must be a string of at most " + maximum + " characters.");
}
return value.textValue();
}
private static List<String> strings(JsonNode parent, String name, int maximum, int stringMaximum) {
JsonNode value = parent.path(name);
if (!value.isArray() || value.size() > maximum) {
throw invalid(name + " must be an array of at most " + maximum + " strings.");
}
List<String> result = new ArrayList<>();
for (JsonNode element : value) {
if (!element.isTextual() || element.textValue().length() > stringMaximum) {
throw invalid(name + " must contain strings of at most " + stringMaximum + " characters.");
}
result.add(element.textValue());
}
return result;
}
private static String singleRoot(ObjectNode expression, Set<String> supported) {
Iterator<String> fields = expression.fieldNames();
if (expression.size() != 1 || !fields.hasNext()) {
throw invalid("An expression must contain exactly one root operator.");
}
String root = fields.next();
if (!supported.contains(root)) {
throw invalid("Unsupported expression operator: " + root);
}
return root;
}
private static boolean present(JsonNode node, String field) {
return node != null && node.hasNonNull(field);
}
private static AwsException invalid(String message) {
return new AwsException("ValidationException", message, 400);
}
}
@@ -20,10 +20,12 @@ public class CostExplorerJsonHandler {
private static final Logger LOG = Logger.getLogger(CostExplorerJsonHandler.class);
private final CostExplorerService service;
private final CostAnomalyService anomalies;
@Inject
public CostExplorerJsonHandler(CostExplorerService service) {
public CostExplorerJsonHandler(CostExplorerService service, CostAnomalyService anomalies) {
this.service = service;
this.anomalies = anomalies;
}
public Response handle(String action, JsonNode request, String region) {
@@ -38,6 +40,29 @@ public class CostExplorerJsonHandler {
case "GetSavingsPlansCoverage" -> Response.ok(service.getSavingsPlansCoverage()).build();
case "GetSavingsPlansUtilization" -> Response.ok(service.getSavingsPlansUtilization()).build();
case "GetCostCategories" -> Response.ok(service.getCostCategories(request)).build();
case "CreateAnomalyMonitor" -> Response.ok(anomalies.createMonitor(request)).build();
case "GetAnomalyMonitors" -> Response.ok(anomalies.getMonitors(request)).build();
case "UpdateAnomalyMonitor" -> Response.ok(anomalies.updateMonitor(request)).build();
case "DeleteAnomalyMonitor" -> {
anomalies.deleteMonitor(request);
yield Response.ok("{}").build();
}
case "CreateAnomalySubscription" -> Response.ok(anomalies.createSubscription(request)).build();
case "GetAnomalySubscriptions" -> Response.ok(anomalies.getSubscriptions(request)).build();
case "UpdateAnomalySubscription" -> Response.ok(anomalies.updateSubscription(request)).build();
case "DeleteAnomalySubscription" -> {
anomalies.deleteSubscription(request);
yield Response.ok("{}").build();
}
case "ListTagsForResource" -> Response.ok(anomalies.listTags(request)).build();
case "TagResource" -> {
anomalies.tagResource(request);
yield Response.ok("{}").build();
}
case "UntagResource" -> {
anomalies.untagResource(request);
yield Response.ok("{}").build();
}
default -> Response.status(400)
.entity(new AwsErrorResponse("UnknownOperationException",
"Unknown operation: AWSInsightsIndexService." + action))
@@ -0,0 +1,250 @@
package io.github.hectorvent.floci.services.ce;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
@QuarkusTest
class CostAnomalyIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String REGION = "us-east-1";
private static final Map<String, Object> THRESHOLD_EXPRESSION = Map.of("Dimensions", Map.of(
"Key", "ANOMALY_TOTAL_IMPACT_ABSOLUTE", "Values", List.of("100"),
"MatchOptions", List.of("GREATER_THAN_OR_EQUAL")));
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void monitorAndSubscriptionLifecyclePreservesSettingsDuringPartialUpdates() {
String account = "941000000001";
String monitorArn = request(account, REGION, "CreateAnomalyMonitor", Map.of(
"AnomalyMonitor", Map.of("MonitorName", "service-costs", "MonitorType", "DIMENSIONAL",
"MonitorDimension", "SERVICE"),
"ResourceTags", List.of(Map.of("Key", "Environment", "Value", "test"))))
.statusCode(200)
.body("MonitorArn", startsWith("arn:aws:ce::" + account + ":anomalymonitor/"))
.extract().path("MonitorArn");
request(account, REGION, "GetAnomalyMonitors", Map.of("MonitorArnList", List.of(monitorArn)))
.statusCode(200)
.body("AnomalyMonitors", hasSize(1))
.body("AnomalyMonitors[0].MonitorArn", equalTo(monitorArn))
.body("AnomalyMonitors[0].MonitorName", equalTo("service-costs"))
.body("AnomalyMonitors[0].MonitorType", equalTo("DIMENSIONAL"))
.body("AnomalyMonitors[0].MonitorDimension", equalTo("SERVICE"));
request(account, REGION, "UpdateAnomalyMonitor", Map.of(
"MonitorArn", monitorArn, "MonitorName", "renamed-service-costs")).statusCode(200);
request(account, REGION, "GetAnomalyMonitors", Map.of("MonitorArnList", List.of(monitorArn)))
.statusCode(200)
.body("AnomalyMonitors[0].MonitorName", equalTo("renamed-service-costs"))
.body("AnomalyMonitors[0].MonitorDimension", equalTo("SERVICE"));
String subscriptionArn = request(account, REGION, "CreateAnomalySubscription", Map.of(
"AnomalySubscription", subscription("daily-cost-alerts", monitorArn),
"ResourceTags", List.of(Map.of("Key", "Environment", "Value", "test"))))
.statusCode(200)
.body("SubscriptionArn", startsWith("arn:aws:ce::" + account + ":anomalysubscription/"))
.extract().path("SubscriptionArn");
for (String resourceArn : List.of(monitorArn, subscriptionArn)) {
request(account, REGION, "ListTagsForResource", Map.of("ResourceArn", resourceArn))
.statusCode(200)
.body("ResourceTags", hasSize(1))
.body("ResourceTags[0].Key", equalTo("Environment"))
.body("ResourceTags[0].Value", equalTo("test"));
request(account, REGION, "TagResource", Map.of("ResourceArn", resourceArn,
"ResourceTags", List.of(Map.of("Key", "Environment", "Value", "production"),
Map.of("Key", "Owner", "Value", "billing"))))
.statusCode(200).body(equalTo("{}"));
request(account, REGION, "ListTagsForResource", Map.of("ResourceArn", resourceArn))
.statusCode(200)
.body("ResourceTags", hasSize(2))
.body("ResourceTags.find { it.Key == 'Environment' }.Value", equalTo("production"))
.body("ResourceTags.find { it.Key == 'Owner' }.Value", equalTo("billing"));
request(account, REGION, "UntagResource", Map.of("ResourceArn", resourceArn,
"ResourceTagKeys", List.of("Owner"))).statusCode(200).body(equalTo("{}"));
request(account, REGION, "ListTagsForResource", Map.of("ResourceArn", resourceArn))
.statusCode(200)
.body("ResourceTags.Key", contains("Environment"));
}
request(account, REGION, "UpdateAnomalySubscription", Map.of(
"SubscriptionArn", subscriptionArn, "SubscriptionName", "renamed-alerts")).statusCode(200);
request(account, REGION, "GetAnomalySubscriptions", Map.of(
"SubscriptionArnList", List.of(subscriptionArn), "MonitorArn", monitorArn))
.statusCode(200)
.body("AnomalySubscriptions", hasSize(1))
.body("AnomalySubscriptions[0].SubscriptionName", equalTo("renamed-alerts"))
.body("AnomalySubscriptions[0].SubscriptionArn", equalTo(subscriptionArn))
.body("AnomalySubscriptions[0].AccountId", equalTo(account))
.body("AnomalySubscriptions[0].Frequency", equalTo("DAILY"))
.body("AnomalySubscriptions[0].MonitorArnList", contains(monitorArn))
.body("AnomalySubscriptions[0].Subscribers[0].Address", equalTo("alerts@example.com"))
.body("AnomalySubscriptions[0].Subscribers[0].Type", equalTo("EMAIL"))
.body("AnomalySubscriptions[0].ThresholdExpression.Dimensions", equalTo(
THRESHOLD_EXPRESSION.get("Dimensions")));
request(account, REGION, "UpdateAnomalySubscription", Map.of(
"SubscriptionArn", subscriptionArn, "Frequency", "WEEKLY",
"Subscribers", List.of(Map.of("Address", "weekly@example.com", "Type", "EMAIL"))))
.statusCode(200);
request(account, REGION, "GetAnomalySubscriptions", Map.of("SubscriptionArnList", List.of(subscriptionArn)))
.statusCode(200)
.body("AnomalySubscriptions[0].SubscriptionName", equalTo("renamed-alerts"))
.body("AnomalySubscriptions[0].Frequency", equalTo("WEEKLY"))
.body("AnomalySubscriptions[0].Subscribers[0].Address", equalTo("weekly@example.com"))
.body("AnomalySubscriptions[0].MonitorArnList", contains(monitorArn));
request(account, REGION, "DeleteAnomalySubscription", Map.of("SubscriptionArn", subscriptionArn))
.statusCode(200).body(equalTo("{}"));
request(account, REGION, "DeleteAnomalyMonitor", Map.of("MonitorArn", monitorArn))
.statusCode(200).body(equalTo("{}"));
request(account, REGION, "GetAnomalySubscriptions", Map.of())
.statusCode(200).body("AnomalySubscriptions", hasSize(0));
request(account, REGION, "GetAnomalyMonitors", Map.of())
.statusCode(200).body("AnomalyMonitors", hasSize(0));
}
@Test
void resourcesAreAccountScopedAndSharedAcrossRequestRegions() {
String firstAccount = "941000000002";
String secondAccount = "941000000003";
String firstMonitor = createMonitor(firstAccount, "same-name", false);
String secondMonitor = createMonitor(secondAccount, "same-name", false);
String firstSubscription = createSubscription(firstAccount, "same-name", firstMonitor);
String secondSubscription = createSubscription(secondAccount, "same-name", secondMonitor);
request(firstAccount, "eu-west-1", "GetAnomalyMonitors", Map.of())
.statusCode(200).body("AnomalyMonitors.MonitorArn", contains(firstMonitor));
request(firstAccount, "eu-west-1", "GetAnomalySubscriptions", Map.of())
.statusCode(200).body("AnomalySubscriptions.SubscriptionArn", contains(firstSubscription));
request(secondAccount, REGION, "GetAnomalyMonitors", Map.of())
.statusCode(200).body("AnomalyMonitors.MonitorArn", contains(secondMonitor));
request(secondAccount, REGION, "GetAnomalySubscriptions", Map.of())
.statusCode(200).body("AnomalySubscriptions.SubscriptionArn", contains(secondSubscription));
request(secondAccount, REGION, "GetAnomalyMonitors", Map.of("MonitorArnList", List.of(firstMonitor)))
.statusCode(400).body("__type", equalTo("UnknownMonitorException"));
request(firstAccount, "eu-west-1", "UpdateAnomalyMonitor", Map.of(
"MonitorArn", firstMonitor, "MonitorName", "renamed-first-account")).statusCode(200);
request(firstAccount, REGION, "GetAnomalyMonitors", Map.of())
.statusCode(200).body("AnomalyMonitors[0].MonitorName", equalTo("renamed-first-account"));
request(secondAccount, REGION, "GetAnomalyMonitors", Map.of())
.statusCode(200).body("AnomalyMonitors[0].MonitorName", equalTo("same-name"));
request(firstAccount, REGION, "DeleteAnomalySubscription", Map.of("SubscriptionArn", firstSubscription))
.statusCode(200);
request(secondAccount, REGION, "DeleteAnomalySubscription", Map.of("SubscriptionArn", secondSubscription))
.statusCode(200);
request(firstAccount, REGION, "DeleteAnomalyMonitor", Map.of("MonitorArn", firstMonitor)).statusCode(200);
request(secondAccount, REGION, "DeleteAnomalyMonitor", Map.of("MonitorArn", secondMonitor)).statusCode(200);
}
@Test
void listOperationsPageWithoutOmittingOrRepeatingResources() {
String account = "941000000004";
String firstMonitor = createMonitor(account, "first-custom", true);
String secondMonitor = createMonitor(account, "second-custom", true);
String firstSubscription = createSubscription(account, "first-alert", firstMonitor);
String secondSubscription = createSubscription(account, "second-alert", firstMonitor);
ValidatableResponse monitorsPage = request(account, REGION, "GetAnomalyMonitors", Map.of("MaxResults", 1))
.statusCode(200).body("AnomalyMonitors", hasSize(1)).body("NextPageToken", notNullValue())
.body("AnomalyMonitors[0].MonitorSpecification.Dimensions.Key", equalTo("LINKED_ACCOUNT"))
.body("AnomalyMonitors[0].MonitorSpecification.Dimensions.Values", contains("111111111111"));
String monitorToken = monitorsPage.extract().path("NextPageToken");
String firstPageMonitor = monitorsPage.extract().path("AnomalyMonitors[0].MonitorArn");
String secondPageMonitor = request(account, REGION, "GetAnomalyMonitors", Map.of(
"MaxResults", 1, "NextPageToken", monitorToken))
.statusCode(200).body("AnomalyMonitors", hasSize(1)).body("NextPageToken", nullValue())
.extract().path("AnomalyMonitors[0].MonitorArn");
assertThat(List.of(firstPageMonitor, secondPageMonitor), containsInAnyOrder(firstMonitor, secondMonitor));
ValidatableResponse subscriptionsPage = request(account, REGION, "GetAnomalySubscriptions", Map.of(
"MonitorArn", firstMonitor, "MaxResults", 1))
.statusCode(200).body("AnomalySubscriptions", hasSize(1)).body("NextPageToken", notNullValue());
String subscriptionToken = subscriptionsPage.extract().path("NextPageToken");
String firstPageSubscription = subscriptionsPage.extract().path("AnomalySubscriptions[0].SubscriptionArn");
String secondPageSubscription = request(account, REGION, "GetAnomalySubscriptions", Map.of(
"MonitorArn", firstMonitor, "MaxResults", 1, "NextPageToken", subscriptionToken))
.statusCode(200).body("AnomalySubscriptions", hasSize(1)).body("NextPageToken", nullValue())
.extract().path("AnomalySubscriptions[0].SubscriptionArn");
assertThat(List.of(firstPageSubscription, secondPageSubscription),
containsInAnyOrder(firstSubscription, secondSubscription));
request(account, REGION, "GetAnomalySubscriptions", Map.of("MonitorArn", secondMonitor))
.statusCode(200).body("AnomalySubscriptions", hasSize(0));
request(account, REGION, "DeleteAnomalySubscription", Map.of("SubscriptionArn", firstSubscription))
.statusCode(200);
request(account, REGION, "DeleteAnomalySubscription", Map.of("SubscriptionArn", secondSubscription))
.statusCode(200);
request(account, REGION, "DeleteAnomalyMonitor", Map.of("MonitorArn", firstMonitor)).statusCode(200);
request(account, REGION, "DeleteAnomalyMonitor", Map.of("MonitorArn", secondMonitor)).statusCode(200);
}
@Test
void malformedDefinitionsAndUnknownMonitorsReturnAwsErrors() {
String account = "941000000005";
request(account, REGION, "CreateAnomalyMonitor", Map.of("AnomalyMonitor", Map.of(
"MonitorType", "DIMENSIONAL", "MonitorDimension", "SERVICE")))
.statusCode(400).body("__type", equalTo("ValidationException"));
request(account, REGION, "CreateAnomalySubscription", Map.of("AnomalySubscription", Map.of(
"SubscriptionName", "missing-settings")))
.statusCode(400).body("__type", equalTo("ValidationException"));
request(account, REGION, "GetAnomalyMonitors", Map.of("MonitorArnList", List.of(
"arn:aws:ce::" + account + ":anomalymonitor/00000000-0000-0000-0000-000000000000")))
.statusCode(400).body("__type", equalTo("UnknownMonitorException"));
}
private String createMonitor(String account, String name, boolean custom) {
Map<String, Object> definition = custom
? Map.of("MonitorName", name, "MonitorType", "CUSTOM", "MonitorSpecification",
Map.of("Dimensions", Map.of("Key", "LINKED_ACCOUNT", "Values", List.of("111111111111"))))
: Map.of("MonitorName", name, "MonitorType", "DIMENSIONAL", "MonitorDimension", "SERVICE");
return request(account, REGION, "CreateAnomalyMonitor", Map.of("AnomalyMonitor", definition))
.statusCode(200).extract().path("MonitorArn");
}
private String createSubscription(String account, String name, String monitorArn) {
return request(account, REGION, "CreateAnomalySubscription", Map.of(
"AnomalySubscription", subscription(name, monitorArn)))
.statusCode(200).extract().path("SubscriptionArn");
}
private Map<String, Object> subscription(String name, String monitorArn) {
return Map.of("SubscriptionName", name, "Frequency", "DAILY", "MonitorArnList", List.of(monitorArn),
"Subscribers", List.of(Map.of("Address", "alerts@example.com", "Type", "EMAIL")),
"ThresholdExpression", THRESHOLD_EXPRESSION);
}
private ValidatableResponse request(String account, String region, String action, Map<String, Object> body) {
return given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService." + action)
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260101/" + region + "/ce/aws4_request")
.body(body)
.when().post("/")
.then();
}
}
@@ -0,0 +1,253 @@
package io.github.hectorvent.floci.services.ce;
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.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CostAnomalyServiceTest {
private static final String ACCOUNT = "111111111111";
private final ObjectMapper mapper = new ObjectMapper();
private CostAnomalyService service;
@BeforeEach
void setUp() {
service = new CostAnomalyService(AccountAwareStorageBackend.inMemory(ACCOUNT),
AccountAwareStorageBackend.inMemory(ACCOUNT), mapper);
}
@Test
void definitionsAreCopiedAndCustomMonitorNamesDoNotActAsIdempotencyKeys() {
ObjectNode request = customMonitor("same-name");
String first = service.createMonitor(request).path("MonitorArn").asText();
((ObjectNode) request.get("AnomalyMonitor")).put("MonitorName", "changed-input");
String second = service.createMonitor(customMonitor("same-name")).path("MonitorArn").asText();
assertNotEquals(first, second);
assertEquals("same-name", monitor(first).path("MonitorName").asText());
assertFalse(monitor(first).has("LastEvaluatedDate"));
ObjectNode returned = (ObjectNode) monitor(first);
returned.put("MonitorName", "changed-output");
assertEquals("same-name", monitor(first).path("MonitorName").asText());
}
@Test
void dimensionalMonitorQuotaDoesNotPreventCustomMonitors() {
ObjectNode request = mapper.valueToTree(Map.of("AnomalyMonitor", Map.of(
"MonitorName", "services", "MonitorType", "DIMENSIONAL", "MonitorDimension", "SERVICE")));
service.createMonitor(request);
assertError("LimitExceededException", () -> service.createMonitor(request));
service.createMonitor(customMonitor("custom"));
assertEquals(2, service.getMonitors(mapper.createObjectNode()).path("AnomalyMonitors").size());
}
@Test
void tagDimensionAcceptsItsKeySpecificationAndRejectsMissingSpecification() {
ObjectNode request = mapper.valueToTree(Map.of("AnomalyMonitor", Map.of(
"MonitorName", "tag-costs", "MonitorType", "DIMENSIONAL", "MonitorDimension", "TAG",
"MonitorSpecification", Map.of("Tags", Map.of("Key", "Environment")))));
String arn = service.createMonitor(request).path("MonitorArn").asText();
assertEquals("Environment", monitor(arn).path("MonitorSpecification").path("Tags").path("Key").asText());
((ObjectNode) request.get("AnomalyMonitor")).remove("MonitorSpecification");
assertError("ValidationException", () -> service.createMonitor(request));
}
@Test
void legacyThresholdIsNormalizedAndExpressionUpdatesReplaceIt() {
String monitorArn = service.createMonitor(customMonitor("legacy-threshold")).path("MonitorArn").asText();
ObjectNode request = subscriptionRequest(monitorArn);
ObjectNode definition = (ObjectNode) request.get("AnomalySubscription");
definition.remove("ThresholdExpression");
definition.put("Threshold", 12.5);
String arn = service.createSubscription(request).path("SubscriptionArn").asText();
JsonNode stored = subscription(arn);
assertEquals("12.5", stored.path("ThresholdExpression").path("Dimensions").path("Values").get(0).asText());
assertEquals(ACCOUNT, stored.path("AccountId").asText());
assertFalse(stored.has("Threshold"));
assertFalse(stored.path("Subscribers").get(0).has("Status"));
ObjectNode update = mapper.createObjectNode().put("SubscriptionArn", arn);
update.set("ThresholdExpression", expression("ANOMALY_TOTAL_IMPACT_PERCENTAGE", "25"));
service.updateSubscription(update);
JsonNode changed = subscription(arn);
assertEquals("ANOMALY_TOTAL_IMPACT_PERCENTAGE",
changed.path("ThresholdExpression").path("Dimensions").path("Key").asText());
assertFalse(changed.has("Threshold"));
assertEquals("DAILY", changed.path("Frequency").asText());
}
@Test
void invalidPartialSubscriptionUpdatesAreAtomic() {
String monitorArn = service.createMonitor(customMonitor("atomic")).path("MonitorArn").asText();
String arn = service.createSubscription(subscriptionRequest(monitorArn)).path("SubscriptionArn").asText();
JsonNode before = subscription(arn).deepCopy();
ObjectNode frequencyUpdate = mapper.createObjectNode()
.put("SubscriptionArn", arn).put("SubscriptionName", "must-not-stick").put("Frequency", "IMMEDIATE");
assertError("ValidationException", () -> service.updateSubscription(frequencyUpdate));
assertEquals(before, subscription(arn));
ObjectNode conflictingThresholds = mapper.createObjectNode().put("SubscriptionArn", arn).put("Threshold", 100);
conflictingThresholds.set("ThresholdExpression", expression("ANOMALY_TOTAL_IMPACT_ABSOLUTE", "100"));
assertError("ValidationException", () -> service.updateSubscription(conflictingThresholds));
assertEquals(before, subscription(arn));
}
@Test
void invalidThresholdExpressionsDoNotCreateSubscriptions() {
String monitorArn = service.createMonitor(customMonitor("invalid-expression")).path("MonitorArn").asText();
for (String value : List.of("-1", "10000000001", "NaN")) {
ObjectNode request = subscriptionRequest(monitorArn);
((ObjectNode) request.get("AnomalySubscription"))
.set("ThresholdExpression", expression("ANOMALY_TOTAL_IMPACT_ABSOLUTE", value));
assertError("ValidationException", () -> service.createSubscription(request));
}
ObjectNode request = subscriptionRequest(monitorArn);
ObjectNode invalidExpression = expression("ANOMALY_TOTAL_IMPACT_ABSOLUTE", "10");
invalidExpression.putArray("Or").add(expression("ANOMALY_TOTAL_IMPACT_PERCENTAGE", "10"));
((ObjectNode) request.get("AnomalySubscription")).set("ThresholdExpression", invalidExpression);
assertError("ValidationException", () -> service.createSubscription(request));
assertEquals(0, service.getSubscriptions(mapper.createObjectNode()).path("AnomalySubscriptions").size());
}
@Test
void monitorDeletionDoesNotCascadeToSubscriptionOrPreventPartialUpdates() {
String monitorArn = service.createMonitor(customMonitor("delete-first")).path("MonitorArn").asText();
String arn = service.createSubscription(subscriptionRequest(monitorArn)).path("SubscriptionArn").asText();
service.deleteMonitor(mapper.createObjectNode().put("MonitorArn", monitorArn));
service.updateSubscription(mapper.createObjectNode()
.put("SubscriptionArn", arn).put("SubscriptionName", "retained"));
assertEquals("retained", subscription(arn).path("SubscriptionName").asText());
service.deleteSubscription(mapper.createObjectNode().put("SubscriptionArn", arn));
assertEquals(0, service.getSubscriptions(mapper.createObjectNode()).path("AnomalySubscriptions").size());
}
@Test
void tagQuotaFailurePreservesExistingTagsAndKeepsThemOutOfDefinitions() {
ObjectNode request = customMonitor("tags");
ArrayNode tags = request.putArray("ResourceTags");
for (int index = 0; index < 50; index++) {
tags.addObject().put("Key", "key-" + index).put("Value", "value");
}
String arn = service.createMonitor(request).path("MonitorArn").asText();
ObjectNode resource = mapper.createObjectNode().put("ResourceArn", arn);
ObjectNode update = resource.deepCopy();
update.putArray("ResourceTags").addObject().put("Key", "extra").put("Value", "not-stored");
assertError("TooManyTagsException", () -> service.tagResource(update));
assertEquals(50, service.listTags(resource).path("ResourceTags").size());
assertFalse(monitor(arn).has("ResourceTags"));
assertFalse(monitor(arn).has("tags"));
ObjectNode overwrite = resource.deepCopy();
overwrite.putArray("ResourceTags").addObject().put("Key", "key-0").put("Value", "changed");
service.tagResource(overwrite);
assertEquals(50, service.listTags(resource).path("ResourceTags").size());
service.deleteMonitor(mapper.createObjectNode().put("MonitorArn", arn));
assertError("ResourceNotFoundException", () -> service.listTags(resource));
}
@Test
void paginationHandlesLargePageSizesAndRejectsInvalidInputs() {
for (int index = 0; index < 3; index++) {
service.createMonitor(customMonitor("page-" + index));
}
ObjectNode first = service.getMonitors(mapper.createObjectNode().put("MaxResults", 1));
ObjectNode rest = service.getMonitors(mapper.createObjectNode().put("MaxResults", Integer.MAX_VALUE)
.put("NextPageToken", first.path("NextPageToken").asText()));
assertEquals(2, rest.path("AnomalyMonitors").size());
assertFalse(rest.has("NextPageToken"));
assertError("ValidationException",
() -> service.getMonitors(mapper.createObjectNode().put("MaxResults", 0)));
assertError("InvalidNextTokenException",
() -> service.getMonitors(mapper.createObjectNode().put("NextPageToken", "!not-base64")));
}
@Test
void monitorsSubscriptionsAndTagsSurviveRestartAndReset(@TempDir Path directory) {
CostAnomalyService original = persistentService(directory);
ObjectNode request = customMonitor("persistent");
request.putArray("ResourceTags").addObject().put("Key", "Owner").put("Value", "billing");
String monitorArn = original.createMonitor(request).path("MonitorArn").asText();
String subscriptionArn = original.createSubscription(subscriptionRequest(monitorArn))
.path("SubscriptionArn").asText();
original.updateMonitor(mapper.createObjectNode().put("MonitorArn", monitorArn).put("MonitorName", "saved"));
CostAnomalyService restored = persistentService(directory);
assertEquals("saved", restored.getMonitors(mapper.createObjectNode())
.path("AnomalyMonitors").get(0).path("MonitorName").asText());
assertEquals(subscriptionArn, restored.getSubscriptions(mapper.createObjectNode())
.path("AnomalySubscriptions").get(0).path("SubscriptionArn").asText());
assertEquals("billing", restored.listTags(mapper.createObjectNode().put("ResourceArn", monitorArn))
.path("ResourceTags").get(0).path("Value").asText());
restored.clear();
CostAnomalyService afterReset = persistentService(directory);
assertTrue(afterReset.getMonitors(mapper.createObjectNode()).path("AnomalyMonitors").isEmpty());
assertTrue(afterReset.getSubscriptions(mapper.createObjectNode()).path("AnomalySubscriptions").isEmpty());
}
private CostAnomalyService persistentService(Path directory) {
PersistentStorage<String, ObjectNode> monitors = new PersistentStorage<>(directory.resolve("monitors.json"),
new TypeReference<Map<String, ObjectNode>>() {});
PersistentStorage<String, ObjectNode> subscriptions = new PersistentStorage<>(
directory.resolve("subscriptions.json"), new TypeReference<Map<String, ObjectNode>>() {});
monitors.load();
subscriptions.load();
return new CostAnomalyService(new AccountAwareStorageBackend<>(monitors, null, ACCOUNT),
new AccountAwareStorageBackend<>(subscriptions, null, ACCOUNT), mapper);
}
private ObjectNode customMonitor(String name) {
return mapper.valueToTree(Map.of("AnomalyMonitor", Map.of("MonitorName", name, "MonitorType", "CUSTOM",
"MonitorSpecification", Map.of("Dimensions", Map.of("Key", "LINKED_ACCOUNT",
"Values", List.of("222222222222"))))));
}
private ObjectNode subscriptionRequest(String monitorArn) {
return mapper.valueToTree(Map.of("AnomalySubscription", Map.of(
"SubscriptionName", "alerts", "Frequency", "DAILY", "MonitorArnList", List.of(monitorArn),
"Subscribers", List.of(Map.of("Type", "EMAIL", "Address", "alerts@example.com")),
"ThresholdExpression", expression("ANOMALY_TOTAL_IMPACT_ABSOLUTE", "100"))));
}
private ObjectNode expression(String dimension, String value) {
return mapper.valueToTree(Map.of("Dimensions", Map.of(
"Key", dimension, "Values", List.of(value), "MatchOptions", List.of("GREATER_THAN_OR_EQUAL"))));
}
private JsonNode monitor(String arn) {
ObjectNode request = mapper.createObjectNode();
request.putArray("MonitorArnList").add(arn);
return service.getMonitors(request).path("AnomalyMonitors").get(0);
}
private JsonNode subscription(String arn) {
ObjectNode request = mapper.createObjectNode();
request.putArray("SubscriptionArnList").add(arn);
return service.getSubscriptions(request).path("AnomalySubscriptions").get(0);
}
private static void assertError(String code, Executable operation) {
AwsException exception = assertThrows(AwsException.class, operation);
assertEquals(code, exception.getErrorCode());
assertEquals(400, exception.getHttpStatus());
}
}
+4 -1
View File
@@ -60,6 +60,10 @@ services:
UpdateTarget: UpdateGatewayTarget
DeleteTarget: DeleteGatewayTarget
ListTargets: ListGatewayTargets
- service: ce
doc: docs/services/ce.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/ce/CostExplorerJsonHandler.java, mode: switch }
- service: cloudformation
doc: docs/services/cloudformation.md
sources:
@@ -404,7 +408,6 @@ deferred_handlers:
- { path: src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java } # non-tabular doc (grouped/inline)
- { path: src/main/java/io/github/hectorvent/floci/services/bcmpricingcalculator/BcmPricingCalculatorJsonHandler.java } # focused workload-estimate surface
- { path: src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java } # no standalone action table yet
- { path: src/main/java/io/github/hectorvent/floci/services/ce/CostExplorerJsonHandler.java } # no standalone action table yet
- { path: src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlJsonHandler.java } # no standalone action table yet
- { path: src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapHandler.java } # non-tabular doc (grouped/inline)
- { path: src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java } # multi-table doc (nested handler)