diff --git a/CHANGELOG.md b/CHANGELOG.md index 878ffa98c2..0118d139ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +## [Unreleased] + + +### Bug Fixes + +* unify service metadata behind a descriptor-backed catalog for enablement, routing, and storage lookups +* include `ec2` and `ecs` in enabled-service reporting and enforce disabled gating for ACM and ECS targeted requests +* return protocol-correct JSON disabled responses for auth-only REST GETs instead of falling back to XML +* honor `floci.storage.services.acm.*` overrides in `StorageFactory` + ## [1.5.2](https://github.com/floci-io/floci/compare/1.5.1...1.5.2) (2026-04-10) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index df27d7f42b..b1e95ff37e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -95,9 +95,12 @@ ln -s AGENT.md COPILOT.md 1. Create a package under `src/main/java/.../services//` 2. Add a Controller (follow the correct protocol — Query, JSON 1.1, REST JSON, or REST XML) 3. Add a Service (`@ApplicationScoped`) and model POJOs -4. Register in `ServiceRegistry` -5. Add config entries in `EmulatorConfig.java` and `application.yml` -6. Add integration tests in `*IntegrationTest.java` +4. Add config entries in `EmulatorConfig.java` and `application.yml` +5. Register a `ServiceDescriptor` in `ResolvedServiceCatalog` +6. Wire controller/handler dispatch for the service +7. Add integration tests in `*IntegrationTest.java` + +`ServiceRegistry`, `ServiceEnabledFilter`, and `StorageFactory` now resolve service metadata from the descriptor catalog. Adding a service should not require new service-keyed switch statements in those consumers. Always implement the **real AWS wire protocol** — never invent custom endpoints. The AWS SDK must work against Floci without modification. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index c9476a813c..239270d76f 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -34,19 +34,8 @@ public class AwsJson11Controller { private static final Logger LOG = Logger.getLogger(AwsJson11Controller.class); - private static final String SSM_TARGET_PREFIX = "AmazonSSM."; - private static final String EVENTBRIDGE_TARGET_PREFIX = "AWSEvents."; - private static final String LOGS_TARGET_PREFIX = "Logs_20140328."; - private static final String SECRETS_MANAGER_TARGET_PREFIX = "secretsmanager."; - private static final String KINESIS_TARGET_PREFIX = "Kinesis_20131202."; - private static final String APIGW_V2_TARGET_PREFIX = "AmazonApiGatewayV2."; - private static final String KMS_TARGET_PREFIX = "TrentService."; - private static final String COGNITO_TARGET_PREFIX = "AWSCognitoIdentityProviderService."; - private static final String ACM_TARGET_PREFIX = "CertificateManager."; - private static final String ECS_TARGET_PREFIX = "AmazonEC2ContainerServiceV20141113."; - private static final String ECR_TARGET_PREFIX = "AmazonEC2ContainerRegistry_V20150921."; - private final ObjectMapper objectMapper; + private final ResolvedServiceCatalog catalog; private final RegionResolver regionResolver; private final SsmJsonHandler ssmJsonHandler; private final EventBridgeHandler eventBridgeHandler; @@ -61,7 +50,8 @@ public class AwsJson11Controller { private final EcrJsonHandler ecrJsonHandler; @Inject - public AwsJson11Controller(ObjectMapper objectMapper, RegionResolver regionResolver, + public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog, + RegionResolver regionResolver, SsmJsonHandler ssmJsonHandler, EventBridgeHandler eventBridgeHandler, CloudWatchLogsHandler cloudWatchLogsHandler, SecretsManagerJsonHandler secretsManagerJsonHandler, @@ -71,6 +61,7 @@ public class AwsJson11Controller { AcmJsonHandler acmJsonHandler, EcsJsonHandler ecsJsonHandler, EcrJsonHandler ecrJsonHandler) { this.objectMapper = objectMapper; + this.catalog = catalog; this.regionResolver = regionResolver; this.ssmJsonHandler = ssmJsonHandler; this.eventBridgeHandler = eventBridgeHandler; @@ -97,71 +88,44 @@ public class AwsJson11Controller { return null; } - String prefix; - String serviceName; - - if (target.startsWith(SSM_TARGET_PREFIX)) { - prefix = SSM_TARGET_PREFIX; - serviceName = "SSM"; - } else if (target.startsWith(EVENTBRIDGE_TARGET_PREFIX)) { - prefix = EVENTBRIDGE_TARGET_PREFIX; - serviceName = "EventBridge"; - } else if (target.startsWith(LOGS_TARGET_PREFIX)) { - prefix = LOGS_TARGET_PREFIX; - serviceName = "Logs"; - } else if (target.startsWith(SECRETS_MANAGER_TARGET_PREFIX)) { - prefix = SECRETS_MANAGER_TARGET_PREFIX; - serviceName = "SecretsManager"; - } else if (target.startsWith(KINESIS_TARGET_PREFIX)) { - prefix = KINESIS_TARGET_PREFIX; - serviceName = "Kinesis"; - } else if (target.startsWith(APIGW_V2_TARGET_PREFIX)) { - prefix = APIGW_V2_TARGET_PREFIX; - serviceName = "ApiGatewayV2"; - } else if (target.startsWith(KMS_TARGET_PREFIX)) { - prefix = KMS_TARGET_PREFIX; - serviceName = "KMS"; - } else if (target.startsWith(COGNITO_TARGET_PREFIX)) { - prefix = COGNITO_TARGET_PREFIX; - serviceName = "Cognito"; - } else if (target.startsWith(ACM_TARGET_PREFIX)) { - prefix = ACM_TARGET_PREFIX; - serviceName = "ACM"; - } else if (target.startsWith(ECS_TARGET_PREFIX)) { - prefix = ECS_TARGET_PREFIX; - serviceName = "ECS"; - } else if (target.startsWith(ECR_TARGET_PREFIX)) { - prefix = ECR_TARGET_PREFIX; - serviceName = "ECR"; - } else { + ServiceCatalog.TargetMatch targetMatch = catalog.matchTarget(target).orElse(null); + if (targetMatch == null) { return JsonErrorResponseUtils.createUnknownOperationErrorResponse(target); } - String action = target.substring(prefix.length()); - LOG.infov("AwsJson11Controller {0} action: {1}", serviceName, action); + String serviceKey = targetMatch.descriptor().externalKey(); + String action = targetMatch.action(); + LOG.infov("AwsJson11Controller {0} action: {1}", serviceKey, action); try { JsonNode request = objectMapper.readTree(body); String region = regionResolver.resolveRegion(httpHeaders); - return switch (serviceName) { - case "SSM" -> ssmJsonHandler.handle(action, request, region); - case "EventBridge" -> eventBridgeHandler.handle(action, request, region); - case "Logs" -> cloudWatchLogsHandler.handle(action, request, region); - case "SecretsManager" -> secretsManagerJsonHandler.handle(action, request, region); - case "Kinesis" -> kinesisJsonHandler.handle(action, request, region); - case "ApiGatewayV2" -> apigwV2JsonHandler.handle(action, request, region); - case "KMS" -> kmsJsonHandler.handle(action, request, region); - case "Cognito" -> cognitoJsonHandler.handle(action, request, region); - case "ACM" -> acmJsonHandler.handle(action, request, region); - case "ECS" -> ecsJsonHandler.handle(action, request, region); - case "ECR" -> ecrJsonHandler.handle(action, request, region); + Response delegated = switch (serviceKey) { + case "ssm" -> ssmJsonHandler.handle(action, request, region); + case "events" -> eventBridgeHandler.handle(action, request, region); + case "logs" -> cloudWatchLogsHandler.handle(action, request, region); + case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region); + case "kinesis" -> kinesisJsonHandler.handle(action, request, region); + case "apigatewayv2" -> apigwV2JsonHandler.handle(action, request, region); + case "kms" -> kmsJsonHandler.handle(action, request, region); + case "cognito-idp" -> cognitoJsonHandler.handle(action, request, region); + case "acm" -> acmJsonHandler.handle(action, request, region); + case "ecs" -> ecsJsonHandler.handle(action, request, region); + case "ecr" -> ecrJsonHandler.handle(action, request, region); default -> null; }; + // catalog.matchTarget is protocol-agnostic: a JSON 1.0 target + // (e.g. DynamoDB_20120810.*) can match here under @Consumes json-1.1. + // Return the AWS-style unknown-operation error rather than null. + if (delegated == null) { + return JsonErrorResponseUtils.createUnknownOperationErrorResponse(target); + } + return delegated; } catch (AwsException e) { return JsonErrorResponseUtils.createErrorResponse(e); } catch (Exception e) { - LOG.errorf("Error processing %s request", serviceName, e); + LOG.errorf("Error processing %s request", serviceKey, e); return JsonErrorResponseUtils.createErrorResponse(e); } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java index be4d3b65e1..8e099b9b81 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java @@ -35,15 +35,8 @@ public class AwsJsonCborController { private static final Logger LOG = Logger.getLogger(AwsJsonCborController.class); private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); - private static final String DYNAMODB_TARGET_PREFIX = "DynamoDB_20120810."; - private static final String DYNAMODB_STREAMS_TARGET_PREFIX = "DynamoDBStreams_20120810."; - private static final String SQS_TARGET_PREFIX = "AmazonSQS."; - private static final String SNS_TARGET_PREFIX = "SNS_20100331."; - private static final String STEPFUNCTIONS_TARGET_PREFIX = "AWSStepFunctions."; - private static final String CLOUDWATCH_TARGET_PREFIX = "GraniteServiceVersion20100801."; - private static final String CLOUDWATCH_SERVICE_ID = "GraniteServiceVersion20100801"; - private final ObjectMapper objectMapper; + private final ResolvedServiceCatalog catalog; private final RegionResolver regionResolver; private final DynamoDbJsonHandler dynamoDbJsonHandler; private final DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler; @@ -53,13 +46,15 @@ public class AwsJsonCborController { private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler; @Inject - public AwsJsonCborController(ObjectMapper objectMapper, RegionResolver regionResolver, + public AwsJsonCborController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog, + RegionResolver regionResolver, DynamoDbJsonHandler dynamoDbJsonHandler, DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler, SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, StepFunctionsJsonHandler sfnJsonHandler, CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler) { this.objectMapper = objectMapper; + this.catalog = catalog; this.regionResolver = regionResolver; this.dynamoDbJsonHandler = dynamoDbJsonHandler; this.dynamoDbStreamsJsonHandler = dynamoDbStreamsJsonHandler; @@ -180,33 +175,18 @@ public class AwsJsonCborController { return null; } - String prefix; - String serviceName; - - if (target.startsWith(DYNAMODB_STREAMS_TARGET_PREFIX)) { - prefix = DYNAMODB_STREAMS_TARGET_PREFIX; - serviceName = "DynamoDBStreams"; - } else if (target.startsWith(DYNAMODB_TARGET_PREFIX)) { - prefix = DYNAMODB_TARGET_PREFIX; - serviceName = "DynamoDB"; - } else if (target.startsWith(SQS_TARGET_PREFIX)) { - prefix = SQS_TARGET_PREFIX; - serviceName = "SQS"; - } else if (target.startsWith(SNS_TARGET_PREFIX)) { - prefix = SNS_TARGET_PREFIX; - serviceName = "SNS"; - } else if (target.startsWith(STEPFUNCTIONS_TARGET_PREFIX)) { - prefix = STEPFUNCTIONS_TARGET_PREFIX; - serviceName = "StepFunctions"; - } else if (target.startsWith(CLOUDWATCH_TARGET_PREFIX)) { - prefix = CLOUDWATCH_TARGET_PREFIX; - serviceName = "CloudWatch"; - } else { + // Upstream CBOR behavior is to return null for targets this controller + // does not dispatch (JAX-RS then serves 204). The JSON 1.0/1.1 + // controllers return UnknownOperationException instead; CBOR stays on + // null here to preserve pre-refactor semantics. + ServiceCatalog.TargetMatch targetMatch = catalog.matchTarget(target).orElse(null); + if (targetMatch == null) { return null; } - String action = target.substring(prefix.length()); - LOG.debugv("{0} CBOR action: {1}", serviceName, action); + String serviceKey = targetMatch.descriptor().externalKey(); + String action = targetMatch.action(); + LOG.debugv("{0} CBOR action: {1}", serviceKey, action); try { JsonNode request = (body != null && body.length > 0) @@ -214,13 +194,17 @@ public class AwsJsonCborController { : objectMapper.createObjectNode(); String region = regionResolver.resolveRegion(httpHeaders); - Response delegated = switch (serviceName) { - case "DynamoDB" -> dynamoDbJsonHandler.handle(action, request, region); - case "DynamoDBStreams" -> dynamoDbStreamsJsonHandler.handle(action, request, region); - case "SQS" -> sqsJsonHandler.handle(action, request, region); - case "SNS" -> snsJsonHandler.handle(action, request, region); - case "StepFunctions" -> sfnJsonHandler.handle(action, request, region); - case "CloudWatch" -> cloudWatchMetricsJsonHandler.handle(action, request, region); + Response delegated = switch (serviceKey) { + case "dynamodb" -> { + if (targetMatch.prefix().startsWith("DynamoDBStreams_")) { + yield dynamoDbStreamsJsonHandler.handle(action, request, region); + } + yield dynamoDbJsonHandler.handle(action, request, region); + } + case "sqs" -> sqsJsonHandler.handle(action, request, region); + case "sns" -> snsJsonHandler.handle(action, request, region); + case "states" -> sfnJsonHandler.handle(action, request, region); + case "monitoring" -> cloudWatchMetricsJsonHandler.handle(action, request, region); default -> null; }; if (delegated == null) { @@ -239,7 +223,7 @@ public class AwsJsonCborController { } catch (AwsException e) { return cborErrorResponse(e, "smithy-protocol"); } catch (Exception e) { - LOG.error("Error processing CBOR request: " + serviceName + "." + action, e); + LOG.error("Error processing CBOR request: " + serviceKey + "." + action, e); return Response.status(500).build(); } } @@ -248,13 +232,21 @@ public class AwsJsonCborController { * Dispatches a CBOR request to the appropriate service handler by SDK service ID. */ private Response dispatchCbor(String serviceId, String operation, JsonNode request, String region) throws Exception { - return switch (serviceId) { - case "DynamoDB" -> dynamoDbJsonHandler.handle(operation, request, region); - case "DynamoDB Streams" -> dynamoDbStreamsJsonHandler.handle(operation, request, region); - case "SQS" -> sqsJsonHandler.handle(operation, request, region); - case "SNS" -> snsJsonHandler.handle(operation, request, region); - case "SFN" -> sfnJsonHandler.handle(operation, request, region); - case CLOUDWATCH_SERVICE_ID -> cloudWatchMetricsJsonHandler.handle(operation, request, region); + ServiceDescriptor descriptor = catalog.byCborSdkServiceId(serviceId).orElse(null); + if (descriptor == null) { + return null; + } + return switch (descriptor.externalKey()) { + case "dynamodb" -> { + if ("DynamoDB Streams".equals(serviceId)) { + yield dynamoDbStreamsJsonHandler.handle(operation, request, region); + } + yield dynamoDbJsonHandler.handle(operation, request, region); + } + case "sqs" -> sqsJsonHandler.handle(operation, request, region); + case "sns" -> snsJsonHandler.handle(operation, request, region); + case "states" -> sfnJsonHandler.handle(operation, request, region); + case "monitoring" -> cloudWatchMetricsJsonHandler.handle(operation, request, region); default -> null; }; } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java index 2022bb3d03..dadd8166fa 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java @@ -29,14 +29,8 @@ public class AwsJsonController { private static final Logger LOG = Logger.getLogger(AwsJsonController.class); - private static final String DYNAMODB_TARGET_PREFIX = "DynamoDB_20120810."; - private static final String DYNAMODB_STREAMS_TARGET_PREFIX = "DynamoDBStreams_20120810."; - private static final String SQS_TARGET_PREFIX = "AmazonSQS."; - private static final String SNS_TARGET_PREFIX = "SNS_20100331."; - private static final String STEPFUNCTIONS_TARGET_PREFIX = "AWSStepFunctions."; - private static final String CLOUDWATCH_TARGET_PREFIX = "GraniteServiceVersion20100801."; - private final ObjectMapper objectMapper; + private final ResolvedServiceCatalog catalog; private final RegionResolver regionResolver; private final DynamoDbJsonHandler dynamoDbJsonHandler; private final DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler; @@ -46,13 +40,15 @@ public class AwsJsonController { private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler; @Inject - public AwsJsonController(ObjectMapper objectMapper, RegionResolver regionResolver, + public AwsJsonController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog, + RegionResolver regionResolver, DynamoDbJsonHandler dynamoDbJsonHandler, DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler, SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, StepFunctionsJsonHandler sfnJsonHandler, CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler) { this.objectMapper = objectMapper; + this.catalog = catalog; this.regionResolver = regionResolver; this.dynamoDbJsonHandler = dynamoDbJsonHandler; this.dynamoDbStreamsJsonHandler = dynamoDbStreamsJsonHandler; @@ -74,53 +70,43 @@ public class AwsJsonController { return null; } - String prefix; - String action; - String serviceName; - - if (target.startsWith(DYNAMODB_STREAMS_TARGET_PREFIX)) { - prefix = DYNAMODB_STREAMS_TARGET_PREFIX; - serviceName = "DynamoDBStreams"; - } else if (target.startsWith(DYNAMODB_TARGET_PREFIX)) { - prefix = DYNAMODB_TARGET_PREFIX; - serviceName = "DynamoDB"; - } else if (target.startsWith(SQS_TARGET_PREFIX)) { - prefix = SQS_TARGET_PREFIX; - serviceName = "SQS"; - } else if (target.startsWith(SNS_TARGET_PREFIX)) { - prefix = SNS_TARGET_PREFIX; - serviceName = "SNS"; - } else if (target.startsWith(STEPFUNCTIONS_TARGET_PREFIX)) { - prefix = STEPFUNCTIONS_TARGET_PREFIX; - serviceName = "StepFunctions"; - } else if (target.startsWith(CLOUDWATCH_TARGET_PREFIX)) { - prefix = CLOUDWATCH_TARGET_PREFIX; - serviceName = "CloudWatch"; - } else { + ServiceCatalog.TargetMatch targetMatch = catalog.matchTarget(target).orElse(null); + if (targetMatch == null) { return JsonErrorResponseUtils.createUnknownOperationErrorResponse(target); } - action = target.substring(prefix.length()); - LOG.debugv("{0} JSON action: {1}", serviceName, action); + String serviceKey = targetMatch.descriptor().externalKey(); + String action = targetMatch.action(); + LOG.debugv("{0} JSON action: {1}", serviceKey, action); Response response; try { JsonNode request = objectMapper.readTree(body); String region = regionResolver.resolveRegion(httpHeaders); - response = switch (serviceName) { - case "DynamoDB" -> dynamoDbJsonHandler.handle(action, request, region); - case "DynamoDBStreams" -> dynamoDbStreamsJsonHandler.handle(action, request, region); - case "SQS" -> sqsJsonHandler.handle(action, request, region); - case "SNS" -> snsJsonHandler.handle(action, request, region); - case "StepFunctions" -> sfnJsonHandler.handle(action, request, region); - case "CloudWatch" -> cloudWatchMetricsJsonHandler.handle(action, request, region); + response = switch (serviceKey) { + case "dynamodb" -> { + if (targetMatch.prefix().startsWith("DynamoDBStreams_")) { + yield dynamoDbStreamsJsonHandler.handle(action, request, region); + } + yield dynamoDbJsonHandler.handle(action, request, region); + } + case "sqs" -> sqsJsonHandler.handle(action, request, region); + case "sns" -> snsJsonHandler.handle(action, request, region); + case "states" -> sfnJsonHandler.handle(action, request, region); + case "monitoring" -> cloudWatchMetricsJsonHandler.handle(action, request, region); default -> null; }; + // catalog.matchTarget is protocol-agnostic: a JSON 1.1 target + // (e.g. AmazonSSM.*) can match here under @Consumes json-1.0. + // Return the AWS-style unknown-operation error rather than null. + if (response == null) { + return JsonErrorResponseUtils.createUnknownOperationErrorResponse(target); + } } catch (AwsException e) { response = JsonErrorResponseUtils.createErrorResponse(e); } catch (Exception e) { - LOG.error("Error processing " + serviceName + " JSON request", e); + LOG.error("Error processing " + serviceKey + " JSON request", e); response = JsonErrorResponseUtils.createErrorResponse(e); } @@ -129,7 +115,7 @@ public class AwsJsonController { // response body" when the header is missing — attach it here at the JSON protocol // boundary so other callers of DynamoDbJsonHandler (CBOR, API Gateway proxy, // Step Functions tasks) keep their original ObjectNode entity. - if ("DynamoDB".equals(serviceName) || "DynamoDBStreams".equals(serviceName)) { + if ("dynamodb".equals(serviceKey)) { return DynamoDbResponses.withCrc32(response, objectMapper); } return response; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 1d5ef1d2af..72cc5b98b4 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -136,6 +136,7 @@ public class AwsQueryController { private final CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler; private final CognitoJsonHandler cognitoJsonHandler; private final Ec2QueryHandler ec2QueryHandler; + private final ResolvedServiceCatalog catalog; private final RegionResolver regionResolver; @Inject @@ -148,6 +149,7 @@ public class AwsQueryController { CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler, CognitoJsonHandler cognitoJsonHandler, Ec2QueryHandler ec2QueryHandler, + ResolvedServiceCatalog catalog, RegionResolver regionResolver) { this.cloudFormationQueryHandler = cloudFormationQueryHandler; this.elastiCacheQueryHandler = elastiCacheQueryHandler; @@ -160,6 +162,7 @@ public class AwsQueryController { this.cloudWatchMetricsQueryHandler = cloudWatchMetricsQueryHandler; this.cognitoJsonHandler = cognitoJsonHandler; this.ec2QueryHandler = ec2QueryHandler; + this.catalog = catalog; this.regionResolver = regionResolver; } @@ -269,15 +272,14 @@ public class AwsQueryController { "AdminAddUserToGroup", "AdminRemoveUserFromGroup", "AdminListGroupsForUser" ); - private static final Set QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation", "email", "cognito-idp", "ec2"); - private String resolveService(String authorization, String action) { if (authorization != null && !authorization.isEmpty()) { Matcher m = SERVICE_PATTERN.matcher(authorization); if (m.find()) { - String svc = m.group(1).toLowerCase(); - if (QUERY_PROTOCOL_SERVICES.contains(svc)) { - return svc; + String scope = m.group(1).toLowerCase(); + ServiceDescriptor descriptor = catalog.byCredentialScope(scope).orElse(null); + if (descriptor != null && descriptor.supportsProtocol(ServiceProtocol.QUERY)) { + return descriptor.externalKey(); } } } 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 new file mode 100644 index 0000000000..d650880d91 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -0,0 +1,246 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.appconfig.AppConfigController; +import io.github.hectorvent.floci.services.appconfig.AppConfigDataController; +import io.github.hectorvent.floci.services.cognito.CognitoOAuthController; +import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController; +import io.github.hectorvent.floci.services.lambda.LambdaController; +import io.github.hectorvent.floci.services.opensearch.OpenSearchController; +import io.github.hectorvent.floci.services.ses.SesController; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.EnumSet; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +@ApplicationScoped +public class ResolvedServiceCatalog { + + private final ServiceCatalog catalog; + + @Inject + public ResolvedServiceCatalog(EmulatorConfig config) { + this.catalog = new ServiceCatalog(List.of( + descriptor("ssm", "ssm", config.services().ssm().enabled(), true, + "ssm", storageMode(config.storage().services().ssm().mode(), config.storage().mode()), + config.storage().services().ssm().flushIntervalMs(), null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("AmazonSSM."), Set.of("ssm"), Set.of(), Set.of()), + descriptor("sqs", "sqs", config.services().sqs().enabled(), true, + "sqs", storageMode(config.storage().services().sqs().mode(), config.storage().mode()), + 5000L, AwsNamespaces.SQS, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY, ServiceProtocol.JSON, ServiceProtocol.CBOR), + Set.of("AmazonSQS."), Set.of("sqs"), Set.of("SQS"), Set.of()), + descriptor("s3", "s3", config.services().s3().enabled(), true, + "s3", storageMode(config.storage().services().s3().mode(), config.storage().mode()), + 5000L, AwsNamespaces.S3, ServiceProtocol.REST_XML, + protocols(ServiceProtocol.REST_XML), + Set.of(), Set.of("s3"), Set.of(), Set.of()), + descriptor("dynamodb", "dynamodb", config.services().dynamodb().enabled(), true, + "dynamodb", storageMode(config.storage().services().dynamodb().mode(), config.storage().mode()), + config.storage().services().dynamodb().flushIntervalMs(), null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON, ServiceProtocol.CBOR), + Set.of("DynamoDB_20120810.", "DynamoDBStreams_20120810."), + Set.of("dynamodb"), Set.of("DynamoDB", "DynamoDB Streams"), Set.of()), + descriptor("sns", "sns", config.services().sns().enabled(), true, + "sns", storageMode(config.storage().services().sns().mode(), config.storage().mode()), + config.storage().services().sns().flushIntervalMs(), AwsNamespaces.SNS, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY, ServiceProtocol.JSON, ServiceProtocol.CBOR), + Set.of("SNS_20100331."), Set.of("sns"), Set.of("SNS"), Set.of()), + descriptor("lambda", "lambda", config.services().lambda().enabled(), true, + "lambda", storageMode(config.storage().services().lambda().mode(), config.storage().mode()), + config.storage().services().lambda().flushIntervalMs(), null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("lambda"), Set.of(), Set.of(LambdaController.class)), + descriptor("apigateway", "apigateway", config.services().apigateway().enabled(), true, + "apigateway", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("apigateway", "execute-api"), Set.of(), Set.of()), + descriptor("iam", "iam", config.services().iam().enabled(), true, + "iam", config.storage().mode(), 5000L, AwsNamespaces.IAM, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY), + Set.of(), Set.of("iam"), Set.of(), Set.of()), + descriptor("sts", "iam", config.services().iam().enabled(), false, + null, null, 5000L, AwsNamespaces.STS, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY), + Set.of(), Set.of("sts"), Set.of(), Set.of()), + descriptor("elasticache", "elasticache", config.services().elasticache().enabled(), true, + null, null, 5000L, AwsNamespaces.EC, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY), + Set.of(), Set.of("elasticache"), Set.of(), Set.of()), + descriptor("rds", "rds", config.services().rds().enabled(), true, + null, null, 5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY), + Set.of(), Set.of("rds"), Set.of(), Set.of()), + descriptor("events", "eventbridge", config.services().eventbridge().enabled(), true, + "eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("AWSEvents."), Set.of("events"), Set.of(), Set.of()), + descriptor("scheduler", "scheduler", config.services().scheduler().enabled(), true, + "scheduler", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of(), Set.of("scheduler"), Set.of(), Set.of()), + descriptor("logs", "cloudwatchlogs", config.services().cloudwatchlogs().enabled(), true, + "cloudwatchlogs", storageMode(config.storage().services().cloudwatchlogs().mode(), config.storage().mode()), + config.storage().services().cloudwatchlogs().flushIntervalMs(), null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("Logs_20140328."), Set.of("logs"), Set.of(), Set.of()), + descriptor("monitoring", "cloudwatchmetrics", config.services().cloudwatchmetrics().enabled(), true, + "cloudwatchmetrics", storageMode(config.storage().services().cloudwatchmetrics().mode(), config.storage().mode()), + config.storage().services().cloudwatchmetrics().flushIntervalMs(), AwsNamespaces.CW, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY, ServiceProtocol.JSON, ServiceProtocol.CBOR), + Set.of("GraniteServiceVersion20100801."), Set.of("monitoring"), + Set.of("GraniteServiceVersion20100801"), Set.of()), + descriptor("secretsmanager", "secretsmanager", config.services().secretsmanager().enabled(), true, + "secretsmanager", storageMode(config.storage().services().secretsmanager().mode(), config.storage().mode()), + config.storage().services().secretsmanager().flushIntervalMs(), null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("secretsmanager."), Set.of("secretsmanager"), Set.of(), Set.of()), + descriptor("apigatewayv2", "apigatewayv2", config.services().apigatewayv2().enabled(), true, + "apigatewayv2", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("AmazonApiGatewayV2."), Set.of("apigatewayv2"), Set.of(), Set.of()), + descriptor("kinesis", "kinesis", config.services().kinesis().enabled(), true, + "kinesis", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("Kinesis_20131202."), Set.of("kinesis"), Set.of(), Set.of()), + descriptor("kms", "kms", config.services().kms().enabled(), true, + "kms", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("TrentService."), Set.of("kms"), Set.of(), Set.of()), + descriptor("cognito-idp", "cognito", config.services().cognito().enabled(), true, + "cognito", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON, ServiceProtocol.JSON, ServiceProtocol.QUERY), + Set.of("AWSCognitoIdentityProviderService."), Set.of("cognito-idp"), Set.of(), + Set.of(CognitoOAuthController.class, CognitoWellKnownController.class)), + descriptor("states", "stepfunctions", config.services().stepfunctions().enabled(), true, + "stepfunctions", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON, ServiceProtocol.CBOR), + Set.of("AWSStepFunctions."), Set.of("states"), Set.of("SFN"), Set.of()), + descriptor("cloudformation", "cloudformation", config.services().cloudformation().enabled(), true, + null, null, 5000L, null, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY), + Set.of(), Set.of("cloudformation"), Set.of(), Set.of()), + descriptor("acm", "acm", config.services().acm().enabled(), true, + "acm", storageMode(config.storage().services().acm().mode(), config.storage().mode()), + config.storage().services().acm().flushIntervalMs(), null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("CertificateManager."), Set.of("acm"), Set.of(), Set.of()), + descriptor("email", "ses", config.services().ses().enabled(), true, + "ses", config.storage().mode(), 5000L, AwsNamespaces.SES, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON, ServiceProtocol.QUERY), + Set.of(), Set.of("email", "ses", "sesv2"), Set.of(), Set.of(SesController.class)), + descriptor("es", "opensearch", config.services().opensearch().enabled(), true, + "opensearch", storageMode(config.storage().services().opensearch().mode(), config.storage().mode()), + config.storage().services().opensearch().flushIntervalMs(), null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("es"), Set.of(), Set.of(OpenSearchController.class)), + descriptor("ec2", "ec2", config.services().ec2().enabled(), true, + null, null, 5000L, AwsNamespaces.EC2, ServiceProtocol.QUERY, + protocols(ServiceProtocol.QUERY), + Set.of(), Set.of("ec2"), Set.of(), Set.of()), + descriptor("ecs", "ecs", config.services().ecs().enabled(), true, + null, null, 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("AmazonEC2ContainerServiceV20141113."), Set.of("ecs"), Set.of(), Set.of()), + descriptor("appconfig", "appconfig", config.services().appconfig().enabled(), true, + "appconfig", storageMode(config.storage().services().appconfig().mode(), config.storage().mode()), + config.storage().services().appconfig().flushIntervalMs(), null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("appconfig"), Set.of(), Set.of(AppConfigController.class)), + descriptor("appconfigdata", "appconfigdata", config.services().appconfigdata().enabled(), true, + "appconfigdata", storageMode(config.storage().services().appconfigdata().mode(), config.storage().mode()), + config.storage().services().appconfigdata().flushIntervalMs(), null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("appconfigdata"), Set.of(), Set.of(AppConfigDataController.class)), + descriptor("ecr", "ecr", config.services().ecr().enabled(), true, + null, null, 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("AmazonEC2ContainerRegistry_V20150921."), Set.of("ecr"), Set.of(), Set.of()) + )); + } + + public Optional byExternalKey(String externalKey) { + return catalog.byExternalKey(externalKey); + } + + public Optional byStorageKey(String storageKey) { + return catalog.byStorageKey(storageKey); + } + + public Optional byTarget(String target) { + return catalog.byTarget(target); + } + + public Optional matchTarget(String target) { + return catalog.matchTarget(target); + } + + public Optional byCredentialScope(String credentialScope) { + return catalog.byCredentialScope(credentialScope); + } + + public Optional byResourceClass(Class resourceClass) { + return catalog.byResourceClass(resourceClass); + } + + public Optional byCborSdkServiceId(String serviceId) { + return catalog.byCborSdkServiceId(serviceId); + } + + public List all() { + return catalog.all(); + } + + public List allStatusDescriptors() { + return catalog.allStatusDescriptors(); + } + + private static ServiceDescriptor descriptor( + String externalKey, + String configKey, + boolean enabled, + boolean includeInStatus, + String storageKey, + String storageMode, + long storageFlushIntervalMs, + String xmlNamespace, + ServiceProtocol defaultProtocol, + Set supportedProtocols, + Set targetPrefixes, + Set credentialScopes, + Set cborSdkServiceIds, + Set> resourceClasses + ) { + return new ServiceDescriptor( + externalKey, + configKey, + enabled, + includeInStatus, + storageKey, + storageMode, + storageFlushIntervalMs, + xmlNamespace, + defaultProtocol, + Set.copyOf(supportedProtocols), + Set.copyOf(targetPrefixes), + Set.copyOf(credentialScopes), + Set.copyOf(cborSdkServiceIds), + Set.copyOf(resourceClasses) + ); + } + + private static String storageMode(Optional override, String globalMode) { + return override.orElse(globalMode); + } + + private static Set protocols(ServiceProtocol... protocols) { + EnumSet values = EnumSet.noneOf(ServiceProtocol.class); + values.addAll(Arrays.asList(protocols)); + return Set.copyOf(values); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceCatalog.java new file mode 100644 index 0000000000..3ae242fd1f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceCatalog.java @@ -0,0 +1,115 @@ +package io.github.hectorvent.floci.core.common; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public class ServiceCatalog { + + private final List all; + private final List statusDescriptors; + private final Map byExternalKey; + private final Map byStorageKey; + private final Map byCredentialScope; + private final Map, ServiceDescriptor> byResourceClass; + private final Map byCborSdkServiceId; + private final List> targetPrefixes; + + public ServiceCatalog(List descriptors) { + this.all = List.copyOf(descriptors); + + Map external = new LinkedHashMap<>(); + Map storage = new LinkedHashMap<>(); + Map credentialScopes = new LinkedHashMap<>(); + Map, ServiceDescriptor> resourceClasses = new LinkedHashMap<>(); + Map cborSdkServiceIds = new LinkedHashMap<>(); + List> targets = new ArrayList<>(); + List status = new ArrayList<>(); + + for (ServiceDescriptor descriptor : descriptors) { + external.put(descriptor.externalKey(), descriptor); + if (descriptor.includeInStatus()) { + status.add(descriptor); + } + if (descriptor.storageKey() != null) { + storage.put(descriptor.storageKey(), descriptor); + } + for (String scope : descriptor.credentialScopes()) { + credentialScopes.put(scope, descriptor); + } + for (Class resourceClass : descriptor.resourceClasses()) { + resourceClasses.put(resourceClass, descriptor); + } + for (String serviceId : descriptor.cborSdkServiceIds()) { + cborSdkServiceIds.put(serviceId, descriptor); + } + for (String prefix : descriptor.targetPrefixes()) { + targets.add(Map.entry(prefix, descriptor)); + } + } + targets.sort(Comparator.comparingInt((Map.Entry entry) -> entry.getKey().length()) + .reversed()); + + this.statusDescriptors = List.copyOf(status); + this.byExternalKey = Map.copyOf(external); + this.byStorageKey = Map.copyOf(storage); + this.byCredentialScope = Map.copyOf(credentialScopes); + this.byResourceClass = Map.copyOf(resourceClasses); + this.byCborSdkServiceId = Map.copyOf(cborSdkServiceIds); + this.targetPrefixes = List.copyOf(targets); + } + + public Optional byExternalKey(String externalKey) { + return Optional.ofNullable(byExternalKey.get(externalKey)); + } + + public Optional byStorageKey(String storageKey) { + return Optional.ofNullable(byStorageKey.get(storageKey)); + } + + public Optional byCredentialScope(String credentialScope) { + return Optional.ofNullable(byCredentialScope.get(credentialScope)); + } + + public Optional byResourceClass(Class resourceClass) { + return Optional.ofNullable(byResourceClass.get(resourceClass)); + } + + public Optional byCborSdkServiceId(String serviceId) { + return Optional.ofNullable(byCborSdkServiceId.get(serviceId)); + } + + public Optional matchTarget(String target) { + if (target == null) { + return Optional.empty(); + } + for (Map.Entry entry : targetPrefixes) { + if (target.startsWith(entry.getKey())) { + return Optional.of(new TargetMatch( + entry.getValue(), + entry.getKey(), + target.substring(entry.getKey().length()) + )); + } + } + return Optional.empty(); + } + + public Optional byTarget(String target) { + return matchTarget(target).map(TargetMatch::descriptor); + } + + public List all() { + return all; + } + + public List allStatusDescriptors() { + return statusDescriptors; + } + + public record TargetMatch(ServiceDescriptor descriptor, String prefix, String action) { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceConfigAccess.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceConfigAccess.java new file mode 100644 index 0000000000..42964aaf5a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceConfigAccess.java @@ -0,0 +1,36 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +@ApplicationScoped +public class ServiceConfigAccess { + + private final ResolvedServiceCatalog catalog; + private final EmulatorConfig config; + + @Inject + public ServiceConfigAccess(ResolvedServiceCatalog catalog, EmulatorConfig config) { + this.catalog = catalog; + this.config = config; + } + + public boolean isEnabled(String externalKey) { + return catalog.byExternalKey(externalKey) + .map(ServiceDescriptor::enabled) + .orElse(true); + } + + public String storageMode(String storageKey) { + return catalog.byStorageKey(storageKey) + .map(ServiceDescriptor::storageMode) + .orElse(config.storage().mode()); + } + + public long storageFlushInterval(String storageKey) { + return catalog.byStorageKey(storageKey) + .map(ServiceDescriptor::storageFlushIntervalMs) + .orElse(5000L); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceDescriptor.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceDescriptor.java new file mode 100644 index 0000000000..2d188ec045 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceDescriptor.java @@ -0,0 +1,29 @@ +package io.github.hectorvent.floci.core.common; + +import java.util.Set; + +public record ServiceDescriptor( + String externalKey, + String configKey, + boolean enabled, + boolean includeInStatus, + String storageKey, + String storageMode, + long storageFlushIntervalMs, + String xmlNamespace, + ServiceProtocol defaultProtocol, + Set supportedProtocols, + Set targetPrefixes, + Set credentialScopes, + Set cborSdkServiceIds, + Set> resourceClasses +) { + + public boolean supportsStorage() { + return storageKey != null; + } + + public boolean supportsProtocol(ServiceProtocol protocol) { + return supportedProtocols.contains(protocol); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java index 2ee815fba4..53b27f26ab 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java @@ -1,10 +1,7 @@ package io.github.hectorvent.floci.core.common; -import io.github.hectorvent.floci.services.cognito.CognitoOAuthController; -import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController; -import io.github.hectorvent.floci.services.ses.SesController; -import io.github.hectorvent.floci.services.appconfig.AppConfigController; -import io.github.hectorvent.floci.services.appconfig.AppConfigDataController; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.inject.Inject; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; @@ -20,102 +17,101 @@ import java.util.regex.Pattern; @Provider public class ServiceEnabledFilter implements ContainerRequestFilter { + private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); private static final Pattern AUTH_SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/"); @Context ResourceInfo resourceInfo; - private final ServiceRegistry serviceRegistry; + private final ServiceConfigAccess serviceConfigAccess; + private final ResolvedServiceCatalog catalog; @Inject - public ServiceEnabledFilter(ServiceRegistry serviceRegistry) { - this.serviceRegistry = serviceRegistry; + public ServiceEnabledFilter(ServiceConfigAccess serviceConfigAccess, ResolvedServiceCatalog catalog) { + this.serviceConfigAccess = serviceConfigAccess; + this.catalog = catalog; } @Override public void filter(ContainerRequestContext ctx) { - String serviceKey = resolveServiceKey(ctx); - if (serviceKey == null) { + ResolvedRequest request = resolveService(ctx); + if (request == null) { return; } - if (!serviceRegistry.isServiceEnabled(serviceKey)) { - ctx.abortWith(disabledResponse(ctx, serviceKey)); + if (!serviceConfigAccess.isEnabled(request.serviceKey())) { + ctx.abortWith(disabledResponse(request)); } } - private String resolveServiceKey(ContainerRequestContext ctx) { + private ResolvedRequest resolveService(ContainerRequestContext ctx) { String target = ctx.getHeaderString("X-Amz-Target"); if (target != null) { - return serviceKeyFromTarget(target); + return catalog.byTarget(target) + .map(descriptor -> new ResolvedRequest( + descriptor.externalKey(), + inferProtocol(ctx).orElse(ServiceProtocol.JSON))) + .orElse(null); } String auth = ctx.getHeaderString("Authorization"); if (auth != null) { Matcher m = AUTH_SERVICE_PATTERN.matcher(auth); if (m.find()) { - return mapCredentialScope(m.group(1).toLowerCase()); + return catalog.byCredentialScope(m.group(1).toLowerCase()) + .map(descriptor -> new ResolvedRequest( + descriptor.externalKey(), + inferProtocol(ctx).orElse(descriptor.defaultProtocol()))) + .orElse(null); } } - return serviceKeyFromMatchedResource(); + return catalog.byResourceClass(resourceClass()) + .map(descriptor -> new ResolvedRequest(descriptor.externalKey(), descriptor.defaultProtocol())) + .orElse(null); } - private String serviceKeyFromTarget(String target) { - if (target.startsWith("AmazonSSM.")) return "ssm"; - if (target.startsWith("AWSEvents.")) return "events"; - if (target.startsWith("Logs_20140328.")) return "logs"; - if (target.startsWith("secretsmanager.")) return "secretsmanager"; - if (target.startsWith("Kinesis_20131202.")) return "kinesis"; - if (target.startsWith("AmazonApiGatewayV2.")) return "apigatewayv2"; - if (target.startsWith("TrentService.")) return "kms"; - if (target.startsWith("AWSCognitoIdentityProviderService.")) return "cognito-idp"; - if (target.startsWith("DynamoDB_20120810.") || target.startsWith("DynamoDBStreams_20120810.")) return "dynamodb"; - if (target.startsWith("AmazonSQS.")) return "sqs"; - if (target.startsWith("SNS_20100331.")) return "sns"; - if (target.startsWith("AWSStepFunctions.")) return "states"; - if (target.startsWith("GraniteServiceVersion20100801.")) return "monitoring"; - return null; + private Class resourceClass() { + return resourceInfo != null ? resourceInfo.getResourceClass() : null; } - private String mapCredentialScope(String scope) { - return switch (scope) { - case "execute-api" -> "apigateway"; - case "ses", "sesv2" -> "email"; - default -> scope; - }; - } - - private String serviceKeyFromMatchedResource() { - Class resourceClass = resourceInfo != null ? resourceInfo.getResourceClass() : null; - if (resourceClass == null) { - return null; - } - if (CognitoOAuthController.class.equals(resourceClass) - || CognitoWellKnownController.class.equals(resourceClass)) { - return "cognito-idp"; - } - if (SesController.class.equals(resourceClass)) { - return "email"; - } - if (AppConfigController.class.equals(resourceClass)) { - return "appconfig"; - } - if (AppConfigDataController.class.equals(resourceClass)) { - return "appconfigdata"; - } - return null; - } - - private Response disabledResponse(ContainerRequestContext ctx, String serviceKey) { - String message = "Service " + serviceKey + " is not enabled."; - String target = ctx.getHeaderString("X-Amz-Target"); + private java.util.Optional inferProtocol(ContainerRequestContext ctx) { String contentType = ctx.getMediaType() != null ? ctx.getMediaType().toString() : ""; - boolean jsonEndpoint = serviceKeyFromMatchedResource() != null; + if (contentType.contains("cbor")) { + return java.util.Optional.of(ServiceProtocol.CBOR); + } + if (contentType.contains("x-www-form-urlencoded")) { + return java.util.Optional.of(ServiceProtocol.QUERY); + } + if (ctx.getHeaderString("X-Amz-Target") != null) { + return java.util.Optional.of(ServiceProtocol.JSON); + } String accept = ctx.getHeaderString("Accept"); - boolean acceptsJson = accept != null && accept.contains("json"); + if (accept != null && accept.contains("cbor")) { + return java.util.Optional.of(ServiceProtocol.CBOR); + } + return java.util.Optional.empty(); + } - if (target != null || contentType.contains("json") || jsonEndpoint || acceptsJson) { + private Response disabledResponse(ResolvedRequest request) { + String message = "Service " + request.serviceKey() + " is not enabled."; + + if (request.protocol() == ServiceProtocol.CBOR) { + try { + byte[] errBytes = CBOR_MAPPER.writeValueAsBytes( + new AwsErrorResponse("ServiceNotAvailableException", message)); + return Response.status(400) + .header("smithy-protocol", "rpc-v2-cbor") + .header("x-amzn-query-error", "ServiceNotAvailableException;Sender") + .type("application/cbor") + .entity(errBytes) + .build(); + } catch (Exception ignored) { + return Response.status(400).build(); + } + } + + if (request.protocol() == ServiceProtocol.JSON || request.protocol() == ServiceProtocol.REST_JSON) { return Response.status(400) .type(MediaType.APPLICATION_JSON) .entity(new AwsErrorResponse("ServiceNotAvailableException", message)) @@ -134,4 +130,7 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { .build(); return Response.status(400).entity(xml).type(MediaType.APPLICATION_XML).build(); } + + private record ResolvedRequest(String serviceKey, ServiceProtocol protocol) { + } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceProtocol.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceProtocol.java new file mode 100644 index 0000000000..38de960e39 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceProtocol.java @@ -0,0 +1,9 @@ +package io.github.hectorvent.floci.core.common; + +public enum ServiceProtocol { + QUERY, + JSON, + CBOR, + REST_JSON, + REST_XML +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java index 6f7f8d9e78..4dc78a463e 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java @@ -1,6 +1,5 @@ package io.github.hectorvent.floci.core.common; -import io.github.hectorvent.floci.config.EmulatorConfig; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -18,79 +17,26 @@ public class ServiceRegistry { private static final Logger LOG = Logger.getLogger(ServiceRegistry.class); - private final EmulatorConfig config; + private final ResolvedServiceCatalog catalog; @Inject - public ServiceRegistry(EmulatorConfig config) { - this.config = config; + public ServiceRegistry(ResolvedServiceCatalog catalog) { + this.catalog = catalog; } public boolean isServiceEnabled(String serviceName) { - return switch (serviceName) { - case "ssm" -> config.services().ssm().enabled(); - case "sqs" -> config.services().sqs().enabled(); - case "s3" -> config.services().s3().enabled(); - case "dynamodb" -> config.services().dynamodb().enabled(); - case "sns" -> config.services().sns().enabled(); - case "lambda" -> config.services().lambda().enabled(); - case "apigateway" -> config.services().apigateway().enabled(); - case "iam", "sts" -> config.services().iam().enabled(); - case "elasticache" -> config.services().elasticache().enabled(); - case "rds" -> config.services().rds().enabled(); - case "events" -> config.services().eventbridge().enabled(); - case "scheduler" -> config.services().scheduler().enabled(); - case "logs" -> config.services().cloudwatchlogs().enabled(); - case "monitoring" -> config.services().cloudwatchmetrics().enabled(); - case "secretsmanager" -> config.services().secretsmanager().enabled(); - case "apigatewayv2" -> config.services().apigatewayv2().enabled(); - case "kinesis" -> config.services().kinesis().enabled(); - case "kms" -> config.services().kms().enabled(); - case "cognito-idp" -> config.services().cognito().enabled(); - case "states" -> config.services().stepfunctions().enabled(); - case "cloudformation" -> config.services().cloudformation().enabled(); - case "acm" -> config.services().acm().enabled(); - case "email" -> config.services().ses().enabled(); - case "es" -> config.services().opensearch().enabled(); - case "ec2" -> config.services().ec2().enabled(); - case "ecs" -> config.services().ecs().enabled(); - case "appconfig" -> config.services().appconfig().enabled(); - case "appconfigdata" -> config.services().appconfigdata().enabled(); - case "ecr" -> config.services().ecr().enabled(); - default -> true; - }; + return catalog.byExternalKey(serviceName) + .map(ServiceDescriptor::enabled) + .orElse(true); } public List getEnabledServices() { List enabled = new ArrayList<>(); - if (config.services().ssm().enabled()) enabled.add("ssm"); - if (config.services().sqs().enabled()) enabled.add("sqs"); - if (config.services().s3().enabled()) enabled.add("s3"); - if (config.services().dynamodb().enabled()) enabled.add("dynamodb"); - if (config.services().sns().enabled()) enabled.add("sns"); - if (config.services().lambda().enabled()) enabled.add("lambda"); - if (config.services().apigateway().enabled()) enabled.add("apigateway"); - if (config.services().iam().enabled()) enabled.add("iam"); - if (config.services().elasticache().enabled()) enabled.add("elasticache"); - if (config.services().rds().enabled()) enabled.add("rds"); - if (config.services().eventbridge().enabled()) enabled.add("events"); - if (config.services().scheduler().enabled()) enabled.add("scheduler"); - if (config.services().cloudwatchlogs().enabled()) enabled.add("logs"); - if (config.services().cloudwatchmetrics().enabled()) enabled.add("monitoring"); - if (config.services().secretsmanager().enabled()) enabled.add("secretsmanager"); - if (config.services().apigatewayv2().enabled()) enabled.add("apigatewayv2"); - if (config.services().kinesis().enabled()) enabled.add("kinesis"); - if (config.services().kms().enabled()) enabled.add("kms"); - if (config.services().cognito().enabled()) enabled.add("cognito-idp"); - if (config.services().stepfunctions().enabled()) enabled.add("states"); - if (config.services().cloudformation().enabled()) enabled.add("cloudformation"); - if (config.services().acm().enabled()) enabled.add("acm"); - if (config.services().ses().enabled()) enabled.add("email"); - if (config.services().opensearch().enabled()) enabled.add("es"); - if (config.services().appconfig().enabled()) enabled.add("appconfig"); - if (config.services().appconfigdata().enabled()) enabled.add("appconfigdata"); - if (config.services().ec2().enabled()) enabled.add("ec2"); - if (config.services().ecs().enabled()) enabled.add("ecs"); - if (config.services().ecr().enabled()) enabled.add("ecr"); + for (ServiceDescriptor descriptor : catalog.allStatusDescriptors()) { + if (descriptor.enabled()) { + enabled.add(descriptor.externalKey()); + } + } return enabled; } @@ -99,35 +45,9 @@ public class ServiceRegistry { */ public Map getServices() { Map services = new LinkedHashMap<>(); - services.put("ssm", status(config.services().ssm().enabled())); - services.put("sqs", status(config.services().sqs().enabled())); - services.put("s3", status(config.services().s3().enabled())); - services.put("dynamodb", status(config.services().dynamodb().enabled())); - services.put("sns", status(config.services().sns().enabled())); - services.put("lambda", status(config.services().lambda().enabled())); - services.put("apigateway", status(config.services().apigateway().enabled())); - services.put("iam", status(config.services().iam().enabled())); - services.put("elasticache", status(config.services().elasticache().enabled())); - services.put("rds", status(config.services().rds().enabled())); - services.put("events", status(config.services().eventbridge().enabled())); - services.put("scheduler", status(config.services().scheduler().enabled())); - services.put("logs", status(config.services().cloudwatchlogs().enabled())); - services.put("monitoring", status(config.services().cloudwatchmetrics().enabled())); - services.put("secretsmanager", status(config.services().secretsmanager().enabled())); - services.put("apigatewayv2", status(config.services().apigatewayv2().enabled())); - services.put("kinesis", status(config.services().kinesis().enabled())); - services.put("kms", status(config.services().kms().enabled())); - services.put("cognito-idp", status(config.services().cognito().enabled())); - services.put("states", status(config.services().stepfunctions().enabled())); - services.put("cloudformation", status(config.services().cloudformation().enabled())); - services.put("acm", status(config.services().acm().enabled())); - services.put("email", status(config.services().ses().enabled())); - services.put("es", status(config.services().opensearch().enabled())); - services.put("ec2", status(config.services().ec2().enabled())); - services.put("ecs", status(config.services().ecs().enabled())); - services.put("appconfig", status(config.services().appconfig().enabled())); - services.put("appconfigdata", status(config.services().appconfigdata().enabled())); - services.put("ecr", status(config.services().ecr().enabled())); + for (ServiceDescriptor descriptor : catalog.allStatusDescriptors()) { + services.put(descriptor.externalKey(), status(descriptor.enabled())); + } return services; } diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java b/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java index 28801fcd03..10d6274c59 100644 --- a/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java +++ b/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.core.storage; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ServiceConfigAccess; import com.fasterxml.jackson.core.type.TypeReference; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -21,13 +22,15 @@ public class StorageFactory { private static final Logger LOG = Logger.getLogger(StorageFactory.class); private final EmulatorConfig config; + private final ServiceConfigAccess serviceConfigAccess; private final List> allBackends = new ArrayList<>(); private final List> hybridBackends = new ArrayList<>(); private final List> walBackends = new ArrayList<>(); @Inject - public StorageFactory(EmulatorConfig config) { + public StorageFactory(EmulatorConfig config, ServiceConfigAccess serviceConfigAccess) { this.config = config; + this.serviceConfigAccess = serviceConfigAccess; } /** @@ -98,37 +101,10 @@ public class StorageFactory { } private String resolveMode(String serviceName) { - String globalMode = config.storage().mode(); - return switch (serviceName) { - case "ssm" -> config.storage().services().ssm().mode().orElse(globalMode); - case "sqs" -> config.storage().services().sqs().mode().orElse(globalMode); - case "s3" -> config.storage().services().s3().mode().orElse(globalMode); - case "dynamodb" -> config.storage().services().dynamodb().mode().orElse(globalMode); - case "sns" -> config.storage().services().sns().mode().orElse(globalMode); - case "lambda" -> config.storage().services().lambda().mode().orElse(globalMode); - case "cloudwatchlogs" -> config.storage().services().cloudwatchlogs().mode().orElse(globalMode); - case "cloudwatchmetrics" -> config.storage().services().cloudwatchmetrics().mode().orElse(globalMode); - case "secretsmanager" -> config.storage().services().secretsmanager().mode().orElse(globalMode); - case "opensearch" -> config.storage().services().opensearch().mode().orElse(globalMode); - case "appconfig" -> config.storage().services().appconfig().mode().orElse(globalMode); - case "appconfigdata" -> config.storage().services().appconfigdata().mode().orElse(globalMode); - default -> globalMode; - }; + return serviceConfigAccess.storageMode(serviceName); } private long resolveFlushInterval(String serviceName) { - return switch (serviceName) { - case "ssm" -> config.storage().services().ssm().flushIntervalMs(); - case "dynamodb" -> config.storage().services().dynamodb().flushIntervalMs(); - case "sns" -> config.storage().services().sns().flushIntervalMs(); - case "lambda" -> config.storage().services().lambda().flushIntervalMs(); - case "cloudwatchlogs" -> config.storage().services().cloudwatchlogs().flushIntervalMs(); - case "cloudwatchmetrics" -> config.storage().services().cloudwatchmetrics().flushIntervalMs(); - case "secretsmanager" -> config.storage().services().secretsmanager().flushIntervalMs(); - case "opensearch" -> config.storage().services().opensearch().flushIntervalMs(); - case "appconfig" -> config.storage().services().appconfig().flushIntervalMs(); - case "appconfigdata" -> config.storage().services().appconfigdata().flushIntervalMs(); - default -> 5000L; - }; + return serviceConfigAccess.storageFlushInterval(serviceName); } } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/CrossProtocolTargetRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/CrossProtocolTargetRoutingIntegrationTest.java new file mode 100644 index 0000000000..e1b5fa7f8c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/CrossProtocolTargetRoutingIntegrationTest.java @@ -0,0 +1,51 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * Regression coverage for the descriptor-backed target matcher. catalog.matchTarget + * is protocol-agnostic: it will return a descriptor for a JSON 1.1 target even when + * the request arrived at the JSON 1.0 controller (and vice versa). Each controller + * must map such mismatches to UnknownOperationException rather than dropping the + * request on a null switch branch. + */ +@QuarkusTest +class CrossProtocolTargetRoutingIntegrationTest { + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void json11ControllerRejectsJson10TargetAsUnknownOperation() { + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "DynamoDB_20120810.ListTables") + .body("{}") + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("UnknownOperationException")); + } + + @Test + void json10ControllerRejectsJson11TargetAsUnknownOperation() { + given() + .contentType("application/x-amz-json-1.0") + .header("X-Amz-Target", "AmazonSSM.ListDocuments") + .body("{}") + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("UnknownOperationException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamStsSharedEnablementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamStsSharedEnablementIntegrationTest.java new file mode 100644 index 0000000000..4e0deaf26d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamStsSharedEnablementIntegrationTest.java @@ -0,0 +1,32 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +@QuarkusTest +@TestProfile(IamStsSharedEnablementIntegrationTest.IamDisabledProfile.class) +class IamStsSharedEnablementIntegrationTest { + + @Inject + ServiceRegistry serviceRegistry; + + @Test + void disablingIamAlsoDisablesSts() { + assertFalse(serviceRegistry.isServiceEnabled("iam")); + assertFalse(serviceRegistry.isServiceEnabled("sts")); + } + + public static final class IamDisabledProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.enabled", "false"); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java new file mode 100644 index 0000000000..2fdfadc839 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class ServiceCatalogRoutingIntegrationTest { + + @Inject + ResolvedServiceCatalog catalog; + + @Test + void targetResolutionExtractsMatchingPrefixAndAction() { + ServiceCatalog.TargetMatch match = catalog.matchTarget("AWSEvents.PutEvents").orElseThrow(); + + assertEquals("events", match.descriptor().externalKey()); + assertEquals("AWSEvents.", match.prefix()); + assertEquals("PutEvents", match.action()); + } + + @Test + void dynamodbStreamsTargetUsesStreamsPrefix() { + ServiceCatalog.TargetMatch match = catalog.matchTarget("DynamoDBStreams_20120810.DescribeStream").orElseThrow(); + + assertEquals("dynamodb", match.descriptor().externalKey()); + assertEquals("DynamoDBStreams_20120810.", match.prefix()); + assertEquals("DescribeStream", match.action()); + } + + @Test + void cborSdkServiceIdsResolveThroughCatalog() { + assertEquals("states", catalog.byCborSdkServiceId("SFN").orElseThrow().externalKey()); + assertEquals("monitoring", catalog.byCborSdkServiceId("GraniteServiceVersion20100801").orElseThrow().externalKey()); + } + + @Test + void queryProtocolAliasesAreDeclaredOnDescriptors() { + assertTrue(catalog.byCredentialScope("sesv2").orElseThrow().supportsProtocol(ServiceProtocol.QUERY)); + assertTrue(catalog.byCredentialScope("cognito-idp").orElseThrow().supportsProtocol(ServiceProtocol.QUERY)); + } + + @Test + void unknownTargetsRemainUnresolved() { + assertTrue(catalog.matchTarget("UnknownService.DoThing").isEmpty()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServiceEnablementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServiceEnablementIntegrationTest.java new file mode 100644 index 0000000000..da6e59067a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/ServiceEnablementIntegrationTest.java @@ -0,0 +1,181 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.quarkus.test.junit.QuarkusTestProfile; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +@TestProfile(ServiceEnablementIntegrationTest.DisabledServicesProfile.class) +class ServiceEnablementIntegrationTest { + + private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void acmTargetedRequestsAreRejected() { + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "CertificateManager.ListCertificates") + .body("{}") + .when() + .post("/") + .then() + .statusCode(400) + .contentType("application/json") + .body("__type", equalTo("ServiceNotAvailableException")) + .body("message", equalTo("Service acm is not enabled.")); + } + + @Test + void ecsTargetedRequestsAreRejected() { + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.ListClusters") + .body("{}") + .when() + .post("/") + .then() + .statusCode(400) + .contentType("application/json") + .body("__type", equalTo("ServiceNotAvailableException")) + .body("message", equalTo("Service ecs is not enabled.")); + } + + @Test + void sqsQueueUrlJsonRequestsAreRejectedWhenServiceDisabled() { + given() + .contentType("application/x-amz-json-1.0") + .header("X-Amz-Target", "AmazonSQS.GetQueueAttributes") + .body(""" + {"QueueUrl":"http://localhost:4566/000000000000/disabled-queue","AttributeNames":["All"]} + """) + .when() + .post("/000000000000/disabled-queue") + .then() + .statusCode(400) + .contentType("application/json") + .body("__type", equalTo("ServiceNotAvailableException")) + .body("message", equalTo("Service sqs is not enabled.")); + } + + @Test + void sqsQueryRequestsReturnXmlWhenServiceDisabled() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", authorization("sqs")) + .formParam("Action", "ListQueues") + .when() + .post("/") + .then() + .statusCode(400) + .contentType("application/xml") + .body(containsString("ServiceNotAvailableException")) + .body(containsString("Service sqs is not enabled.")); + } + + @Test + void dynamodbTargetedCborRequestsReturnCborErrors() throws Exception { + JsonNode body = cborBody( + given() + .contentType("application/cbor") + .accept("application/cbor") + .header("X-Amz-Target", "DynamoDB_20120810.ListTables") + .body(CBOR_MAPPER.writeValueAsBytes(Map.of())) + .when() + .post("/") + .then() + .statusCode(400) + .contentType("application/cbor") + .extract().asByteArray() + ); + + assertEquals("ServiceNotAvailableException", body.get("__type").asText()); + assertEquals("Service dynamodb is not enabled.", body.get("message").asText()); + } + + @Test + void dynamodbSmithyCborRequestsReturnCborErrors() throws Exception { + JsonNode body = cborBody( + given() + .contentType("application/cbor") + .accept("application/cbor") + .header("Authorization", authorization("dynamodb")) + .body(CBOR_MAPPER.writeValueAsBytes(Map.of())) + .when() + .post("/service/DynamoDB/operation/ListTables") + .then() + .statusCode(400) + .contentType("application/cbor") + .extract().asByteArray() + ); + + assertEquals("ServiceNotAvailableException", body.get("__type").asText()); + assertEquals("Service dynamodb is not enabled.", body.get("message").asText()); + } + + @Test + void signedLambdaGetRequestsReturnJsonWhenServiceDisabled() { + given() + .header("Authorization", authorization("lambda")) + .when() + .get("/2015-03-31/functions") + .then() + .statusCode(400) + .contentType("application/json") + .body("__type", equalTo("ServiceNotAvailableException")) + .body("message", equalTo("Service lambda is not enabled.")); + } + + @Test + void signedOpenSearchGetRequestsReturnJsonWhenServiceDisabled() { + given() + .header("Authorization", authorization("es")) + .when() + .get("/2021-01-01/domain") + .then() + .statusCode(400) + .contentType("application/json") + .body("__type", equalTo("ServiceNotAvailableException")) + .body("message", equalTo("Service es is not enabled.")); + } + + private static JsonNode cborBody(byte[] body) throws Exception { + return CBOR_MAPPER.readTree(body); + } + + private static String authorization(String service) { + return "AWS4-HMAC-SHA256 Credential=test/20260411/us-east-1/" + service + + "/aws4_request, SignedHeaders=host;x-amz-date, Signature=deadbeef"; + } + + public static final class DisabledServicesProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.services.acm.enabled", "false", + "floci.services.dynamodb.enabled", "false", + "floci.services.ecs.enabled", "false", + "floci.services.lambda.enabled", "false", + "floci.services.opensearch.enabled", "false", + "floci.services.sqs.enabled", "false" + ); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServiceRegistryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServiceRegistryIntegrationTest.java new file mode 100644 index 0000000000..95d2454800 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/ServiceRegistryIntegrationTest.java @@ -0,0 +1,25 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class ServiceRegistryIntegrationTest { + + @Inject + ServiceRegistry serviceRegistry; + + @Test + void enabledServicesIncludeEc2AndEcs() { + assertTrue(serviceRegistry.getEnabledServices().contains("ec2")); + assertTrue(serviceRegistry.getEnabledServices().contains("ecs")); + } + + @Test + void unknownServicesDefaultToEnabled() { + assertTrue(serviceRegistry.isServiceEnabled("totally-unknown-service")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryServiceCatalogIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryServiceCatalogIntegrationTest.java new file mode 100644 index 0000000000..5d3fff8462 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryServiceCatalogIntegrationTest.java @@ -0,0 +1,42 @@ +package io.github.hectorvent.floci.core.storage; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +@QuarkusTest +@TestProfile(StorageFactoryServiceCatalogIntegrationTest.AcmPersistentStorageProfile.class) +class StorageFactoryServiceCatalogIntegrationTest { + + @Inject + StorageFactory storageFactory; + + @Test + void acmStorageOverrideIsApplied() { + StorageBackend backend = storageFactory.create( + "acm", + "acm-test.json", + new TypeReference>() {} + ); + + assertInstanceOf(PersistentStorage.class, backend); + } + + public static final class AcmPersistentStorageProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.storage.mode", "memory", + "floci.storage.services.acm.mode", "persistent", + "floci.storage.persistent-path", "/tmp/floci-service-registry-unification-tests" + ); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java index 6dc87974f1..372ccb1d30 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java @@ -16,12 +16,16 @@ import static org.hamcrest.Matchers.*; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class SesIntegrationTest { + private static String authorization(String service) { + return "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/" + service + "/aws4_request"; + } + @Test @Order(1) void verifyEmailIdentity() { given() .contentType("application/x-www-form-urlencoded") - .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .header("Authorization", authorization("email")) .formParam("Action", "VerifyEmailIdentity") .formParam("EmailAddress", "sender@example.com") .when() @@ -37,7 +41,7 @@ class SesIntegrationTest { void verifyEmailIdentity_second() { given() .contentType("application/x-www-form-urlencoded") - .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .header("Authorization", authorization("email")) .formParam("Action", "VerifyEmailIdentity") .formParam("EmailAddress", "recipient@example.com") .when() @@ -51,7 +55,7 @@ class SesIntegrationTest { void verifyDomainIdentity() { given() .contentType("application/x-www-form-urlencoded") - .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .header("Authorization", authorization("email")) .formParam("Action", "VerifyDomainIdentity") .formParam("Domain", "example.com") .when() @@ -228,7 +232,21 @@ class SesIntegrationTest { void getAccountSendingEnabled() { given() .contentType("application/x-www-form-urlencoded") - .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .header("Authorization", authorization("email")) + .formParam("Action", "GetAccountSendingEnabled") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("true")); + } + + @Test + @Order(14) + void getAccountSendingEnabled_acceptsSesv2CredentialScopeAlias() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", authorization("sesv2")) .formParam("Action", "GetAccountSendingEnabled") .when() .post("/") @@ -242,7 +260,7 @@ class SesIntegrationTest { void getIdentityDkimAttributes() { given() .contentType("application/x-www-form-urlencoded") - .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .header("Authorization", authorization("email")) .formParam("Action", "GetIdentityDkimAttributes") .formParam("Identities.member.1", "example.com") .when()