From a0fd815366ab72c089ea96f0c8af79d0bcceae93 Mon Sep 17 00:00:00 2001 From: "Franklin G. Mendoza" Date: Sat, 12 Sep 2026 08:59:21 -0400 Subject: [PATCH] feat(oam): emulate observability access manager (#3440) * feat(oam): emulate observability access manager * fix(oam): honor explicit deny statements --- README.md | 3 +- compatibility-tests/sdk-test-java/pom.xml | 5 + .../java/com/floci/test/TestFixtures.java | 9 + .../src/test/java/com/floci/test/OamTest.java | 28 ++ docs/services/index.md | 1 + docs/services/oam.md | 85 ++++ mkdocs.yml | 1 + .../floci/config/EmulatorConfig.java | 6 + .../core/common/ResolvedServiceCatalog.java | 5 + .../floci/services/oam/OamController.java | 209 ++++++++++ .../floci/services/oam/OamService.java | 387 ++++++++++++++++++ .../floci/services/oam/model/OamLink.java | 44 ++ .../floci/services/oam/model/OamSink.java | 34 ++ src/main/resources/application.yml | 2 + .../services/oam/OamIntegrationTest.java | 168 ++++++++ src/test/resources/application.yml | 2 + 16 files changed, 988 insertions(+), 1 deletion(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OamTest.java create mode 100644 docs/services/oam.md create mode 100644 src/main/java/io/github/hectorvent/floci/services/oam/OamController.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/oam/OamService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/oam/model/OamLink.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/oam/model/OamSink.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/oam/OamIntegrationTest.java diff --git a/README.md b/README.md index 3800690d9e..66ff7d24c7 100644 --- a/README.md +++ b/README.md @@ -232,7 +232,7 @@ Floci supports local emulation for application services, data services, eventing | Category | Services | |---|---| | Core app services | S3, SQS, SNS, DynamoDB, Lambda, IAM, KMS, Secrets Manager, SSM | -| Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch RUM, Managed Prometheus (AMP) | +| Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch OAM, CloudWatch RUM, Managed Prometheus (AMP) | | API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, ACM, Route53, Route 53 Resolver, Cloud Map, Global Accelerator | | Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic | | Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock, Bedrock Runtime, Bedrock AgentCore | @@ -272,6 +272,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | EventBridge Scheduler | In-process | Schedule groups, schedules, flexible time windows, retry policies, DLQs | | CloudWatch Logs | In-process | Log groups, streams, ingestion, filtering | | CloudWatch Metrics | In-process | Custom metrics, statistics, alarms | +| CloudWatch OAM | In-process | Full 15-operation sink, policy, cross-account link, and tagging API | | ElastiCache | Real Docker | Redis / Valkey protocol, IAM auth, SigV4 validation | | MemoryDB | Real Docker | Redis / Valkey protocol via real containers; JSON 1.1 control plane; reuses ElastiCache RESP proxy | | RDS | Real Docker | PostgreSQL, MySQL, MariaDB, IAM auth, JDBC-compatible engines | diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 334324f35c..3f0d2288fb 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -512,6 +512,11 @@ software.amazon.awssdk resourceexplorer2 + + + software.amazon.awssdk + oam + software.amazon.awssdk 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 5896826697..baa8938f2f 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 @@ -26,6 +26,7 @@ import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.opensearch.OpenSearchClient; +import software.amazon.awssdk.services.oam.OamClient; import software.amazon.awssdk.services.neptune.NeptuneClient; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.redshift.RedshiftClient; @@ -1294,6 +1295,14 @@ public final class TestFixtures { .build(); } + public static OamClient oamClient() { + return OamClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static ResourceExplorer2Client resourceExplorer2Client() { return resourceExplorer2Client(REGION); } diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OamTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OamTest.java new file mode 100644 index 0000000000..4b015403c9 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OamTest.java @@ -0,0 +1,28 @@ +package com.floci.test; + +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.oam.OamClient; +import software.amazon.awssdk.services.oam.model.CreateSinkRequest; +import software.amazon.awssdk.services.oam.model.DeleteSinkRequest; +import software.amazon.awssdk.services.oam.model.GetSinkRequest; +import software.amazon.awssdk.services.oam.model.ListSinksRequest; + +import static org.junit.jupiter.api.Assertions.*; + +class OamTest { + @Test + void sinkLifecycle() { + try (OamClient client = TestFixtures.oamClient()) { + var created = client.createSink(CreateSinkRequest.builder().name("sdk-oam-sink").build()); + assertNotNull(created.arn()); + assertEquals("sdk-oam-sink", created.name()); + + var fetched = client.getSink(GetSinkRequest.builder().identifier(created.arn()).build()); + assertEquals(created.arn(), fetched.arn()); + assertTrue(client.listSinks(ListSinksRequest.builder().build()).items().stream() + .anyMatch(item -> created.arn().equals(item.arn()))); + + client.deleteSink(DeleteSinkRequest.builder().identifier(created.arn()).build()); + } + } +} diff --git a/docs/services/index.md b/docs/services/index.md index ac898c1320..7d0986233b 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -41,6 +41,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 16 | | [EventBridge Scheduler](scheduler.md) | `/schedules/*`, `/schedule-groups/*`, `/tags/*` | REST JSON | 12 | | [EventBridge Pipes](pipes.md) | `/v1/pipes/*` | REST JSON | 7 | +| [CloudWatch OAM](oam.md) | REST paths such as `POST /CreateSink` and `POST /CreateLink` | REST JSON | 15 | | [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 17 | | [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 11 | | [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 | diff --git a/docs/services/oam.md b/docs/services/oam.md new file mode 100644 index 0000000000..3d047d9458 --- /dev/null +++ b/docs/services/oam.md @@ -0,0 +1,85 @@ +# CloudWatch Observability Access Manager (`oam:*`) + +**Protocol:** REST JSON +**Signing name:** `oam` +**API version:** `2022-06-10` + +Floci emulates the CloudWatch Observability Access Manager control plane for cross-account observability links. Sinks and links are account and Region scoped, and attached-link discovery crosses source-account storage partitions in the same way the AWS API exposes source links to a monitoring sink. + +## Supported operations + +| Operation | Notes | +|---|---| +| `CreateSink` | Creates the single sink allowed for the calling account and Region | +| `GetSink` | Returns one sink by ARN | +| `ListSinks` | Lists sinks for the calling account and Region | +| `PutSinkPolicy` | Stores and validates the sink resource policy | +| `GetSinkPolicy` | Returns the current policy for a sink | +| `DeleteSink` | Rejects deletion while links remain attached | +| `CreateLink` | Creates a source-account link after evaluating the sink policy | +| `GetLink` | Returns one source-account link | +| `ListLinks` | Lists links owned by the calling source account | +| `ListAttachedLinks` | Lists links from all source accounts attached to a sink | +| `UpdateLink` | Replaces shared resource types and optional metric/log filters | +| `DeleteLink` | Deletes a source-account link | +| `ListTagsForResource` | Returns tags for a sink or link | +| `TagResource` | Adds or replaces tags on a sink or link | +| `UntagResource` | Removes tag keys from a sink or link | + +## Sink policies + +`PutSinkPolicy` accepts IAM-style JSON policies. For `CreateLink`, Floci evaluates the policy's `Effect`, `Principal`, `Action`, `Resource`, and the `oam:ResourceTypes` condition. Individual account principals, account root ARNs, wildcard principals, exact sink ARNs, and wildcard resources are supported. + +Organization-based conditions are not currently resolved through AWS Organizations metadata. Policies that depend on organization condition keys should use explicit account principals when testing locally. + +## Resource types and filters + +Floci accepts the resource types modeled by the current OAM API: + +- `AWS::CloudWatch::Metric` +- `AWS::Logs::LogGroup` +- `AWS::XRay::Trace` +- `AWS::ApplicationInsights::Application` +- `AWS::InternetMonitor::Monitor` +- `AWS::ApplicationSignals::Service` +- `AWS::ApplicationSignals::ServiceLevelObjective` + +Metric and log-group filters are persisted with the link. Updating a filter to `*` removes that filter, matching the AWS update contract. + +## Quotas and validation + +- One sink per account per Region. +- Up to five links per source account per Region. +- `ListSinks` accepts `MaxResults` from 1 to 100. +- `ListLinks` accepts `MaxResults` from 1 to 5. +- `ListAttachedLinks` accepts `MaxResults` from 1 to 1000. +- A sink cannot be deleted while links are attached. +- Sinks and links support up to 50 tags. + +Floci resolves the account-derived label variables to the local account ID because the emulator has no AWS account email/name directory attached to OAM itself. + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_OAM_ENABLED` | `true` | Enable or disable OAM | + +## Example + +```bash +export AWS_ENDPOINT_URL=http://localhost:4566 +export AWS_DEFAULT_REGION=us-east-1 +export AWS_ACCESS_KEY_ID=test +export AWS_SECRET_ACCESS_KEY=test + +sink_arn=$(aws oam create-sink --name local-observability --query Arn --output text) + +aws oam put-sink-policy \ + --sink-identifier "$sink_arn" \ + --policy '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"oam:CreateLink","Resource":"*"}]}' + +aws oam create-link \ + --sink-identifier "$sink_arn" \ + --label-template local-source \ + --resource-types AWS::CloudWatch::Metric AWS::Logs::LogGroup +``` diff --git a/mkdocs.yml b/mkdocs.yml index f42f797d54..b45cca9cf7 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -154,6 +154,7 @@ nav: - EventBridge Pipes: services/pipes.md - EventBridge Scheduler: services/scheduler.md - CloudWatch: services/cloudwatch.md + - CloudWatch OAM: services/oam.md - CloudWatch RUM: services/rum.md - Managed Prometheus (AMP): services/managed-prometheus.md - GuardDuty: services/guardduty.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 1c1646d949..0aa7eb9e72 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -703,6 +703,7 @@ public interface EmulatorConfig { CostExplorerServiceConfig ce(); CurServiceConfig cur(); BcmDataExportsServiceConfig bcmDataExports(); + OamServiceConfig oam(); ConfigServiceConfig configservice(); CloudTrailServiceConfig cloudtrail(); CloudControlServiceConfig cloudcontrol(); @@ -1922,6 +1923,11 @@ public interface EmulatorConfig { int schemaWorkerShutdownTimeoutSeconds(); } + interface OamServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface BcmDataExportsServiceConfig { @WithDefault("true") boolean enabled(); 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 9ef752f4b9..bb70d135b9 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 @@ -29,6 +29,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaController; import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsController; import io.github.hectorvent.floci.services.lambdamicrovms.LambdaNetworkConnectorsController; import io.github.hectorvent.floci.services.opensearch.OpenSearchController; +import io.github.hectorvent.floci.services.oam.OamController; import io.github.hectorvent.floci.services.cloudfront.CloudFrontController; import io.github.hectorvent.floci.services.cloudfront.CloudFrontServingController; import io.github.hectorvent.floci.services.route53.Route53Controller; @@ -558,6 +559,10 @@ public class ResolvedServiceCatalog { "bcmdataexports", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), Set.of("AWSBillingAndCostManagementDataExports."), Set.of("bcm-data-exports"), Set.of(), Set.of()), + descriptor("oam", "oam", config.services().oam().enabled(), true, + "oam", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("oam"), Set.of(), Set.of(OamController.class)), descriptor("cloudfront", "cloudfront", config.services().cloudfront().enabled(), true, "cloudfront", storageMode(config.storage().services().cloudfront().mode(), config.storage().mode()), 5000L, AwsNamespaces.CLOUDFRONT, ServiceProtocol.REST_XML, diff --git a/src/main/java/io/github/hectorvent/floci/services/oam/OamController.java b/src/main/java/io/github/hectorvent/floci/services/oam/OamController.java new file mode 100644 index 0000000000..f9dfdf6126 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/oam/OamController.java @@ -0,0 +1,209 @@ +package io.github.hectorvent.floci.services.oam; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.oam.model.OamLink; +import io.github.hectorvent.floci.services.oam.model.OamSink; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Path("/") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class OamController { + private final OamService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public OamController(OamService service, RegionResolver regionResolver, ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST @Path("/CreateSink") + public Response createSink(@Context HttpHeaders headers, Map request) { + OamSink sink = service.createSink(string(request, "Name"), stringMap(request.get("Tags")), region(headers)); + return Response.ok(sinkBody(sink, true)).build(); + } + + @POST @Path("/GetSink") + public Response getSink(Map request) { + OamSink sink = service.getSink(string(request, "Identifier")); + return Response.ok(sinkBody(sink, boolDefaultTrue(request, "IncludeTags"))).build(); + } + + @POST @Path("/ListSinks") + public Response listSinks(@Context HttpHeaders headers, Map request) { + int max = maxResults(request, 100, 100); + int start = OamService.decodeToken(string(request, "NextToken")); + List all = service.listSinks(region(headers)); + int end = Math.min(start + max, all.size()); + List> items = all.subList(Math.min(start, all.size()), end).stream() + .map(s -> Map.of("Arn", s.getArn(), "Id", s.getId(), "Name", s.getName())).toList(); + Map out = new LinkedHashMap<>(); out.put("Items", items); + if (end < all.size()) out.put("NextToken", OamService.encodeToken(end)); + return Response.ok(out).build(); + } + + @POST @Path("/PutSinkPolicy") + public Response putSinkPolicy(Map request) { + String arn = string(request, "SinkIdentifier"); + String policy = string(request, "Policy"); + service.putSinkPolicy(arn, policy); + OamSink sink = service.getSink(arn); + return Response.ok(Map.of("Policy", policy, "SinkArn", sink.getArn(), "SinkId", sink.getId())).build(); + } + + @POST @Path("/GetSinkPolicy") + public Response getSinkPolicy(Map request) { + OamSink sink = service.getSink(string(request, "SinkIdentifier")); + Map out = new LinkedHashMap<>(); + if (sink.getPolicy() != null) out.put("Policy", sink.getPolicy()); + out.put("SinkArn", sink.getArn()); out.put("SinkId", sink.getId()); + return Response.ok(out).build(); + } + + @POST @Path("/DeleteSink") + public Response deleteSink(Map request) { + service.deleteSink(string(request, "Identifier")); + return Response.ok(Map.of()).build(); + } + + @POST @Path("/CreateLink") + public Response createLink(@Context HttpHeaders headers, Map request) { + OamLink link = service.createLink(string(request, "SinkIdentifier"), string(request, "LabelTemplate"), + stringList(request.get("ResourceTypes")), objectMap(request.get("LinkConfiguration")), + stringMap(request.get("Tags")), region(headers)); + return Response.ok(linkBody(link, true)).build(); + } + + @POST @Path("/GetLink") + public Response getLink(Map request) { + return Response.ok(linkBody(service.getLink(string(request, "Identifier")), boolDefaultTrue(request, "IncludeTags"))).build(); + } + + @POST @Path("/ListLinks") + public Response listLinks(@Context HttpHeaders headers, Map request) { + int max = maxResults(request, 5, 5); + int start = OamService.decodeToken(string(request, "NextToken")); + List all = service.listLinks(region(headers)); + int safeStart = Math.min(start, all.size()); int end = Math.min(safeStart + max, all.size()); + List> items = all.subList(safeStart, end).stream().map(this::linkSummary).toList(); + Map out = new LinkedHashMap<>(); out.put("Items", items); + if (end < all.size()) out.put("NextToken", OamService.encodeToken(end)); + return Response.ok(out).build(); + } + + @POST @Path("/ListAttachedLinks") + public Response listAttachedLinks(Map request) { + int max = maxResults(request, 100, 1000); + int start = OamService.decodeToken(string(request, "NextToken")); + List all = service.listAttachedLinks(string(request, "SinkIdentifier")); + int safeStart = Math.min(start, all.size()); int end = Math.min(safeStart + max, all.size()); + List> items = all.subList(safeStart, end).stream().map(link -> Map.of( + "Label", link.getLabel(), "LinkArn", link.getArn(), "ResourceTypes", link.getResourceTypes())).toList(); + Map out = new LinkedHashMap<>(); out.put("Items", items); + if (end < all.size()) out.put("NextToken", OamService.encodeToken(end)); + return Response.ok(out).build(); + } + + @POST @Path("/UpdateLink") + public Response updateLink(Map request) { + OamLink link = service.updateLink(string(request, "Identifier"), stringList(request.get("ResourceTypes")), + objectMap(request.get("LinkConfiguration"))); + return Response.ok(linkBody(link, boolDefaultTrue(request, "IncludeTags"))).build(); + } + + @POST @Path("/DeleteLink") + public Response deleteLink(Map request) { + service.deleteLink(string(request, "Identifier")); + return Response.ok(Map.of()).build(); + } + + @GET @Path("/tags/{resourceArn:.+}") + public Response listTags(@PathParam("resourceArn") String resourceArn) { + return Response.ok(Map.of("Tags", service.tags(decode(resourceArn)))).build(); + } + + @PUT @Path("/tags/{resourceArn:.+}") + public Response tag(@PathParam("resourceArn") String resourceArn, Map request) { + service.tag(decode(resourceArn), stringMap(request.get("Tags"))); + return Response.ok(Map.of()).build(); + } + + @DELETE @Path("/tags/{resourceArn:.+}") + public Response untag(@PathParam("resourceArn") String resourceArn, @QueryParam("tagKeys") List tagKeys) { + service.untag(decode(resourceArn), tagKeys); + return Response.ok(Map.of()).build(); + } + + private Map sinkBody(OamSink sink, boolean includeTags) { + Map out = new LinkedHashMap<>(); + out.put("Arn", sink.getArn()); out.put("Id", sink.getId()); out.put("Name", sink.getName()); + if (includeTags) out.put("Tags", sink.getTags()); + return out; + } + + private Map linkBody(OamLink link, boolean includeTags) { + Map out = linkSummary(link); + out.put("LabelTemplate", link.getLabelTemplate()); + if (!link.getLinkConfiguration().isEmpty()) out.put("LinkConfiguration", link.getLinkConfiguration()); + if (includeTags) out.put("Tags", link.getTags()); + return out; + } + + private Map linkSummary(OamLink link) { + Map out = new LinkedHashMap<>(); + out.put("Arn", link.getArn()); out.put("Id", link.getId()); out.put("Label", link.getLabel()); + out.put("ResourceTypes", link.getResourceTypes()); out.put("SinkArn", link.getSinkArn()); + return out; + } + + private String region(HttpHeaders headers) { return regionResolver.resolveRegion(headers); } + private static String decode(String value) { return URLDecoder.decode(value, StandardCharsets.UTF_8); } + private static String string(Map request, String key) { Object v = request == null ? null : request.get(key); return v == null ? null : String.valueOf(v); } + private static boolean boolDefaultTrue(Map request, String key) { + Object value = request == null ? null : request.get(key); + return value == null || (value instanceof Boolean b ? b : Boolean.parseBoolean(String.valueOf(value))); + } + private static int maxResults(Map request, int defaultValue, int max) { + Object value = request == null ? null : request.get("MaxResults"); + if (value == null) return defaultValue; + int parsed; + try { parsed = value instanceof Number n ? n.intValue() : Integer.parseInt(String.valueOf(value)); } + catch (Exception e) { throw new AwsException("InvalidParameterException", "MaxResults is invalid.", 400); } + if (parsed < 1 || parsed > max) throw new AwsException("InvalidParameterException", "MaxResults must be between 1 and " + max + ".", 400); + return parsed; + } + @SuppressWarnings("unchecked") private static Map objectMap(Object value) { return value instanceof Map m ? new LinkedHashMap<>((Map) m) : null; } + @SuppressWarnings("unchecked") private static Map stringMap(Object value) { + if (!(value instanceof Map map)) return null; + Map out = new LinkedHashMap<>(); map.forEach((k, v) -> out.put(String.valueOf(k), v == null ? "" : String.valueOf(v))); return out; + } + private static List stringList(Object value) { + if (!(value instanceof List list)) return null; + return list.stream().map(String::valueOf).toList(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/oam/OamService.java b/src/main/java/io/github/hectorvent/floci/services/oam/OamService.java new file mode 100644 index 0000000000..6bc8edf72d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/oam/OamService.java @@ -0,0 +1,387 @@ +package io.github.hectorvent.floci.services.oam; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.oam.model.OamLink; +import io.github.hectorvent.floci.services.oam.model.OamSink; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +@ApplicationScoped +public class OamService { + private static final Pattern SINK_NAME = Pattern.compile("[A-Za-z0-9_.-]{1,255}"); + private static final Set RESOURCE_TYPES = Set.of( + "AWS::CloudWatch::Metric", "AWS::Logs::LogGroup", "AWS::XRay::Trace", + "AWS::ApplicationInsights::Application", "AWS::InternetMonitor::Monitor", + "AWS::ApplicationSignals::Service", "AWS::ApplicationSignals::ServiceLevelObjective"); + + private final StorageBackend sinks; + private final StorageBackend links; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public OamService(StorageFactory storageFactory, RegionResolver regionResolver, ObjectMapper objectMapper) { + this(storageFactory.create("oam", "oam-sinks.json", new TypeReference>() {}), + storageFactory.create("oam", "oam-links.json", new TypeReference>() {}), + regionResolver, objectMapper); + } + + OamService(StorageBackend sinks, StorageBackend links, + RegionResolver regionResolver, ObjectMapper objectMapper) { + this.sinks = sinks; + this.links = links; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + public OamSink createSink(String name, Map tags, String region) { + if (name == null) throw missing("Name"); + if (!SINK_NAME.matcher(name).matches()) throw invalid("Name is invalid."); + validateTags(tags); + if (!listSinks(region).isEmpty()) { + throw new AwsException("ConflictException", "A sink already exists in this Region.", 409); + } + String id = UUID.randomUUID().toString(); + OamSink sink = new OamSink(); + sink.setId(id); + sink.setName(name); + sink.setRegion(region); + sink.setOwnerAccountId(regionResolver.getAccountId()); + sink.setArn(AwsArnUtils.Arn.of("oam", region, sink.getOwnerAccountId(), "sink/" + id).toString()); + sink.setTags(tags); + sinks.put(sink.getArn(), sink); + return sink; + } + + public OamSink getSink(String identifier) { + require(identifier, "Identifier"); + return getSinkAcrossAccounts(identifier); + } + + public List listSinks(String region) { + return sinks.scan(_ -> true).stream() + .filter(s -> region.equals(s.getRegion())) + .sorted(java.util.Comparator.comparing(OamSink::getArn)).toList(); + } + + public void putSinkPolicy(String sinkIdentifier, String policy) { + require(sinkIdentifier, "SinkIdentifier"); + require(policy, "Policy"); + try { + JsonNode document = objectMapper.readTree(policy); + if (!document.isObject() || !document.has("Statement")) throw new IllegalArgumentException(); + } catch (Exception e) { + throw invalid("Policy must be valid IAM policy JSON."); + } + OamSink sink = getOwnedSink(sinkIdentifier); + sink.setPolicy(policy); + sinks.put(sink.getArn(), sink); + } + + public OamLink createLink(String sinkIdentifier, String labelTemplate, List resourceTypes, + Map linkConfiguration, Map tags, String region) { + require(sinkIdentifier, "SinkIdentifier"); + require(labelTemplate, "LabelTemplate"); + if (labelTemplate.length() > 64) throw invalid("LabelTemplate must be between 1 and 64 characters."); + validateResourceTypes(resourceTypes); + validateLinkConfiguration(linkConfiguration); + validateTags(tags); + if (listLinks(region).size() >= 5) { + throw new AwsException("ServiceQuotaExceededException", "A source account can have at most five links.", 429); + } + OamSink sink = getSinkAcrossAccounts(sinkIdentifier); + if (!region.equals(sink.getRegion())) throw invalid("The sink must be in the same Region as the link."); + authorizeLinkAction(sink, regionResolver.getAccountId(), resourceTypes, "oam:CreateLink"); + boolean duplicate = listLinks(region).stream().anyMatch(l -> sink.getArn().equals(l.getSinkArn())); + if (duplicate) throw new AwsException("ConflictException", "A link to this sink already exists.", 409); + + String id = UUID.randomUUID().toString(); + OamLink link = new OamLink(); + link.setId(id); + link.setArn(AwsArnUtils.Arn.of("oam", region, regionResolver.getAccountId(), "link/" + id).toString()); + link.setSourceAccountId(regionResolver.getAccountId()); + link.setRegion(region); + link.setSinkArn(sink.getArn()); + link.setLabelTemplate(labelTemplate); + link.setLabel(resolveLabel(labelTemplate, regionResolver.getAccountId())); + link.setResourceTypes(resourceTypes); + link.setLinkConfiguration(normalizeConfiguration(linkConfiguration)); + link.setTags(tags); + links.put(link.getArn(), link); + return link; + } + + public OamLink getLink(String identifier) { + require(identifier, "Identifier"); + return links.get(identifier).orElseThrow(() -> notFound("Link", identifier)); + } + + public List listLinks(String region) { + return links.scan(_ -> true).stream().filter(l -> region.equals(l.getRegion())) + .sorted(java.util.Comparator.comparing(OamLink::getArn)).toList(); + } + + public List listAttachedLinks(String sinkIdentifier) { + OamSink sink = getOwnedSink(sinkIdentifier); + Collection all; + if (links instanceof AccountAwareStorageBackend aware) { + @SuppressWarnings("unchecked") + AccountAwareStorageBackend typed = (AccountAwareStorageBackend) aware; + all = typed.scanAllAccounts(); + } else { + all = links.scan(_ -> true); + } + return all.stream().filter(l -> sink.getArn().equals(l.getSinkArn())) + .sorted(java.util.Comparator.comparing(OamLink::getArn)).toList(); + } + + public OamLink updateLink(String identifier, List resourceTypes, + Map linkConfiguration) { + validateResourceTypes(resourceTypes); + validateLinkConfiguration(linkConfiguration); + OamLink link = getLink(identifier); + OamSink sink = getSinkAcrossAccounts(link.getSinkArn()); + authorizeLinkAction(sink, regionResolver.getAccountId(), resourceTypes, "oam:UpdateLink"); + link.setResourceTypes(resourceTypes); + link.setLinkConfiguration(normalizeConfiguration(linkConfiguration)); + links.put(link.getArn(), link); + return link; + } + + public void deleteLink(String identifier) { + OamLink link = getLink(identifier); + links.delete(link.getArn()); + } + + public void deleteSink(String identifier) { + OamSink sink = getOwnedSink(identifier); + if (!listAttachedLinks(sink.getArn()).isEmpty()) { + throw new AwsException("ConflictException", "The sink still has attached links.", 409); + } + sinks.delete(sink.getArn()); + } + + public Map tags(String arn) { return new LinkedHashMap<>(resourceTags(arn)); } + + public void tag(String arn, Map tags) { + validateTags(tags); + Map merged = new LinkedHashMap<>(resourceTags(arn)); + merged.putAll(tags == null ? Map.of() : tags); + if (merged.size() > 50) throw new AwsException("TooManyTagsException", "A resource can have no more than 50 tags.", 400); + saveTags(arn, merged); + } + + public void untag(String arn, List tagKeys) { + if (tagKeys == null) throw missing("TagKeys"); + Map updated = new LinkedHashMap<>(resourceTags(arn)); + tagKeys.forEach(updated::remove); + saveTags(arn, updated); + } + + private OamSink getOwnedSink(String identifier) { + OamSink sink = sinks.get(identifier).orElseThrow(() -> notFound("Sink", identifier)); + if (!regionResolver.getAccountId().equals(sink.getOwnerAccountId())) throw notFound("Sink", identifier); + return sink; + } + + private OamSink getSinkAcrossAccounts(String arn) { + String owner = arnAccount(arn); + if (owner == null) throw invalid("SinkIdentifier must be a sink ARN."); + if (sinks instanceof AccountAwareStorageBackend aware) { + @SuppressWarnings("unchecked") + AccountAwareStorageBackend typed = (AccountAwareStorageBackend) aware; + return typed.getForAccount(owner, arn).orElseThrow(() -> notFound("Sink", arn)); + } + return sinks.get(arn).orElseThrow(() -> notFound("Sink", arn)); + } + + private Map resourceTags(String arn) { + if (arn != null && arn.contains(":sink/")) return getOwnedSink(arn).getTags(); + if (arn != null && arn.contains(":link/")) return getLink(arn).getTags(); + throw notFound("Resource", arn); + } + + private void saveTags(String arn, Map tags) { + if (arn != null && arn.contains(":sink/")) { + OamSink sink = getOwnedSink(arn); sink.setTags(tags); sinks.put(arn, sink); return; + } + if (arn != null && arn.contains(":link/")) { + OamLink link = getLink(arn); link.setTags(tags); links.put(arn, link); return; + } + throw notFound("Resource", arn); + } + + private void authorizeLinkAction(OamSink sink, String sourceAccountId, List resourceTypes, String action) { + if (sink.getPolicy() == null || sink.getPolicy().isBlank()) { + throw invalid("The sink policy does not allow this source account to perform " + action + "."); + } + try { + JsonNode root = objectMapper.readTree(sink.getPolicy()); + JsonNode statements = root.path("Statement"); + if (!statements.isArray()) statements = objectMapper.createArrayNode().add(statements); + boolean allowed = false; + for (JsonNode statement : statements) { + if (!actionMatches(statement.get("Action"), action)) continue; + if (!principalMatches(statement.get("Principal"), sourceAccountId)) continue; + if (!resourceMatches(statement.get("Resource"), sink.getArn())) continue; + if (!resourceTypeConditionMatches(statement.get("Condition"), resourceTypes)) continue; + + String effect = statement.path("Effect").asText(); + if ("Deny".equalsIgnoreCase(effect)) { + throw invalid("The sink policy explicitly denies this source account from performing " + action + "."); + } + if ("Allow".equalsIgnoreCase(effect)) { + allowed = true; + } + } + if (!allowed) throw invalid("The sink policy does not allow this source account to perform " + action + "."); + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw invalid("The sink policy could not be evaluated."); + } + } + + private static boolean actionMatches(JsonNode node, String action) { + if (node == null) return false; + if (node.isTextual()) return "*".equals(node.asText()) || action.equalsIgnoreCase(node.asText()); + if (node.isArray()) for (JsonNode n : node) if (actionMatches(n, action)) return true; + return false; + } + + private static boolean principalMatches(JsonNode node, String account) { + if (node == null) return false; + if (node.isTextual()) return "*".equals(node.asText()) || principalValueMatches(node.asText(), account); + JsonNode aws = node.path("AWS"); + if (aws.isTextual()) return principalValueMatches(aws.asText(), account); + if (aws.isArray()) for (JsonNode n : aws) if (principalValueMatches(n.asText(), account)) return true; + return false; + } + + private static boolean principalValueMatches(String value, String account) { + return "*".equals(value) || account.equals(value) || ("arn:aws:iam::" + account + ":root").equals(value); + } + + private static boolean resourceMatches(JsonNode node, String arn) { + if (node == null) return true; + if (node.isTextual()) return "*".equals(node.asText()) || arn.equals(node.asText()); + if (node.isArray()) for (JsonNode n : node) if (resourceMatches(n, arn)) return true; + return false; + } + + private static boolean resourceTypeConditionMatches(JsonNode condition, List requested) { + if (condition == null || condition.isMissingNode() || condition.isNull()) { + return true; + } + List allowed = new ArrayList<>(); + var operators = condition.fields(); + while (operators.hasNext()) { + Map.Entry operator = operators.next(); + JsonNode entries = operator.getValue(); + if (!entries.isObject()) { + return false; + } + var conditions = entries.fields(); + while (conditions.hasNext()) { + Map.Entry entry = conditions.next(); + if (!"oam:ResourceTypes".equalsIgnoreCase(entry.getKey())) { + // Unknown condition keys cannot be safely treated as satisfied. In particular, + // organization-scoped policies must not degrade into a wildcard allow. + return false; + } + JsonNode values = entry.getValue(); + if (values.isArray()) { + values.forEach(v -> allowed.add(v.asText())); + } else { + allowed.add(values.asText()); + } + } + } + return allowed.isEmpty() || allowed.containsAll(requested); + } + + private static void validateResourceTypes(List types) { + if (types == null) throw missing("ResourceTypes"); + if (types.isEmpty() || types.size() > 50 || types.stream().anyMatch(t -> !RESOURCE_TYPES.contains(t))) { + throw invalid("ResourceTypes contains an unsupported value."); + } + } + + private static void validateLinkConfiguration(Map config) { + if (config == null) return; + for (String name : List.of("MetricConfiguration", "LogGroupConfiguration")) { + Object value = config.get(name); + if (value instanceof Map m && m.containsKey("Filter")) { + String filter = String.valueOf(m.get("Filter")); + if (filter.isBlank() || filter.length() > 2000) throw invalid("LinkConfiguration filter is invalid."); + } + } + } + + private static Map normalizeConfiguration(Map config) { + if (config == null) return Map.of(); + Map out = new LinkedHashMap<>(config); + out.entrySet().removeIf(e -> e.getValue() instanceof Map m && "*".equals(String.valueOf(m.get("Filter")))); + return out; + } + + private static void validateTags(Map tags) { + if (tags == null) return; + if (tags.size() > 50) throw new AwsException("TooManyTagsException", "A resource can have no more than 50 tags.", 400); + for (Map.Entry e : tags.entrySet()) { + if (e.getKey() == null || e.getKey().isEmpty() || e.getKey().length() > 128 + || (e.getValue() != null && e.getValue().length() > 256)) { + throw new AwsException("ValidationException", "Tag key or value is invalid.", 400); + } + } + } + + private static String resolveLabel(String template, String account) { + return template.replace("$AccountName", account).replace("$AccountEmailNoDomain", account) + .replace("$AccountEmail", account); + } + + private static String arnAccount(String arn) { + try { return AwsArnUtils.parse(arn).accountId(); } catch (Exception e) { return null; } + } + + public static String encodeToken(int offset) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(String.valueOf(offset).getBytes(StandardCharsets.UTF_8)); + } + + public static int decodeToken(String token) { + if (token == null || token.isBlank()) return 0; + try { + int offset = Integer.parseInt(new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8)); + if (offset < 0) throw new NumberFormatException(); + return offset; + } catch (Exception e) { + throw invalid("NextToken is invalid."); + } + } + + private static void require(String value, String field) { if (value == null || value.isBlank()) throw missing(field); } + private static AwsException missing(String field) { return new AwsException("MissingRequiredParameterException", "Missing required parameter: " + field, 400); } + private static AwsException invalid(String message) { return new AwsException("InvalidParameterException", message, 400); } + private static AwsException notFound(String type, String id) { return new AwsException("ResourceNotFoundException", type + " " + id + " not found.", 404); } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/oam/model/OamLink.java b/src/main/java/io/github/hectorvent/floci/services/oam/model/OamLink.java new file mode 100644 index 0000000000..664c02edd4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/oam/model/OamLink.java @@ -0,0 +1,44 @@ +package io.github.hectorvent.floci.services.oam.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +public class OamLink { + private String arn; + private String id; + private String label; + private String labelTemplate; + private String sinkArn; + private String region; + private String sourceAccountId; + private List resourceTypes = List.of(); + private Map linkConfiguration = new LinkedHashMap<>(); + private Map tags = new LinkedHashMap<>(); + + public OamLink() {} + + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getLabel() { return label; } + public void setLabel(String label) { this.label = label; } + public String getLabelTemplate() { return labelTemplate; } + public void setLabelTemplate(String labelTemplate) { this.labelTemplate = labelTemplate; } + public String getSinkArn() { return sinkArn; } + public void setSinkArn(String sinkArn) { this.sinkArn = sinkArn; } + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + public String getSourceAccountId() { return sourceAccountId; } + public void setSourceAccountId(String sourceAccountId) { this.sourceAccountId = sourceAccountId; } + public List getResourceTypes() { return resourceTypes; } + public void setResourceTypes(List resourceTypes) { this.resourceTypes = resourceTypes == null ? List.of() : List.copyOf(resourceTypes); } + public Map getLinkConfiguration() { return linkConfiguration; } + public void setLinkConfiguration(Map linkConfiguration) { this.linkConfiguration = linkConfiguration == null ? new LinkedHashMap<>() : new LinkedHashMap<>(linkConfiguration); } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags); } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/oam/model/OamSink.java b/src/main/java/io/github/hectorvent/floci/services/oam/model/OamSink.java new file mode 100644 index 0000000000..36fa73c8bb --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/oam/model/OamSink.java @@ -0,0 +1,34 @@ +package io.github.hectorvent.floci.services.oam.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +@RegisterForReflection +public class OamSink { + private String arn; + private String id; + private String name; + private String region; + private String ownerAccountId; + private String policy; + private Map tags = new LinkedHashMap<>(); + + public OamSink() {} + + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + public String getOwnerAccountId() { return ownerAccountId; } + public void setOwnerAccountId(String ownerAccountId) { this.ownerAccountId = ownerAccountId; } + public String getPolicy() { return policy; } + public void setPolicy(String policy) { this.policy = policy; } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags); } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index a8227e5af3..13be06c3cc 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -605,6 +605,8 @@ floci: bcm-data-exports: enabled: true emit-mode: synchronous + oam: + enabled: true cloudtrail: enabled: true lightsail: diff --git a/src/test/java/io/github/hectorvent/floci/services/oam/OamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/oam/OamIntegrationTest.java new file mode 100644 index 0000000000..375d94cbf4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/oam/OamIntegrationTest.java @@ -0,0 +1,168 @@ +package io.github.hectorvent.floci.services.oam; + +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.*; + +@QuarkusTest +class OamIntegrationTest { + + private static final String MONITORING = + "AWS4-HMAC-SHA256 Credential=111111111111/20260911/us-east-1/oam/aws4_request"; + private static final String SOURCE = + "AWS4-HMAC-SHA256 Credential=222222222222/20260911/us-east-1/oam/aws4_request"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void sinkLinkLifecycleWorksAcrossAccounts() { + String sinkArn = given() + .header("Authorization", MONITORING) + .contentType("application/json") + .body("{\"Name\":\"central-observability\"}") + .when().post("/CreateSink") + .then().statusCode(200) + .body("Name", equalTo("central-observability")) + .body("Arn", startsWith("arn:aws:oam:us-east-1:111111111111:sink/")) + .extract().path("Arn"); + + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"AWS\":\"arn:aws:iam::222222222222:root\"}," + + "\"Action\":[\"oam:CreateLink\",\"oam:UpdateLink\"],\"Resource\":\"" + sinkArn + "\"," + + "\"Condition\":{\"ForAllValues:StringEquals\":{\"oam:ResourceTypes\":[" + + "\"AWS::CloudWatch::Metric\",\"AWS::Logs::LogGroup\"]}}}]}"; + + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("SinkIdentifier", sinkArn, "Policy", policy)) + .when().post("/PutSinkPolicy") + .then().statusCode(200).body("SinkArn", equalTo(sinkArn)); + + String linkArn = given().header("Authorization", SOURCE).contentType("application/json") + .body(java.util.Map.of( + "SinkIdentifier", sinkArn, + "LabelTemplate", "source-account", + "ResourceTypes", java.util.List.of("AWS::CloudWatch::Metric"))) + .when().post("/CreateLink") + .then().statusCode(200) + .body("SinkArn", equalTo(sinkArn)) + .body("ResourceTypes", contains("AWS::CloudWatch::Metric")) + .extract().path("Arn"); + + given().header("Authorization", SOURCE).contentType("application/json").body("{}") + .when().post("/ListLinks") + .then().statusCode(200).body("Items.Arn", contains(linkArn)); + + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("SinkIdentifier", sinkArn)) + .when().post("/ListAttachedLinks") + .then().statusCode(200).body("Items.LinkArn", contains(linkArn)); + + given().header("Authorization", SOURCE).contentType("application/json") + .body(java.util.Map.of( + "Identifier", linkArn, + "ResourceTypes", java.util.List.of("AWS::CloudWatch::Metric", "AWS::Logs::LogGroup"), + "LinkConfiguration", java.util.Map.of( + "MetricConfiguration", java.util.Map.of("Filter", "Namespace LIKE 'AWS/%'")))) + .when().post("/UpdateLink") + .then().statusCode(200) + .body("ResourceTypes.size()", equalTo(2)) + .body("LinkConfiguration.MetricConfiguration.Filter", equalTo("Namespace LIKE 'AWS/%'")); + + given().header("Authorization", SOURCE).contentType("application/json") + .body(java.util.Map.of("Identifier", linkArn)) + .when().post("/DeleteLink") + .then().statusCode(200); + + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("Identifier", sinkArn)) + .when().post("/DeleteSink") + .then().statusCode(200); + } + + @Test + void sinkPolicyRejectsUnauthorizedSourceAccount() { + String sinkArn = given().header("Authorization", MONITORING).contentType("application/json") + .body("{\"Name\":\"policy-test\"}") + .when().post("/CreateSink") + .then().statusCode(200).extract().path("Arn"); + + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"AWS\":\"arn:aws:iam::333333333333:root\"}," + + "\"Action\":\"oam:CreateLink\",\"Resource\":\"*\"}]}"; + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("SinkIdentifier", sinkArn, "Policy", policy)) + .when().post("/PutSinkPolicy") + .then().statusCode(200); + + given().header("Authorization", SOURCE).contentType("application/json") + .body(java.util.Map.of( + "SinkIdentifier", sinkArn, + "LabelTemplate", "denied", + "ResourceTypes", java.util.List.of("AWS::CloudWatch::Metric"))) + .when().post("/CreateLink") + .then().statusCode(400).body("__type", containsString("InvalidParameterException")); + + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("Identifier", sinkArn)) + .when().post("/DeleteSink") + .then().statusCode(200); + } + @Test + void unsupportedOrganizationConditionDoesNotBecomeWildcardAllow() { + String sinkArn = given().header("Authorization", MONITORING).contentType("application/json") + .body("{\"Name\":\"org-policy-test\"}") + .when().post("/CreateSink") + .then().statusCode(200).extract().path("Arn"); + + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":\"*\",\"Action\":\"oam:CreateLink\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:PrincipalOrgID\":\"o-example\"}}}]}"; + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("SinkIdentifier", sinkArn, "Policy", policy)) + .when().post("/PutSinkPolicy").then().statusCode(200); + + given().header("Authorization", SOURCE).contentType("application/json") + .body(java.util.Map.of("SinkIdentifier", sinkArn, "LabelTemplate", "source", + "ResourceTypes", java.util.List.of("AWS::CloudWatch::Metric"))) + .when().post("/CreateLink") + .then().statusCode(400).body("__type", containsString("InvalidParameterException")); + + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("Identifier", sinkArn)) + .when().post("/DeleteSink").then().statusCode(200); + } + + @Test + void explicitDenyOverridesMatchingAllow() { + String sinkArn = given().header("Authorization", MONITORING).contentType("application/json") + .body("{\"Name\":\"explicit-deny-test\"}") + .when().post("/CreateSink") + .then().statusCode(200).extract().path("Arn"); + + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"oam:CreateLink\",\"Resource\":\"*\"}," + + "{\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"arn:aws:iam::222222222222:root\"}," + + "\"Action\":\"oam:CreateLink\",\"Resource\":\"*\"}]}"; + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("SinkIdentifier", sinkArn, "Policy", policy)) + .when().post("/PutSinkPolicy").then().statusCode(200); + + given().header("Authorization", SOURCE).contentType("application/json") + .body(java.util.Map.of("SinkIdentifier", sinkArn, "LabelTemplate", "source", + "ResourceTypes", java.util.List.of("AWS::CloudWatch::Metric"))) + .when().post("/CreateLink") + .then().statusCode(400).body("__type", containsString("InvalidParameterException")); + + given().header("Authorization", MONITORING).contentType("application/json") + .body(java.util.Map.of("Identifier", sinkArn)) + .when().post("/DeleteSink").then().statusCode(200); + } + +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 418d3f6e0f..45c5e51678 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -342,6 +342,8 @@ floci: bcm-data-exports: enabled: true emit-mode: off + oam: + enabled: true cloudtrail: enabled: true flush-interval-seconds: 3600