mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
* 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.
314 lines
8.9 KiB
Python
314 lines
8.9 KiB
Python
"""Shared fixtures for AWS service integration tests."""
|
|
|
|
import os
|
|
import uuid
|
|
import io
|
|
import zipfile
|
|
|
|
import logging
|
|
|
|
import boto3
|
|
import pytest
|
|
from botocore.config import Config
|
|
from botocore.exceptions import ClientError
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def endpoint_url():
|
|
"""Return the Floci endpoint URL."""
|
|
return os.environ.get("FLOCI_ENDPOINT", "http://localhost:4566")
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def aws_config(endpoint_url):
|
|
"""Common AWS configuration from environment variables."""
|
|
return {
|
|
"endpoint_url": endpoint_url,
|
|
"region_name": os.environ.get("AWS_DEFAULT_REGION", "us-east-1"),
|
|
"aws_access_key_id": os.environ.get("AWS_ACCESS_KEY_ID", "test"),
|
|
"aws_secret_access_key": os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),
|
|
}
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def client_config():
|
|
"""Botocore client configuration with retry settings."""
|
|
return Config(retries={"max_attempts": 1})
|
|
|
|
|
|
# ============================================
|
|
# Service Client Fixtures
|
|
# ============================================
|
|
|
|
|
|
@pytest.fixture
|
|
def ssm_client(aws_config, client_config):
|
|
"""Create SSM client."""
|
|
return boto3.client("ssm", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def sqs_client(aws_config, client_config):
|
|
"""Create SQS client."""
|
|
return boto3.client("sqs", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def sns_client(aws_config, client_config):
|
|
"""Create SNS client."""
|
|
return boto3.client("sns", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def s3_client(aws_config, client_config):
|
|
"""Create S3 client."""
|
|
return boto3.client("s3", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def dynamodb_client(aws_config, client_config):
|
|
"""Create DynamoDB client."""
|
|
return boto3.client("dynamodb", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def lambda_client(aws_config, client_config):
|
|
"""Create Lambda client."""
|
|
return boto3.client("lambda", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def iam_client(aws_config, client_config):
|
|
"""Create IAM client."""
|
|
return boto3.client("iam", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def sts_client(aws_config, client_config):
|
|
"""Create STS client."""
|
|
return boto3.client("sts", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def secretsmanager_client(aws_config, client_config):
|
|
"""Create Secrets Manager client."""
|
|
return boto3.client("secretsmanager", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def kms_client(aws_config, client_config):
|
|
"""Create KMS client."""
|
|
return boto3.client("kms", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def kinesis_client(aws_config, client_config):
|
|
"""Create Kinesis client."""
|
|
return boto3.client("kinesis", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def cloudwatch_client(aws_config, client_config):
|
|
"""Create CloudWatch client."""
|
|
return boto3.client("cloudwatch", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def glue_client(aws_config, client_config):
|
|
"""Create Glue client."""
|
|
return boto3.client("glue", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def resourcegroupstaggingapi_client(aws_config, client_config):
|
|
"""Create Resource Groups Tagging API client."""
|
|
return boto3.client("resourcegroupstaggingapi", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def logs_client(aws_config, client_config):
|
|
"""Create CloudWatch Logs client."""
|
|
return boto3.client("logs", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def cognito_client(aws_config, client_config):
|
|
"""Create Cognito Identity Provider client."""
|
|
return boto3.client("cognito-idp", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def cloudformation_client(aws_config, client_config):
|
|
"""Create CloudFormation client."""
|
|
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."""
|
|
return boto3.client("acm", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def ecr_client(aws_config, client_config):
|
|
"""Create ECR client."""
|
|
return boto3.client("ecr", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def neptune_client(aws_config, client_config):
|
|
"""Create Neptune client."""
|
|
return boto3.client("neptune", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def pipes_client(aws_config, client_config):
|
|
"""Create EventBridge Pipes client."""
|
|
return boto3.client("pipes", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def ses_client(aws_config, client_config):
|
|
"""Create SES (v1) client."""
|
|
return boto3.client("ses", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def sesv2_client(aws_config, client_config):
|
|
"""Create SES v2 client."""
|
|
return boto3.client("sesv2", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def iot_client(aws_config, client_config):
|
|
"""Create AWS IoT client."""
|
|
return boto3.client("iot", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def iot_data_client(aws_config, client_config):
|
|
"""Create AWS IoT Data client."""
|
|
return boto3.client("iot-data", config=client_config, **aws_config)
|
|
|
|
|
|
@pytest.fixture
|
|
def iot_jobs_data_client(aws_config, client_config):
|
|
"""Create AWS IoT Jobs Data client."""
|
|
return boto3.client("iot-jobs-data", config=client_config, **aws_config)
|
|
|
|
|
|
# ============================================
|
|
# Utility Fixtures
|
|
# ============================================
|
|
|
|
|
|
@pytest.fixture
|
|
def unique_name():
|
|
"""Generate a unique name for test resources."""
|
|
return f"pytest-{uuid.uuid4().hex[:8]}"
|
|
|
|
|
|
@pytest.fixture
|
|
def minimal_lambda_zip():
|
|
"""Create a minimal Node.js Lambda deployment package."""
|
|
code = (
|
|
"exports.handler = async (event) => {\n"
|
|
" console.log('[handler] event:', JSON.stringify(event));\n"
|
|
" const name = (event && event.name) ? event.name : 'World';\n"
|
|
" return { statusCode: 200, body: JSON.stringify({ message: `Hello, ${name}!`, input: event }) };\n"
|
|
"};\n"
|
|
)
|
|
buf = io.BytesIO()
|
|
with zipfile.ZipFile(buf, "w") as zf:
|
|
zf.writestr("index.js", code)
|
|
return buf.getvalue()
|
|
|
|
|
|
# ============================================
|
|
# Resource Fixtures with Cleanup
|
|
# ============================================
|
|
|
|
|
|
@pytest.fixture
|
|
def test_bucket(s3_client, unique_name):
|
|
"""Create and cleanup a test S3 bucket."""
|
|
bucket_name = f"test-bucket-{unique_name}"
|
|
s3_client.create_bucket(Bucket=bucket_name)
|
|
|
|
yield bucket_name
|
|
|
|
# Cleanup: empty and delete bucket
|
|
try:
|
|
paginator = s3_client.get_paginator("list_objects_v2")
|
|
for page in paginator.paginate(Bucket=bucket_name):
|
|
if "Contents" in page:
|
|
for obj in page["Contents"]:
|
|
s3_client.delete_object(Bucket=bucket_name, Key=obj["Key"])
|
|
s3_client.delete_bucket(Bucket=bucket_name)
|
|
except ClientError as e:
|
|
logger.warning("Failed to clean up S3 bucket %s: %s", bucket_name, e)
|
|
|
|
|
|
@pytest.fixture
|
|
def test_queue(sqs_client, unique_name):
|
|
"""Create and cleanup a test SQS queue."""
|
|
queue_name = f"test-queue-{unique_name}"
|
|
response = sqs_client.create_queue(QueueName=queue_name)
|
|
queue_url = response["QueueUrl"]
|
|
|
|
yield queue_url
|
|
|
|
# Cleanup
|
|
try:
|
|
sqs_client.delete_queue(QueueUrl=queue_url)
|
|
except ClientError as e:
|
|
logger.warning("Failed to clean up SQS queue %s: %s", queue_url, e)
|
|
|
|
|
|
@pytest.fixture
|
|
def test_topic(sns_client, unique_name):
|
|
"""Create and cleanup a test SNS topic."""
|
|
topic_name = f"test-topic-{unique_name}"
|
|
response = sns_client.create_topic(Name=topic_name)
|
|
topic_arn = response["TopicArn"]
|
|
|
|
yield topic_arn
|
|
|
|
# Cleanup
|
|
try:
|
|
sns_client.delete_topic(TopicArn=topic_arn)
|
|
except ClientError as e:
|
|
logger.warning("Failed to clean up SNS topic %s: %s", topic_arn, e)
|
|
|
|
|
|
@pytest.fixture
|
|
def test_table(dynamodb_client, unique_name):
|
|
"""Create and cleanup a test DynamoDB table."""
|
|
table_name = f"test-table-{unique_name}"
|
|
dynamodb_client.create_table(
|
|
TableName=table_name,
|
|
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
|
|
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
|
|
BillingMode="PAY_PER_REQUEST",
|
|
)
|
|
|
|
# Wait for table to be active
|
|
waiter = dynamodb_client.get_waiter("table_exists")
|
|
waiter.wait(TableName=table_name, WaiterConfig={"Delay": 1, "MaxAttempts": 30})
|
|
|
|
yield table_name
|
|
|
|
# Cleanup
|
|
try:
|
|
dynamodb_client.delete_table(TableName=table_name)
|
|
except ClientError as e:
|
|
logger.warning("Failed to clean up DynamoDB table %s: %s", table_name, e)
|