From 1b3417a7a3c2e90b2fa8e13a552cdfdb134d8cc0 Mon Sep 17 00:00:00 2001 From: Sam Fakhreddine Date: Fri, 28 Aug 2026 09:58:39 -0600 Subject: [PATCH] feat(config): compliance evaluation loop, retention, pagination (#2642) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(config): add compliance evaluation loop, retention, and pagination Replace the hardcoded INSUFFICIENT_DATA compliance with real aggregation over evaluations reported via PutEvaluations / PutExternalEvaluation: - New actions (13): PutEvaluations, PutExternalEvaluation, DeleteEvaluationResults, DescribeComplianceByResource, GetComplianceDetailsByConfigRule, GetComplianceDetailsByResource, GetComplianceSummaryByConfigRule, GetComplianceSummaryByResourceType, DeleteConfigurationRecorder, DeleteDeliveryChannel, PutRetentionConfiguration, DescribeRetentionConfigurations, DeleteRetentionConfiguration - PutConfigRule now round-trips the full AWS rule shape (Description, Scope, SourceDetails, InputParameters, MaximumExecutionFrequency, EvaluationModes) instead of silently dropping fields - Evaluations persist to config-evaluations.json and are cascade-deleted with their rule; retention persists to config-retention.json - NextToken/Limit pagination on describe/get operations with AWS page sizes and InvalidNextTokenException/InvalidLimitException validation - DescribeConfigRules with an unknown name now fails with NoSuchConfigRuleException, matching AWS - boto3 compatibility suite: tests/test_config.py Since Floci performs no Lambda invocation, PutEvaluations accepts the config rule name as the ResultToken; documented in the service doc's deviations section. * fix: honor Limit field in Config pagination requests * fix(config): enforce the modeled rule enums and the ComplianceTypes filter shape PutConfigRule now deserializes the whole modeled ConfigRule and stores it, so Source.Owner, MaximumExecutionFrequency, ConfigRuleState and EvaluationModes[].Mode were persisted and echoed back verbatim — a rule AWS would have rejected with InvalidParameterValueException read back as a valid one. The ComplianceTypes filter on the four compliance reads was likewise unchecked: an unmodeled value or a list longer than the shape's max of 3 simply matched nothing, which a caller reads as an empty result rather than as a rejection. * fix(config): validate the nested SourceDetails enums and Scope cardinality The stored ConfigRule carries SourceDetails, whose EventSource (aws.config only), MessageType and MaximumExecutionFrequency are all enum-typed, and a Scope whose ComplianceResourceTypes list is capped at 100. All four were persisted and echoed back by DescribeConfigRules verbatim, one level below the members the previous commit checked. * fix(config): reject a missing ConfigRuleName on DeleteConfigRule store.remove(ruleName) throws NullPointerException on the backing ConcurrentHashMap when ruleName is null (the handler passes null when ConfigRuleName is absent from the request), producing a 500 instead of the modeled NoSuchConfigRuleException. Guard on isBlank(ruleName) first, matching the existing requireRule() idiom used by the sibling evaluation operations for the same field. * fix(config): keep the newest evaluation when PutEvaluations reorders storeEvaluations() unconditionally overwrote the stored compliance result for a resource/rule pair, so an older evaluation arriving after a newer one (e.g. an out-of-order Lambda invocation) regressed compliance details, aggregates, and summaries back to the stale value. Compare against the stored OrderingTimestamp and skip the incoming evaluation when it is older than what is already recorded. * fix(config): make PutEvaluations atomic per resource/rule key storeEvaluations() read the current evaluation with a plain get() and wrote the new one with a separate put(), so two concurrent PutEvaluations calls for the same resource could both read the old value before either wrote, letting an older OrderingTimestamp win the race regardless of arrival order. Replace the read-then-write with ConcurrentHashMap.compute(), which is atomic per key. Added a stress test exercising 16 concurrent writers per resource key across 100 attempts; it passes reliably under the fix. The race window in the prior get/put shape is narrow enough (a handful of nanoseconds between the two calls) that it did not reproduce deterministically under test scheduling even with that much contention -- the fix is justified by the non-atomic read-then-write shape itself, not by a forced failure. * fix(config): enforce DescribeConfigRules' 25-name limit ConfigRuleNames is modeled with Maximum 25 items (confirmed against botocore's config service-2.json) but describeConfigRules had no size check, so 26+ names were processed instead of rejected with InvalidParameterValueException like every other array-size limit this PR already enforces. * fix(config): close the DeleteConfigRule/PutEvaluations deletion race PutEvaluations (and PutExternalEvaluation, DeleteEvaluationResults) checked a rule's existence via requireRule and then wrote to the evaluations map as two separate steps. If DeleteConfigRule ran in between -- removing the rule and its evaluation bucket -- the pending PutEvaluations call would recreate the bucket via computeIfAbsent after the delete, orphaning evaluations under the deleted rule's name. A later rule created with that same name would then inherit the deleted rule's compliance details and evaluation status. Guard the check-then-act with a per-rule monitor (ruleKey(region, ruleName)), matching the lockFor()-keyed-monitor idiom already used by DocDbService for the identical class of race between a tag update and a delete. Added a stress test racing PutEvaluations against DeleteConfigRule across 200 attempts, then recreating the rule under the same name and asserting a clean (INSUFFICIENT_DATA) evaluation state. It passes under the fix; as with the earlier PutEvaluations-ordering race, it did not reproduce RED against the pre-fix code even under that much contention -- the race window between the existence check and the map write is too narrow to hit deterministically without injecting an artificial delay into production code. The fix is justified by the non-atomic check-then-act shape itself, confirmed by reading the code. --- README.md | 2 +- .../sdk-test-python/conftest.py | 6 + .../sdk-test-python/tests/test_config.py | 291 ++++++++ docs/services/config.md | 78 +- docs/services/index.md | 2 +- .../configservice/AwsConfigService.java | 703 ++++++++++++++++-- .../ConfigServiceJsonHandler.java | 206 +++-- .../configservice/model/Compliance.java | 14 + .../model/ComplianceByConfigRule.java | 14 + .../model/ComplianceByResource.java | 15 + .../model/ComplianceContributorCount.java | 14 + .../model/ComplianceSummary.java | 15 + .../ComplianceSummaryByResourceType.java | 14 + .../configservice/model/ConfigEvaluation.java | 19 + .../configservice/model/ConfigRule.java | 10 +- .../model/ConfigRuleEvaluationStatus.java | 5 +- .../configservice/model/ConfigRuleSource.java | 6 +- .../model/CustomPolicyDetails.java | 15 + .../model/EvaluationModeConfiguration.java | 13 + .../configservice/model/EvaluationResult.java | 18 + .../model/EvaluationResultIdentifier.java | 14 + .../model/EvaluationResultQualifier.java | 16 + .../model/RetentionConfiguration.java | 14 + .../services/configservice/model/Scope.java | 18 + .../configservice/model/SourceDetail.java | 15 + ...onfigServiceEvaluationConcurrencyTest.java | 147 ++++ .../AwsConfigServicePersistenceTest.java | 70 +- .../ComplianceEvaluationIntegrationTest.java | 580 +++++++++++++++ .../ConfigPaginationIntegrationTest.java | 230 ++++++ .../ConfigRuleIntegrationTest.java | 249 ++++++- .../ConfigurationRecorderIntegrationTest.java | 116 +++ .../DescribeConfigRulesLimitTest.java | 35 + ...RetentionConfigurationIntegrationTest.java | 131 ++++ 33 files changed, 2970 insertions(+), 125 deletions(-) create mode 100644 compatibility-tests/sdk-test-python/tests/test_config.py create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/Compliance.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceByConfigRule.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceByResource.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceContributorCount.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceSummary.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceSummaryByResourceType.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigEvaluation.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/CustomPolicyDetails.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationModeConfiguration.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResult.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResultIdentifier.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResultQualifier.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/RetentionConfiguration.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/Scope.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/configservice/model/SourceDetail.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServiceEvaluationConcurrencyTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/configservice/ComplianceEvaluationIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/configservice/ConfigPaginationIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/configservice/DescribeConfigRulesLimitTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/configservice/RetentionConfigurationIntegrationTest.java diff --git a/README.md b/README.md index 6f9b6c0f1c..772b469ddd 100644 --- a/README.md +++ b/README.md @@ -300,7 +300,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | Elastic Beanstalk | In-process | Applications, application versions, environments, configuration templates, platform and solution stack metadata | | AWS Backup | In-process | Vaults, backup plans, selections, simulated job lifecycle, recovery points | | AWS FIS | In-process | All 26 management APIs for templates, experiments, target accounts, action and target discovery, safety lever, tagging, and pagination; experiment execution is a safe control-plane simulation and does not inject faults into other services | -| AWS Config | In-process | Config rules, configuration recorders, delivery channels, conformance packs, tagging | +| AWS Config | In-process | Config rules, evaluation-driven compliance (PutEvaluations, compliance details and summaries), configuration recorders, delivery channels, retention configuration, conformance packs, tagging | | Organizations | In-process | Organizations, roots, nested OUs, member accounts, all policy types with `FullAWSAccess` and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable Floci accounts and member accounts can read the organization they belong to | | CloudTrail | In-process | Trails, event selectors (S3 data events with bucket/prefix matching), `StartLogging`/`StopLogging`, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits `AccessDenied` records | | CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, tagging | diff --git a/compatibility-tests/sdk-test-python/conftest.py b/compatibility-tests/sdk-test-python/conftest.py index 21a121a0f8..5e7cb3b28a 100644 --- a/compatibility-tests/sdk-test-python/conftest.py +++ b/compatibility-tests/sdk-test-python/conftest.py @@ -145,6 +145,12 @@ def cloudformation_client(aws_config, client_config): return boto3.client("cloudformation", config=client_config, **aws_config) +@pytest.fixture +def config_client(aws_config, client_config): + """Create AWS Config client.""" + return boto3.client("config", config=client_config, **aws_config) + + @pytest.fixture def acm_client(aws_config, client_config): """Create ACM client.""" diff --git a/compatibility-tests/sdk-test-python/tests/test_config.py b/compatibility-tests/sdk-test-python/tests/test_config.py new file mode 100644 index 0000000000..b3dfe67fe1 --- /dev/null +++ b/compatibility-tests/sdk-test-python/tests/test_config.py @@ -0,0 +1,291 @@ +"""AWS Config integration tests.""" + +import datetime + +import pytest +from botocore.exceptions import ClientError + +LAMBDA_SOURCE = "arn:aws:lambda:us-east-1:000000000000:function:compliance-checker" + + +def _put_custom_rule(config_client, rule_name, **overrides): + """Create a minimal CUSTOM_LAMBDA config rule.""" + rule = { + "ConfigRuleName": rule_name, + "Source": {"Owner": "CUSTOM_LAMBDA", "SourceIdentifier": LAMBDA_SOURCE}, + } + rule.update(overrides) + config_client.put_config_rule(ConfigRule=rule) + + +class TestConfigRuleLifecycle: + """Test config rule CRUD with a full-shape round-trip.""" + + def test_put_describe_round_trip(self, config_client, unique_name): + """Test PutConfigRule stores every field and DescribeConfigRules returns them.""" + rule_name = f"rule-{unique_name}" + _put_custom_rule( + config_client, + rule_name, + Description="Checks bucket policies", + Scope={"ComplianceResourceTypes": ["AWS::S3::Bucket"], "TagKey": "env"}, + Source={ + "Owner": "CUSTOM_LAMBDA", + "SourceIdentifier": LAMBDA_SOURCE, + "SourceDetails": [ + {"EventSource": "aws.config", "MessageType": "ConfigurationItemChangeNotification"} + ], + }, + InputParameters='{"maxPolicySize": 5}', + MaximumExecutionFrequency="Six_Hours", + ) + + try: + rules = config_client.describe_config_rules(ConfigRuleNames=[rule_name])["ConfigRules"] + assert len(rules) == 1 + rule = rules[0] + assert rule["ConfigRuleName"] == rule_name + assert rule["ConfigRuleArn"].startswith("arn:aws:config:") + assert rule["ConfigRuleId"] + assert rule["ConfigRuleState"] == "ACTIVE" + assert rule["Description"] == "Checks bucket policies" + assert rule["Scope"]["ComplianceResourceTypes"] == ["AWS::S3::Bucket"] + assert rule["Scope"]["TagKey"] == "env" + assert rule["Source"]["Owner"] == "CUSTOM_LAMBDA" + assert rule["Source"]["SourceIdentifier"] == LAMBDA_SOURCE + assert rule["Source"]["SourceDetails"][0]["EventSource"] == "aws.config" + assert rule["InputParameters"] == '{"maxPolicySize": 5}' + assert rule["MaximumExecutionFrequency"] == "Six_Hours" + assert rule["EvaluationModes"] == [{"Mode": "DETECTIVE"}] + finally: + config_client.delete_config_rule(ConfigRuleName=rule_name) + + def test_describe_unknown_rule_fails(self, config_client, unique_name): + """Test DescribeConfigRules with an unknown name raises NoSuchConfigRuleException.""" + with pytest.raises(ClientError) as exc: + config_client.describe_config_rules(ConfigRuleNames=[f"missing-{unique_name}"]) + assert exc.value.response["Error"]["Code"] == "NoSuchConfigRuleException" + + def test_delete_unknown_rule_fails(self, config_client, unique_name): + """Test DeleteConfigRule with an unknown name raises NoSuchConfigRuleException.""" + with pytest.raises(ClientError) as exc: + config_client.delete_config_rule(ConfigRuleName=f"missing-{unique_name}") + assert exc.value.response["Error"]["Code"] == "NoSuchConfigRuleException" + + +class TestComplianceLoop: + """Test the evaluation-driven compliance loop.""" + + def test_evaluations_drive_compliance(self, config_client, unique_name): + """Test PutEvaluations records results that compliance reads aggregate.""" + rule_name = f"loop-{unique_name}" + resource_id = f"bucket-{unique_name}" + _put_custom_rule(config_client, rule_name) + + try: + # TestMode validates but persists nothing + config_client.put_evaluations( + ResultToken=rule_name, + TestMode=True, + Evaluations=[ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": resource_id, + "ComplianceType": "NON_COMPLIANT", + "OrderingTimestamp": datetime.datetime(2024, 1, 1, tzinfo=datetime.timezone.utc), + } + ], + ) + compliance = config_client.describe_compliance_by_config_rule( + ConfigRuleNames=[rule_name] + )["ComplianceByConfigRules"][0]["Compliance"] + assert compliance["ComplianceType"] == "INSUFFICIENT_DATA" + + # Real evaluations flip the rule to NON_COMPLIANT + response = config_client.put_evaluations( + ResultToken=rule_name, + Evaluations=[ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": resource_id, + "ComplianceType": "NON_COMPLIANT", + "Annotation": "Bucket policy too permissive", + "OrderingTimestamp": datetime.datetime(2024, 1, 1, tzinfo=datetime.timezone.utc), + } + ], + ) + assert response["FailedEvaluations"] == [] + + compliance = config_client.describe_compliance_by_config_rule( + ConfigRuleNames=[rule_name] + )["ComplianceByConfigRules"][0]["Compliance"] + assert compliance["ComplianceType"] == "NON_COMPLIANT" + assert compliance["ComplianceContributorCount"]["CappedCount"] == 1 + assert compliance["ComplianceContributorCount"]["CapExceeded"] is False + + details = config_client.get_compliance_details_by_config_rule( + ConfigRuleName=rule_name + )["EvaluationResults"] + assert len(details) == 1 + qualifier = details[0]["EvaluationResultIdentifier"]["EvaluationResultQualifier"] + assert qualifier["ConfigRuleName"] == rule_name + assert qualifier["ResourceType"] == "AWS::S3::Bucket" + assert qualifier["ResourceId"] == resource_id + assert details[0]["ComplianceType"] == "NON_COMPLIANT" + assert details[0]["Annotation"] == "Bucket policy too permissive" + assert isinstance(details[0]["ResultRecordedTime"], datetime.datetime) + + by_resource = config_client.get_compliance_details_by_resource( + ResourceType="AWS::S3::Bucket", ResourceId=resource_id + )["EvaluationResults"] + assert len(by_resource) == 1 + assert ( + by_resource[0]["EvaluationResultIdentifier"]["EvaluationResultQualifier"]["ConfigRuleName"] + == rule_name + ) + + resources = config_client.describe_compliance_by_resource( + ResourceType="AWS::S3::Bucket", ResourceId=resource_id + )["ComplianceByResources"] + assert len(resources) == 1 + assert resources[0]["Compliance"]["ComplianceType"] == "NON_COMPLIANT" + + summary = config_client.get_compliance_summary_by_config_rule()["ComplianceSummary"] + assert summary["NonCompliantResourceCount"]["CappedCount"] >= 1 + assert isinstance(summary["ComplianceSummaryTimestamp"], datetime.datetime) + + by_type = config_client.get_compliance_summary_by_resource_type( + ResourceTypes=["AWS::S3::Bucket"] + )["ComplianceSummariesByResourceType"] + assert len(by_type) == 1 + assert by_type[0]["ResourceType"] == "AWS::S3::Bucket" + assert by_type[0]["ComplianceSummary"]["NonCompliantResourceCount"]["CappedCount"] >= 1 + + # DeleteEvaluationResults returns the rule to INSUFFICIENT_DATA + config_client.delete_evaluation_results(ConfigRuleName=rule_name) + compliance = config_client.describe_compliance_by_config_rule( + ConfigRuleNames=[rule_name] + )["ComplianceByConfigRules"][0]["Compliance"] + assert compliance["ComplianceType"] == "INSUFFICIENT_DATA" + finally: + config_client.delete_config_rule(ConfigRuleName=rule_name) + + def test_put_external_evaluation(self, config_client, unique_name): + """Test PutExternalEvaluation records a result for the named rule.""" + rule_name = f"external-{unique_name}" + _put_custom_rule(config_client, rule_name) + + try: + config_client.put_external_evaluation( + ConfigRuleName=rule_name, + ExternalEvaluation={ + "ComplianceResourceType": "AWS::EC2::Instance", + "ComplianceResourceId": f"i-{unique_name}", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": datetime.datetime(2024, 1, 1, tzinfo=datetime.timezone.utc), + }, + ) + compliance = config_client.describe_compliance_by_config_rule( + ConfigRuleNames=[rule_name] + )["ComplianceByConfigRules"][0]["Compliance"] + assert compliance["ComplianceType"] == "COMPLIANT" + finally: + config_client.delete_config_rule(ConfigRuleName=rule_name) + + def test_put_evaluations_error_cases(self, config_client, unique_name): + """Test PutEvaluations validation errors surface AWS error codes.""" + evaluation = { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": f"bucket-{unique_name}", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": datetime.datetime(2024, 1, 1, tzinfo=datetime.timezone.utc), + } + + with pytest.raises(ClientError) as exc: + config_client.put_evaluations(ResultToken="", Evaluations=[evaluation]) + assert exc.value.response["Error"]["Code"] == "InvalidResultTokenException" + + with pytest.raises(ClientError) as exc: + config_client.put_evaluations( + ResultToken=f"missing-{unique_name}", Evaluations=[evaluation] + ) + assert exc.value.response["Error"]["Code"] == "NoSuchConfigRuleException" + + +class TestRecorderChannelLifecycle: + """Test configuration recorder and delivery channel lifecycle.""" + + def test_recorder_and_channel_lifecycle(self, config_client): + """Test recorder/channel setup, the guarded channel delete, and both deletes.""" + config_client.put_configuration_recorder( + ConfigurationRecorder={ + "name": "default", + "roleARN": "arn:aws:iam::000000000000:role/config-role", + "recordingGroup": {"allSupported": True}, + } + ) + + try: + config_client.put_delivery_channel( + DeliveryChannel={"name": "default", "s3BucketName": "config-bucket"} + ) + config_client.start_configuration_recorder(ConfigurationRecorderName="default") + + with pytest.raises(ClientError) as exc: + config_client.delete_delivery_channel(DeliveryChannelName="default") + assert exc.value.response["Error"]["Code"] == "LastDeliveryChannelDeleteFailedException" + + config_client.stop_configuration_recorder(ConfigurationRecorderName="default") + config_client.delete_delivery_channel(DeliveryChannelName="default") + + with pytest.raises(ClientError) as exc: + config_client.delete_delivery_channel(DeliveryChannelName="default") + assert exc.value.response["Error"]["Code"] == "NoSuchDeliveryChannelException" + finally: + config_client.delete_configuration_recorder(ConfigurationRecorderName="default") + + assert config_client.describe_configuration_recorders()["ConfigurationRecorders"] == [] + + +class TestRetention: + """Test retention configuration lifecycle.""" + + def test_retention_lifecycle(self, config_client): + """Test put/describe/delete retention configuration.""" + retention = config_client.put_retention_configuration(RetentionPeriodInDays=365) + assert retention["RetentionConfiguration"]["Name"] == "default" + assert retention["RetentionConfiguration"]["RetentionPeriodInDays"] == 365 + + try: + configurations = config_client.describe_retention_configurations()["RetentionConfigurations"] + assert len(configurations) == 1 + assert configurations[0]["RetentionPeriodInDays"] == 365 + finally: + config_client.delete_retention_configuration(RetentionConfigurationName="default") + + assert config_client.describe_retention_configurations()["RetentionConfigurations"] == [] + + +class TestPagination: + """Test NextToken pagination through the boto3 paginator.""" + + def test_describe_config_rules_paginates(self, config_client, unique_name): + """Test the boto3 paginator walks every page of DescribeConfigRules.""" + rule_names = [f"pg-{unique_name}-{i:03d}" for i in range(30)] + for rule_name in rule_names: + _put_custom_rule(config_client, rule_name) + + try: + first_page = config_client.describe_config_rules() + assert len(first_page["ConfigRules"]) == 25 + assert first_page["NextToken"] + + collected = [] + paginator = config_client.get_paginator("describe_config_rules") + for page in paginator.paginate(): + collected.extend(rule["ConfigRuleName"] for rule in page["ConfigRules"]) + for rule_name in rule_names: + assert rule_name in collected + finally: + for rule_name in rule_names: + config_client.delete_config_rule(ConfigRuleName=rule_name) diff --git a/docs/services/config.md b/docs/services/config.md index b26a87bc89..6c7ae8160c 100644 --- a/docs/services/config.md +++ b/docs/services/config.md @@ -9,19 +9,33 @@ | Action | Description | |---|---| -| `PutConfigRule` | Create or update a config rule | -| `DeleteConfigRule` | Delete a config rule | -| `DescribeConfigRules` | List config rules, optionally filtered by name | -| `DescribeComplianceByConfigRule` | Get compliance summary for config rules | +| `PutConfigRule` | Create or update a config rule (full rule shape round-trips: description, scope, source details, input parameters, execution frequency, evaluation modes) | +| `DeleteConfigRule` | Delete a config rule and its evaluation results | +| `DescribeConfigRules` | List config rules, optionally filtered by name, paginated via `NextToken` | | `DescribeConfigRuleEvaluationStatus` | Get evaluation status for config rules | | `StartConfigRulesEvaluation` | Trigger evaluation for config rules | +### Compliance & Evaluations + +| Action | Description | +|---|---| +| `PutEvaluations` | Report evaluation results for a config rule (supports `TestMode`) | +| `PutExternalEvaluation` | Report a single external evaluation for a config rule | +| `DeleteEvaluationResults` | Delete all evaluation results for a config rule | +| `DescribeComplianceByConfigRule` | Get rule-level compliance aggregated from reported evaluations | +| `DescribeComplianceByResource` | Get resource-level compliance aggregated across rules | +| `GetComplianceDetailsByConfigRule` | List the evaluation results recorded for a rule | +| `GetComplianceDetailsByResource` | List the evaluation results recorded for a resource | +| `GetComplianceSummaryByConfigRule` | Count compliant and non-compliant rules | +| `GetComplianceSummaryByResourceType` | Count compliant and non-compliant resources, grouped by type | + ### Configuration Recorder | Action | Description | |---|---| | `PutConfigurationRecorder` | Create or update a configuration recorder | | `DescribeConfigurationRecorders` | List configuration recorders | +| `DeleteConfigurationRecorder` | Delete a configuration recorder | | `StartConfigurationRecorder` | Start recording configuration changes | | `StopConfigurationRecorder` | Stop recording configuration changes | | `DescribeConfigurationRecorderStatus` | Get the status of configuration recorders | @@ -32,6 +46,15 @@ |---|---| | `PutDeliveryChannel` | Create or update a delivery channel | | `DescribeDeliveryChannels` | List delivery channels | +| `DeleteDeliveryChannel` | Delete a delivery channel (fails while the recorder is running) | + +### Retention Configuration + +| Action | Description | +|---|---| +| `PutRetentionConfiguration` | Set the retention period (30-2557 days) | +| `DescribeRetentionConfigurations` | List retention configurations | +| `DeleteRetentionConfiguration` | Delete the retention configuration | ### Conformance Packs @@ -39,7 +62,7 @@ |---|---| | `PutConformancePack` | Create or update a conformance pack | | `DeleteConformancePack` | Delete a conformance pack | -| `DescribeConformancePacks` | List conformance packs | +| `DescribeConformancePacks` | List conformance packs, paginated via `Limit`/`NextToken` | | `DescribeConformancePackStatus` | Get the deployment status of conformance packs | ### Tagging @@ -64,6 +87,8 @@ export AWS_ENDPOINT_URL=http://localhost:4566 # Create a config rule aws configservice put-config-rule --config-rule '{ "ConfigRuleName": "s3-bucket-versioning", + "Description": "Checks that versioning is enabled", + "Scope": {"ComplianceResourceTypes": ["AWS::S3::Bucket"]}, "Source": { "Owner": "AWS", "SourceIdentifier": "S3_BUCKET_VERSIONING_ENABLED" @@ -73,6 +98,28 @@ aws configservice put-config-rule --config-rule '{ # List config rules aws configservice describe-config-rules +# Report evaluation results (the ResultToken is the rule name, see Deviations) +aws configservice put-evaluations \ + --result-token s3-bucket-versioning \ + --evaluations '[{ + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "my-bucket", + "ComplianceType": "NON_COMPLIANT", + "Annotation": "Versioning is suspended", + "OrderingTimestamp": 1700000000.0 + }]' + +# Rule compliance now reflects the reported evaluations +aws configservice describe-compliance-by-config-rule \ + --config-rule-names s3-bucket-versioning + +# Inspect per-resource evaluation results +aws configservice get-compliance-details-by-config-rule \ + --config-rule-name s3-bucket-versioning + +# Set the retention period +aws configservice put-retention-configuration --retention-period-in-days 365 + # Create a configuration recorder aws configservice put-configuration-recorder --configuration-recorder '{ "name": "default", @@ -106,5 +153,24 @@ aws configservice tag-resource \ aws configservice delete-config-rule --config-rule-name s3-bucket-versioning ``` +## Deviations + !!! note - Compliance status always returns `INSUFFICIENT_DATA` since Floci does not perform actual resource evaluation. Config rules, recorders, and conformance packs are stored and returned correctly, but no real configuration recording or compliance checking takes place. + Compliance is driven entirely by evaluations reported through `PutEvaluations` and + `PutExternalEvaluation` — Floci does not record resource configurations or run rule + evaluations itself. Until an evaluation is reported, compliance returns + `INSUFFICIENT_DATA`. + + - **ResultToken**: real AWS hands custom rules an opaque token inside the evaluation + event. Floci has no evaluation event, so `PutEvaluations` expects the config rule + name as the token (a `:` form is also accepted). + - `StartConfigRulesEvaluation` marks the rule as invoked but does not call the rule's + Lambda function. + - `FirstActivatedTime` and invocation timestamps are runtime state and are not + persisted across restarts. + - `DescribeConfigRules` and `DescribeComplianceByConfigRule` use a fixed page size + of 25. + - Configuration recorders and delivery channels are stored and validated, but no + configuration items or snapshots are produced. + - Conformance pack status is always `CREATE_SUCCESSFUL`; pack templates are stored, + not evaluated. diff --git a/docs/services/index.md b/docs/services/index.md index fa294f7851..51ecfb1cc5 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -97,7 +97,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 17 | | [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 18 | | [Cloud Map](cloudmap.md) | `POST /` + `X-Amz-Target: Route53AutoNaming_v20170314.*` | JSON 1.1 | 22 | -| [AWS Config](config.md) | `POST /` + `X-Amz-Target: StarlingDoveService.*` | JSON 1.1 | 20 | +| [AWS Config](config.md) | `POST /` + `X-Amz-Target: StarlingDoveService.*` | JSON 1.1 | 33 | | [CloudTrail](cloudtrail.md) | `POST /` + `X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.*` | JSON 1.1 | 9 | | [Textract](textract.md) | `POST /` + `X-Amz-Target: Textract.*` | JSON 1.1 | 6 | | [Transcribe](transcribe.md) | `POST /` + `X-Amz-Target: Transcribe.*` | JSON 1.1 | 8 | diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/AwsConfigService.java b/src/main/java/io/github/hectorvent/floci/services/configservice/AwsConfigService.java index 109e5c2379..9e08348bbe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/configservice/AwsConfigService.java +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/AwsConfigService.java @@ -6,22 +6,38 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackedMap; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.configservice.model.Compliance; +import io.github.hectorvent.floci.services.configservice.model.ComplianceByConfigRule; +import io.github.hectorvent.floci.services.configservice.model.ComplianceByResource; +import io.github.hectorvent.floci.services.configservice.model.ComplianceContributorCount; +import io.github.hectorvent.floci.services.configservice.model.ComplianceSummary; +import io.github.hectorvent.floci.services.configservice.model.ComplianceSummaryByResourceType; +import io.github.hectorvent.floci.services.configservice.model.ConfigEvaluation; import io.github.hectorvent.floci.services.configservice.model.ConfigRule; import io.github.hectorvent.floci.services.configservice.model.ConfigRuleEvaluationStatus; -import io.github.hectorvent.floci.services.configservice.model.ConfigRuleSource; import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorder; import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorderStatus; import io.github.hectorvent.floci.services.configservice.model.ConformancePack; import io.github.hectorvent.floci.services.configservice.model.ConformancePackStatusDetail; import io.github.hectorvent.floci.services.configservice.model.DeliveryChannel; +import io.github.hectorvent.floci.services.configservice.model.EvaluationModeConfiguration; +import io.github.hectorvent.floci.services.configservice.model.EvaluationResult; +import io.github.hectorvent.floci.services.configservice.model.EvaluationResultIdentifier; +import io.github.hectorvent.floci.services.configservice.model.EvaluationResultQualifier; +import io.github.hectorvent.floci.services.configservice.model.RetentionConfiguration; +import io.github.hectorvent.floci.services.configservice.model.SourceDetail; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -29,6 +45,34 @@ import java.util.stream.Collectors; @ApplicationScoped public class AwsConfigService { + private static final Set VALID_COMPLIANCE_TYPES = + Set.of("COMPLIANT", "NON_COMPLIANT", "NOT_APPLICABLE", "INSUFFICIENT_DATA"); + private static final String NO_SUCH_CONFIG_RULE_MESSAGE = + "The ConfigRule provided in the request is invalid. Please check the configRule name."; + private static final String INVALID_NEXT_TOKEN_MESSAGE = + "The specified next token is not valid. Specify the nextToken string that was returned " + + "in the previous response to get the next page of results."; + /** Enum shapes from the Config model (config/2014-11-12/service-2.json). */ + private static final Set VALID_RULE_OWNERS = + Set.of("CUSTOM_LAMBDA", "AWS", "CUSTOM_POLICY"); + private static final Set VALID_EXECUTION_FREQUENCIES = + Set.of("One_Hour", "Three_Hours", "Six_Hours", "Twelve_Hours", "TwentyFour_Hours"); + private static final Set VALID_RULE_STATES = + Set.of("ACTIVE", "DELETING", "DELETING_RESULTS", "EVALUATING"); + private static final Set VALID_EVALUATION_MODES = Set.of("DETECTIVE", "PROACTIVE"); + private static final Set VALID_EVENT_SOURCES = Set.of("aws.config"); + private static final Set VALID_MESSAGE_TYPES = Set.of( + "ConfigurationItemChangeNotification", "ConfigurationSnapshotDeliveryCompleted", + "ScheduledNotification", "OversizedConfigurationItemChangeNotification"); + /** {@code ComplianceTypes} is a list of ComplianceType with {@code max: 3}. */ + private static final int MAX_COMPLIANCE_TYPE_FILTERS = 3; + /** {@code Scope.ComplianceResourceTypes} is {@code max: 100}. */ + private static final int MAX_COMPLIANCE_RESOURCE_TYPES = 100; + /** {@code DescribeConfigRulesRequest.ConfigRuleNames} is {@code max: 25}. */ + private static final int MAX_DESCRIBE_CONFIG_RULE_NAMES = 25; + private static final int RULE_CONTRIBUTOR_CAP = 25; + private static final int RESOURCE_CONTRIBUTOR_CAP = 100; + private final RegionResolver regionResolver; private final StorageFactory storageFactory; @@ -36,16 +80,28 @@ public class AwsConfigService { private Map> configRules = new ConcurrentHashMap<>(); // region -> packName -> pack (nested) private Map> conformancePacks = new ConcurrentHashMap<>(); + // region -> ruleName -> resourceKey("Type|Id") -> evaluation (doubly nested) + private Map>> evaluations = new ConcurrentHashMap<>(); - // region -> recorder / channel (flat) + // region -> recorder / channel / retention (flat) private Map configurationRecorders = new ConcurrentHashMap<>(); private Map deliveryChannels = new ConcurrentHashMap<>(); + private Map retentionConfigurations = new ConcurrentHashMap<>(); // recorder run-state is transient runtime state (not persisted) private final ConcurrentHashMap recorderRunning = new ConcurrentHashMap<>(); private final ConcurrentHashMap recorderLastStartTime = new ConcurrentHashMap<>(); private final ConcurrentHashMap recorderLastStopTime = new ConcurrentHashMap<>(); + // per-rule evaluation timing is transient runtime state, keyed region + "|" + ruleName + private final ConcurrentHashMap ruleFirstActivatedTime = new ConcurrentHashMap<>(); + private final ConcurrentHashMap ruleLastInvokedTime = new ConcurrentHashMap<>(); + + // guards the check-then-act between a rule's existence and its evaluations, keyed + // region + "|" + ruleName, so DeleteConfigRule can't race PutEvaluations/PutExternalEvaluation + // into recreating a deleted rule's evaluation bucket for a later same-named rule to inherit + private final ConcurrentHashMap ruleLocks = new ConcurrentHashMap<>(); + // resourceArn -> {tagKey -> tagValue} (flat outer, mutable inner) private Map> tags = new ConcurrentHashMap<>(); @@ -64,15 +120,20 @@ public class AwsConfigService { new TypeReference>>() {}); this.conformancePacks = storageBacked("config-conformance-packs.json", new TypeReference>>() {}); + this.evaluations = storageBacked("config-evaluations.json", + new TypeReference>>>() {}); this.configurationRecorders = storageBacked("config-recorders.json", new TypeReference>() {}); this.deliveryChannels = storageBacked("config-delivery-channels.json", new TypeReference>() {}); + this.retentionConfigurations = storageBacked("config-retention.json", + new TypeReference>() {}); this.tags = storageBacked("config-tags.json", new TypeReference>>() {}); normalizeRegionMaps(configRules); normalizeRegionMaps(conformancePacks); normalizeRegionMaps(tags); + normalizeEvaluationMaps(); } private Map storageBacked(String fileName, TypeReference> typeReference) { @@ -89,6 +150,18 @@ public class AwsConfigService { } } + /** Same as {@link #normalizeRegionMaps} but for the doubly nested evaluations map. */ + private void normalizeEvaluationMaps() { + for (Map.Entry>> regionEntry + : new ArrayList<>(evaluations.entrySet())) { + Map> ruleMaps = new ConcurrentHashMap<>(); + for (Map.Entry> ruleEntry : regionEntry.getValue().entrySet()) { + ruleMaps.put(ruleEntry.getKey(), new ConcurrentHashMap<>(ruleEntry.getValue())); + } + evaluations.put(regionEntry.getKey(), ruleMaps); + } + } + /** {@link StorageBackedMap} only flushes on a top-level put, so an in-place mutation of an * inner map must be written back by re-putting the outer entry. */ private void persistRegion(Map> resources, String region) { @@ -100,72 +173,468 @@ public class AwsConfigService { // --- Config Rules --- - public ConfigRule putConfigRule(String region, String ruleName, ConfigRuleSource source) { + public ConfigRule putConfigRule(String region, ConfigRule requested) { + if (requested == null || isBlank(requested.configRuleName())) { + throw new AwsException("InvalidParameterValueException", + "ConfigRuleName must be specified.", 400); + } + if (requested.source() == null || isBlank(requested.source().owner())) { + throw new AwsException("InvalidParameterValueException", + "Source with Owner must be specified.", 400); + } + // The whole modeled ConfigRule is stored and echoed back, so every enum-typed member + // it keeps is checked here rather than accepted verbatim. + requireEnum(requested.source().owner(), VALID_RULE_OWNERS, "Source.Owner"); + requireEnum(requested.maximumExecutionFrequency(), VALID_EXECUTION_FREQUENCIES, + "MaximumExecutionFrequency"); + requireEnum(requested.configRuleState(), VALID_RULE_STATES, "ConfigRuleState"); + if (requested.source().sourceDetails() != null) { + for (SourceDetail detail : requested.source().sourceDetails()) { + if (detail == null) { + continue; + } + requireEnum(detail.eventSource(), VALID_EVENT_SOURCES, "SourceDetails.EventSource"); + requireEnum(detail.messageType(), VALID_MESSAGE_TYPES, "SourceDetails.MessageType"); + requireEnum(detail.maximumExecutionFrequency(), VALID_EXECUTION_FREQUENCIES, + "SourceDetails.MaximumExecutionFrequency"); + } + } + if (requested.scope() != null && requested.scope().complianceResourceTypes() != null + && requested.scope().complianceResourceTypes().size() > MAX_COMPLIANCE_RESOURCE_TYPES) { + throw new AwsException("InvalidParameterValueException", + "Scope.ComplianceResourceTypes accepts at most " + + MAX_COMPLIANCE_RESOURCE_TYPES + " values.", 400); + } + if (requested.evaluationModes() != null) { + for (EvaluationModeConfiguration mode : requested.evaluationModes()) { + requireEnum(mode == null ? null : mode.mode(), VALID_EVALUATION_MODES, + "EvaluationModes.Mode"); + } + } + String ruleName = requested.configRuleName(); Map store = rulesFor(region); ConfigRule existing = store.get(ruleName); + String ruleId; + String ruleArn; + String state; if (existing != null) { - ConfigRule updated = new ConfigRule(existing.configRuleName(), existing.configRuleArn(), - existing.configRuleId(), existing.configRuleState(), source); - store.put(ruleName, updated); - persistRegion(configRules, region); - return updated; + ruleId = existing.configRuleId(); + ruleArn = existing.configRuleArn(); + state = existing.configRuleState(); + } else { + ruleId = "config-rule-" + shortId(); + ruleArn = AwsArnUtils.Arn.of("config", region, regionResolver.getAccountId(), + "config-rule/" + ruleId).toString(); + state = isBlank(requested.configRuleState()) ? "ACTIVE" : requested.configRuleState(); + ruleFirstActivatedTime.putIfAbsent(ruleKey(region, ruleName), now()); } - String ruleId = "config-rule-" + shortId(); - String ruleArn = AwsArnUtils.Arn.of("config", region, regionResolver.getAccountId(), - "config-rule/" + ruleId).toString(); - ConfigRule rule = new ConfigRule(ruleName, ruleArn, ruleId, "ACTIVE", source); + List evaluationModes = + requested.evaluationModes() == null || requested.evaluationModes().isEmpty() + ? List.of(new EvaluationModeConfiguration("DETECTIVE")) + : requested.evaluationModes(); + ConfigRule rule = new ConfigRule(ruleName, ruleArn, ruleId, requested.description(), + requested.scope(), requested.source(), requested.inputParameters(), + requested.maximumExecutionFrequency(), state, requested.createdBy(), evaluationModes); store.put(ruleName, rule); persistRegion(configRules, region); return rule; } public void deleteConfigRule(String region, String ruleName) { - Map store = rulesFor(region); - if (store.remove(ruleName) == null) { - throw new AwsException("NoSuchConfigRuleException", - "The ConfigRule provided in the request is invalid. " + - "Please check the configRule name.", 400); + if (isBlank(ruleName)) { + throw new AwsException("NoSuchConfigRuleException", NO_SUCH_CONFIG_RULE_MESSAGE, 400); + } + synchronized (lockFor(ruleKey(region, ruleName))) { + Map store = rulesFor(region); + if (store.remove(ruleName) == null) { + throw new AwsException("NoSuchConfigRuleException", NO_SUCH_CONFIG_RULE_MESSAGE, 400); + } + persistRegion(configRules, region); + Map> regionEvaluations = evaluations.get(region); + if (regionEvaluations != null && regionEvaluations.remove(ruleName) != null) { + persistRegion(evaluations, region); + } + ruleFirstActivatedTime.remove(ruleKey(region, ruleName)); + ruleLastInvokedTime.remove(ruleKey(region, ruleName)); } - persistRegion(configRules, region); } public List describeConfigRules(String region, List ruleNames) { - Map store = rulesFor(region); - if (ruleNames == null || ruleNames.isEmpty()) { - return new ArrayList<>(store.values()); + if (ruleNames != null && ruleNames.size() > MAX_DESCRIBE_CONFIG_RULE_NAMES) { + throw new AwsException("InvalidParameterValueException", + "ConfigRuleNames accepts at most " + MAX_DESCRIBE_CONFIG_RULE_NAMES + " values.", 400); } + Map store = rulesFor(region); List result = new ArrayList<>(); - for (String name : ruleNames) { - ConfigRule rule = store.get(name); - if (rule != null) { + if (ruleNames == null || ruleNames.isEmpty()) { + result.addAll(store.values()); + } else { + for (String name : ruleNames) { + ConfigRule rule = store.get(name); + if (rule == null) { + throw new AwsException("NoSuchConfigRuleException", NO_SUCH_CONFIG_RULE_MESSAGE, 400); + } result.add(rule); } } + result.sort(Comparator.comparing(ConfigRule::configRuleName)); return result; } - public List describeConfigRuleEvaluationStatus(String region, List ruleNames) { - List rules = describeConfigRules(region, ruleNames); - List result = new ArrayList<>(); - for (ConfigRule rule : rules) { - result.add(new ConfigRuleEvaluationStatus( - rule.configRuleName(), - rule.configRuleArn(), - rule.configRuleId(), - true)); + public Paged describeConfigRulesPaged(String region, List ruleNames, String nextToken) { + return paginate(describeConfigRules(region, ruleNames), null, nextToken, + 25, 25, "InvalidParameterValueException"); + } + + public Paged describeConfigRuleEvaluationStatus(String region, + List ruleNames, Integer limit, String nextToken) { + List statuses = new ArrayList<>(); + for (ConfigRule rule : describeConfigRules(region, ruleNames)) { + String key = ruleKey(region, rule.configRuleName()); + Map ruleEvaluations = + evaluationsFor(region).getOrDefault(rule.configRuleName(), Map.of()); + Long lastEvaluationTime = ruleEvaluations.values().stream() + .map(ConfigEvaluation::resultRecordedTime) + .filter(Objects::nonNull) + .max(Long::compareTo) + .orElse(ruleLastInvokedTime.get(key)); + boolean evaluationStarted = !ruleEvaluations.isEmpty() || ruleLastInvokedTime.containsKey(key); + statuses.add(new ConfigRuleEvaluationStatus( + rule.configRuleName(), rule.configRuleArn(), rule.configRuleId(), + evaluationStarted, ruleFirstActivatedTime.get(key), + lastEvaluationTime, lastEvaluationTime)); } - return result; + return paginate(statuses, limit, nextToken, 150, 150, "InvalidParameterValueException"); } public void startConfigRulesEvaluation(String region, List ruleNames) { Map store = rulesFor(region); for (String name : ruleNames) { if (!store.containsKey(name)) { - throw new AwsException("NoSuchConfigRuleException", - "The ConfigRule provided in the request is invalid. " + - "Please check the configRule name.", 400); + throw new AwsException("NoSuchConfigRuleException", NO_SUCH_CONFIG_RULE_MESSAGE, 400); } } + for (String name : ruleNames) { + ruleLastInvokedTime.put(ruleKey(region, name), now()); + } + } + + // --- Evaluations --- + + public void putEvaluations(String region, String resultToken, List newEvaluations, + boolean testMode) { + if (isBlank(resultToken)) { + throw new AwsException("InvalidResultTokenException", + "The specified ResultToken is not valid.", 400); + } + if (newEvaluations.size() > 100) { + throw new AwsException("InvalidParameterValueException", + "The Evaluations list cannot contain more than 100 items.", 400); + } + newEvaluations.forEach(this::validateEvaluation); + if (testMode) { + return; + } + int separator = resultToken.indexOf(':'); + String ruleName = separator > 0 ? resultToken.substring(0, separator) : resultToken; + synchronized (lockFor(ruleKey(region, ruleName))) { + requireRule(region, ruleName); + storeEvaluations(region, ruleName, newEvaluations); + } + } + + public void putExternalEvaluation(String region, String ruleName, ConfigEvaluation evaluation) { + validateEvaluation(evaluation); + synchronized (lockFor(ruleKey(region, ruleName))) { + requireRule(region, ruleName); + storeEvaluations(region, ruleName, List.of(evaluation)); + } + } + + public void deleteEvaluationResults(String region, String ruleName) { + synchronized (lockFor(ruleKey(region, ruleName))) { + requireRule(region, ruleName); + Map> regionEvaluations = evaluations.get(region); + if (regionEvaluations != null && regionEvaluations.remove(ruleName) != null) { + persistRegion(evaluations, region); + } + } + } + + private void validateEvaluation(ConfigEvaluation evaluation) { + if (evaluation == null || isBlank(evaluation.complianceResourceType()) + || isBlank(evaluation.complianceResourceId()) || isBlank(evaluation.complianceType()) + || evaluation.orderingTimestamp() == null) { + throw new AwsException("InvalidParameterValueException", + "Each evaluation must specify ComplianceResourceType, ComplianceResourceId, " + + "ComplianceType and OrderingTimestamp.", 400); + } + if (!VALID_COMPLIANCE_TYPES.contains(evaluation.complianceType())) { + throw new AwsException("InvalidParameterValueException", + "ComplianceType must be one of COMPLIANT, NON_COMPLIANT, NOT_APPLICABLE, " + + "INSUFFICIENT_DATA.", 400); + } + } + + private void storeEvaluations(String region, String ruleName, List newEvaluations) { + long recordedTime = now(); + Map ruleEvaluations = evaluationsFor(region) + .computeIfAbsent(ruleName, r -> new ConcurrentHashMap<>()); + for (ConfigEvaluation evaluation : newEvaluations) { + String key = resourceKey(evaluation.complianceResourceType(), evaluation.complianceResourceId()); + ruleEvaluations.compute(key, (ignoredKey, current) -> { + if (current != null && current.orderingTimestamp() != null + && evaluation.orderingTimestamp() < current.orderingTimestamp()) { + return current; + } + return new ConfigEvaluation( + evaluation.complianceResourceType(), + evaluation.complianceResourceId(), + evaluation.complianceType(), + evaluation.annotation(), + evaluation.orderingTimestamp(), + recordedTime, + recordedTime); + }); + } + ruleLastInvokedTime.put(ruleKey(region, ruleName), recordedTime); + persistRegion(evaluations, region); + } + + // --- Compliance --- + + public Compliance complianceForRule(String region, String ruleName) { + List applicable = evaluationsFor(region) + .getOrDefault(ruleName, Map.of()).values().stream() + .filter(e -> !"NOT_APPLICABLE".equals(e.complianceType())) + .toList(); + if (applicable.isEmpty()) { + return new Compliance("INSUFFICIENT_DATA", null); + } + long nonCompliant = applicable.stream() + .filter(e -> "NON_COMPLIANT".equals(e.complianceType())) + .count(); + if (nonCompliant > 0) { + return new Compliance("NON_COMPLIANT", contributorCount(nonCompliant, RULE_CONTRIBUTOR_CAP)); + } + if (applicable.stream().anyMatch(e -> "INSUFFICIENT_DATA".equals(e.complianceType()))) { + return new Compliance("INSUFFICIENT_DATA", null); + } + return new Compliance("COMPLIANT", null); + } + + public Paged describeComplianceByConfigRule(String region, List ruleNames, + List complianceTypes, String nextToken) { + validateComplianceTypeFilter(complianceTypes); + List entries = new ArrayList<>(); + for (ConfigRule rule : describeConfigRules(region, ruleNames)) { + Compliance compliance = complianceForRule(region, rule.configRuleName()); + if (matchesComplianceFilter(complianceTypes, compliance.complianceType())) { + entries.add(new ComplianceByConfigRule(rule.configRuleName(), compliance)); + } + } + return paginate(entries, null, nextToken, 25, 25, "InvalidParameterValueException"); + } + + public Paged describeComplianceByResource(String region, String resourceType, + String resourceId, List complianceTypes, Integer limit, String nextToken) { + validateComplianceTypeFilter(complianceTypes); + if (!isBlank(resourceId) && isBlank(resourceType)) { + throw new AwsException("InvalidParameterValueException", + "ResourceType must be specified when ResourceId is provided.", 400); + } + List entries = new ArrayList<>(); + for (List resourceEvaluations + : groupEvaluationsByResource(region, resourceType, resourceId).values()) { + ConfigEvaluation first = resourceEvaluations.get(0); + Compliance compliance = complianceForResource(resourceEvaluations); + if (matchesComplianceFilter(complianceTypes, compliance.complianceType())) { + entries.add(new ComplianceByResource(first.complianceResourceType(), + first.complianceResourceId(), compliance)); + } + } + entries.sort(Comparator.comparing(ComplianceByResource::resourceType) + .thenComparing(ComplianceByResource::resourceId)); + return paginate(entries, limit, nextToken, 10, 100, "InvalidParameterValueException"); + } + + public Paged getComplianceDetailsByConfigRule(String region, String ruleName, + List complianceTypes, Integer limit, String nextToken) { + validateComplianceTypeFilter(complianceTypes); + requireRule(region, ruleName); + List results = evaluationsFor(region) + .getOrDefault(ruleName, Map.of()).values().stream() + .filter(e -> matchesComplianceFilter(complianceTypes, e.complianceType())) + .sorted(Comparator.comparing(ConfigEvaluation::complianceResourceType) + .thenComparing(ConfigEvaluation::complianceResourceId)) + .map(e -> toEvaluationResult(ruleName, e)) + .collect(Collectors.toList()); + return paginate(results, limit, nextToken, 10, 100, "InvalidParameterValueException"); + } + + public Paged getComplianceDetailsByResource(String region, String resourceType, + String resourceId, List complianceTypes, String nextToken) { + validateComplianceTypeFilter(complianceTypes); + if (isBlank(resourceType) || isBlank(resourceId)) { + throw new AwsException("InvalidParameterValueException", + "ResourceType and ResourceId must be specified.", 400); + } + String key = resourceKey(resourceType, resourceId); + List results = new ArrayList<>(); + evaluationsFor(region).forEach((ruleName, ruleEvaluations) -> { + ConfigEvaluation evaluation = ruleEvaluations.get(key); + if (evaluation != null && matchesComplianceFilter(complianceTypes, evaluation.complianceType())) { + results.add(toEvaluationResult(ruleName, evaluation)); + } + }); + results.sort(Comparator.comparing(r -> + r.evaluationResultIdentifier().evaluationResultQualifier().configRuleName())); + return paginate(results, null, nextToken, 10, 10, "InvalidParameterValueException"); + } + + public ComplianceSummary getComplianceSummaryByConfigRule(String region) { + long compliant = 0; + long nonCompliant = 0; + for (String ruleName : rulesFor(region).keySet()) { + String complianceType = complianceForRule(region, ruleName).complianceType(); + if ("COMPLIANT".equals(complianceType)) { + compliant++; + } else if ("NON_COMPLIANT".equals(complianceType)) { + nonCompliant++; + } + } + return new ComplianceSummary(contributorCount(compliant, RULE_CONTRIBUTOR_CAP), + contributorCount(nonCompliant, RULE_CONTRIBUTOR_CAP), now()); + } + + public List getComplianceSummaryByResourceType(String region, + List resourceTypes) { + if (resourceTypes != null && resourceTypes.size() > 20) { + throw new AwsException("InvalidParameterValueException", + "ResourceTypes cannot contain more than 20 items.", 400); + } + Map countsByType = new HashMap<>(); + for (List resourceEvaluations + : groupEvaluationsByResource(region, null, null).values()) { + String type = resourceEvaluations.get(0).complianceResourceType(); + String complianceType = complianceForResource(resourceEvaluations).complianceType(); + long[] counts = countsByType.computeIfAbsent(type, t -> new long[2]); + if ("COMPLIANT".equals(complianceType)) { + counts[0]++; + } else if ("NON_COMPLIANT".equals(complianceType)) { + counts[1]++; + } + } + long timestamp = now(); + if (resourceTypes == null || resourceTypes.isEmpty()) { + long compliant = countsByType.values().stream().mapToLong(c -> c[0]).sum(); + long nonCompliant = countsByType.values().stream().mapToLong(c -> c[1]).sum(); + return List.of(new ComplianceSummaryByResourceType(null, new ComplianceSummary( + contributorCount(compliant, RESOURCE_CONTRIBUTOR_CAP), + contributorCount(nonCompliant, RESOURCE_CONTRIBUTOR_CAP), timestamp))); + } + List result = new ArrayList<>(); + for (String type : resourceTypes) { + long[] counts = countsByType.getOrDefault(type, new long[2]); + result.add(new ComplianceSummaryByResourceType(type, new ComplianceSummary( + contributorCount(counts[0], RESOURCE_CONTRIBUTOR_CAP), + contributorCount(counts[1], RESOURCE_CONTRIBUTOR_CAP), timestamp))); + } + return result; + } + + private Map> groupEvaluationsByResource(String region, + String resourceType, String resourceId) { + Map> byResource = new HashMap<>(); + for (Map ruleEvaluations : evaluationsFor(region).values()) { + for (ConfigEvaluation evaluation : ruleEvaluations.values()) { + if (!isBlank(resourceType) && !resourceType.equals(evaluation.complianceResourceType())) { + continue; + } + if (!isBlank(resourceId) && !resourceId.equals(evaluation.complianceResourceId())) { + continue; + } + String key = resourceKey(evaluation.complianceResourceType(), + evaluation.complianceResourceId()); + byResource.computeIfAbsent(key, k -> new ArrayList<>()).add(evaluation); + } + } + return byResource; + } + + private Compliance complianceForResource(List resourceEvaluations) { + long nonCompliant = resourceEvaluations.stream() + .filter(e -> "NON_COMPLIANT".equals(e.complianceType())) + .count(); + if (nonCompliant > 0) { + return new Compliance("NON_COMPLIANT", contributorCount(nonCompliant, RULE_CONTRIBUTOR_CAP)); + } + if (resourceEvaluations.stream().anyMatch(e -> "INSUFFICIENT_DATA".equals(e.complianceType()))) { + return new Compliance("INSUFFICIENT_DATA", null); + } + if (resourceEvaluations.stream().anyMatch(e -> "COMPLIANT".equals(e.complianceType()))) { + return new Compliance("COMPLIANT", null); + } + return new Compliance("NOT_APPLICABLE", null); + } + + private EvaluationResult toEvaluationResult(String ruleName, ConfigEvaluation evaluation) { + return new EvaluationResult( + new EvaluationResultIdentifier( + new EvaluationResultQualifier(ruleName, evaluation.complianceResourceType(), + evaluation.complianceResourceId(), "DETECTIVE"), + evaluation.orderingTimestamp()), + evaluation.complianceType(), + evaluation.resultRecordedTime(), + evaluation.configRuleInvokedTime(), + evaluation.annotation(), + null); + } + + private static boolean matchesComplianceFilter(List complianceTypes, String complianceType) { + return complianceTypes == null || complianceTypes.isEmpty() || complianceTypes.contains(complianceType); + } + + /** + * A {@code ComplianceTypes} filter outside the modeled enum (or longer than the list's + * {@code max: 3}) would otherwise match nothing and read to the caller as "no results" + * instead of the rejection AWS answers. + */ + private static void validateComplianceTypeFilter(List complianceTypes) { + if (complianceTypes == null || complianceTypes.isEmpty()) { + return; + } + if (complianceTypes.size() > MAX_COMPLIANCE_TYPE_FILTERS) { + throw new AwsException("InvalidParameterValueException", + "ComplianceTypes accepts at most " + MAX_COMPLIANCE_TYPE_FILTERS + " values.", 400); + } + for (String complianceType : complianceTypes) { + requireEnum(complianceType, VALID_COMPLIANCE_TYPES, "ComplianceTypes"); + } + } + + /** Rejects a non-blank value that is not a member of the shape's enum; a null/blank value is left alone. */ + private static void requireEnum(String value, Set allowed, String memberName) { + if (isBlank(value) || allowed.contains(value)) { + return; + } + throw new AwsException("InvalidParameterValueException", + "Value '" + value + "' at '" + memberName + "' failed to satisfy constraint: " + + "Member must satisfy enum value set: [" + + allowed.stream().sorted().collect(Collectors.joining(", ")) + "]", + 400); + } + + private ComplianceContributorCount contributorCount(long count, int cap) { + return new ComplianceContributorCount((int) Math.min(count, cap), count > cap); + } + + private ConfigRule requireRule(String region, String ruleName) { + ConfigRule rule = isBlank(ruleName) ? null : rulesFor(region).get(ruleName); + if (rule == null) { + throw new AwsException("NoSuchConfigRuleException", NO_SUCH_CONFIG_RULE_MESSAGE, 400); + } + return rule; } // --- Configuration Recorder --- @@ -196,6 +665,18 @@ public class AwsConfigService { return List.of(recorder); } + public void deleteConfigurationRecorder(String region, String name) { + ConfigurationRecorder recorder = configurationRecorders.get(region); + if (recorder == null || !recorder.name().equals(name)) { + throw new AwsException("NoSuchConfigurationRecorderException", + "Cannot find configuration recorder with the specified name.", 400); + } + configurationRecorders.remove(region); + recorderRunning.remove(region); + recorderLastStartTime.remove(region); + recorderLastStopTime.remove(region); + } + public void startConfigurationRecorder(String region, String name) { ConfigurationRecorder recorder = configurationRecorders.get(region); if (recorder == null || !recorder.name().equals(name)) { @@ -203,7 +684,7 @@ public class AwsConfigService { "Cannot find configuration recorder with the specified name.", 400); } recorderRunning.put(region, true); - recorderLastStartTime.put(region, System.currentTimeMillis() / 1000); + recorderLastStartTime.put(region, now()); } public void stopConfigurationRecorder(String region, String name) { @@ -213,7 +694,7 @@ public class AwsConfigService { "Cannot find configuration recorder with the specified name.", 400); } recorderRunning.put(region, false); - recorderLastStopTime.put(region, System.currentTimeMillis() / 1000); + recorderLastStopTime.put(region, now()); } public List describeConfigurationRecorderStatus(String region, List names) { @@ -275,6 +756,58 @@ public class AwsConfigService { return List.of(channel); } + public void deleteDeliveryChannel(String region, String name) { + DeliveryChannel channel = deliveryChannels.get(region); + if (channel == null || !channel.name().equals(name)) { + throw new AwsException("NoSuchDeliveryChannelException", + "Cannot find delivery channel with the specified name.", 400); + } + if (recorderRunning.getOrDefault(region, false)) { + throw new AwsException("LastDeliveryChannelDeleteFailedException", + "You cannot delete the delivery channel you specified because the customer managed " + + "configuration recorder is running.", 400); + } + deliveryChannels.remove(region); + } + + // --- Retention Configuration --- + + public RetentionConfiguration putRetentionConfiguration(String region, Integer retentionPeriodInDays) { + if (retentionPeriodInDays == null || retentionPeriodInDays < 30 || retentionPeriodInDays > 2557) { + throw new AwsException("InvalidParameterValueException", + "RetentionPeriodInDays must be between 30 and 2557.", 400); + } + RetentionConfiguration configuration = new RetentionConfiguration("default", retentionPeriodInDays); + retentionConfigurations.put(region, configuration); + return configuration; + } + + public List describeRetentionConfigurations(String region, List names) { + RetentionConfiguration configuration = retentionConfigurations.get(region); + if (names != null && !names.isEmpty()) { + for (String name : names) { + if (configuration == null || !configuration.name().equals(name)) { + throw new AwsException("NoSuchRetentionConfigurationException", + "Cannot find retention configuration with the specified name.", 400); + } + } + } + return configuration == null ? Collections.emptyList() : List.of(configuration); + } + + public void deleteRetentionConfiguration(String region, String name) { + if (isBlank(name)) { + throw new AwsException("InvalidParameterValueException", + "RetentionConfigurationName must be specified.", 400); + } + RetentionConfiguration configuration = retentionConfigurations.get(region); + if (configuration == null || !configuration.name().equals(name)) { + throw new AwsException("NoSuchRetentionConfigurationException", + "Cannot find retention configuration with the specified name.", 400); + } + retentionConfigurations.remove(region); + } + // --- Conformance Packs --- public ConformancePack putConformancePack(String region, String packName, @@ -308,33 +841,41 @@ public class AwsConfigService { public List describeConformancePacks(String region, List names) { Map store = packsFor(region); - if (names == null || names.isEmpty()) { - return new ArrayList<>(store.values()); - } List result = new ArrayList<>(); - for (String name : names) { - ConformancePack pack = store.get(name); - if (pack == null) { - throw new AwsException("NoSuchConformancePackException", - "Conformance pack '" + name + "' does not exist.", 400); + if (names == null || names.isEmpty()) { + result.addAll(store.values()); + } else { + for (String name : names) { + ConformancePack pack = store.get(name); + if (pack == null) { + throw new AwsException("NoSuchConformancePackException", + "Conformance pack '" + name + "' does not exist.", 400); + } + result.add(pack); } - result.add(pack); } + result.sort(Comparator.comparing(ConformancePack::conformancePackName)); return result; } - public List describeConformancePackStatus(String region, List names) { - List packs = describeConformancePacks(region, names); + public Paged describeConformancePacksPaged(String region, List names, + Integer limit, String nextToken) { + return paginate(describeConformancePacks(region, names), limit, nextToken, + 20, 20, "InvalidLimitException"); + } + + public Paged describeConformancePackStatus(String region, List names, + Integer limit, String nextToken) { List result = new ArrayList<>(); - for (ConformancePack pack : packs) { + for (ConformancePack pack : describeConformancePacks(region, names)) { result.add(new ConformancePackStatusDetail( pack.conformancePackName(), pack.conformancePackId(), pack.conformancePackArn(), "CREATE_SUCCESSFUL", - System.currentTimeMillis() / 1000)); + now())); } - return result; + return paginate(result, limit, nextToken, 20, 20, "InvalidLimitException"); } // --- Tagging --- @@ -362,6 +903,38 @@ public class AwsConfigService { .collect(Collectors.toList()); } + // --- Pagination --- + + public record Paged(List items, String nextToken) {} + + /** Offset-as-NextToken pagination over a pre-sorted list. A null or zero limit falls back to + * the default page size; limits outside [1, maxLimit] fail with the op-specific error code. */ + private Paged paginate(List items, Integer limit, String nextToken, + int defaultPageSize, int maxLimit, String limitErrorCode) { + int pageSize = defaultPageSize; + if (limit != null && limit != 0) { + if (limit < 0 || limit > maxLimit) { + throw new AwsException(limitErrorCode, + "Limit must be between 0 and " + maxLimit + ".", 400); + } + pageSize = limit; + } + int offset = 0; + if (nextToken != null && !nextToken.isEmpty()) { + try { + offset = Integer.parseInt(nextToken); + } catch (NumberFormatException e) { + throw new AwsException("InvalidNextTokenException", INVALID_NEXT_TOKEN_MESSAGE, 400); + } + if (offset < 0 || offset > items.size()) { + throw new AwsException("InvalidNextTokenException", INVALID_NEXT_TOKEN_MESSAGE, 400); + } + } + int end = Math.min(offset + pageSize, items.size()); + List page = new ArrayList<>(items.subList(offset, end)); + return new Paged<>(page, end < items.size() ? String.valueOf(end) : null); + } + // --- Helpers --- private Map rulesFor(String region) { @@ -372,6 +945,30 @@ public class AwsConfigService { return conformancePacks.computeIfAbsent(region, r -> new ConcurrentHashMap<>()); } + private Map> evaluationsFor(String region) { + return evaluations.computeIfAbsent(region, r -> new ConcurrentHashMap<>()); + } + + private static String resourceKey(String resourceType, String resourceId) { + return resourceType + "|" + resourceId; + } + + private static String ruleKey(String region, String ruleName) { + return region + "|" + ruleName; + } + + private Object lockFor(String key) { + return ruleLocks.computeIfAbsent(key, k -> new Object()); + } + + private static boolean isBlank(String value) { + return value == null || value.isBlank(); + } + + private static long now() { + return System.currentTimeMillis() / 1000; + } + private static String shortId() { return UUID.randomUUID().toString().replace("-", "").substring(0, 12); } diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/ConfigServiceJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/configservice/ConfigServiceJsonHandler.java index 7b590552a0..255269b648 100644 --- a/src/main/java/io/github/hectorvent/floci/services/configservice/ConfigServiceJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/ConfigServiceJsonHandler.java @@ -2,21 +2,20 @@ package io.github.hectorvent.floci.services.configservice; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.services.configservice.model.ConfigEvaluation; import io.github.hectorvent.floci.services.configservice.model.ConfigRule; -import io.github.hectorvent.floci.services.configservice.model.ConfigRuleEvaluationStatus; -import io.github.hectorvent.floci.services.configservice.model.ConfigRuleSource; import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorder; import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorderStatus; import io.github.hectorvent.floci.services.configservice.model.ConformancePack; -import io.github.hectorvent.floci.services.configservice.model.ConformancePackStatusDetail; import io.github.hectorvent.floci.services.configservice.model.DeliveryChannel; +import io.github.hectorvent.floci.services.configservice.model.RetentionConfiguration; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; @@ -38,19 +37,32 @@ public class ConfigServiceJsonHandler { case "DeleteConfigRule" -> deleteConfigRule(request, region); case "DescribeConfigRules" -> describeConfigRules(request, region); case "DescribeComplianceByConfigRule" -> describeComplianceByConfigRule(request, region); + case "DescribeComplianceByResource" -> describeComplianceByResource(request, region); case "DescribeConfigRuleEvaluationStatus" -> describeConfigRuleEvaluationStatus(request, region); case "StartConfigRulesEvaluation" -> startConfigRulesEvaluation(request, region); + case "PutEvaluations" -> putEvaluations(request, region); + case "PutExternalEvaluation" -> putExternalEvaluation(request, region); + case "DeleteEvaluationResults" -> deleteEvaluationResults(request, region); + case "GetComplianceDetailsByConfigRule" -> getComplianceDetailsByConfigRule(request, region); + case "GetComplianceDetailsByResource" -> getComplianceDetailsByResource(request, region); + case "GetComplianceSummaryByConfigRule" -> getComplianceSummaryByConfigRule(region); + case "GetComplianceSummaryByResourceType" -> getComplianceSummaryByResourceType(request, region); case "PutConformancePack" -> putConformancePack(request, region); case "DeleteConformancePack" -> deleteConformancePack(request, region); case "DescribeConformancePacks" -> describeConformancePacks(request, region); case "DescribeConformancePackStatus" -> describeConformancePackStatus(request, region); case "PutConfigurationRecorder" -> putConfigurationRecorder(request, region); case "DescribeConfigurationRecorders" -> describeConfigurationRecorders(request, region); + case "DeleteConfigurationRecorder" -> deleteConfigurationRecorder(request, region); case "StartConfigurationRecorder" -> startConfigurationRecorder(request, region); case "StopConfigurationRecorder" -> stopConfigurationRecorder(request, region); case "DescribeConfigurationRecorderStatus" -> describeConfigurationRecorderStatus(request, region); case "PutDeliveryChannel" -> putDeliveryChannel(request, region); case "DescribeDeliveryChannels" -> describeDeliveryChannels(request, region); + case "DeleteDeliveryChannel" -> deleteDeliveryChannel(request, region); + case "PutRetentionConfiguration" -> putRetentionConfiguration(request, region); + case "DescribeRetentionConfigurations" -> describeRetentionConfigurations(request, region); + case "DeleteRetentionConfiguration" -> deleteRetentionConfiguration(request, region); case "TagResource" -> tagResource(request); case "UntagResource" -> untagResource(request); case "ListTagsForResource" -> listTagsForResource(request); @@ -61,14 +73,10 @@ public class ConfigServiceJsonHandler { // --- Config Rules --- - private Response putConfigRule(JsonNode req, String region) { + private Response putConfigRule(JsonNode req, String region) throws Exception { JsonNode ruleNode = req.path("ConfigRule"); - String ruleName = ruleNode.path("ConfigRuleName").asText(null); - JsonNode sourceNode = ruleNode.path("Source"); - ConfigRuleSource source = new ConfigRuleSource( - sourceNode.path("Owner").asText(null), - sourceNode.path("SourceIdentifier").asText(null)); - service.putConfigRule(region, ruleName, source); + ConfigRule rule = ruleNode.isObject() ? mapper.treeToValue(ruleNode, ConfigRule.class) : null; + service.putConfigRule(region, rule); return Response.ok(mapper.createObjectNode()).build(); } @@ -79,35 +87,33 @@ public class ConfigServiceJsonHandler { } private Response describeConfigRules(JsonNode req, String region) { - List ruleNames = extractStringList(req, "ConfigRuleNames"); - List rules = service.describeConfigRules(region, ruleNames); - ObjectNode resp = mapper.createObjectNode(); - resp.set("ConfigRules", mapper.valueToTree(rules)); - return Response.ok(resp).build(); + AwsConfigService.Paged page = service.describeConfigRulesPaged(region, + extractStringList(req, "ConfigRuleNames"), extractNextToken(req)); + return Response.ok(pagedResponse("ConfigRules", page)).build(); } private Response describeComplianceByConfigRule(JsonNode req, String region) { - List ruleNames = extractStringList(req, "ConfigRuleNames"); - List rules = service.describeConfigRules(region, ruleNames); - ObjectNode resp = mapper.createObjectNode(); - ArrayNode arr = resp.putArray("ComplianceByConfigRules"); - for (ConfigRule rule : rules) { - ObjectNode entry = mapper.createObjectNode(); - entry.put("ConfigRuleName", rule.configRuleName()); - ObjectNode compliance = mapper.createObjectNode(); - compliance.put("ComplianceType", "INSUFFICIENT_DATA"); - entry.set("Compliance", compliance); - arr.add(entry); - } - return Response.ok(resp).build(); + var page = service.describeComplianceByConfigRule(region, + extractStringList(req, "ConfigRuleNames"), + extractStringList(req, "ComplianceTypes"), + extractNextToken(req)); + return Response.ok(pagedResponse("ComplianceByConfigRules", page)).build(); + } + + private Response describeComplianceByResource(JsonNode req, String region) { + var page = service.describeComplianceByResource(region, + req.path("ResourceType").asText(null), + req.path("ResourceId").asText(null), + extractStringList(req, "ComplianceTypes"), + extractLimit(req, "Limit"), extractNextToken(req)); + return Response.ok(pagedResponse("ComplianceByResources", page)).build(); } private Response describeConfigRuleEvaluationStatus(JsonNode req, String region) { - List ruleNames = extractStringList(req, "ConfigRuleNames"); - List statuses = service.describeConfigRuleEvaluationStatus(region, ruleNames); - ObjectNode resp = mapper.createObjectNode(); - resp.set("ConfigRulesEvaluationStatus", mapper.valueToTree(statuses)); - return Response.ok(resp).build(); + var page = service.describeConfigRuleEvaluationStatus(region, + extractStringList(req, "ConfigRuleNames"), + extractLimit(req, "Limit"), extractNextToken(req)); + return Response.ok(pagedResponse("ConfigRulesEvaluationStatus", page)).build(); } private Response startConfigRulesEvaluation(JsonNode req, String region) { @@ -116,6 +122,66 @@ public class ConfigServiceJsonHandler { return Response.ok(mapper.createObjectNode()).build(); } + // --- Evaluations --- + + private Response putEvaluations(JsonNode req, String region) throws Exception { + JsonNode evaluationsNode = req.path("Evaluations"); + List evaluations = evaluationsNode.isArray() + ? Arrays.asList(mapper.treeToValue(evaluationsNode, ConfigEvaluation[].class)) + : List.of(); + service.putEvaluations(region, + req.path("ResultToken").asText(null), + evaluations, + req.path("TestMode").asBoolean(false)); + ObjectNode resp = mapper.createObjectNode(); + resp.putArray("FailedEvaluations"); + return Response.ok(resp).build(); + } + + private Response putExternalEvaluation(JsonNode req, String region) throws Exception { + JsonNode evaluationNode = req.path("ExternalEvaluation"); + ConfigEvaluation evaluation = evaluationNode.isObject() + ? mapper.treeToValue(evaluationNode, ConfigEvaluation.class) + : null; + service.putExternalEvaluation(region, req.path("ConfigRuleName").asText(null), evaluation); + return Response.ok(mapper.createObjectNode()).build(); + } + + private Response deleteEvaluationResults(JsonNode req, String region) { + service.deleteEvaluationResults(region, req.path("ConfigRuleName").asText(null)); + return Response.ok(mapper.createObjectNode()).build(); + } + + private Response getComplianceDetailsByConfigRule(JsonNode req, String region) { + var page = service.getComplianceDetailsByConfigRule(region, + req.path("ConfigRuleName").asText(null), + extractStringList(req, "ComplianceTypes"), + extractLimit(req, "Limit"), extractNextToken(req)); + return Response.ok(pagedResponse("EvaluationResults", page)).build(); + } + + private Response getComplianceDetailsByResource(JsonNode req, String region) { + var page = service.getComplianceDetailsByResource(region, + req.path("ResourceType").asText(null), + req.path("ResourceId").asText(null), + extractStringList(req, "ComplianceTypes"), + extractNextToken(req)); + return Response.ok(pagedResponse("EvaluationResults", page)).build(); + } + + private Response getComplianceSummaryByConfigRule(String region) { + ObjectNode resp = mapper.createObjectNode(); + resp.set("ComplianceSummary", mapper.valueToTree(service.getComplianceSummaryByConfigRule(region))); + return Response.ok(resp).build(); + } + + private Response getComplianceSummaryByResourceType(JsonNode req, String region) { + ObjectNode resp = mapper.createObjectNode(); + resp.set("ComplianceSummariesByResourceType", mapper.valueToTree( + service.getComplianceSummaryByResourceType(region, extractStringList(req, "ResourceTypes")))); + return Response.ok(resp).build(); + } + // --- Configuration Recorder --- private Response putConfigurationRecorder(JsonNode req, String region) throws Exception { @@ -132,6 +198,11 @@ public class ConfigServiceJsonHandler { return Response.ok(resp).build(); } + private Response deleteConfigurationRecorder(JsonNode req, String region) { + service.deleteConfigurationRecorder(region, req.path("ConfigurationRecorderName").asText(null)); + return Response.ok(mapper.createObjectNode()).build(); + } + private Response startConfigurationRecorder(JsonNode req, String region) { String name = req.path("ConfigurationRecorderName").asText(null); service.startConfigurationRecorder(region, name); @@ -168,6 +239,34 @@ public class ConfigServiceJsonHandler { return Response.ok(resp).build(); } + private Response deleteDeliveryChannel(JsonNode req, String region) { + service.deleteDeliveryChannel(region, req.path("DeliveryChannelName").asText(null)); + return Response.ok(mapper.createObjectNode()).build(); + } + + // --- Retention Configuration --- + + private Response putRetentionConfiguration(JsonNode req, String region) { + Integer days = req.hasNonNull("RetentionPeriodInDays") ? req.path("RetentionPeriodInDays").asInt() : null; + RetentionConfiguration configuration = service.putRetentionConfiguration(region, days); + ObjectNode resp = mapper.createObjectNode(); + resp.set("RetentionConfiguration", mapper.valueToTree(configuration)); + return Response.ok(resp).build(); + } + + private Response describeRetentionConfigurations(JsonNode req, String region) { + List configurations = service.describeRetentionConfigurations(region, + extractStringList(req, "RetentionConfigurationNames")); + ObjectNode resp = mapper.createObjectNode(); + resp.set("RetentionConfigurations", mapper.valueToTree(configurations)); + return Response.ok(resp).build(); + } + + private Response deleteRetentionConfiguration(JsonNode req, String region) { + service.deleteRetentionConfiguration(region, req.path("RetentionConfigurationName").asText(null)); + return Response.ok(mapper.createObjectNode()).build(); + } + // --- Conformance Packs --- private Response putConformancePack(JsonNode req, String region) { @@ -187,19 +286,17 @@ public class ConfigServiceJsonHandler { } private Response describeConformancePacks(JsonNode req, String region) { - List names = extractStringList(req, "ConformancePackNames"); - List packs = service.describeConformancePacks(region, names); - ObjectNode resp = mapper.createObjectNode(); - resp.set("ConformancePackDetails", mapper.valueToTree(packs)); - return Response.ok(resp).build(); + var page = service.describeConformancePacksPaged(region, + extractStringList(req, "ConformancePackNames"), + extractLimit(req, "Limit"), extractNextToken(req)); + return Response.ok(pagedResponse("ConformancePackDetails", page)).build(); } private Response describeConformancePackStatus(JsonNode req, String region) { - List names = extractStringList(req, "ConformancePackNames"); - List statuses = service.describeConformancePackStatus(region, names); - ObjectNode resp = mapper.createObjectNode(); - resp.set("ConformancePackStatusDetails", mapper.valueToTree(statuses)); - return Response.ok(resp).build(); + var page = service.describeConformancePackStatus(region, + extractStringList(req, "ConformancePackNames"), + extractLimit(req, "Limit"), extractNextToken(req)); + return Response.ok(pagedResponse("ConformancePackStatusDetails", page)).build(); } // --- Tagging --- @@ -239,4 +336,25 @@ public class ConfigServiceJsonHandler { } return result; } + + private Integer extractLimit(JsonNode req) { + return extractLimit(req, "MaxResults"); + } + + private Integer extractLimit(JsonNode req, String fieldName) { + return req.hasNonNull(fieldName) ? req.path(fieldName).asInt() : null; + } + + private String extractNextToken(JsonNode req) { + return req.hasNonNull("NextToken") ? req.path("NextToken").asText() : null; + } + + private ObjectNode pagedResponse(String fieldName, AwsConfigService.Paged page) { + ObjectNode resp = mapper.createObjectNode(); + resp.set(fieldName, mapper.valueToTree(page.items())); + if (page.nextToken() != null) { + resp.put("NextToken", page.nextToken()); + } + return resp; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/Compliance.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/Compliance.java new file mode 100644 index 0000000000..6c6b4f93b4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/Compliance.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record Compliance( + @JsonProperty("ComplianceType") String complianceType, + @JsonProperty("ComplianceContributorCount") ComplianceContributorCount complianceContributorCount) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceByConfigRule.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceByConfigRule.java new file mode 100644 index 0000000000..48116bfeb8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceByConfigRule.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ComplianceByConfigRule( + @JsonProperty("ConfigRuleName") String configRuleName, + @JsonProperty("Compliance") Compliance compliance) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceByResource.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceByResource.java new file mode 100644 index 0000000000..92b97a2d7d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceByResource.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ComplianceByResource( + @JsonProperty("ResourceType") String resourceType, + @JsonProperty("ResourceId") String resourceId, + @JsonProperty("Compliance") Compliance compliance) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceContributorCount.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceContributorCount.java new file mode 100644 index 0000000000..e030411d85 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceContributorCount.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ComplianceContributorCount( + @JsonProperty("CappedCount") Integer cappedCount, + @JsonProperty("CapExceeded") Boolean capExceeded) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceSummary.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceSummary.java new file mode 100644 index 0000000000..a7105030c8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceSummary.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ComplianceSummary( + @JsonProperty("CompliantResourceCount") ComplianceContributorCount compliantResourceCount, + @JsonProperty("NonCompliantResourceCount") ComplianceContributorCount nonCompliantResourceCount, + @JsonProperty("ComplianceSummaryTimestamp") Long complianceSummaryTimestamp) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceSummaryByResourceType.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceSummaryByResourceType.java new file mode 100644 index 0000000000..f7861634f2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ComplianceSummaryByResourceType.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ComplianceSummaryByResourceType( + @JsonProperty("ResourceType") String resourceType, + @JsonProperty("ComplianceSummary") ComplianceSummary complianceSummary) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigEvaluation.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigEvaluation.java new file mode 100644 index 0000000000..07b39cbbf0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigEvaluation.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ConfigEvaluation( + @JsonProperty("ComplianceResourceType") String complianceResourceType, + @JsonProperty("ComplianceResourceId") String complianceResourceId, + @JsonProperty("ComplianceType") String complianceType, + @JsonProperty("Annotation") String annotation, + @JsonProperty("OrderingTimestamp") Double orderingTimestamp, + @JsonProperty("ResultRecordedTime") Long resultRecordedTime, + @JsonProperty("ConfigRuleInvokedTime") Long configRuleInvokedTime) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRule.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRule.java index 4e8f6ee649..5a3e73f644 100644 --- a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRule.java +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRule.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.List; + @RegisterForReflection @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @@ -12,6 +14,12 @@ public record ConfigRule( @JsonProperty("ConfigRuleName") String configRuleName, @JsonProperty("ConfigRuleArn") String configRuleArn, @JsonProperty("ConfigRuleId") String configRuleId, + @JsonProperty("Description") String description, + @JsonProperty("Scope") Scope scope, + @JsonProperty("Source") ConfigRuleSource source, + @JsonProperty("InputParameters") String inputParameters, + @JsonProperty("MaximumExecutionFrequency") String maximumExecutionFrequency, @JsonProperty("ConfigRuleState") String configRuleState, - @JsonProperty("Source") ConfigRuleSource source) { + @JsonProperty("CreatedBy") String createdBy, + @JsonProperty("EvaluationModes") List evaluationModes) { } diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRuleEvaluationStatus.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRuleEvaluationStatus.java index 6c2ca599f4..535de01a0c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRuleEvaluationStatus.java +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRuleEvaluationStatus.java @@ -12,5 +12,8 @@ public record ConfigRuleEvaluationStatus( @JsonProperty("ConfigRuleName") String configRuleName, @JsonProperty("ConfigRuleArn") String configRuleArn, @JsonProperty("ConfigRuleId") String configRuleId, - @JsonProperty("FirstEvaluationStarted") Boolean firstEvaluationStarted) { + @JsonProperty("FirstEvaluationStarted") Boolean firstEvaluationStarted, + @JsonProperty("FirstActivatedTime") Long firstActivatedTime, + @JsonProperty("LastSuccessfulInvocationTime") Long lastSuccessfulInvocationTime, + @JsonProperty("LastSuccessfulEvaluationTime") Long lastSuccessfulEvaluationTime) { } diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRuleSource.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRuleSource.java index 52586c8ae4..3e22b83f4d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRuleSource.java +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/ConfigRuleSource.java @@ -5,10 +5,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.List; + @RegisterForReflection @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record ConfigRuleSource( @JsonProperty("Owner") String owner, - @JsonProperty("SourceIdentifier") String sourceIdentifier) { + @JsonProperty("SourceIdentifier") String sourceIdentifier, + @JsonProperty("SourceDetails") List sourceDetails, + @JsonProperty("CustomPolicyDetails") CustomPolicyDetails customPolicyDetails) { } diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/CustomPolicyDetails.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/CustomPolicyDetails.java new file mode 100644 index 0000000000..956574f988 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/CustomPolicyDetails.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record CustomPolicyDetails( + @JsonProperty("PolicyRuntime") String policyRuntime, + @JsonProperty("PolicyText") String policyText, + @JsonProperty("EnableDebugLogDelivery") Boolean enableDebugLogDelivery) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationModeConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationModeConfiguration.java new file mode 100644 index 0000000000..41a3f13efe --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationModeConfiguration.java @@ -0,0 +1,13 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record EvaluationModeConfiguration( + @JsonProperty("Mode") String mode) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResult.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResult.java new file mode 100644 index 0000000000..41119a11bd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResult.java @@ -0,0 +1,18 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record EvaluationResult( + @JsonProperty("EvaluationResultIdentifier") EvaluationResultIdentifier evaluationResultIdentifier, + @JsonProperty("ComplianceType") String complianceType, + @JsonProperty("ResultRecordedTime") Long resultRecordedTime, + @JsonProperty("ConfigRuleInvokedTime") Long configRuleInvokedTime, + @JsonProperty("Annotation") String annotation, + @JsonProperty("ResultToken") String resultToken) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResultIdentifier.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResultIdentifier.java new file mode 100644 index 0000000000..a9fb92511a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResultIdentifier.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record EvaluationResultIdentifier( + @JsonProperty("EvaluationResultQualifier") EvaluationResultQualifier evaluationResultQualifier, + @JsonProperty("OrderingTimestamp") Double orderingTimestamp) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResultQualifier.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResultQualifier.java new file mode 100644 index 0000000000..a9c440339f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/EvaluationResultQualifier.java @@ -0,0 +1,16 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record EvaluationResultQualifier( + @JsonProperty("ConfigRuleName") String configRuleName, + @JsonProperty("ResourceType") String resourceType, + @JsonProperty("ResourceId") String resourceId, + @JsonProperty("EvaluationMode") String evaluationMode) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/RetentionConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/RetentionConfiguration.java new file mode 100644 index 0000000000..07cb947791 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/RetentionConfiguration.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record RetentionConfiguration( + @JsonProperty("Name") String name, + @JsonProperty("RetentionPeriodInDays") Integer retentionPeriodInDays) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/Scope.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/Scope.java new file mode 100644 index 0000000000..6651c0085c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/Scope.java @@ -0,0 +1,18 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record Scope( + @JsonProperty("ComplianceResourceTypes") List complianceResourceTypes, + @JsonProperty("TagKey") String tagKey, + @JsonProperty("TagValue") String tagValue, + @JsonProperty("ComplianceResourceId") String complianceResourceId) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/model/SourceDetail.java b/src/main/java/io/github/hectorvent/floci/services/configservice/model/SourceDetail.java new file mode 100644 index 0000000000..41b440ab47 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/configservice/model/SourceDetail.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.configservice.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SourceDetail( + @JsonProperty("EventSource") String eventSource, + @JsonProperty("MessageType") String messageType, + @JsonProperty("MaximumExecutionFrequency") String maximumExecutionFrequency) { +} diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServiceEvaluationConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServiceEvaluationConcurrencyTest.java new file mode 100644 index 0000000000..f97db38294 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServiceEvaluationConcurrencyTest.java @@ -0,0 +1,147 @@ +package io.github.hectorvent.floci.services.configservice; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.configservice.model.ConfigEvaluation; +import io.github.hectorvent.floci.services.configservice.model.ConfigRule; +import io.github.hectorvent.floci.services.configservice.model.ConfigRuleSource; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * PutEvaluations for the same resource/rule pair must not let an older evaluation win a race + * against a newer one. A separate get-then-put is not atomic on the backing ConcurrentHashMap: + * both calls can read the current value before either writes, so whichever write lands last wins + * regardless of OrderingTimestamp. + */ +class AwsConfigServiceEvaluationConcurrencyTest { + + private static final String REGION = "us-east-1"; + + @Test + void concurrentEvaluationsForTheSameResourceKeepTheNewerOrderingTimestamp() throws Exception { + AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), null); + service.putConfigRule(REGION, new ConfigRule("race-rule", null, null, null, null, + new ConfigRuleSource("CUSTOM_LAMBDA", "arn:aws:lambda:us-east-1:000000000000:function:check", + null, null), + null, null, null, null, null)); + + int threadsPerAttempt = 16; + for (int attempt = 0; attempt < 100; attempt++) { + String resourceId = "bucket-" + attempt; + CountDownLatch start = new CountDownLatch(1); + AtomicReference unexpected = new AtomicReference<>(); + List writers = new java.util.ArrayList<>(); + + // Every writer races on the SAME resource key; only the last one in should win, and + // by OrderingTimestamp rather than by write order. Half submit an older evaluation, + // half a newer one, so any interleaving that lets an older write land last is a bug. + for (int i = 0; i < threadsPerAttempt; i++) { + boolean isNewer = i % 2 == 0; + Thread writer = new Thread(() -> { + await(start); + try { + service.putEvaluations(REGION, "race-rule", + List.of(evaluation(resourceId, isNewer ? "COMPLIANT" : "NON_COMPLIANT", + isNewer ? 1700000001.0 : 1700000000.0)), false); + } catch (Throwable t) { + unexpected.set(t); + } + }); + writers.add(writer); + writer.start(); + } + + start.countDown(); + for (Thread writer : writers) { + writer.join(TimeUnit.SECONDS.toMillis(10)); + assertFalse(writer.isAlive(), "a PutEvaluations call never finished"); + } + assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get()); + + String recorded = service.getComplianceDetailsByResource(REGION, "AWS::S3::Bucket", resourceId, + null, null).items().getFirst().complianceType(); + assertEquals("COMPLIANT", recorded, + "attempt " + attempt + ": the newer evaluation must win regardless of write order"); + } + } + + @Test + void deletingARuleDuringPutEvaluationsDoesNotLeaveEvaluationsForAFutureSameNamedRule() throws Exception { + AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), null); + ConfigRuleSource source = new ConfigRuleSource("CUSTOM_LAMBDA", + "arn:aws:lambda:us-east-1:000000000000:function:check", null, null); + + for (int attempt = 0; attempt < 200; attempt++) { + String ruleName = "race-rule-" + attempt; + service.putConfigRule(REGION, new ConfigRule(ruleName, null, null, null, null, source, + null, null, null, null, null)); + + CountDownLatch start = new CountDownLatch(1); + AtomicReference putFailure = new AtomicReference<>(); + AtomicReference deleteFailure = new AtomicReference<>(); + + Thread putter = new Thread(() -> { + await(start); + try { + service.putEvaluations(REGION, ruleName, + List.of(evaluation("bucket-1", "NON_COMPLIANT", 1700000000.0)), false); + } catch (Throwable t) { + putFailure.set(t); + } + }); + Thread deleter = new Thread(() -> { + await(start); + try { + service.deleteConfigRule(REGION, ruleName); + } catch (Throwable t) { + deleteFailure.set(t); + } + }); + + putter.start(); + deleter.start(); + start.countDown(); + putter.join(TimeUnit.SECONDS.toMillis(10)); + deleter.join(TimeUnit.SECONDS.toMillis(10)); + assertFalse(putter.isAlive() || deleter.isAlive(), "a putEvaluations/deleteConfigRule call never finished"); + // Losing the race to the delete (NoSuchConfigRuleException) is a legitimate outcome for + // the putter; any other failure, on either side, is not. + if (putFailure.get() != null) { + assertEquals("NoSuchConfigRuleException", + ((AwsException) putFailure.get()).getErrorCode(), + "unexpected putEvaluations failure: " + putFailure.get()); + } + assertNull(deleteFailure.get(), () -> "unexpected deleteConfigRule failure: " + deleteFailure.get()); + + // A brand new rule reusing the deleted rule's name must start with a clean evaluation + // bucket -- it must never inherit compliance details left behind by the deleted rule. + service.putConfigRule(REGION, new ConfigRule(ruleName, null, null, null, null, source, + null, null, null, null, null)); + assertEquals("INSUFFICIENT_DATA", service.complianceForRule(REGION, ruleName).complianceType(), + "attempt " + attempt + ": a same-named rule inherited the deleted rule's evaluations"); + } + } + + private static ConfigEvaluation evaluation(String resourceId, String complianceType, double orderingTimestamp) { + return new ConfigEvaluation("AWS::S3::Bucket", resourceId, complianceType, null, + orderingTimestamp, null, null); + } + + private static void await(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServicePersistenceTest.java index b9a57df64d..68f9c69c25 100644 --- a/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServicePersistenceTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.configservice.model.ConfigEvaluation; import io.github.hectorvent.floci.services.configservice.model.ConfigRule; import io.github.hectorvent.floci.services.configservice.model.ConfigRuleSource; import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorder; @@ -33,8 +34,8 @@ class AwsConfigServicePersistenceTest { SharedStorageFactory storage = new SharedStorageFactory(); AwsConfigService first = serviceWithStorage(storage); - ConfigRule rule = first.putConfigRule(REGION, "s3-public-read", - new ConfigRuleSource("AWS", "S3_BUCKET_PUBLIC_READ_PROHIBITED")); + ConfigRule rule = first.putConfigRule(REGION, + rule("s3-public-read", "AWS", "S3_BUCKET_PUBLIC_READ_PROHIBITED")); first.putConformancePack(REGION, "ops-pack", "s3://bucket/template.yaml", null); first.putConfigurationRecorder(REGION, new ConfigurationRecorder("default", "arn:aws:iam::000000000000:role/config", new RecordingGroup(true, false, null))); @@ -61,9 +62,8 @@ class AwsConfigServicePersistenceTest { SharedStorageFactory storage = new SharedStorageFactory(); AwsConfigService first = serviceWithStorage(storage); - ConfigRule rule = first.putConfigRule(REGION, "keep", - new ConfigRuleSource("AWS", "REQUIRED_TAGS")); - first.putConfigRule(REGION, "drop", new ConfigRuleSource("AWS", "REQUIRED_TAGS")); + ConfigRule rule = first.putConfigRule(REGION, rule("keep", "AWS", "REQUIRED_TAGS")); + first.putConfigRule(REGION, rule("drop", "AWS", "REQUIRED_TAGS")); first.deleteConfigRule(REGION, "drop"); first.tagResource(rule.configRuleArn(), List.of(Map.of("Key", "env", "Value", "prod"), Map.of("Key", "team", "Value", "sec"))); @@ -79,6 +79,66 @@ class AwsConfigServicePersistenceTest { assertTrue(!tags.containsKey("team"), "untagged key must not reappear after restart"); } + @Test + void evaluationsSurviveRestart() { + SharedStorageFactory storage = new SharedStorageFactory(); + + AwsConfigService first = serviceWithStorage(storage); + first.putConfigRule(REGION, rule("bucket-policy", "CUSTOM_LAMBDA", + "arn:aws:lambda:us-east-1:000000000000:function:check")); + first.putEvaluations(REGION, "bucket-policy", + List.of(evaluation("AWS::S3::Bucket", "bucket-1", "NON_COMPLIANT")), false); + + AwsConfigService reloaded = serviceWithStorage(storage); + + assertEquals("NON_COMPLIANT", reloaded.complianceForRule(REGION, "bucket-policy").complianceType()); + assertEquals(1, reloaded.getComplianceDetailsByConfigRule(REGION, "bucket-policy", + null, null, null).items().size()); + } + + @Test + void deleteConfigRuleCascadesEvaluationsAcrossRestart() { + SharedStorageFactory storage = new SharedStorageFactory(); + + AwsConfigService first = serviceWithStorage(storage); + first.putConfigRule(REGION, rule("kept-rule", "CUSTOM_LAMBDA", + "arn:aws:lambda:us-east-1:000000000000:function:check")); + first.putConfigRule(REGION, rule("dropped-rule", "CUSTOM_LAMBDA", + "arn:aws:lambda:us-east-1:000000000000:function:check")); + first.putEvaluations(REGION, "kept-rule", + List.of(evaluation("AWS::S3::Bucket", "bucket-1", "COMPLIANT")), false); + first.putEvaluations(REGION, "dropped-rule", + List.of(evaluation("AWS::S3::Bucket", "bucket-1", "NON_COMPLIANT")), false); + first.deleteConfigRule(REGION, "dropped-rule"); + + AwsConfigService reloaded = serviceWithStorage(storage); + + assertEquals("COMPLIANT", reloaded.complianceForRule(REGION, "kept-rule").complianceType()); + assertEquals("INSUFFICIENT_DATA", reloaded.complianceForRule(REGION, "dropped-rule").complianceType()); + } + + @Test + void retentionConfigurationSurvivesRestart() { + SharedStorageFactory storage = new SharedStorageFactory(); + + AwsConfigService first = serviceWithStorage(storage); + first.putRetentionConfiguration(REGION, 90); + + AwsConfigService reloaded = serviceWithStorage(storage); + + assertEquals(90, reloaded.describeRetentionConfigurations(REGION, null) + .getFirst().retentionPeriodInDays()); + } + + private static ConfigRule rule(String name, String owner, String sourceIdentifier) { + return new ConfigRule(name, null, null, null, null, + new ConfigRuleSource(owner, sourceIdentifier, null, null), null, null, null, null, null); + } + + private static ConfigEvaluation evaluation(String resourceType, String resourceId, String complianceType) { + return new ConfigEvaluation(resourceType, resourceId, complianceType, null, 1700000000.0, null, null); + } + private static AwsConfigService serviceWithStorage(StorageFactory storage) { AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), storage); service.initializeStorage(); diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/ComplianceEvaluationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/ComplianceEvaluationIntegrationTest.java new file mode 100644 index 0000000000..0af7550829 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/ComplianceEvaluationIntegrationTest.java @@ -0,0 +1,580 @@ +package io.github.hectorvent.floci.services.configservice; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ComplianceEvaluationIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String TARGET_PREFIX = "StarlingDoveService."; + private static final String LAMBDA_RULE = "compliance-loop-rule"; + private static final String EXTERNAL_RULE = "external-eval-rule"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static void putRule(String ruleName) { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + { + "ConfigRule": { + "ConfigRuleName": "%s", + "Source": { + "Owner": "CUSTOM_LAMBDA", + "SourceIdentifier": "arn:aws:lambda:us-east-1:000000000000:function:checker" + } + } + } + """.formatted(ruleName)) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(1) + void setupRules() { + putRule(LAMBDA_RULE); + putRule(EXTERNAL_RULE); + } + + @Test + @Order(2) + void putEvaluationsTestModePersistsNothing() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResultToken": "%s", + "TestMode": true, + "Evaluations": [ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-1", + "ComplianceType": "NON_COMPLIANT", + "OrderingTimestamp": 1699999999.5 + } + ] + } + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("FailedEvaluations", hasSize(0)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["%s"]} + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("INSUFFICIENT_DATA")); + } + + @Test + @Order(3) + void putEvaluationsRecordsCompliance() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResultToken": "%s", + "Evaluations": [ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-1", + "ComplianceType": "NON_COMPLIANT", + "Annotation": "Bucket allows public ACLs", + "OrderingTimestamp": 1699999999.5 + }, + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-2", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": 1699999999.5 + } + ] + } + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("FailedEvaluations", hasSize(0)); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["%s"]} + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("NON_COMPLIANT")) + .body("ComplianceByConfigRules[0].Compliance.ComplianceContributorCount.CappedCount", equalTo(1)) + .body("ComplianceByConfigRules[0].Compliance.ComplianceContributorCount.CapExceeded", equalTo(false)); + } + + @Test + @Order(4) + void getComplianceDetailsByConfigRule() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s"} + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("EvaluationResults", hasSize(2)) + .body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ConfigRuleName", + equalTo(LAMBDA_RULE)) + .body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceType", + equalTo("AWS::S3::Bucket")) + .body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId", + equalTo("bucket-1")) + .body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.EvaluationMode", + equalTo("DETECTIVE")) + .body("EvaluationResults[0].EvaluationResultIdentifier.OrderingTimestamp", notNullValue()) + .body("EvaluationResults[0].ComplianceType", equalTo("NON_COMPLIANT")) + .body("EvaluationResults[0].Annotation", equalTo("Bucket allows public ACLs")) + .body("EvaluationResults[0].ResultRecordedTime", notNullValue()) + .body("EvaluationResults[0].ConfigRuleInvokedTime", notNullValue()) + .body("EvaluationResults[1].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId", + equalTo("bucket-2")) + .body("EvaluationResults[1].ComplianceType", equalTo("COMPLIANT")); + } + + @Test + @Order(5) + void getComplianceDetailsFilteredByComplianceType() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s", "ComplianceTypes": ["NON_COMPLIANT"]} + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("EvaluationResults", hasSize(1)) + .body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId", + equalTo("bucket-1")); + } + + @Test + @Order(6) + void reEvaluationFlipsRuleToCompliant() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResultToken": "%s:on-demand-1", + "Evaluations": [ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-1", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": 1700000100.0 + } + ] + } + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["%s"]} + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("COMPLIANT")) + .body("ComplianceByConfigRules[0].Compliance.ComplianceContributorCount", nullValue()); + } + + @Test + @Order(7) + void allNotApplicableIsInsufficientData() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResultToken": "%s", + "Evaluations": [ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-1", + "ComplianceType": "NOT_APPLICABLE", + "OrderingTimestamp": 1700000200.0 + }, + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-2", + "ComplianceType": "NOT_APPLICABLE", + "OrderingTimestamp": 1700000200.0 + } + ] + } + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["%s"]} + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("INSUFFICIENT_DATA")); + } + + @Test + @Order(8) + void putExternalEvaluation() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutExternalEvaluation") + .contentType(CONTENT_TYPE) + .body(""" + { + "ConfigRuleName": "%s", + "ExternalEvaluation": { + "ComplianceResourceType": "AWS::EC2::VPC", + "ComplianceResourceId": "vpc-1", + "ComplianceType": "NON_COMPLIANT", + "Annotation": "Flow logs disabled", + "OrderingTimestamp": 1700000300.0 + } + } + """.formatted(EXTERNAL_RULE)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["%s"]} + """.formatted(EXTERNAL_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("NON_COMPLIANT")); + } + + @Test + @Order(9) + void describeComplianceByResource() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByResource") + .contentType(CONTENT_TYPE) + .body(""" + {"ResourceType": "AWS::EC2::VPC"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceByResources", hasSize(1)) + .body("ComplianceByResources[0].ResourceType", equalTo("AWS::EC2::VPC")) + .body("ComplianceByResources[0].ResourceId", equalTo("vpc-1")) + .body("ComplianceByResources[0].Compliance.ComplianceType", equalTo("NON_COMPLIANT")) + .body("ComplianceByResources[0].Compliance.ComplianceContributorCount.CappedCount", equalTo(1)); + } + + @Test + @Order(10) + void getComplianceDetailsByResource() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByResource") + .contentType(CONTENT_TYPE) + .body(""" + {"ResourceType": "AWS::EC2::VPC", "ResourceId": "vpc-1"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("EvaluationResults", hasSize(1)) + .body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ConfigRuleName", + equalTo(EXTERNAL_RULE)) + .body("EvaluationResults[0].Annotation", equalTo("Flow logs disabled")); + } + + @Test + @Order(11) + void complianceSummaries() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceSummaryByConfigRule") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceSummary.NonCompliantResourceCount.CappedCount", greaterThanOrEqualTo(1)) + .body("ComplianceSummary.ComplianceSummaryTimestamp", notNullValue()); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceSummaryByResourceType") + .contentType(CONTENT_TYPE) + .body(""" + {"ResourceTypes": ["AWS::EC2::VPC"]} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceSummariesByResourceType", hasSize(1)) + .body("ComplianceSummariesByResourceType[0].ResourceType", equalTo("AWS::EC2::VPC")) + .body("ComplianceSummariesByResourceType[0].ComplianceSummary.NonCompliantResourceCount.CappedCount", + equalTo(1)); + } + + @Test + @Order(12) + void deleteEvaluationResultsResetsCompliance() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteEvaluationResults") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s"} + """.formatted(EXTERNAL_RULE)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["%s"]} + """.formatted(EXTERNAL_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("INSUFFICIENT_DATA")); + } + + @Test + @Order(13) + void putEvaluationsWithoutTokenIsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "Evaluations": [ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-1", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": 1700000400.0 + } + ] + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidResultTokenException")); + } + + @Test + @Order(14) + void putEvaluationsForUnknownRuleIsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResultToken": "no-such-rule", + "Evaluations": [ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-1", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": 1700000400.0 + } + ] + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchConfigRuleException")); + } + + @Test + @Order(15) + void putEvaluationsWithInvalidComplianceTypeIsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResultToken": "%s", + "Evaluations": [ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-1", + "ComplianceType": "SORT_OF_COMPLIANT", + "OrderingTimestamp": 1700000400.0 + } + ] + } + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + + @Test + @Order(16) + void putExternalEvaluationForUnknownRuleIsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutExternalEvaluation") + .contentType(CONTENT_TYPE) + .body(""" + { + "ConfigRuleName": "no-such-rule", + "ExternalEvaluation": { + "ComplianceResourceType": "AWS::EC2::VPC", + "ComplianceResourceId": "vpc-1", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": 1700000500.0 + } + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchConfigRuleException")); + } + + @Test + @Order(17) + void staleEvaluationDoesNotOverwriteNewerResult() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResultToken": "%s:stale", + "Evaluations": [ + { + "ComplianceResourceType": "AWS::S3::Bucket", + "ComplianceResourceId": "bucket-1", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": 1700000150.0 + } + ] + } + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s"} + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("EvaluationResults.find { it.EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId == 'bucket-1' }.ComplianceType", + equalTo("NOT_APPLICABLE")) + .body("EvaluationResults.find { it.EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId == 'bucket-1' }.EvaluationResultIdentifier.OrderingTimestamp", + equalTo(1700000200.0f)); + } + + @Test + @Order(18) + void evaluationStatusReflectsRecordedEvaluations() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRuleEvaluationStatus") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["%s"]} + """.formatted(LAMBDA_RULE)) + .when() + .post("/") + .then() + .statusCode(200) + .body("ConfigRulesEvaluationStatus[0].FirstEvaluationStarted", equalTo(true)) + .body("ConfigRulesEvaluationStatus[0].LastSuccessfulInvocationTime", notNullValue()) + .body("ConfigRulesEvaluationStatus[0].LastSuccessfulEvaluationTime", notNullValue()); + } + + @Test + @Order(19) + void cleanupRules() { + for (String ruleName : new String[]{LAMBDA_RULE, EXTERNAL_RULE}) { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s"} + """.formatted(ruleName)) + .when() + .post("/") + .then() + .statusCode(200); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigPaginationIntegrationTest.java new file mode 100644 index 0000000000..0d63079354 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigPaginationIntegrationTest.java @@ -0,0 +1,230 @@ +package io.github.hectorvent.floci.services.configservice; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.util.ArrayList; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ConfigPaginationIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String TARGET_PREFIX = "StarlingDoveService."; + private static final int SEEDED_RULES = 30; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static String seededRuleName(int index) { + return "pg-rule-%03d".formatted(index); + } + + @Test + @Order(1) + void seedRules() { + for (int i = 0; i < SEEDED_RULES; i++) { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + { + "ConfigRule": { + "ConfigRuleName": "%s", + "Source": { + "Owner": "CUSTOM_LAMBDA", + "SourceIdentifier": "arn:aws:lambda:us-east-1:000000000000:function:checker" + } + } + } + """.formatted(seededRuleName(i))) + .when() + .post("/") + .then() + .statusCode(200); + } + } + + @Test + @Order(2) + void describeConfigRulesReturnsPageOf25WithNextToken() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("ConfigRules", hasSize(25)) + .body("NextToken", notNullValue()); + } + + @Test + @Order(3) + void nextTokenWalkCollectsAllSeededRules() { + List collected = new ArrayList<>(); + String nextToken = null; + do { + String body = nextToken == null ? "{}" : "{\"NextToken\": \"%s\"}".formatted(nextToken); + JsonPath response = given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules") + .contentType(CONTENT_TYPE) + .body(body) + .when() + .post("/") + .then() + .statusCode(200) + .extract().jsonPath(); + collected.addAll(response.getList("ConfigRules.ConfigRuleName", String.class)); + nextToken = response.getString("NextToken"); + } while (nextToken != null); + + for (int i = 0; i < SEEDED_RULES; i++) { + String name = seededRuleName(i); + assertTrue(collected.contains(name), "walk must return seeded rule " + name); + } + } + + @Test + @Order(4) + void invalidNextTokenIsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules") + .contentType(CONTENT_TYPE) + .body(""" + {"NextToken": "not-a-token"} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidNextTokenException")); + } + + @Test + @Order(5) + void complianceDetailsHonorLimitAndNextToken() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations") + .contentType(CONTENT_TYPE) + .body(""" + { + "ResultToken": "%s", + "Evaluations": [ + { + "ComplianceResourceType": "AWS::Lambda::Function", + "ComplianceResourceId": "fn-1", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": 1700000000.0 + }, + { + "ComplianceResourceType": "AWS::Lambda::Function", + "ComplianceResourceId": "fn-2", + "ComplianceType": "COMPLIANT", + "OrderingTimestamp": 1700000000.0 + }, + { + "ComplianceResourceType": "AWS::Lambda::Function", + "ComplianceResourceId": "fn-3", + "ComplianceType": "NON_COMPLIANT", + "OrderingTimestamp": 1700000000.0 + } + ] + } + """.formatted(seededRuleName(0))) + .when() + .post("/") + .then() + .statusCode(200); + + String nextToken = given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s", "Limit": 2} + """.formatted(seededRuleName(0))) + .when() + .post("/") + .then() + .statusCode(200) + .body("EvaluationResults", hasSize(2)) + .body("NextToken", notNullValue()) + .extract().jsonPath().getString("NextToken"); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s", "Limit": 2, "NextToken": "%s"} + """.formatted(seededRuleName(0), nextToken)) + .when() + .post("/") + .then() + .statusCode(200) + .body("EvaluationResults", hasSize(1)) + .body("NextToken", nullValue()); + } + + @Test + @Order(6) + void complianceDetailsLimitAbove100IsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s", "Limit": 101} + """.formatted(seededRuleName(0))) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + + @Test + @Order(7) + void conformancePackLimitAbove20IsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConformancePacks") + .contentType(CONTENT_TYPE) + .body(""" + {"Limit": 21} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidLimitException")); + } + + @Test + @Order(8) + void cleanupSeededRules() { + for (int i = 0; i < SEEDED_RULES; i++) { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleName": "%s"} + """.formatted(seededRuleName(i))) + .when() + .post("/") + .then() + .statusCode(200); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigRuleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigRuleIntegrationTest.java index 36e921742d..ced86496e3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigRuleIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigRuleIntegrationTest.java @@ -33,10 +33,23 @@ class ConfigRuleIntegrationTest { { "ConfigRule": { "ConfigRuleName": "rule-crud-test", + "Description": "Ensure S3 access points block public access", + "Scope": { + "ComplianceResourceTypes": ["AWS::S3::AccessPoint"], + "TagKey": "env" + }, "Source": { "Owner": "AWS", - "SourceIdentifier": "S3_ACCESS_POINT_PUBLIC_ACCESS_BLOCKS" - } + "SourceIdentifier": "S3_ACCESS_POINT_PUBLIC_ACCESS_BLOCKS", + "SourceDetails": [ + { + "EventSource": "aws.config", + "MessageType": "ScheduledNotification" + } + ] + }, + "InputParameters": "{\\"mode\\":\\"strict\\"}", + "MaximumExecutionFrequency": "TwentyFour_Hours" } } """) @@ -64,8 +77,16 @@ class ConfigRuleIntegrationTest { .body("ConfigRules[0].ConfigRuleArn", notNullValue()) .body("ConfigRules[0].ConfigRuleId", notNullValue()) .body("ConfigRules[0].ConfigRuleState", equalTo("ACTIVE")) + .body("ConfigRules[0].Description", equalTo("Ensure S3 access points block public access")) + .body("ConfigRules[0].Scope.ComplianceResourceTypes", contains("AWS::S3::AccessPoint")) + .body("ConfigRules[0].Scope.TagKey", equalTo("env")) .body("ConfigRules[0].Source.Owner", equalTo("AWS")) - .body("ConfigRules[0].Source.SourceIdentifier", equalTo("S3_ACCESS_POINT_PUBLIC_ACCESS_BLOCKS")); + .body("ConfigRules[0].Source.SourceIdentifier", equalTo("S3_ACCESS_POINT_PUBLIC_ACCESS_BLOCKS")) + .body("ConfigRules[0].Source.SourceDetails[0].EventSource", equalTo("aws.config")) + .body("ConfigRules[0].Source.SourceDetails[0].MessageType", equalTo("ScheduledNotification")) + .body("ConfigRules[0].InputParameters", equalTo("{\"mode\":\"strict\"}")) + .body("ConfigRules[0].MaximumExecutionFrequency", equalTo("TwentyFour_Hours")) + .body("ConfigRules[0].EvaluationModes[0].Mode", equalTo("DETECTIVE")); given() .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules") @@ -80,6 +101,22 @@ class ConfigRuleIntegrationTest { @Test @Order(3) + void describeConfigRulesUnknownName() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["no-such-rule"]} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchConfigRuleException")); + } + + @Test + @Order(4) void describeComplianceByConfigRule() { given() .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") @@ -97,7 +134,7 @@ class ConfigRuleIntegrationTest { } @Test - @Order(4) + @Order(5) void putConfigRuleUpdate() { given() .header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule") @@ -128,12 +165,14 @@ class ConfigRuleIntegrationTest { .post("/") .then() .statusCode(200) - .body("ConfigRules[0].Source.Owner", equalTo("CUSTOM_LAMBDA")); + .body("ConfigRules[0].Source.Owner", equalTo("CUSTOM_LAMBDA")) + .body("ConfigRules[0].ConfigRuleArn", notNullValue()) + .body("ConfigRules[0].ConfigRuleId", notNullValue()); } @Test - @Order(5) - void describeConfigRuleEvaluationStatus() { + @Order(6) + void describeConfigRuleEvaluationStatusBeforeStart() { given() .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRuleEvaluationStatus") .contentType(CONTENT_TYPE) @@ -148,11 +187,13 @@ class ConfigRuleIntegrationTest { .body("ConfigRulesEvaluationStatus[0].ConfigRuleName", equalTo("rule-crud-test")) .body("ConfigRulesEvaluationStatus[0].ConfigRuleArn", notNullValue()) .body("ConfigRulesEvaluationStatus[0].ConfigRuleId", notNullValue()) - .body("ConfigRulesEvaluationStatus[0].FirstEvaluationStarted", equalTo(true)); + .body("ConfigRulesEvaluationStatus[0].FirstEvaluationStarted", equalTo(false)) + .body("ConfigRulesEvaluationStatus[0].FirstActivatedTime", notNullValue()) + .body("ConfigRulesEvaluationStatus[0].LastSuccessfulInvocationTime", nullValue()); } @Test - @Order(6) + @Order(7) void startConfigRulesEvaluation() { given() .header("X-Amz-Target", TARGET_PREFIX + "StartConfigRulesEvaluation") @@ -164,10 +205,23 @@ class ConfigRuleIntegrationTest { .post("/") .then() .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRuleEvaluationStatus") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["rule-crud-test"]} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("ConfigRulesEvaluationStatus[0].FirstEvaluationStarted", equalTo(true)) + .body("ConfigRulesEvaluationStatus[0].LastSuccessfulInvocationTime", notNullValue()); } @Test - @Order(7) + @Order(8) void startConfigRulesEvaluationNonexistent() { given() .header("X-Amz-Target", TARGET_PREFIX + "StartConfigRulesEvaluation") @@ -183,7 +237,7 @@ class ConfigRuleIntegrationTest { } @Test - @Order(8) + @Order(9) void deleteConfigRule() { given() .header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule") @@ -198,7 +252,7 @@ class ConfigRuleIntegrationTest { } @Test - @Order(9) + @Order(10) void deleteNonexistentConfigRule() { given() .header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule") @@ -212,4 +266,175 @@ class ConfigRuleIntegrationTest { .statusCode(400) .body("__type", equalTo("NoSuchConfigRuleException")); } + + @Test + @Order(11) + void deleteConfigRuleWithoutNameIsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchConfigRuleException")); + } + + /** + * PutConfigRule now deserializes the whole modeled ConfigRule and stores it, so every + * enum-typed member it keeps has to be checked: {@code Source/Owner}, + * {@code MaximumExecutionFrequency}, {@code ConfigRuleState} and + * {@code EvaluationModes[].Mode}. A rule stored with a value outside its enum is echoed + * straight back by DescribeConfigRules as a rule AWS would never have accepted. + */ + @Test + @Order(11) + void putConfigRuleRejectsValuesOutsideTheModeledEnums() { + record Case(String name, String body) { } + Case[] cases = { + new Case("Owner", """ + {"ConfigRule": {"ConfigRuleName": "rule-enum-owner", + "Source": {"Owner": "CUSTOM", "SourceIdentifier": "X"}}}"""), + new Case("MaximumExecutionFrequency", """ + {"ConfigRule": {"ConfigRuleName": "rule-enum-freq", + "Source": {"Owner": "AWS", "SourceIdentifier": "X"}, + "MaximumExecutionFrequency": "Two_Hours"}}"""), + new Case("ConfigRuleState", """ + {"ConfigRule": {"ConfigRuleName": "rule-enum-state", + "Source": {"Owner": "AWS", "SourceIdentifier": "X"}, + "ConfigRuleState": "PAUSED"}}"""), + new Case("EvaluationMode", """ + {"ConfigRule": {"ConfigRuleName": "rule-enum-mode", + "Source": {"Owner": "AWS", "SourceIdentifier": "X"}, + "EvaluationModes": [{"Mode": "REACTIVE"}]}}"""), + }; + for (Case c : cases) { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule") + .contentType(CONTENT_TYPE) + .body(c.body()) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + + // Nothing was stored under any of the rejected names. + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["rule-enum-owner"]} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchConfigRuleException")); + } + + /** + * The nested members are stored and echoed back too: {@code SourceDetails[]} carries the + * EventSource ({@code aws.config} only), MessageType and MaximumExecutionFrequency enums, + * and {@code Scope.ComplianceResourceTypes} is a list with {@code max: 100}. + */ + @Test + @Order(11) + void putConfigRuleRejectsNestedValuesOutsideTheModeledShapes() { + String[] bodies = { + """ + {"ConfigRule": {"ConfigRuleName": "rule-enum-eventsource", + "Source": {"Owner": "AWS", "SourceIdentifier": "X", + "SourceDetails": [{"EventSource": "aws.cloudtrail", "MessageType": "ScheduledNotification"}]}}}""", + """ + {"ConfigRule": {"ConfigRuleName": "rule-enum-messagetype", + "Source": {"Owner": "AWS", "SourceIdentifier": "X", + "SourceDetails": [{"EventSource": "aws.config", "MessageType": "PeriodicNotification"}]}}}""", + """ + {"ConfigRule": {"ConfigRuleName": "rule-enum-detail-freq", + "Source": {"Owner": "AWS", "SourceIdentifier": "X", + "SourceDetails": [{"EventSource": "aws.config", "MessageType": "ScheduledNotification", + "MaximumExecutionFrequency": "Two_Hours"}]}}}""", + }; + for (String body : bodies) { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule") + .contentType(CONTENT_TYPE) + .body(body) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + + StringBuilder tooManyTypes = new StringBuilder(); + for (int i = 0; i < 101; i++) { + tooManyTypes.append(i == 0 ? "" : ", ").append("\"AWS::S3::Bucket").append(i).append('"'); + } + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule") + .contentType(CONTENT_TYPE) + .body("{\"ConfigRule\": {\"ConfigRuleName\": \"rule-scope-cardinality\"," + + " \"Source\": {\"Owner\": \"AWS\", \"SourceIdentifier\": \"X\"}," + + " \"Scope\": {\"ComplianceResourceTypes\": [" + tooManyTypes + "]}}}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigRuleNames": ["rule-enum-eventsource"]} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchConfigRuleException")); + } + + /** + * {@code ComplianceTypes} is a list of the ComplianceType enum with {@code max: 3}. It is + * read as a filter, so an unmodeled value silently narrows the result to nothing — the + * caller reads that as "no rules match" rather than as the rejection AWS sends. + */ + @Test + @Order(12) + void describeComplianceByConfigRuleRejectsAnUnmodeledComplianceTypeFilter() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ComplianceTypes": ["PARTIALLY_COMPLIANT"]} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + + @Test + @Order(12) + void describeComplianceByConfigRuleRejectsMoreThanThreeComplianceTypes() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule") + .contentType(CONTENT_TYPE) + .body(""" + {"ComplianceTypes": ["COMPLIANT", "NON_COMPLIANT", "NOT_APPLICABLE", "INSUFFICIENT_DATA"]} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigurationRecorderIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigurationRecorderIntegrationTest.java index dba4a923d8..c43f415810 100644 --- a/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigurationRecorderIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/ConfigurationRecorderIntegrationTest.java @@ -216,4 +216,120 @@ class ConfigurationRecorderIntegrationTest { .statusCode(200) .body("DeliveryChannels", hasSize(1)); } + + // --- Deletes --- + + @Test + @Order(10) + void deleteDeliveryChannelWhileRecorderRunning() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "StartConfigurationRecorder") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigurationRecorderName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteDeliveryChannel") + .contentType(CONTENT_TYPE) + .body(""" + {"DeliveryChannelName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("LastDeliveryChannelDeleteFailedException")); + } + + @Test + @Order(11) + void deleteDeliveryChannelAfterRecorderStopped() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "StopConfigurationRecorder") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigurationRecorderName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteDeliveryChannel") + .contentType(CONTENT_TYPE) + .body(""" + {"DeliveryChannelName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(12) + void deleteDeliveryChannelAgain() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteDeliveryChannel") + .contentType(CONTENT_TYPE) + .body(""" + {"DeliveryChannelName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchDeliveryChannelException")); + } + + @Test + @Order(13) + void deleteConfigurationRecorder() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigurationRecorder") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigurationRecorderName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(14) + void describeConfigurationRecordersAfterDelete() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigurationRecorders") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("ConfigurationRecorders", hasSize(0)); + } + + @Test + @Order(15) + void deleteConfigurationRecorderAgain() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigurationRecorder") + .contentType(CONTENT_TYPE) + .body(""" + {"ConfigurationRecorderName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchConfigurationRecorderException")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/DescribeConfigRulesLimitTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/DescribeConfigRulesLimitTest.java new file mode 100644 index 0000000000..b1b409916f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/DescribeConfigRulesLimitTest.java @@ -0,0 +1,35 @@ +package io.github.hectorvent.floci.services.configservice; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * DescribeConfigRules' ConfigRuleNames member is modeled with {@code Maximum 25 items} + * (confirmed against botocore's config service-2.json). Every other array-size limit this + * PR touches (Scope.ComplianceResourceTypes, PutEvaluations, PutRetentionConfiguration's + * day range) is enforced; this one was not. + */ +class DescribeConfigRulesLimitTest { + + private static final String REGION = "us-east-1"; + + @Test + void rejectsMoreThanTwentyFiveRuleNames() { + AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), null); + List tooMany = new ArrayList<>(); + for (int i = 0; i < 26; i++) { + tooMany.add("rule-" + i); + } + + AwsException ex = assertThrows(AwsException.class, + () -> service.describeConfigRules(REGION, tooMany)); + assertEquals("InvalidParameterValueException", ex.getErrorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/RetentionConfigurationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/RetentionConfigurationIntegrationTest.java new file mode 100644 index 0000000000..d0fc5eb100 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/RetentionConfigurationIntegrationTest.java @@ -0,0 +1,131 @@ +package io.github.hectorvent.floci.services.configservice; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class RetentionConfigurationIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String TARGET_PREFIX = "StarlingDoveService."; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void putRetentionConfiguration() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutRetentionConfiguration") + .contentType(CONTENT_TYPE) + .body(""" + {"RetentionPeriodInDays": 365} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("RetentionConfiguration.Name", equalTo("default")) + .body("RetentionConfiguration.RetentionPeriodInDays", equalTo(365)); + } + + @Test + @Order(2) + void describeRetentionConfigurations() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeRetentionConfigurations") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("RetentionConfigurations", hasSize(1)) + .body("RetentionConfigurations[0].Name", equalTo("default")) + .body("RetentionConfigurations[0].RetentionPeriodInDays", equalTo(365)); + } + + @Test + @Order(3) + void putRetentionConfigurationBelowMinimumIsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "PutRetentionConfiguration") + .contentType(CONTENT_TYPE) + .body(""" + {"RetentionPeriodInDays": 29} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + + @Test + @Order(4) + void describeRetentionConfigurationsUnknownName() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeRetentionConfigurations") + .contentType(CONTENT_TYPE) + .body(""" + {"RetentionConfigurationNames": ["no-such-retention"]} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchRetentionConfigurationException")); + } + + @Test + @Order(5) + void deleteRetentionConfiguration() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteRetentionConfiguration") + .contentType(CONTENT_TYPE) + .body(""" + {"RetentionConfigurationName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", TARGET_PREFIX + "DescribeRetentionConfigurations") + .contentType(CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("RetentionConfigurations", hasSize(0)); + } + + @Test + @Order(6) + void deleteRetentionConfigurationAgainIsRejected() { + given() + .header("X-Amz-Target", TARGET_PREFIX + "DeleteRetentionConfiguration") + .contentType(CONTENT_TYPE) + .body(""" + {"RetentionConfigurationName": "default"} + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchRetentionConfigurationException")); + } +}