Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(AWS): monthly AWS parity run conformance (#1298)
Nahuel Nucera896b03b1cf28
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5873b185..70172308 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,12 +8,24 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **SNS — `$or` operator in subscription filter policies** — a filter policy with a top-level `$or` key was matched with plain AND semantics, so `$or` never matched and every message was silently dropped as non-matching. `$or` is now evaluated the way AWS does: a recognized `$or` (an array of at least two objects whose field names are not reserved rule keywords) matches when any of its member policies matches, sibling keys are AND-ed with it, member keys are AND-ed internally, and nested `$or` is supported; an unrecognized `$or` is treated as a literal attribute name, as on AWS. Applies to the `MessageAttributes` filter scope. Reported by @StiliyanDr.- **RDS — `StopDBCluster` / `StartDBCluster` now stop and start Aurora compute** — both operations only flipped metadata: a "stopped" cluster's backing container kept running and accepting SQL connections, and its members never left `available`. `StopDBCluster` now stops the cluster's shared container — preserving the container, volume, and data, exactly like Aurora keeps the cluster volume — and marks the cluster and every member `stopped`. `StartDBCluster` restarts the preserved container (recreating compute from the persistent named volume when the container is gone or unrestartable) and, like `CreateDBInstance`, returns immediately with a transitional status while a readiness worker flips the cluster and members to `available` once the database accepts authenticated connections. Invalid transitions return the AWS-exact `InvalidDBClusterStateFault` messages — including `CreateDBInstance`/`DeleteDBInstance` against a stopped cluster — and a warm boot keeps an intentionally stopped cluster stopped instead of reviving its compute. A start whose compute genuinely fails to come back lands the cluster back on `stopped` (retryable) instead of reporting a dead endpoint as `available`, and a stop that cannot stop the container surfaces an error instead of publishing a false `stopped`. Contributed by @kiran01bm.- **RDS — Aurora PostgreSQL engine versions are validated at create time** — `CreateDBCluster` / `CreateDBInstance` accepted any `EngineVersion` string for `aurora-postgresql`: because the Docker image is derived from the major alone, a bogus minor like `16.99` silently ran PostgreSQL 16 while claiming to be `16.99`, and only an unknown major produced a visible image-pull failure. An unknown version — anything `DescribeDBEngineVersions` doesn't advertise and that isn't a dot-boundary prefix of an advertised version (bare majors like `16` stay accepted, since real AWS resolves them server-side) — now fails immediately with `InvalidParameterCombination` / `Cannot find version {version} for aurora-postgresql`, matching real AWS and the existing aurora-mysql behavior; `DescribeOrderableDBInstanceOptions` rejects unknown versions the same way instead of echoing a fabricated option. The advertised catalog is refreshed to the full creatable set real AWS returns (41 versions, 11.9 through 18.4, including `-limitless` variants, as of 2026-08-06) and is a single shared constant used by both the catalog and the validator; the default `aurora-postgresql` version is now `17.7` (AWS's current default) and the CloudFormation `AWS::RDS::DBCluster` provisioner uses that shared default instead of a hard-coded `15.4`. Contributed by @kiran01bm.- **RDS — duplicate DB instance wire code matches AWS** — a duplicate `CreateDBInstance`, `CreateDBInstanceReadReplica`, or `RestoreDBInstanceFromDBSnapshot` target returned wire code `DBInstanceAlreadyExistsFault`, but real AWS omits the `Fault` suffix for instance-level error codes (cluster-level codes such as `DBClusterAlreadyExistsFault` keep it). SDKs match the exact string to produce their typed error — aws-sdk-go-v2, for example, deserialized the response as a generic API error instead of the typed `DBInstanceAlreadyExistsFault`. The wire code is now `DBInstanceAlreadyExists`. This deliberately reverts the v1.1.18 change, which mistook the SDK exception *shape name* for the *wire code* — the model's `error.code` field (`DBInstanceAlreadyExists`) is what SDKs match, and exact-string tests now pin the correct direction. Contributed by @kiran01bm.### Added- **CodeBuild - builds can really run (`MINISTACK_CODEBUILD_EXECUTE=1`)** - `StartBuild` returned a build that was already `SUCCEEDED`, so a pipeline rehearsed against MiniStack reported a pass without a single phase having run, and a buildspec that fails on AWS still looked green locally. With the flag set, `StartBuild` returns `IN_PROGRESS` and the project's inline buildspec is handed to the official AWS CodeBuild local agent (`public.ecr.aws/codebuild/local-builds`), which runs the phases in the project's `environment.image` the way CodeBuild does - the phase semantics come from AWS's own agent instead of a reimplemented executor. `BatchGetBuilds` reflects progress while the build runs: the agent's `Phase complete: <PHASE> State: <STATUS>` lines become `phases` entries, and the container's exit status maps to `SUCCEEDED` / `FAILED`, with `FAULT` when Docker is unreachable. `environment.environmentVariables`, `privilegedMode`, and the `CODEBUILD_BUILD_ID` / `_ARN` / `_NUMBER` / `_INITIATOR` variables reach the build. The build reaches back into MiniStack: `AWS_ENDPOINT_URL` (plus placeholder credentials) is injected unless the project declares its own, so `aws s3 cp` inside a build hits this emulator rather than real AWS. `timeoutInMinutes` is enforced (the build is stopped and its phase reported `TIMED_OUT`), and a restored build that was in flight when MiniStack stopped is reported `FAULT` rather than polling as running forever. `StopBuild` is honoured deterministically: it records the intent before removing the container, so the worker reports the requested `STOPPED` instead of racing it to `FAULT`. Build output also reaches CloudWatch Logs: the record already advertised `logs.groupName` / `logs.streamName`, and an executed build now writes the agent output there, so `aws logs get-log-events` and `aws logs tail` read back a real build log instead of an empty stream. Default behaviour is unchanged - without the flag builds stay metadata-only. Requires the Docker socket; the agent image and workspace path are fixed internals, not configurable.+## [1.4.14] — 2026-08-06++### Added+- **EventBridge Pipes — the SDK data plane is now reachable** — Pipes was fully built (pipe store, background poller, region scoping, persistence, CloudFormation provisioner) but had no REST route, so `aws pipes list-pipes` fell through to S3 virtual-host addressing and returned `NoSuchBucket`. `ListPipes`, `CreatePipe`, `DescribePipe`, `UpdatePipe`, `DeletePipe`, `StartPipe`, `StopPipe`, and the tag operations are now served over boto3 / Terraform / CDK at `pipes.<region>` and `/v1/pipes`, reusing the existing store.+- **AWS Config** — control plane for config rules, configuration recorders, and delivery channels: `PutConfigRule` / `DescribeConfigRules` / `DeleteConfigRule`, recorder and delivery-channel CRUD plus their status reads, `StartConfigurationRecorder` / `StopConfigurationRecorder`, and the compliance and evaluation-status reads.+- **Cloud Control API (`cloudcontrol`)** — the generic resource control plane behind Terraform's `awscc` provider and CDK L1 constructs: `CreateResource` / `GetResource` / `UpdateResource` / `DeleteResource` / `ListResources` plus the resource-request status and cancel operations, with the AWS `ProgressEvent` and `ResourceDescription` shapes (`Properties` as a JSON string).++### Fixed+- **Query-protocol services MiniStack does not implement now return a parseable error** — a call to an unimplemented Query service (`redshift`, `elasticbeanstalk`, `cloudsearch`, `sdb`, `importexport`) fell through to S3 and returned a 405 `<Error>` root that botocore's query parser can't read, raising a bare `KeyError('Error')` instead of a `ClientError`. Such requests now return a Query `<ErrorResponse>` envelope (`<Type>Sender</Type>`, code `InvalidAction`) at HTTP 400.+- **AWS Backup, CloudFront, Inspector2, and MediaConnect — unrouted read operations** — services MiniStack ships whose REST sub-paths returned `Unknown path`, so an SDK call reached the service and got an error where AWS returns data. Roughly 96 read operations across the four now return AWS-shaped responses (Backup 47, Inspector2 22, CloudFront 14, MediaConnect 13); operations that require a resource store MiniStack does not keep were left unrouted rather than given a fabricated shape.+## [1.4.13] — 2026-08-06### Fixeddiff --git a/ministack/app.py b/ministack/app.pyindex 28f21980..328cf630 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -263,11 +263,13 @@ SERVICE_REGISTRY = {"athena": {"module": "athena"},"autoscaling": {"module": "autoscaling"},"cloudformation": {"module": "cloudformation"},+ "cloudcontrol": {"module": "cloudcontrol"},"cloudfront": {"module": "cloudfront"},"cloudfront-keyvaluestore": {"module": "cloudfront_keyvaluestore"},"codebuild": {"module": "codebuild"},"cognito-identity": {"module": "cognito"},"cognito-idp": {"module": "cognito"},+ "config": {"module": "config"},"dynamodb": {"module": "dynamodb"},"dynamodbstreams": {"module": "dynamodb_streams"},"ec2": {"module": "ec2"},@@ -296,6 +298,7 @@ SERVICE_REGISTRY = {"opensearch": {"module": "opensearch", "aliases": ("es", "elasticsearch")},"organizations": {"module": "organizations"},"monitoring": {"module": "cloudwatch", "aliases": ("cloudwatch",)},+ "pipes": {"module": "pipes"},"rds-data": {"module": "rds_data"},"rds": {"module": "rds"},"resource-groups": {"module": "resource_groups"},@@ -1731,6 +1734,34 @@ def _routing_params(method: str, path: str, headers: dict, body: bytes, query_pareturn routing_params+def _unknown_query_error(body: bytes, request_id: str):+ """A form-encoded (Query-protocol) request reached the router for a service+ MiniStack does not implement (redshift, elasticbeanstalk, cloudsearch, sdb,+ importexport, ...). Real AWS answers with the Query ``<ErrorResponse>``+ envelope at HTTP 400 (``<Type>Sender</Type>``, code ``InvalidAction``);+ falling through to S3 returns a 405 ``<Error>`` root that botocore's query+ parser can't read, raising a bare ``KeyError('Error')`` instead of a+ ``ClientError``."""+ action = ""+ try:+ from urllib.parse import parse_qs+ action = (parse_qs(body.decode("utf-8", "replace")).get("Action") or [""])[0]+ except Exception:+ pass+ msg = (+ f"The action {action} is not valid for this web service."+ if action else "The requested action is not valid for this web service."+ )+ msg = msg.replace("&", "&").replace("<", "<").replace(">", ">")+ xml = (+ '<?xml version="1.0" encoding="UTF-8"?>\n'+ '<ErrorResponse xmlns="http://webservices.amazon.com/doc/2010-05-08/">'+ f"<Error><Type>Sender</Type><Code>InvalidAction</Code><Message>{msg}</Message></Error>"+ f"<RequestId>{request_id}</RequestId></ErrorResponse>"+ )+ return 400, {"Content-Type": "text/xml"}, xml.encode()++async def _dispatch_service_request(method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str):@@ -1741,6 +1772,9 @@ async def _dispatch_service_request(logger.debug("%s %s -> service=%s region=%s", method, path, service, region)+ if service == "unknown_query":+ return _unknown_query_error(body, request_id)+handler = SERVICE_HANDLERS.get(service)if not handler:return (diff --git a/ministack/core/router.py b/ministack/core/router.pyindex d5503a0a..14ec3972 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -361,6 +361,21 @@ SERVICE_PATTERNS = {"path_prefixes": ["/schedules", "/schedule-groups"],"credential_scope": "scheduler",},+ "pipes": {+ "host_patterns": [r"pipes\."],+ "path_prefixes": ["/v1/pipes"],+ "credential_scope": "pipes",+ },+ "cloudcontrol": {+ "target_prefixes": ["CloudApiService"],+ "host_patterns": [r"cloudcontrolapi\."],+ "credential_scope": "cloudcontrolapi",+ },+ "config": {+ "target_prefixes": ["StarlingDoveService"],+ "host_patterns": [r"config\."],+ "credential_scope": "config",+ },"eks": {"host_patterns": [r"eks\."],"path_prefixes": ["/oidc/"],@@ -1014,6 +1029,18 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->if re.search(hp, host):return svc+ # 6a. A Query-protocol call to a service we don't implement (redshift,+ # elasticbeanstalk, cloudsearch, sdb, importexport, ...) is a POST to the+ # service root with an x-www-form-urlencoded body (Action=...&Version=...).+ # Real AWS answers with a Query <ErrorResponse> envelope at HTTP 400;+ # falling through to S3 returns a 405 <Error> root that botocore's query+ # parser can't read (it raises a bare KeyError('Error')). Restrict to+ # POST-to-root so we don't hijack S3 requests whose body carries a+ # form-urlencoded Content-Type (e.g. urllib defaults it on a raw PUT body).+ if (method == "POST" and path in ("/", "")+ and "application/x-www-form-urlencoded" in headers.get("content-type", "")):+ return "unknown_query"+# 6. Default to S3 (same as real LocalStack behavior)return "s3"diff --git a/ministack/services/backup.py b/ministack/services/backup.pyindex a80728a3..abbc2b9c 100644--- a/ministack/services/backup.py+++ b/ministack/services/backup.py@@ -10,6 +10,14 @@ Supports:ListBackupSelectionsJobs: StartBackupJob, StopBackupJob, DescribeBackupJob, ListBackupJobsTags: TagResource, UntagResource, ListTags++Read-only surface (empty/default documents — no persisted state for these+resource families yet, so lists come back empty and singleton lookups return+ResourceNotFoundException, matching real AWS):+ Copy/Restore/Report/Scan jobs, Frameworks, Report plans, Recovery points,+ Protected resources, Legal holds, Restore-testing plans/selections,+ Backup-plan templates, Tiering configurations, account/region/global+ settings, supported resource types, vault access-policy / notifications."""import copy@@ -565,6 +573,266 @@ def _list_tags(arn):return _ok({"Tags": dict(tag_dict)})+# ---------------------------------------------------------------------------+# Read-only surface (empty / default documents)+#+# MiniStack does not yet persist copy jobs, restore jobs, report jobs/plans,+# frameworks, recovery points, protected resources, legal holds,+# restore-testing plans/selections, backup-plan templates or tiering+# configurations. Real AWS returns empty lists for the List* operations on+# these families and ResourceNotFoundException for a Get*/Describe* of a+# specific (necessarily absent) resource. AWS Backup returns HTTP 400 for+# ResourceNotFoundException (not 404), so these handlers use _not_found().+#+# Shapes and JSON key casing are taken verbatim from the botocore+# backup/2018-11-15 service-2.json (rest-json) output shapes.+# ---------------------------------------------------------------------------++# AWS resource types supported by AWS Backup (GetSupportedResourceTypes).+_SUPPORTED_RESOURCE_TYPES = [+ "Aurora", "CloudFormation", "DocumentDB", "DynamoDB", "EBS", "EC2",+ "EFS", "EKS", "FSx", "Neptune", "RDS", "Redshift", "S3",+ "SAP HANA on Amazon EC2", "Storage Gateway", "Timestream", "VirtualMachine",+]+++def _not_found(msg):+ # AWS Backup returns HTTP 400 for ResourceNotFoundException.+ return _err("ResourceNotFoundException", msg, 400)+++def _empty_list(query, key):+ """List* on a family MiniStack does not persist yet: AWS-correct empty page."""+ return _paginate([], query, key)+++# --- Copy jobs -------------------------------------------------------------++def _list_copy_jobs(query):+ return _empty_list(query, "CopyJobs")+++def _describe_copy_job(copy_job_id):+ return _not_found(f"Copy job '{copy_job_id}' not found.")+++# --- Restore jobs ----------------------------------------------------------++def _list_restore_jobs(query):+ return _empty_list(query, "RestoreJobs")+++def _describe_restore_job(restore_job_id):+ return _not_found(f"Restore job '{restore_job_id}' not found.")+++def _get_restore_job_metadata(restore_job_id):+ return _not_found(f"Restore job '{restore_job_id}' not found.")+++def _list_restore_jobs_by_resource(query):+ return _empty_list(query, "RestoreJobs")+++# --- Report jobs / plans ---------------------------------------------------++def _list_report_jobs(query):+ return _empty_list(query, "ReportJobs")+++def _describe_report_job(report_job_id):+ return _not_found(f"Report job '{report_job_id}' not found.")+++def _list_report_plans(query):+ return _empty_list(query, "ReportPlans")+++def _describe_report_plan(report_plan_name):+ return _not_found(f"Report plan '{report_plan_name}' not found.")+++# --- Frameworks ------------------------------------------------------------++def _list_frameworks(query):+ return _empty_list(query, "Frameworks")+++def _describe_framework(framework_name):+ return _not_found(f"Framework '{framework_name}' not found.")+++# --- Recovery points -------------------------------------------------------++def _list_recovery_points_by_vault(vault_name, query):+ if vault_name not in _vaults:+ return _not_found(f"Vault '{vault_name}' not found.")+ return _empty_list(query, "RecoveryPoints")+++def _describe_recovery_point(vault_name, recovery_point_arn):+ if vault_name not in _vaults:+ return _not_found(f"Vault '{vault_name}' not found.")+ return _not_found(f"Recovery point '{recovery_point_arn}' not found.")+++def _get_recovery_point_index_details(vault_name, recovery_point_arn):+ if vault_name not in _vaults:+ return _not_found(f"Vault '{vault_name}' not found.")+ return _not_found(f"Recovery point '{recovery_point_arn}' not found.")+++def _get_recovery_point_restore_metadata(vault_name, recovery_point_arn):+ if vault_name not in _vaults:+ return _not_found(f"Vault '{vault_name}' not found.")+ return _not_found(f"Recovery point '{recovery_point_arn}' not found.")+++def _list_recovery_points_by_resource(query):+ return _empty_list(query, "RecoveryPoints")+++# --- Protected resources ---------------------------------------------------++def _list_protected_resources(query):+ return _empty_list(query, "Results")+++def _list_protected_resources_by_vault(vault_name, query):+ if vault_name not in _vaults:+ return _not_found(f"Vault '{vault_name}' not found.")+ return _empty_list(query, "Results")+++def _describe_protected_resource(resource_arn):+ return _not_found(f"Protected resource '{resource_arn}' not found.")+++# --- Legal holds -----------------------------------------------------------++def _list_legal_holds(query):+ return _empty_list(query, "LegalHolds")+++def _get_legal_hold(legal_hold_id):+ return _not_found(f"Legal hold '{legal_hold_id}' not found.")+++def _list_recovery_points_by_legal_hold(legal_hold_id, query):+ return _not_found(f"Legal hold '{legal_hold_id}' not found.")+++# --- Restore testing -------------------------------------------------------++def _list_restore_testing_plans(query):+ return _empty_list(query, "RestoreTestingPlans")+++def _get_restore_testing_plan(plan_name):+ return _not_found(f"Restore testing plan '{plan_name}' not found.")+++def _list_restore_testing_selections(plan_name, query):+ return _not_found(f"Restore testing plan '{plan_name}' not found.")+++def _get_restore_testing_selection(plan_name, selection_name):+ return _not_found(f"Restore testing plan '{plan_name}' not found.")+++# --- Scan jobs -------------------------------------------------------------++def _list_scan_jobs(query):+ return _empty_list(query, "ScanJobs")+++def _describe_scan_job(scan_job_id):+ return _not_found(f"Scan job '{scan_job_id}' not found.")+++# --- Audit summaries (aggregations) ----------------------------------------++def _list_backup_job_summaries(query):+ return _ok({"BackupJobSummaries": []})+++def _list_copy_job_summaries(query):+ return _ok({"CopyJobSummaries": []})+++def _list_restore_job_summaries(query):+ return _ok({"RestoreJobSummaries": []})+++def _list_scan_job_summaries(query):+ return _ok({"ScanJobSummaries": []})+++# --- Backup plan templates -------------------------------------------------++def _list_backup_plan_templates(query):+ return _paginate([], query, "BackupPlanTemplatesList")+++# --- Indexed recovery points -----------------------------------------------++def _list_indexed_recovery_points(query):+ return _empty_list(query, "IndexedRecoveryPoints")+++# --- Tiering configurations ------------------------------------------------++def _list_tiering_configurations(query):+ return _empty_list(query, "TieringConfigurations")+++def _get_tiering_configuration(name):+ return _not_found(f"Tiering configuration '{name}' not found.")+++# --- Logically air-gapped restore access vaults ----------------------------++def _list_restore_access_backup_vaults(vault_name, query):+ if vault_name not in _vaults:+ return _not_found(f"Vault '{vault_name}' not found.")+ return _empty_list(query, "RestoreAccessBackupVaults")+++# --- Vault access policy / notifications -----------------------------------++def _get_vault_access_policy(vault_name):+ # Real AWS returns ResourceNotFoundException when no policy is set (and when+ # the vault itself is absent). MiniStack persists no vault access policies.+ if vault_name not in _vaults:+ return _not_found(f"Vault '{vault_name}' not found.")+ return _not_found(f"No access policy is associated with vault '{vault_name}'.")+++def _get_vault_notifications(vault_name):+ # Real AWS returns ResourceNotFoundException when no notification config is+ # set. MiniStack persists no vault notification configurations.+ if vault_name not in _vaults:+ return _not_found(f"Vault '{vault_name}' not found.")+ return _not_found(f"No notifications are associated with vault '{vault_name}'.")+++# --- Account / region / global settings (always-present defaults) ----------++def _describe_region_settings():+ return _ok({+ "ResourceTypeOptInPreference": {},+ "ResourceTypeManagementPreference": {},+ })+++def _describe_global_settings():+ return _ok({"GlobalSettings": {}})+++def _get_supported_resource_types():+ return _ok({"ResourceTypes": list(_SUPPORTED_RESOURCE_TYPES)})++# ---------------------------------------------------------------------------# Request Router# ---------------------------------------------------------------------------@@ -590,6 +858,48 @@ async def handle_request(method, path, headers, body_bytes, query_params):return _describe_vault(name)if method == "DELETE":return _delete_vault(name)+ # /backup-vaults/{vaultName}/<sub-resource>+ if len(parts) >= 3:+ name = parts[1]+ sub = parts[2]+ if method == "GET":+ if sub == "access-policy" and len(parts) == 3:+ return _get_vault_access_policy(name)+ if sub == "notification-configuration" and len(parts) == 3:+ return _get_vault_notifications(name)+ if sub == "resources" and len(parts) == 3:+ return _list_protected_resources_by_vault(name, query)+ if sub == "recovery-points":+ if len(parts) == 3:+ return _list_recovery_points_by_vault(name, query)+ # /backup-vaults/{name}/recovery-points/{rpArn}[/index|/restore-metadata]+ if parts[-1] == "index":+ rp = "/".join(parts[3:-1])+ return _get_recovery_point_index_details(name, rp)+ if parts[-1] == "restore-metadata":+ rp = "/".join(parts[3:-1])+ return _get_recovery_point_restore_metadata(name, rp)+ rp = "/".join(parts[3:])+ return _describe_recovery_point(name, rp)++ # /logically-air-gapped-backup-vaults/{vaultName}/restore-access-backup-vaults+ if (+ len(parts) == 3+ and parts[0] == "logically-air-gapped-backup-vaults"+ and parts[2] == "restore-access-backup-vaults"+ and method == "GET"+ ):+ return _list_restore_access_backup_vaults(parts[1], query)++ # /backup/template/plans — ListBackupPlanTemplates+ if (+ len(parts) == 3+ and parts[0] == "backup"+ and parts[1] == "template"+ and parts[2] == "plans"+ and method == "GET"+ ):+ return _list_backup_plan_templates(query)# /backup/plans (and nested selections/versions)if len(parts) >= 2 and parts[0] == "backup" and parts[1] == "plans":@@ -657,4 +967,113 @@ async def handle_request(method, path, headers, body_bytes, query_params):if method == "POST":return _untag_resource(arn, body)+ # -------------------------------------------------------------------+ # Read-only families with no persisted state (empty / not-found docs).+ # -------------------------------------------------------------------++ # /copy-jobs and /copy-jobs/{copyJobId}+ if parts and parts[0] == "copy-jobs" and method == "GET":+ if len(parts) == 1:+ return _list_copy_jobs(query)+ if len(parts) == 2:+ return _describe_copy_job(parts[1])++ # /restore-jobs, /restore-jobs/{id}, /restore-jobs/{id}/metadata+ if parts and parts[0] == "restore-jobs" and method == "GET":+ if len(parts) == 1:+ return _list_restore_jobs(query)+ if len(parts) == 2:+ return _describe_restore_job(parts[1])+ if len(parts) == 3 and parts[2] == "metadata":+ return _get_restore_job_metadata(parts[1])++ # /resources and /resources/{resourceArn}[/recovery-points|/restore-jobs]+ if parts and parts[0] == "resources" and method == "GET":+ if len(parts) == 1:+ return _list_protected_resources(query)+ if parts[-1] == "recovery-points":+ return _list_recovery_points_by_resource(query)+ if parts[-1] == "restore-jobs":+ return _list_restore_jobs_by_resource(query)+ return _describe_protected_resource("/".join(parts[1:]))++ # /legal-holds, /legal-holds/{id}, /legal-holds/{id}/recovery-points+ if parts and parts[0] == "legal-holds" and method == "GET":+ if len(parts) == 1:+ return _list_legal_holds(query)+ if len(parts) == 2:+ return _get_legal_hold(parts[1])+ if len(parts) == 3 and parts[2] == "recovery-points":+ return _list_recovery_points_by_legal_hold(parts[1], query)++ # /restore-testing/plans[/{name}[/selections[/{sel}]]]+ if len(parts) >= 2 and parts[0] == "restore-testing" and parts[1] == "plans" and method == "GET":+ if len(parts) == 2:+ return _list_restore_testing_plans(query)+ if len(parts) == 3:+ return _get_restore_testing_plan(parts[2])+ if len(parts) == 4 and parts[3] == "selections":+ return _list_restore_testing_selections(parts[2], query)+ if len(parts) == 5 and parts[3] == "selections":+ return _get_restore_testing_selection(parts[2], parts[4])++ # /scan/jobs and /scan/jobs/{scanJobId}+ if len(parts) >= 2 and parts[0] == "scan" and parts[1] == "jobs" and method == "GET":+ if len(parts) == 2:+ return _list_scan_jobs(query)+ if len(parts) == 3:+ return _describe_scan_job(parts[2])++ # /tiering-configurations and /tiering-configurations/{name}+ if parts and parts[0] == "tiering-configurations" and method == "GET":+ if len(parts) == 1:+ return _list_tiering_configurations(query)+ if len(parts) == 2:+ return _get_tiering_configuration(parts[1])++ # /indexes/recovery-point — ListIndexedRecoveryPoints+ if (+ len(parts) == 2+ and parts[0] == "indexes"+ and parts[1] == "recovery-point"+ and method == "GET"+ ):+ return _list_indexed_recovery_points(query)++ # /audit/* — frameworks, report-jobs, report-plans and summaries+ if len(parts) >= 2 and parts[0] == "audit" and method == "GET":+ sub = parts[1]+ if sub == "frameworks":+ if len(parts) == 2:+ return _list_frameworks(query)+ if len(parts) == 3:+ return _describe_framework(parts[2])+ if sub == "report-jobs":+ if len(parts) == 2:+ return _list_report_jobs(query)+ if len(parts) == 3:+ return _describe_report_job(parts[2])+ if sub == "report-plans":+ if len(parts) == 2:+ return _list_report_plans(query)+ if len(parts) == 3:+ return _describe_report_plan(parts[2])+ if sub == "backup-job-summaries":+ return _list_backup_job_summaries(query)+ if sub == "copy-job-summaries":+ return _list_copy_job_summaries(query)+ if sub == "restore-job-summaries":+ return _list_restore_job_summaries(query)+ if sub == "scan-job-summaries":+ return _list_scan_job_summaries(query)++ # Singleton account / global settings and supported resource types.+ if parts and method == "GET":+ if parts == ["account-settings"]:+ return _describe_region_settings()+ if parts == ["global-settings"]:+ return _describe_global_settings()+ if parts == ["supported-resource-types"]:+ return _get_supported_resource_types()+return _err("ValidationException", f"No route for {method} {path}", 400)diff --git a/ministack/services/cloudcontrol.py b/ministack/services/cloudcontrol.pynew file mode 100644index 00000000..8eed1db2--- /dev/null+++ b/ministack/services/cloudcontrol.py@@ -0,0 +1,408 @@+"""+AWS Cloud Control API Emulator.+JSON-based API via X-Amz-Target (prefix: CloudApiService).++Cloud Control is a generic CRUD-over-any-typeName control plane: the same eight+operations manage every CloudFormation resource type. Terraform's `awscc`+provider and CDK L1 constructs sit on top of it, so a small op count covers a+large surface.++Resources are stored keyed by (TypeName, Identifier). `DesiredState` /+`Properties` are JSON strings, exactly as real AWS transports them. Mutating+operations (Create/Update/Delete) are synchronous here but return the same+`ProgressEvent` shape real AWS returns for its asynchronous requests, always+with OperationStatus=SUCCESS. Every request is also recorded so+ListResourceRequests / GetResourceRequestStatus can replay it.++Supported: CreateResource, GetResource, UpdateResource, DeleteResource,+ ListResources, ListResourceRequests, GetResourceRequestStatus,+ CancelResourceRequest.++Verified against botocore cloudcontrol/2021-09-30/service-2.json:+ targetPrefix=CloudApiService, jsonVersion=1.0, protocol=json,+ endpointPrefix/signingName=cloudcontrolapi.+"""++import json+import logging+import time++from ministack.core.responses import (+ AccountRegionScopedDict,+ error_response_json,+ json_response,+ new_uuid,+)++logger = logging.getLogger("cloudcontrol")++from ministack.core.persistence import load_state++# (TypeName, Identifier) -> {"TypeName", "Identifier", "Properties" (JSON str)}+_resources = AccountRegionScopedDict()+# RequestToken -> ProgressEvent dict+_requests = AccountRegionScopedDict()+++# ── Persistence ────────────────────────────────────────────++def get_state():+ return {"resources": _resources, "requests": _requests}+++def restore_state(data):+ if not data:+ return+ resources = data.get("resources")+ if isinstance(resources, AccountRegionScopedDict):+ _resources.update(resources)+ requests = data.get("requests")+ if isinstance(requests, AccountRegionScopedDict):+ _requests.update(requests)+++try:+ _restored = load_state("cloudcontrol")+ if _restored:+ restore_state(_restored)+except Exception:+ logging.getLogger(__name__).exception(+ "Failed to restore persisted state; continuing with fresh store"+ )+++# ── Helpers ────────────────────────────────────────────────++def _resource_key(type_name, identifier):+ return f"{type_name}\x00{identifier}"+++def _extract_identifier(props):+ """Derive a primary identifier from a resource's properties.++ Real Cloud Control derives the identifier from the resource type's schema+ primaryIdentifier. Without those schemas we pick a stable, deterministic+ value: a common id-like property if present, else a generated id.+ """+ for candidate in ("Id", "Name", "Arn", "BucketName", "Identifier",+ "PhysicalResourceId", "ResourceId"):+ val = props.get(candidate)+ if isinstance(val, (str, int)) and str(val):+ return str(val)+ return new_uuid()+++def _progress_event(operation, status, type_name=None, identifier=None,+ request_token=None, resource_model=None,+ status_message=None, error_code=None):+ """Build a botocore-correct ProgressEvent.++ Members present in the botocore ProgressEvent shape: TypeName, Identifier,+ RequestToken, HooksRequestToken, Operation, OperationStatus, EventTime,+ ResourceModel, StatusMessage, ErrorCode, RetryAfter. We omit optional+ members we don't populate rather than send nulls, matching how AWS drops+ absent members from JSON responses.+ """+ event = {+ "TypeName": type_name,+ "RequestToken": request_token or new_uuid(),+ "Operation": operation,+ "OperationStatus": status,+ "EventTime": int(time.time()),+ }+ if identifier is not None:+ event["Identifier"] = identifier+ if resource_model is not None:+ event["ResourceModel"] = resource_model+ if status_message is not None:+ event["StatusMessage"] = status_message+ if error_code is not None:+ event["ErrorCode"] = error_code+ return event+++def _record_request(event):+ _requests[event["RequestToken"]] = event+ return event+++# ── Operations ─────────────────────────────────────────────++def _create_resource(data):+ type_name = data.get("TypeName")+ desired_state = data.get("DesiredState")+ if not type_name or desired_state is None:+ return error_response_json(+ "InvalidRequestException",+ "TypeName and DesiredState are required",+ 400,+ )+ try:+ props = json.loads(desired_state) if isinstance(desired_state, str) else dict(desired_state)+ except (json.JSONDecodeError, TypeError, ValueError):+ return error_response_json(+ "InvalidRequestException",+ "DesiredState must be a JSON document",+ 400,+ )++ identifier = _extract_identifier(props)+ key = _resource_key(type_name, identifier)+ if key in _resources:+ return error_response_json(+ "AlreadyExistsException",+ f"Resource of type '{type_name}' with identifier '{identifier}' already exists.",+ 400,+ )+ properties = json.dumps(props)+ _resources[key] = {+ "TypeName": type_name,+ "Identifier": identifier,+ "Properties": properties,+ }+ logger.info("Created %s %s", type_name, identifier)+ event = _record_request(_progress_event(+ "CREATE", "SUCCESS", type_name=type_name, identifier=identifier,+ resource_model=properties,+ ))+ return json_response({"ProgressEvent": event})+++def _get_resource(data):+ type_name = data.get("TypeName")+ identifier = data.get("Identifier")+ rec = _resources.get(_resource_key(type_name, identifier))+ if not rec:+ return error_response_json(+ "ResourceNotFoundException",+ f"Resource of type '{type_name}' with identifier '{identifier}' was not found.",+ 400,+ )+ return json_response({+ "TypeName": type_name,+ "ResourceDescription": {+ "Identifier": rec["Identifier"],+ "Properties": rec["Properties"],+ },+ })+++def _update_resource(data):+ type_name = data.get("TypeName")+ identifier = data.get("Identifier")+ patch_document = data.get("PatchDocument")+ key = _resource_key(type_name, identifier)+ rec = _resources.get(key)+ if not rec:+ return error_response_json(+ "ResourceNotFoundException",+ f"Resource of type '{type_name}' with identifier '{identifier}' was not found.",+ 400,+ )+ if patch_document is None:+ return error_response_json(+ "InvalidRequestException",+ "PatchDocument is required",+ 400,+ )+ try:+ patch = json.loads(patch_document) if isinstance(patch_document, str) else patch_document+ except (json.JSONDecodeError, TypeError, ValueError):+ return error_response_json(+ "InvalidRequestException",+ "PatchDocument must be a JSON document",+ 400,+ )++ props = json.loads(rec["Properties"])+ try:+ props = _apply_json_patch(props, patch)+ except _PatchError as exc:+ return error_response_json("InvalidRequestException", str(exc), 400)++ properties = json.dumps(props)+ rec["Properties"] = properties+ _resources[key] = rec+ logger.info("Updated %s %s", type_name, identifier)+ event = _record_request(_progress_event(+ "UPDATE", "SUCCESS", type_name=type_name, identifier=identifier,+ resource_model=properties,+ ))+ return json_response({"ProgressEvent": event})+++def _delete_resource(data):+ type_name = data.get("TypeName")+ identifier = data.get("Identifier")+ key = _resource_key(type_name, identifier)+ if key not in _resources:+ return error_response_json(+ "ResourceNotFoundException",+ f"Resource of type '{type_name}' with identifier '{identifier}' was not found.",+ 400,+ )+ del _resources[key]+ logger.info("Deleted %s %s", type_name, identifier)+ event = _record_request(_progress_event(+ "DELETE", "SUCCESS", type_name=type_name, identifier=identifier,+ ))+ return json_response({"ProgressEvent": event})+++def _list_resources(data):+ type_name = data.get("TypeName")+ if not type_name:+ return error_response_json(+ "InvalidRequestException",+ "TypeName is required",+ 400,+ )+ descriptions = [+ {"Identifier": rec["Identifier"], "Properties": rec["Properties"]}+ for rec in _resources.values()+ if rec.get("TypeName") == type_name+ ]+ return json_response({+ "TypeName": type_name,+ "ResourceDescriptions": descriptions,+ })+++def _list_resource_requests(data):+ filt = data.get("ResourceRequestStatusFilter") or {}+ operations = set(filt.get("Operations") or [])+ statuses = set(filt.get("OperationStatuses") or [])+ summaries = []+ for event in _requests.values():+ if operations and event.get("Operation") not in operations:+ continue+ if statuses and event.get("OperationStatus") not in statuses:+ continue+ summaries.append(event)+ return json_response({"ResourceRequestStatusSummaries": summaries})+++def _get_resource_request_status(data):+ request_token = data.get("RequestToken")+ event = _requests.get(request_token)+ if not event:+ return error_response_json(+ "RequestTokenNotFoundException",+ f"Request token '{request_token}' was not found.",+ 400,+ )+ return json_response({"ProgressEvent": event})+++def _cancel_resource_request(data):+ request_token = data.get("RequestToken")+ event = _requests.get(request_token)+ if not event:+ return error_response_json(+ "RequestTokenNotFoundException",+ f"Request token '{request_token}' was not found.",+ 400,+ )+ # A SUCCESS/FAILED request can't be cancelled: real AWS rejects it. Our+ # requests complete synchronously, so they are always terminal.+ if event.get("OperationStatus") in ("SUCCESS", "FAILED", "CANCEL_COMPLETE"):+ return error_response_json(+ "ConflictException",+ f"Only IN_PROGRESS requests can be cancelled. Request '{request_token}' "+ f"is {event.get('OperationStatus')}.",+ 400,+ )+ event["OperationStatus"] = "CANCEL_COMPLETE"+ _requests[request_token] = event+ return json_response({"ProgressEvent": event})+++# ── RFC 6902 JSON Patch (minimal) ──────────────────────────++class _PatchError(Exception):+ pass+++def _apply_json_patch(doc, operations):+ """Apply a subset of RFC 6902 (add/replace/remove) sufficient for+ Cloud Control UpdateResource property mutations."""+ if not isinstance(operations, list):+ raise _PatchError("PatchDocument must be a JSON array of operations")+ for op in operations:+ if not isinstance(op, dict):+ raise _PatchError("Each patch operation must be an object")+ kind = op.get("op")+ path = op.get("path", "")+ tokens = [t.replace("~1", "/").replace("~0", "~")+ for t in path.split("/")[1:]] if path else []+ if kind in ("add", "replace"):+ _patch_set(doc, tokens, op.get("value"))+ elif kind == "remove":+ _patch_remove(doc, tokens)+ else:+ raise _PatchError(f"Unsupported patch op: {kind}")+ return doc+++def _patch_set(doc, tokens, value):+ if not tokens:+ raise _PatchError("Empty patch path")+ cur = doc+ for tok in tokens[:-1]:+ if isinstance(cur, dict):+ cur = cur.setdefault(tok, {})+ else:+ raise _PatchError("Patch path traverses a non-object")+ if isinstance(cur, dict):+ cur[tokens[-1]] = value+ else:+ raise _PatchError("Patch path traverses a non-object")+++def _patch_remove(doc, tokens):+ if not tokens:+ raise _PatchError("Empty patch path")+ cur = doc+ for tok in tokens[:-1]:+ if isinstance(cur, dict) and tok in cur:+ cur = cur[tok]+ else:+ raise _PatchError("Patch path not found")+ if isinstance(cur, dict):+ cur.pop(tokens[-1], None)+++# ── Request handler ────────────────────────────────────────++async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ action = target.split(".")[-1] if "." in target else ""++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return error_response_json("SerializationException", "Invalid JSON", 400)++ handlers = {+ "CreateResource": _create_resource,+ "GetResource": _get_resource,+ "UpdateResource": _update_resource,+ "DeleteResource": _delete_resource,+ "ListResources": _list_resources,+ "ListResourceRequests": _list_resource_requests,+ "GetResourceRequestStatus": _get_resource_request_status,+ "CancelResourceRequest": _cancel_resource_request,+ }++ handler = handlers.get(action)+ if not handler:+ logger.warning("Unknown CloudControl action: %s", action)+ return error_response_json(+ "InvalidAction", f"Unknown action: {action}", 400+ )+ return handler(data)+++def reset():+ _resources.clear()+ _requests.clear()diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.pyindex f2f5164d..018c37ad 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -84,6 +84,26 @@ _RHP_CFG_RE = re.compile(r"^/2020-05-31/response-headers-policy/([^/]+)/config$"_RHP_ID_RE = re.compile(r"^/2020-05-31/response-headers-policy/([^/]+)/?$")_DIST_BY_RHP_RE = re.compile(r"^/2020-05-31/distributionsByResponseHeadersPolicyId/([^/]+)/?$")+# ---------------------------------------------------------------------------+# Read-only surface for resource families MiniStack does not yet persist.+# These return AWS-shaped empty collections so the SDK gets a valid response+# instead of a routing fall-through. Shapes verified against botocore+# cloudfront service-2.json (2020-05-31): each list container's XML root is+# the payload member's locationName, MaxItems defaults to 100, an empty list+# omits Items, and NextMarker is omitted when there is no next page.+# ---------------------------------------------------------------------------+_KEY_GROUP_LIST_RE = re.compile(r"^/2020-05-31/key-group/?$")+_PUBLIC_KEY_LIST_RE = re.compile(r"^/2020-05-31/public-key/?$")+_FLE_LIST_RE = re.compile(r"^/2020-05-31/field-level-encryption/?$")+_FLE_PROFILE_LIST_RE = re.compile(r"^/2020-05-31/field-level-encryption-profile/?$")+_CDP_LIST_RE = re.compile(r"^/2020-05-31/continuous-deployment-policy/?$")+_OAI_LIST_RE = re.compile(r"^/2020-05-31/origin-access-identity/cloudfront/?$")+_STREAMING_DIST_LIST_RE = re.compile(r"^/2020-05-31/streaming-distribution/?$")+_VPC_ORIGIN_LIST_RE = re.compile(r"^/2020-05-31/vpc-origin/?$")+_REALTIME_LOG_LIST_RE = re.compile(r"^/2020-05-31/realtime-log-config/?$")+_ANYCAST_IP_LIST_RE = re.compile(r"^/2020-05-31/anycast-ip-list/?$")+_MONITORING_SUB_RE = re.compile(r"^/2020-05-31/distributions/([^/]+)/monitoring-subscription/?$")+# ---------------------------------------------------------------------------# In-memory state# ---------------------------------------------------------------------------@@ -1183,6 +1203,7 @@ def _build_orp_xml(parent, policy):_ORP_SPEC = {"label": "origin request policy", "resource_tag": "OriginRequestPolicy","config_tag": "OriginRequestPolicyConfig", "path": "/2020-05-31/origin-request-policy",+ "list_tag": "OriginRequestPolicyList", "summary_tag": "OriginRequestPolicySummary","missing": "NoSuchOriginRequestPolicy", "dup": "OriginRequestPolicyAlreadyExists","in_use": "OriginRequestPolicyInUse", "parse": _parse_orp_config,"build_resource": _build_orp_xml, "build_config": _build_orp_config_xml,@@ -1382,12 +1403,127 @@ def _build_rhp_xml(parent, policy):_RHP_SPEC = {"label": "response headers policy", "resource_tag": "ResponseHeadersPolicy","config_tag": "ResponseHeadersPolicyConfig", "path": "/2020-05-31/response-headers-policy",+ "list_tag": "ResponseHeadersPolicyList", "summary_tag": "ResponseHeadersPolicySummary","missing": "NoSuchResponseHeadersPolicy", "dup": "ResponseHeadersPolicyAlreadyExists","in_use": "ResponseHeadersPolicyInUse", "parse": _parse_rhp_config,"build_resource": _build_rhp_xml, "build_config": _build_rhp_config_xml,}+# ---------------------------------------------------------------------------+# Read-only list handlers for resource families with no backing store.+# Shapes verified against botocore cloudfront service-2.json (2020-05-31).+# ---------------------------------------------------------------------------+_DEFAULT_MAX_ITEMS = "100"+++def _empty_marker_list(query_params, root_tag, with_marker):+ """Build an AWS-shaped empty collection.++ ``with_marker=False`` matches the ``KeyGroupList`` family+ (NextMarker/MaxItems/Quantity); ``with_marker=True`` matches the+ ``CloudFrontOriginAccessIdentityList`` family, which additionally carries+ Marker + IsTruncated. Both omit ``Items`` when empty and omit+ ``NextMarker`` when there is no next page.+ """+ max_items = _qval(query_params, "MaxItems", _DEFAULT_MAX_ITEMS) or _DEFAULT_MAX_ITEMS+ marker = _qval(query_params, "Marker", "")++ def build(root):+ if with_marker:+ SubElement(root, "Marker").text = marker+ SubElement(root, "MaxItems").text = max_items+ SubElement(root, "IsTruncated").text = "false"+ SubElement(root, "Quantity").text = "0"+ else:+ SubElement(root, "MaxItems").text = max_items+ SubElement(root, "Quantity").text = "0"++ return _xml_response(root_tag, build)+++def _list_realtime_log_configs(query_params):+ """RealtimeLogConfigs has no Quantity; carries MaxItems/IsTruncated/Marker."""+ max_items = _qval(query_params, "MaxItems", _DEFAULT_MAX_ITEMS) or _DEFAULT_MAX_ITEMS+ marker = _qval(query_params, "Marker", "")++ def build(root):+ SubElement(root, "MaxItems").text = max_items+ SubElement(root, "IsTruncated").text = "false"+ SubElement(root, "Marker").text = marker++ return _xml_response("RealtimeLogConfigs", build)+++def _list_anycast_ip_lists(query_params):+ """AnycastIpListCollection: Marker/MaxItems/IsTruncated/Quantity, Items omitted when empty."""+ max_items = _qval(query_params, "MaxItems", _DEFAULT_MAX_ITEMS) or _DEFAULT_MAX_ITEMS+ marker = _qval(query_params, "Marker", "")++ def build(root):+ SubElement(root, "Marker").text = marker+ SubElement(root, "MaxItems").text = max_items+ SubElement(root, "IsTruncated").text = "false"+ SubElement(root, "Quantity").text = "0"++ return _xml_response("AnycastIpListCollection", build)+++def _list_cache_policies(query_params):+ """CachePolicyList wrapping stored custom cache policies (Type=custom)."""+ max_items = _qval(query_params, "MaxItems", _DEFAULT_MAX_ITEMS) or _DEFAULT_MAX_ITEMS+ policies = list(_cache_policies.values())++ def build(root):+ SubElement(root, "MaxItems").text = max_items+ SubElement(root, "Quantity").text = str(len(policies))+ if policies:+ items_el = SubElement(root, "Items")+ for policy in policies:+ summary = SubElement(items_el, "CachePolicySummary")+ SubElement(summary, "Type").text = "custom"+ cp = SubElement(summary, "CachePolicy")+ _build_cache_policy_xml(cp, policy)++ return _xml_response("CachePolicyList", build)+++def _list_policies(store, spec, query_params):+ """Generic ``*PolicyList`` wrapping stored custom policies (Type=custom).++ Shared by origin request policies and response headers policies; the+ summary member and resource tag come from ``spec``.+ """+ max_items = _qval(query_params, "MaxItems", _DEFAULT_MAX_ITEMS) or _DEFAULT_MAX_ITEMS+ policies = list(store.values())++ def build(root):+ SubElement(root, "MaxItems").text = max_items+ SubElement(root, "Quantity").text = str(len(policies))+ if policies:+ items_el = SubElement(root, "Items")+ for policy in policies:+ summary = SubElement(items_el, spec["summary_tag"])+ SubElement(summary, "Type").text = "custom"+ res = SubElement(summary, spec["resource_tag"])+ spec["build_resource"](res, policy)++ return _xml_response(spec["list_tag"], build)+++def _get_monitoring_subscription(dist_id):+ """MiniStack does not persist monitoring subscriptions. Real AWS returns+ NoSuchDistribution (404) for an unknown distribution and+ NoSuchMonitoringSubscription (404) when none is configured."""+ if dist_id not in _distributions:+ return _error("NoSuchDistribution", "The specified distribution does not exist.", 404)+ return _error(+ "NoSuchMonitoringSubscription",+ "A monitoring subscription does not exist for the specified distribution.",+ 404,+ )++# ---------------------------------------------------------------------------# Request dispatcher# ---------------------------------------------------------------------------@@ -1487,6 +1623,8 @@ async def handle_request(method, path, headers, body, query_params):if m:if method == "POST":return _create_cache_policy(body)+ if method == "GET":+ return _list_cache_policies(query_params)m = _CACHE_POLICY_ID_RE.match(path)if m:@@ -1513,6 +1651,8 @@ async def handle_request(method, path, headers, body, query_params):if m:if method == "POST":return _policy_create(_origin_request_policies, _ORP_SPEC, body)+ if method == "GET":+ return _list_policies(_origin_request_policies, _ORP_SPEC, query_params)m = _ORP_ID_RE.match(path)if m:@@ -1539,6 +1679,8 @@ async def handle_request(method, path, headers, body, query_params):if m:if method == "POST":return _policy_create(_response_headers_policies, _RHP_SPEC, body)+ if method == "GET":+ return _list_policies(_response_headers_policies, _RHP_SPEC, query_params)m = _RHP_ID_RE.match(path)if m:@@ -1609,6 +1751,53 @@ async def handle_request(method, path, headers, body, query_params):if method == "GET":return _list_kvstores(query_params)+ # Read-only list surface for resource families with no backing store.+ # Family split matches botocore: KeyGroupList-style carry no Marker/+ # IsTruncated; the OAI/StreamingDistribution/VpcOrigin family does.+ m = _KEY_GROUP_LIST_RE.match(path)+ if m and method == "GET":+ return _empty_marker_list(query_params, "KeyGroupList", with_marker=False)++ m = _PUBLIC_KEY_LIST_RE.match(path)+ if m and method == "GET":+ return _empty_marker_list(query_params, "PublicKeyList", with_marker=False)++ m = _FLE_LIST_RE.match(path)+ if m and method == "GET":+ return _empty_marker_list(query_params, "FieldLevelEncryptionList", with_marker=False)++ m = _FLE_PROFILE_LIST_RE.match(path)+ if m and method == "GET":+ return _empty_marker_list(query_params, "FieldLevelEncryptionProfileList", with_marker=False)++ m = _CDP_LIST_RE.match(path)+ if m and method == "GET":+ return _empty_marker_list(query_params, "ContinuousDeploymentPolicyList", with_marker=False)++ m = _OAI_LIST_RE.match(path)+ if m and method == "GET":+ return _empty_marker_list(query_params, "CloudFrontOriginAccessIdentityList", with_marker=True)++ m = _STREAMING_DIST_LIST_RE.match(path)+ if m and method == "GET":+ return _empty_marker_list(query_params, "StreamingDistributionList", with_marker=True)++ m = _VPC_ORIGIN_LIST_RE.match(path)+ if m and method == "GET":+ return _empty_marker_list(query_params, "VpcOriginList", with_marker=True)++ m = _REALTIME_LOG_LIST_RE.match(path)+ if m and method == "GET":+ return _list_realtime_log_configs(query_params)++ m = _ANYCAST_IP_LIST_RE.match(path)+ if m and method == "GET":+ return _list_anycast_ip_lists(query_params)++ m = _MONITORING_SUB_RE.match(path)+ if m and method == "GET":+ return _get_monitoring_subscription(m.group(1))+return _error("NoSuchResource", f"No route for {method} {path}", 404)diff --git a/ministack/services/config.py b/ministack/services/config.pynew file mode 100644index 00000000..1db9c0f5--- /dev/null+++ b/ministack/services/config.py@@ -0,0 +1,428 @@+"""+AWS Config Service Emulator.+JSON-based API via X-Amz-Target (prefix: StarlingDoveService).++Verified against botocore config/2014-11-12/service-2.json:+ metadata.targetPrefix = "StarlingDoveService"+ metadata.jsonVersion = "1.1"+ metadata.protocol = "json"+ metadata.endpointPrefix = "config"++Supports the read-focused control plane the compliance/IaC benchmarks reach+for, plus minimal CRUD to keep reads coherent:+ PutConfigRule, DescribeConfigRules, DeleteConfigRule,+ PutConfigurationRecorder, DescribeConfigurationRecorders,+ DescribeConfigurationRecorderStatus,+ PutDeliveryChannel, DescribeDeliveryChannels, DescribeDeliveryChannelStatus,+ StartConfigurationRecorder, StopConfigurationRecorder,+ DescribeComplianceByConfigRule, GetComplianceDetailsByConfigRule,+ DescribeConfigRuleEvaluationStatus.++JSON-protocol timestamps are INT epoch seconds. Stores are per account+region.+"""++import copy+import json+import logging+import time++from ministack.core.persistence import load_state+from ministack.core.responses import (+ AccountRegionScopedDict,+ error_response_json,+ get_account_id,+ get_region,+ json_response,+ new_uuid,+)++logger = logging.getLogger("config")+++# ── Stores (per account + region) ─────────────────────────────+# AWS Config: at most one recorder and one delivery channel per region, but the+# describe APIs still return lists. Config rules are keyed by name.+_config_rules = AccountRegionScopedDict() # ConfigRuleName -> ConfigRule dict+_recorders = AccountRegionScopedDict() # name -> recorder dict {rec, recording, status...}+_delivery_channels = AccountRegionScopedDict() # name -> delivery channel dict+++def _config_rule_arn(rule_id):+ return (+ f"arn:aws:config:{get_region()}:{get_account_id()}"+ f":config-rule/{rule_id}"+ )+++# ── Persistence ───────────────────────────────────────────────++def get_state():+ return copy.deepcopy(+ {+ "_config_rules": _config_rules,+ "_recorders": _recorders,+ "_delivery_channels": _delivery_channels,+ }+ )+++def restore_state(data):+ if not data:+ return+ _config_rules.clear()+ _recorders.clear()+ _delivery_channels.clear()+ for store, key in (+ (_config_rules, "_config_rules"),+ (_recorders, "_recorders"),+ (_delivery_channels, "_delivery_channels"),+ ):+ restored = data.get(key, {})+ if isinstance(restored, AccountRegionScopedDict):+ store.update(restored)+ else:+ for k, v in restored.items():+ store[k] = v+++try:+ _restored = load_state("config")+ if _restored:+ restore_state(_restored)+except Exception:+ logging.getLogger(__name__).exception(+ "Failed to restore persisted state; continuing with fresh store"+ )+++# ── Config Rules ──────────────────────────────────────────────++def _put_config_rule(data):+ rule = data.get("ConfigRule") or {}+ name = rule.get("ConfigRuleName")+ if not name:+ return error_response_json(+ "InvalidParameterValueException",+ "ConfigRule.ConfigRuleName is a required field",+ 400,+ )+ existing = _config_rules.get(name)+ rule_id = existing["ConfigRuleId"] if existing else "config-rule-" + new_uuid()[:6]++ stored = {+ "ConfigRuleName": name,+ "ConfigRuleArn": _config_rule_arn(rule_id),+ "ConfigRuleId": rule_id,+ "Source": rule.get("Source", {}),+ "ConfigRuleState": rule.get("ConfigRuleState", "ACTIVE"),+ }+ for optional in ("Description", "Scope", "InputParameters",+ "MaximumExecutionFrequency", "CreatedBy", "EvaluationModes"):+ if optional in rule:+ stored[optional] = rule[optional]+ _config_rules[name] = stored+ logger.info("Put config rule %s", name)+ return json_response({})+++def _describe_config_rules(data):+ names = data.get("ConfigRuleNames") or []+ if names:+ rules = []+ for n in names:+ rec = _config_rules.get(n)+ if not rec:+ return error_response_json(+ "NoSuchConfigRuleException",+ f"The ConfigRule '{n}' provided in the request is invalid. "+ "Please check the configRule name",+ 400,+ )+ rules.append(rec)+ else:+ rules = list(_config_rules.values())+ return json_response({"ConfigRules": rules})+++def _delete_config_rule(data):+ name = data.get("ConfigRuleName")+ if name not in _config_rules:+ return error_response_json(+ "NoSuchConfigRuleException",+ f"The ConfigRule '{name}' provided in the request is invalid. "+ "Please check the configRule name",+ 400,+ )+ del _config_rules[name]+ return json_response({})+++# ── Configuration Recorder ────────────────────────────────────++def _put_configuration_recorder(data):+ recorder = data.get("ConfigurationRecorder") or {}+ name = recorder.get("name") or "default"+ existing = _recorders.get(name)+ stored = existing or {+ "recording": False,+ "lastStatus": "Pending",+ "lastStartTime": None,+ "lastStopTime": None,+ "lastStatusChangeTime": int(time.time()),+ }+ rec = {"name": name}+ for optional in ("roleARN", "recordingGroup", "recordingMode"):+ if optional in recorder:+ rec[optional] = recorder[optional]+ stored["recorder"] = rec+ _recorders[name] = stored+ logger.info("Put configuration recorder %s", name)+ return json_response({})+++def _describe_configuration_recorders(data):+ names = data.get("ConfigurationRecorderNames") or []+ if names:+ out = []+ for n in names:+ rec = _recorders.get(n)+ if not rec:+ return error_response_json(+ "NoSuchConfigurationRecorderException",+ f"Cannot find configuration recorder with the specified name '{n}'.",+ 400,+ )+ out.append(rec["recorder"])+ else:+ out = [r["recorder"] for r in _recorders.values()]+ return json_response({"ConfigurationRecorders": out})+++def _describe_configuration_recorder_status(data):+ names = data.get("ConfigurationRecorderNames") or []+ if names:+ recorders = []+ for n in names:+ rec = _recorders.get(n)+ if not rec:+ return error_response_json(+ "NoSuchConfigurationRecorderException",+ f"Cannot find configuration recorder with the specified name '{n}'.",+ 400,+ )+ recorders.append(rec)+ else:+ recorders = list(_recorders.values())+ statuses = [_recorder_status(r) for r in recorders]+ return json_response({"ConfigurationRecordersStatus": statuses})+++def _recorder_status(rec):+ status = {+ "name": rec["recorder"]["name"],+ "recording": rec.get("recording", False),+ "lastStatus": rec.get("lastStatus", "Pending"),+ }+ for ts_field in ("lastStartTime", "lastStopTime", "lastStatusChangeTime"):+ if rec.get(ts_field) is not None:+ status[ts_field] = rec[ts_field]+ return status+++def _start_configuration_recorder(data):+ name = data.get("ConfigurationRecorderName")+ rec = _recorders.get(name)+ if not rec:+ return error_response_json(+ "NoSuchConfigurationRecorderException",+ f"Cannot find configuration recorder with the specified name '{name}'.",+ 400,+ )+ now = int(time.time())+ rec["recording"] = True+ rec["lastStatus"] = "Success"+ rec["lastStartTime"] = now+ rec["lastStatusChangeTime"] = now+ return json_response({})+++def _stop_configuration_recorder(data):+ name = data.get("ConfigurationRecorderName")+ rec = _recorders.get(name)+ if not rec:+ return error_response_json(+ "NoSuchConfigurationRecorderException",+ f"Cannot find configuration recorder with the specified name '{name}'.",+ 400,+ )+ now = int(time.time())+ rec["recording"] = False+ rec["lastStatus"] = "Success"+ rec["lastStopTime"] = now+ rec["lastStatusChangeTime"] = now+ return json_response({})+++# ── Delivery Channel ──────────────────────────────────────────++def _put_delivery_channel(data):+ channel = data.get("DeliveryChannel") or {}+ name = channel.get("name") or "default"+ stored = {"name": name}+ for optional in ("s3BucketName", "s3KeyPrefix", "s3KmsKeyArn",+ "snsTopicARN", "configSnapshotDeliveryProperties"):+ if optional in channel:+ stored[optional] = channel[optional]+ _delivery_channels[name] = stored+ logger.info("Put delivery channel %s", name)+ return json_response({})+++def _describe_delivery_channels(data):+ names = data.get("DeliveryChannelNames") or []+ if names:+ out = []+ for n in names:+ ch = _delivery_channels.get(n)+ if not ch:+ return error_response_json(+ "NoSuchDeliveryChannelException",+ f"Cannot find delivery channel with specified name '{n}'.",+ 400,+ )+ out.append(ch)+ else:+ out = list(_delivery_channels.values())+ return json_response({"DeliveryChannels": out})+++def _describe_delivery_channel_status(data):+ names = data.get("DeliveryChannelNames") or []+ if names:+ channels = []+ for n in names:+ ch = _delivery_channels.get(n)+ if not ch:+ return error_response_json(+ "NoSuchDeliveryChannelException",+ f"Cannot find delivery channel with specified name '{n}'.",+ 400,+ )+ channels.append(ch)+ else:+ channels = list(_delivery_channels.values())+ statuses = [{"name": ch["name"]} for ch in channels]+ return json_response({"DeliveryChannelsStatus": statuses})+++# ── Compliance ────────────────────────────────────────────────++def _describe_compliance_by_config_rule(data):+ names = data.get("ConfigRuleNames") or []+ if names:+ results = []+ for n in names:+ if n not in _config_rules:+ return error_response_json(+ "NoSuchConfigRuleException",+ f"The ConfigRule '{n}' provided in the request is invalid. "+ "Please check the configRule name",+ 400,+ )+ results.append(_compliance_by_rule(n))+ else:+ results = [_compliance_by_rule(n) for n in _config_rules.keys()]+ return json_response({"ComplianceByConfigRules": results})+++def _compliance_by_rule(name):+ # No evaluations have run in the emulator, so compliance is INSUFFICIENT_DATA+ # — the shape real AWS returns for a rule that has never been evaluated.+ return {+ "ConfigRuleName": name,+ "Compliance": {"ComplianceType": "INSUFFICIENT_DATA"},+ }+++def _get_compliance_details_by_config_rule(data):+ name = data.get("ConfigRuleName")+ if name not in _config_rules:+ return error_response_json(+ "NoSuchConfigRuleException",+ f"The ConfigRule '{name}' provided in the request is invalid. "+ "Please check the configRule name",+ 400,+ )+ # No evaluation engine — no per-resource results yet.+ return json_response({"EvaluationResults": []})+++def _describe_config_rule_evaluation_status(data):+ names = data.get("ConfigRuleNames") or []+ if names:+ statuses = []+ for n in names:+ rec = _config_rules.get(n)+ if not rec:+ return error_response_json(+ "NoSuchConfigRuleException",+ f"The ConfigRule '{n}' provided in the request is invalid. "+ "Please check the configRule name",+ 400,+ )+ statuses.append(_evaluation_status(rec))+ else:+ statuses = [_evaluation_status(r) for r in _config_rules.values()]+ return json_response({"ConfigRulesEvaluationStatus": statuses})+++def _evaluation_status(rec):+ return {+ "ConfigRuleName": rec["ConfigRuleName"],+ "ConfigRuleArn": rec["ConfigRuleArn"],+ "ConfigRuleId": rec["ConfigRuleId"],+ "FirstEvaluationStarted": False,+ }+++# ── Request handler ───────────────────────────────────────────++async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ action = target.split(".")[-1] if "." in target else ""++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return error_response_json("SerializationException", "Invalid JSON", 400)++ handlers = {+ "PutConfigRule": _put_config_rule,+ "DescribeConfigRules": _describe_config_rules,+ "DeleteConfigRule": _delete_config_rule,+ "PutConfigurationRecorder": _put_configuration_recorder,+ "DescribeConfigurationRecorders": _describe_configuration_recorders,+ "DescribeConfigurationRecorderStatus": _describe_configuration_recorder_status,+ "PutDeliveryChannel": _put_delivery_channel,+ "DescribeDeliveryChannels": _describe_delivery_channels,+ "DescribeDeliveryChannelStatus": _describe_delivery_channel_status,+ "StartConfigurationRecorder": _start_configuration_recorder,+ "StopConfigurationRecorder": _stop_configuration_recorder,+ "DescribeComplianceByConfigRule": _describe_compliance_by_config_rule,+ "GetComplianceDetailsByConfigRule": _get_compliance_details_by_config_rule,+ "DescribeConfigRuleEvaluationStatus": _describe_config_rule_evaluation_status,+ }++ handler = handlers.get(action)+ if not handler:+ logger.warning("Unknown Config action: %s", action)+ return error_response_json(+ "InvalidAction", f"Unknown Config action: {action}", 400+ )+ return handler(data)+++def reset():+ _config_rules.clear()+ _recorders.clear()+ _delivery_channels.clear()diff --git a/ministack/services/inspector2.py b/ministack/services/inspector2.pyindex 4bdab7e9..f440172c 100644--- a/ministack/services/inspector2.py+++ b/ministack/services/inspector2.py@@ -960,6 +960,167 @@ def _delete_filter(data, account_id):return json_response({})+# ---------------------------------------------------------------------------+# Read-only ops with no local state — return AWS-correct empty/default shapes.+# Key names + shape categories verified against botocore inspector2 2020-06-08+# service-2.json. These accounts are not org-enrolled and have no members,+# delegated admins, CIS scans, code-security integrations, etc., so every list+# is empty and singletons return their default/disabled shape.+# ---------------------------------------------------------------------------+++def _batch_get_account_status(data, account_id):+ account_ids = data.get("accountIds") or [account_id]+ config = _get_config(account_id)++ def _rt_status(key):+ return {"status": config[key]["status"]}++ accounts = []+ for aid in account_ids:+ cfg = _get_config(aid)+ accounts.append(+ {+ "accountId": aid,+ "state": {"status": "DISABLED", "errorCode": "SUCCESS", "errorMessage": ""},+ "resourceState": {+ "ec2": {"status": cfg["ec2"]["status"], "errorCode": "SUCCESS", "errorMessage": ""},+ "ecr": {"status": cfg["ecr"]["status"], "errorCode": "SUCCESS", "errorMessage": ""},+ "lambda": {"status": cfg["lambda"]["status"], "errorCode": "SUCCESS", "errorMessage": ""},+ "lambdaCode": {"status": cfg["lambdaCode"]["status"], "errorCode": "SUCCESS", "errorMessage": ""},+ },+ }+ )+ return json_response({"accounts": accounts, "failedAccounts": []})+++def _batch_get_free_trial_info(data, account_id):+ account_ids = data.get("accountIds") or [account_id]+ accounts = []+ for aid in account_ids:+ accounts.append(+ {+ "accountId": aid,+ "freeTrialInfo": [],+ }+ )+ return json_response({"accounts": accounts, "failedAccounts": []})+++def _batch_get_member_ec2_deep_inspection_status(data, account_id):+ return json_response({"accountIds": [], "failedAccountIds": []})+++def _batch_get_code_snippet(data, account_id):+ return json_response({"codeSnippetResults": [], "errors": []})+++def _list_members(data, account_id):+ return json_response({"members": []})+++def _get_member(data, account_id):+ account_id_arg = data.get("accountId", "")+ return _resource_not_found(+ f"arn:aws:inspector2:{get_region()}:{account_id_arg or account_id}:member"+ )+++def _list_delegated_admin_accounts(data, account_id):+ return json_response({"delegatedAdminAccounts": []})+++def _get_delegated_admin_account(data, account_id):+ return json_response({})+++def _describe_organization_configuration(data, account_id):+ return json_response(+ {+ "autoEnable": {"ec2": False, "ecr": False, "lambda": False, "lambdaCode": False},+ "maxAccountLimitReached": False,+ }+ )+++def _get_configuration(data, account_id):+ # rescanDuration/scanMode are nested one level under *State per the AWS+ # model; boto3 drops leaf values placed directly on ecrConfiguration.+ return json_response(+ {+ "ecrConfiguration": {+ "rescanDurationState": {+ "rescanDuration": "LIFETIME",+ "status": "SUCCESS",+ }+ },+ "ec2Configuration": {+ "scanModeState": {+ "scanMode": "EC2_HYBRID",+ "scanModeStatus": "SUCCESS",+ }+ },+ }+ )+++def _get_ec2_deep_inspection_configuration(data, account_id):+ return json_response({"packagePaths": [], "orgPackagePaths": [], "status": "DISABLED"})+++def _list_account_permissions(data, account_id):+ return json_response({"permissions": []})+++def _list_usage_totals(data, account_id):+ account_ids = data.get("accountIds") or [account_id]+ totals = [{"accountId": aid, "usage": []} for aid in account_ids]+ return json_response({"totals": totals})+++def _get_findings_report_status(data, account_id):+ return json_response({"status": "SUCCEEDED"})+++def _get_sbom_export(data, account_id):+ return json_response({"status": "SUCCEEDED"})+++def _list_cis_scans(data, account_id):+ return json_response({"scans": []})+++def _list_cis_scan_configurations(data, account_id):+ return json_response({"scanConfigurations": []})+++def _list_cis_scan_results_by_checks(data, account_id):+ return json_response({"checkAggregations": []})+++def _list_cis_scan_results_by_target(data, account_id):+ return json_response({"targetResourceAggregations": []})+++def _get_cis_scan_report(data, account_id):+ return json_response({"status": "SUCCEEDED"})+++def _get_cis_scan_result_details(data, account_id):+ return json_response({"scanResultDetails": []})+++def _get_encryption_key(data, account_id):+ # No customer-managed CMK is configured for scanning in this emulator.+ # Real AWS returns ResourceNotFoundException when no key exists for the+ # requested resourceType/scanType.+ return error_response_json(+ "ResourceNotFoundException",+ "No encryption key found for the requested resource.",+ 400,+ )++_path_handlers = {"/enable": _enable,"/disable": _disable,@@ -975,6 +1136,29 @@ _path_handlers = {"/filters/create": _create_filter,"/filters/list": _list_filters,"/filters/delete": _delete_filter,+ # Read-only ops routed to AWS-correct empty/default shapes.+ "/status/batch/get": _batch_get_account_status,+ "/freetrialinfo/batchget": _batch_get_free_trial_info,+ "/ec2deepinspectionstatus/member/batch/get": _batch_get_member_ec2_deep_inspection_status,+ "/codesnippet/batchget": _batch_get_code_snippet,+ "/members/list": _list_members,+ "/members/get": _get_member,+ "/delegatedadminaccounts/list": _list_delegated_admin_accounts,+ "/delegatedadminaccounts/get": _get_delegated_admin_account,+ "/organizationconfiguration/describe": _describe_organization_configuration,+ "/configuration/get": _get_configuration,+ "/ec2deepinspectionconfiguration/get": _get_ec2_deep_inspection_configuration,+ "/accountpermissions/list": _list_account_permissions,+ "/usage/list": _list_usage_totals,+ "/reporting/status/get": _get_findings_report_status,+ "/sbomexport/get": _get_sbom_export,+ "/cis/scan/list": _list_cis_scans,+ "/cis/scan-configuration/list": _list_cis_scan_configurations,+ "/cis/scan-result/check/list": _list_cis_scan_results_by_checks,+ "/cis/scan-result/resource/list": _list_cis_scan_results_by_target,+ "/cis/scan/report/get": _get_cis_scan_report,+ "/cis/scan-result/details/get": _get_cis_scan_result_details,+ "/encryptionkey/get": _get_encryption_key,}_async_handlers = {}diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex b37a8626..6ae8c61b 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1824,9 +1824,22 @@ def _create_function(data: dict):if "ImageConfig" in data:config["ImageConfigResponse"] = {"ImageConfig": data["ImageConfig"]}+ # Self-managed code storage (July 2026): S3ObjectStorageMode=REFERENCE keeps+ # the code in the caller's bucket; GetFunction echoes the resolved S3 object+ # and any SourceKMSKeyArn. Stored on the record (not the echoed config) so it+ # does not leak into GetFunctionConfiguration.+ _s3_object_ref = None+ if code_data.get("S3Bucket") and code_data.get("S3Key"):+ _s3_object_ref = {"S3Bucket": code_data["S3Bucket"], "S3Key": code_data["S3Key"]}+ if code_data.get("S3ObjectVersion"):+ _s3_object_ref["S3ObjectVersion"] = code_data["S3ObjectVersion"]+_functions[name] = {"config": config,"code_zip": code_zip,+ "s3_object_storage_mode": code_data.get("S3ObjectStorageMode"),+ "source_kms_key_arn": code_data.get("SourceKMSKeyArn"),+ "s3_object_ref": _s3_object_ref,"versions": {},"next_version": 1,"tags": data.get("Tags", {}),@@ -1887,6 +1900,12 @@ def _get_function(name: str, qualifier: str | None = None):"RepositoryType": "S3","Location": _presigned_code_url(name),}+ # Self-managed code storage: echo the resolved S3 object (REFERENCE mode)+ # and any customer key, matching real Lambda's GetFunction code location.+ if func.get("source_kms_key_arn"):+ code_info["SourceKMSKeyArn"] = func["source_kms_key_arn"]+ if func.get("s3_object_storage_mode") == "REFERENCE" and func.get("s3_object_ref"):+ code_info["ResolvedS3Object"] = func["s3_object_ref"]result: dict = {"Configuration": effective_config,"Code": code_info,@@ -2201,6 +2220,16 @@ def _update_code(name: str, data: dict):func["config"]["CodeSha256"] = base64.b64encode(hashlib.sha256(code_zip).digest(),).decode()+ # Self-managed code storage (July 2026): track the resolved S3 object / mode.+ if "S3ObjectStorageMode" in data:+ func["s3_object_storage_mode"] = data.get("S3ObjectStorageMode")+ if "SourceKMSKeyArn" in data:+ func["source_kms_key_arn"] = data.get("SourceKMSKeyArn")+ if data.get("S3Bucket") and data.get("S3Key"):+ _ref = {"S3Bucket": data["S3Bucket"], "S3Key": data["S3Key"]}+ if data.get("S3ObjectVersion"):+ _ref["S3ObjectVersion"] = data["S3ObjectVersion"]+ func["s3_object_ref"] = _reffunc["config"]["LastModified"] = _now_iso()# AWS-match: UpdateFunctionCode marks status InProgress while the runtime# re-initialises, then flips to Successful. Terraform's FunctionUpdated@@ -5468,6 +5497,14 @@ def _create_esm(data: dict):"Enabled": enabled,"FunctionResponseTypes": data.get("FunctionResponseTypes", []),}+ # Optional stream/poll settings — stored on create (previously only picked+ # up on UpdateEventSourceMapping), so GetEventSourceMapping echoes them and+ # the poller can honor MaximumRecordAgeInSeconds + the OnFailure destination.+ for _opt in ("MaximumRetryAttempts", "MaximumRecordAgeInSeconds",+ "BisectBatchOnFunctionError", "ParallelizationFactor",+ "DestinationConfig"):+ if _opt in data:+ esm[_opt] = data[_opt]if event_source_spec.service != "sqs":esm["StartingPosition"] = data.get("StartingPosition", "LATEST")_init_stream_position(esm_id, event_source_arn, esm["StartingPosition"])@@ -5960,6 +5997,73 @@ def _poll_kinesis():return processed_any+def _send_ddb_stream_failure_record(esm, func_rec, batch, stream_arn, result, condition):+ """July 2026: send a DynamoDB-stream ESM on-failure invocation record to the+ configured `DestinationConfig.OnFailure` target (SQS/SNS) when a batch ages+ past `MaximumRecordAgeInSeconds` (`MaxRecordAgeExceeded`) or exhausts its+ retries (`RetryAttemptsExhausted`). Matches the AWS `DDBStreamBatchInfo`+ destination-record shape; the records themselves are not included."""+ dest = ((esm.get("DestinationConfig") or {}).get("OnFailure") or {}).get("Destination")+ if not dest:+ return+ config = func_rec.get("config") or func_rec+ first = (batch[0] or {}).get("dynamodb", {}) if batch else {}+ last = (batch[-1] or {}).get("dynamodb", {}) if batch else {}++ def _iso(ts):+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(float(ts)))++ now = time.time()+ envelope = {+ "requestContext": {+ "requestId": new_uuid(),+ "functionArn": config.get("FunctionArn", ""),+ "condition": condition,+ "approximateInvokeCount": 1,+ },+ "responseContext": {+ "statusCode": 200,+ "executedVersion": "$LATEST",+ "functionError": result.get("function_error") or "Unhandled",+ },+ "version": "1.0",+ "timestamp": _iso(now),+ "DDBStreamBatchInfo": {+ "shardId": "shardId-00000000000000000000-00000000",+ "startSequenceNumber": str(first.get("SequenceNumber", "")),+ "endSequenceNumber": str(last.get("SequenceNumber", "")),+ "approximateArrivalOfFirstRecord": _iso(first.get("ApproximateCreationDateTime", now)),+ "approximateArrivalOfLastRecord": _iso(last.get("ApproximateCreationDateTime", now)),+ "batchSize": len(batch),+ "streamArn": stream_arn,+ },+ }+ body = json.dumps(envelope)+ try:+ spec = parse_arn(dest)+ except ArnParseError:+ return+ try:+ if spec.service == "sqs":+ import ministack.services.sqs as _sqs+ target_q = _sqs._queue_by_arn(dest)+ if target_q is not None:+ target_q["messages"].append({+ "id": new_uuid(), "body": body,+ "md5_body": hashlib.md5(body.encode()).hexdigest(), "md5_attrs": "",+ "receipt_handle": None, "sent_at": now, "visible_at": now,+ "receive_count": 0, "first_receive_at": None, "message_attributes": {},+ "sys": {"SenderId": get_account_id(), "SentTimestamp": str(int(now * 1000))},+ "group_id": None, "dedup_id": None, "dedup_cache_key": None, "seq": None,+ })+ elif spec.service == "sns":+ import ministack.services.sns as _sns+ if dest in _sns._topics:+ _sns._fanout(dest, new_uuid(), body, "Lambda ESM failure", "", {})+ except Exception as exc:+ logger.error("DynamoDB ESM on-failure dispatch failed: %s", exc)++def _poll_dynamodb_streams():"""Returns True if any table advanced past a batch this pass (successfullyinvoked, or filtered out entirely)."""@@ -6049,6 +6153,24 @@ def _poll_dynamodb_streams():"ESM: Lambda %s failed processing DynamoDB stream batch from %s (errorType=%s errorMessage=%s)\n%s",func_name, table_name, err_type, err_msg, result.get("log", ""),)+ # July 2026: enforce MaximumRecordAgeInSeconds. If the oldest+ # record in the failing batch has aged past the limit, discard+ # the batch to the OnFailure destination (MaxRecordAgeExceeded)+ # and advance the shard so a poison batch can't block it forever.+ max_age = esm.get("MaximumRecordAgeInSeconds")+ if max_age and int(max_age) > 0:+ oldest = min(+ (float((r.get("dynamodb") or {}).get("ApproximateCreationDateTime", time.time()))+ for r in batch),+ default=time.time(),+ )+ if (time.time() - oldest) > int(max_age):+ _send_ddb_stream_failure_record(+ esm, func_rec, batch, source_arn, result, "MaxRecordAgeExceeded")+ with _dynamodb_stream_positions_lock:+ _dynamodb_stream_positions[esm_id] = pos + raw_len+ processed_any = True+ continue# Position doesn't advance on failure, so the next pass# would refetch this exact batch — don't report it as# processed.diff --git a/ministack/services/mediaconnect.py b/ministack/services/mediaconnect.pyindex 5d3007fa..c4299417 100644--- a/ministack/services/mediaconnect.py+++ b/ministack/services/mediaconnect.py@@ -11,7 +11,14 @@ Wire field names are camelCase per the AWS service model — the in-memoryrecords also use camelCase so reads and writes round-trip without translation.Supports:- Flows: CreateFlow, DescribeFlow, ListFlows, UpdateFlow+ Flows: CreateFlow, DescribeFlow, ListFlows, UpdateFlow,+ DescribeFlowSourceMetadata, DescribeFlowSourceThumbnail+ Read-only collections (empty — this stub owns no such resources):+ ListBridges, ListEntitlements, ListGateways, ListGatewayInstances,+ ListOfferings, ListReservations+ Describe-by-ARN for the above (NotFoundException — never owned here):+ DescribeBridge, DescribeGateway, DescribeGatewayInstance,+ DescribeReservation, DescribeOfferingTags: ListTagsForResource"""@@ -247,13 +254,93 @@ def _list_tags(arn):return json_response({"tags": _tags.get(arn, {})})+# ---------------------------------------------------------------------------+# Read-only collection ops with no local state.+#+# This emulator is a Flow control-plane stub: it does not model bridges,+# gateways, entitlements, reservations, or reserved-outputs offerings. Those+# resources never exist here, so every List returns an empty collection and+# every Describe-by-ARN returns NotFoundException — matching real AWS for an+# account that owns none of them. Wire key names verified against botocore+# mediaconnect 2018-11-14 service-2.json.+# ---------------------------------------------------------------------------++def _list_bridges(query):+ return json_response({"bridges": []})+++def _list_entitlements(query):+ return json_response({"entitlements": []})+++def _list_gateways(query):+ return json_response({"gateways": []})+++def _list_gateway_instances(query):+ return json_response({"instances": []})+++def _list_offerings(query):+ return json_response({"offerings": []})+++def _list_reservations(query):+ return json_response({"reservations": []})+++def _not_found_by_arn(kind, arn):+ return _error(404, "NotFoundException", f"{kind} {arn} not found.")+++def _describe_flow_source_metadata(arn):+ flow = _flows.get(arn)+ if not flow:+ return _error(404, "NotFoundException", f"Flow {arn} not found.")+ return json_response({"flowArn": arn, "messages": []})+++def _describe_flow_source_thumbnail(arn):+ flow = _flows.get(arn)+ if not flow:+ return _error(404, "NotFoundException", f"Flow {arn} not found.")+ return json_response({"thumbnailDetails": {"flowArn": arn, "thumbnailMessages": []}})++# ---------------------------------------------------------------------------# Request Router# ---------------------------------------------------------------------------_FLOW_ARN_RE = re.compile(r"^/v1/flows/(arn:aws:mediaconnect:[^/]+:[^/]+:flow:[^/]+:[^/]+)$")+_FLOW_SOURCE_METADATA_RE = re.compile(+ r"^/v1/flows/(arn:aws:mediaconnect:[^/]+:[^/]+:flow:[^/]+:[^/]+)/source-metadata$"+)+_FLOW_SOURCE_THUMBNAIL_RE = re.compile(+ r"^/v1/flows/(arn:aws:mediaconnect:[^/]+:[^/]+:flow:[^/]+:[^/]+)/source-thumbnail$"+)_TAGS_ARN_RE = re.compile(r"^/tags/(.+)$")+# Read-only collection endpoints (all GET, no request body needed).+_LIST_ROUTES = {+ "/v1/bridges": _list_bridges,+ "/v1/entitlements": _list_entitlements,+ "/v1/gateways": _list_gateways,+ "/v1/gateway-instances": _list_gateway_instances,+ "/v1/offerings": _list_offerings,+ "/v1/reservations": _list_reservations,+}++# Describe-by-ARN endpoints for resources this stub never owns: {prefix: (kind,)}.+# Each returns NotFoundException for any ARN, matching an account with none of+# these resources. Ordered longest-prefix-first at match time.+_DESCRIBE_BY_ARN_ROUTES = (+ ("/v1/gateway-instances/", "GatewayInstance"),+ ("/v1/bridges/", "Bridge"),+ ("/v1/gateways/", "Gateway"),+ ("/v1/reservations/", "Reservation"),+ ("/v1/offerings/", "Offering"),+)+async def handle_request(method, path, headers, body_bytes, query_params):try:@@ -271,6 +358,20 @@ async def handle_request(method, path, headers, body_bytes, query_params):if path == "/v1/flows" and method == "GET":return _list_flows(query)+ # GET /v1/{bridges,entitlements,gateways,gateway-instances,offerings,reservations}+ if method == "GET" and path in _LIST_ROUTES:+ return _LIST_ROUTES[path](query)++ # GET /v1/flows/{FlowArn}/source-metadata -- DescribeFlowSourceMetadata+ m = _FLOW_SOURCE_METADATA_RE.match(path)+ if m and method == "GET":+ return _describe_flow_source_metadata(urllib.parse.unquote(m.group(1)))++ # GET /v1/flows/{FlowArn}/source-thumbnail -- DescribeFlowSourceThumbnail+ m = _FLOW_SOURCE_THUMBNAIL_RE.match(path)+ if m and method == "GET":+ return _describe_flow_source_thumbnail(urllib.parse.unquote(m.group(1)))+# /v1/flows/{FlowArn} -- DescribeFlow / UpdateFlowm = _FLOW_ARN_RE.match(path)if m:@@ -280,6 +381,13 @@ async def handle_request(method, path, headers, body_bytes, query_params):if method == "PUT":return _update_flow(arn, body)+ # GET /v1/{bridges,gateways,gateway-instances,reservations,offerings}/{Arn}+ if method == "GET":+ for prefix, kind in _DESCRIBE_BY_ARN_ROUTES:+ if path.startswith(prefix) and path[len(prefix):]:+ arn = urllib.parse.unquote(path[len(prefix):])+ return _not_found_by_arn(kind, arn)+# GET /tags/{ResourceArn}m = _TAGS_ARN_RE.match(path)if m and method == "GET":diff --git a/ministack/services/pipes.py b/ministack/services/pipes.pyindex a930fb9d..d4bee502 100644--- a/ministack/services/pipes.py+++ b/ministack/services/pipes.py@@ -1,10 +1,15 @@"""-Minimal EventBridge Pipes runtime for local CloudFormation use.+EventBridge Pipes service emulator.-Scope intentionally limited to:+REST/JSON protocol — /v1/pipes/* and /tags/* paths.++SDK surface:+ ListPipes, CreatePipe, DescribePipe, UpdatePipe, DeletePipe,+ StartPipe, StopPipe, ListTagsForResource, TagResource, UntagResource++Runtime (background poller + CloudFormation) scope is intentionally limited to:- Source: DynamoDB Streams- Target: SNS-- Lifecycle: create/delete (via CloudFormation handlers)"""import copy@@ -13,6 +18,7 @@ import loggingimport osimport threadingimport time+from urllib.parse import unquotefrom ministack.core.arn import ArnParseError, parse_arnfrom ministack.core.persistence import load_state@@ -142,6 +148,7 @@ def register_pipe(desired_state: str = "RUNNING",starting_position: str = "LATEST",tags: dict | None = None,+ description: str = "",):pipe_region = get_region()# AWS rejects cross-region source/target ARNs before role validation.@@ -159,17 +166,20 @@ def register_pipe(if start not in ("LATEST", "TRIM_HORIZON"):start = "LATEST"+ now = int(time.time())_pipes[name] = {"Name": name,"Arn": arn,"RoleArn": role_arn,+ "Description": description or "","Source": source,"Target": target,"DesiredState": state,"CurrentState": state,"StartingPosition": start,"Tags": tags or {},- "CreationTime": int(time.time()),+ "CreationTime": now,+ "LastModifiedTime": now,}_positions[arn] = _initial_position(_pipes[name])@@ -330,3 +340,296 @@ def _initial_position(pipe: dict) -> int:if pipe.get("StartingPosition") == "TRIM_HORIZON":return _ddb.stream_start_position(table_name, **scope)return _ddb.stream_end_position(table_name, **scope)+++# ---------------------------------------------------------------------------+# REST/JSON request handler (endpointPrefix "pipes", protocol rest-json).+#+# Op / method / requestUri (botocore pipes/2015-10-07/service-2.json):+# ListPipes GET /v1/pipes+# CreatePipe POST /v1/pipes/{Name}+# DescribePipe GET /v1/pipes/{Name}+# UpdatePipe PUT /v1/pipes/{Name}+# DeletePipe DELETE /v1/pipes/{Name}+# StartPipe POST /v1/pipes/{Name}/start+# StopPipe POST /v1/pipes/{Name}/stop+# ListTagsForResource GET /tags/{resourceArn}+# TagResource POST /tags/{resourceArn}+# UntagResource DELETE /tags/{resourceArn}+#+# JSON-protocol timestamps are int epoch seconds (Timestamp shape).+# ---------------------------------------------------------------------------++_VALID_REQUESTED_STATE = ("RUNNING", "STOPPED")+++def _json_resp(status, body):+ return status, {"Content-Type": "application/json"}, json.dumps(body).encode()+++def _error(status, code, message):+ return (+ status,+ {"Content-Type": "application/json", "x-amzn-errortype": code},+ json.dumps({"__type": code, "message": message}).encode(),+ )+++def _not_found(name):+ # Matches the real AWS NotFoundException message for DescribePipe/DeletePipe+ # etc. (member: "message").+ return _error(404, "NotFoundException", f"Pipe {name} does not exist.")+++def _single(v):+ return v[0] if isinstance(v, list) else v+++def _lifecycle_response(pipe):+ """Shape shared by CreatePipe/UpdatePipe/DeletePipe/StartPipe/StopPipe."""+ return {+ "Arn": pipe.get("Arn", ""),+ "Name": pipe.get("Name", ""),+ "DesiredState": pipe.get("DesiredState", "RUNNING"),+ "CurrentState": pipe.get("CurrentState", "RUNNING"),+ "CreationTime": int(pipe.get("CreationTime", 0)),+ "LastModifiedTime": int(pipe.get("LastModifiedTime", pipe.get("CreationTime", 0))),+ }+++def _summary(pipe):+ """ListPipes Pipe summary member shape."""+ out = {+ "Name": pipe.get("Name", ""),+ "Arn": pipe.get("Arn", ""),+ "DesiredState": pipe.get("DesiredState", "RUNNING"),+ "CurrentState": pipe.get("CurrentState", "RUNNING"),+ "StateReason": pipe.get("StateReason", ""),+ "CreationTime": int(pipe.get("CreationTime", 0)),+ "LastModifiedTime": int(pipe.get("LastModifiedTime", pipe.get("CreationTime", 0))),+ "Source": pipe.get("Source", ""),+ "Target": pipe.get("Target", ""),+ }+ if pipe.get("Enrichment"):+ out["Enrichment"] = pipe["Enrichment"]+ return out+++def _describe_response(pipe):+ return {+ "Arn": pipe.get("Arn", ""),+ "Name": pipe.get("Name", ""),+ "Description": pipe.get("Description", ""),+ "DesiredState": pipe.get("DesiredState", "RUNNING"),+ "CurrentState": pipe.get("CurrentState", "RUNNING"),+ "StateReason": pipe.get("StateReason", ""),+ "Source": pipe.get("Source", ""),+ "Target": pipe.get("Target", ""),+ "RoleArn": pipe.get("RoleArn", ""),+ "Tags": pipe.get("Tags", {}) or {},+ "CreationTime": int(pipe.get("CreationTime", 0)),+ "LastModifiedTime": int(pipe.get("LastModifiedTime", pipe.get("CreationTime", 0))),+ }+++def _find_pipe_by_arn(arn):+ for pipe in _pipes.values():+ if pipe.get("Arn") == arn:+ return pipe+ return None+++def _create_pipe(name, body):+ if name in _pipes:+ return _error(409, "ConflictException", f"Pipe {name} already exists.")+ source = body.get("Source", "")+ target = body.get("Target", "")+ role_arn = body.get("RoleArn", "")+ desired = str(body.get("DesiredState", "RUNNING")).upper()+ if desired not in _VALID_REQUESTED_STATE:+ return _error(+ 400,+ "ValidationException",+ f"DesiredState must be one of {list(_VALID_REQUESTED_STATE)}.",+ )+ try:+ pipe = register_pipe(+ name=name,+ source=source,+ target=target,+ role_arn=role_arn,+ desired_state=desired,+ tags=body.get("Tags") or {},+ description=body.get("Description", "") or "",+ )+ except ValueError as e:+ return _error(400, "ValidationException", str(e))+ return _json_resp(200, _lifecycle_response(pipe))+++def _describe_pipe(name):+ pipe = _pipes.get(name)+ if pipe is None:+ return _not_found(name)+ return _json_resp(200, _describe_response(pipe))+++def _update_pipe(name, body):+ pipe = _pipes.get(name)+ if pipe is None:+ return _not_found(name)+ if "Description" in body:+ pipe["Description"] = body.get("Description", "") or ""+ if "RoleArn" in body:+ pipe["RoleArn"] = body.get("RoleArn", "") or ""+ if "Target" in body and body.get("Target"):+ pipe["Target"] = body["Target"]+ if "DesiredState" in body:+ desired = str(body.get("DesiredState", "")).upper()+ if desired not in _VALID_REQUESTED_STATE:+ return _error(+ 400,+ "ValidationException",+ f"DesiredState must be one of {list(_VALID_REQUESTED_STATE)}.",+ )+ pipe["DesiredState"] = desired+ pipe["CurrentState"] = desired+ pipe["LastModifiedTime"] = int(time.time())+ _pipes[name] = pipe+ return _json_resp(200, _lifecycle_response(pipe))+++def _delete_pipe_op(name):+ pipe = _pipes.get(name)+ if pipe is None:+ return _not_found(name)+ resp = {+ "Arn": pipe.get("Arn", ""),+ "Name": pipe.get("Name", ""),+ "DesiredState": "DELETED",+ "CurrentState": "DELETING",+ "CreationTime": int(pipe.get("CreationTime", 0)),+ "LastModifiedTime": int(pipe.get("LastModifiedTime", pipe.get("CreationTime", 0))),+ }+ delete_pipe(name)+ return _json_resp(200, resp)+++def _set_state(name, desired):+ pipe = _pipes.get(name)+ if pipe is None:+ return _not_found(name)+ pipe["DesiredState"] = desired+ pipe["CurrentState"] = desired+ pipe["LastModifiedTime"] = int(time.time())+ _pipes[name] = pipe+ return _json_resp(200, _lifecycle_response(pipe))+++def _list_pipes(query):+ name_prefix = _single(query.get("NamePrefix"))+ desired_state = _single(query.get("DesiredState"))+ current_state = _single(query.get("CurrentState"))+ source_prefix = _single(query.get("SourcePrefix"))+ target_prefix = _single(query.get("TargetPrefix"))+ limit = _single(query.get("Limit"))++ pipes = sorted(_pipes.values(), key=lambda p: p.get("Name", ""))+ result = []+ for pipe in pipes:+ if name_prefix and not pipe.get("Name", "").startswith(name_prefix):+ continue+ if desired_state and pipe.get("DesiredState") != desired_state:+ continue+ if current_state and pipe.get("CurrentState") != current_state:+ continue+ if source_prefix and not pipe.get("Source", "").startswith(source_prefix):+ continue+ if target_prefix and not pipe.get("Target", "").startswith(target_prefix):+ continue+ result.append(_summary(pipe))++ next_token = None+ if limit:+ try:+ n = int(limit)+ if 0 < n < len(result):+ next_token = result[n]["Name"]+ result = result[:n]+ except (TypeError, ValueError):+ pass++ body = {"Pipes": result}+ if next_token is not None:+ body["NextToken"] = next_token+ return _json_resp(200, body)+++def _list_tags(arn):+ pipe = _find_pipe_by_arn(arn)+ if pipe is None:+ return _not_found(arn)+ return _json_resp(200, {"tags": pipe.get("Tags", {}) or {}})+++def _tag_resource(arn, body):+ pipe = _find_pipe_by_arn(arn)+ if pipe is None:+ return _not_found(arn)+ pipe.setdefault("Tags", {}).update(body.get("tags", {}) or {})+ return _json_resp(200, {})+++def _untag_resource(arn, query):+ pipe = _find_pipe_by_arn(arn)+ if pipe is None:+ return _not_found(arn)+ keys = query.get("tagKeys", [])+ if not isinstance(keys, list):+ keys = [keys]+ tags = pipe.setdefault("Tags", {})+ for k in keys:+ tags.pop(k, None)+ return _json_resp(200, {})+++async def handle_request(method, path, headers, body_bytes, query_params):+ try:+ body = json.loads(body_bytes) if body_bytes else {}+ except (json.JSONDecodeError, TypeError):+ body = {}+ if not isinstance(body, dict):+ body = {}++ # Pipe lifecycle sub-actions: /v1/pipes/{Name}/start | /stop+ if path.startswith("/v1/pipes/"):+ rest = path[len("/v1/pipes/"):]+ if rest.endswith("/start"):+ return _set_state(unquote(rest[: -len("/start")]), "RUNNING")+ if rest.endswith("/stop"):+ return _set_state(unquote(rest[: -len("/stop")]), "STOPPED")+ name = unquote(rest)+ if name:+ if method == "POST":+ return _create_pipe(name, body)+ if method == "GET":+ return _describe_pipe(name)+ if method == "PUT":+ return _update_pipe(name, body)+ if method == "DELETE":+ return _delete_pipe_op(name)++ if path == "/v1/pipes" and method == "GET":+ return _list_pipes(query_params)++ # Tag routes: /tags/{resourceArn+}+ if path.startswith("/tags/"):+ arn = unquote(path[len("/tags/"):])+ if method == "GET":+ return _list_tags(arn)+ if method == "POST":+ return _tag_resource(arn, body)+ if method == "DELETE":+ return _untag_resource(arn, query_params)++ return _error(400, "ValidationException", f"No route for {method} {path}")diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.pyindex 4f6706a0..47813772 100644--- a/ministack/services/secretsmanager.py+++ b/ministack/services/secretsmanager.py@@ -176,6 +176,34 @@ def resolve_secret_string(secret_id, version_stage="AWSCURRENT"):return ver.get("SecretString")+def _emit_secret_label_updated(secret, label, version_id):+ """Native Secrets Manager → EventBridge ``Secret Label Updated`` event, fired+ when a staging label moves to a new version — for every label except+ ``AWSPENDING`` / ``AWSPREVIOUS`` (custom labels included). Metadata-only+ changes (tags, description, rotation config, policy) do not emit. Delivered+ to the default event bus; failures are swallowed so they never break the+ mutation. (AWS: Secret event notifications.)"""+ try:+ from ministack.services import eventbridge as _eb+ _eb._dispatch_event({+ "EventId": new_uuid(),+ "Source": "aws.secretsmanager",+ "DetailType": "Secret Label Updated",+ "Detail": json.dumps({+ "name": secret["Name"],+ "labelUpdated": label,+ "versionId": version_id,+ }),+ "EventBusName": "default",+ "Time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ "Resources": [secret["ARN"]],+ "Account": get_account_id(),+ "Region": get_region(),+ })+ except Exception:+ logger.exception("SecretsManager→EventBridge delivery failed for %s", secret.get("Name"))++def _apply_current_promotion(secret, new_vid):"""Promote *new_vid* to AWSCURRENT.@@ -212,6 +240,7 @@ def _apply_current_promotion(secret, new_vid):ver["Stages"].append("AWSCURRENT")if "AWSPENDING" in ver["Stages"]:ver["Stages"].remove("AWSPENDING")+ _emit_secret_label_updated(secret, "AWSCURRENT", new_vid)def _vid_to_stages(secret):@@ -747,6 +776,9 @@ def _put_secret_value(data):_apply_current_promotion(secret, vid)else:secret["Versions"][vid]["Stages"] = list(stages)+ for _lbl in stages:+ if _lbl not in ("AWSCURRENT", "AWSPENDING", "AWSPREVIOUS"):+ _emit_secret_label_updated(secret, _lbl, vid)secret["LastChangedDate"] = now_sync_replicas(secret)@@ -835,6 +867,8 @@ def _update_secret_version_stage(data):if move_to_vid:_remove_stage_everywhere(secret, version_stage, except_version_id=move_to_vid)_add_stage(secret, move_to_vid, version_stage)+ if version_stage not in ("AWSPENDING", "AWSPREVIOUS"):+ _emit_secret_label_updated(secret, version_stage, move_to_vid)if old_current_vid and old_current_vid != move_to_vid:_remove_stage_everywhere(secret, "AWSPREVIOUS")diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 0cd038ea..508f8c69 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -1473,7 +1473,40 @@ def _matches_filter_policy(sub: dict, message_attributes: dict) -> bool:if scope == "MessageBody":return True+ return _policy_matches(policy, message_attributes)+++_OR_RESERVED_MEMBER_KEYS = frozenset({+ "anything-but", "prefix", "suffix", "equals-ignore-case",+ "numeric", "exists", "cidr",+})+++def _is_or_operator(value) -> bool:+ """True when a ``$or`` value is SNS's OR operator rather than a literal+ attribute name. AWS recognizes ``$or`` only when it holds an array of at+ least two objects, none of whose field names are reserved rule keywords;+ otherwise ``$or`` is treated as an ordinary attribute name."""+ if not isinstance(value, list) or len(value) < 2:+ return False+ for member in value:+ if not isinstance(member, dict):+ return False+ if any(key in _OR_RESERVED_MEMBER_KEYS for key in member):+ return False+ return True+++def _policy_matches(policy: dict, message_attributes: dict) -> bool:+ """Match one filter-policy object against the message attributes. Sibling+ keys are AND-ed; a recognized ``$or`` matches when any of its member+ policies matches (evaluated recursively, so nested ``$or`` works)."""for key, allowed_values in policy.items():+ if key == "$or" and _is_or_operator(allowed_values):+ if not any(_policy_matches(member, message_attributes)+ for member in allowed_values):+ return False+ continueattr = message_attributes.get(key)if attr is None:return Falsediff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex 81129017..44c46fe1 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -619,10 +619,13 @@ async def _act_receive_message(data: dict, qurl: str) -> dict:q = _get_q(url)max_n = min(int(data.get("MaxNumberOfMessages", 1)), 10)- vis = int(data.get("VisibilityTimeout")- or q["attributes"].get("VisibilityTimeout", "30"))- wait = int(data.get("WaitTimeSeconds")- or q["attributes"].get("ReceiveMessageWaitTimeSeconds", "0"))+ # An explicit request value wins even when it is 0 — a supplied+ # VisibilityTimeout=0 / WaitTimeSeconds=0 must NOT fall back to the queue+ # attribute (0 is falsy in Python; keying on presence is required).+ _vis = data.get("VisibilityTimeout")+ vis = int(_vis if _vis is not None else q["attributes"].get("VisibilityTimeout", "30"))+ _wait = data.get("WaitTimeSeconds")+ wait = int(_wait if _wait is not None else q["attributes"].get("ReceiveMessageWaitTimeSeconds", "0"))attr_names = (data.get("AttributeNames")or data.get("MessageSystemAttributeNames") or [])diff --git a/tests/test_backup.py b/tests/test_backup.pyindex 864deb08..a419be03 100644--- a/tests/test_backup.py+++ b/tests/test_backup.py@@ -594,6 +594,147 @@ def test_backup_tags_are_region_scoped(backup, backup_west):assert backup_west.list_tags(ResourceArn=west_arn)["Tags"] == {}+# ---------------------------------------------------------------------------+# Read-only surface (empty-list / default documents)+# ---------------------------------------------------------------------------++def test_backup_list_copy_jobs_empty(backup):+ resp = backup.list_copy_jobs()+ assert resp["CopyJobs"] == []+++def test_backup_list_restore_jobs_empty(backup):+ resp = backup.list_restore_jobs()+ assert resp["RestoreJobs"] == []+++def test_backup_list_report_jobs_empty(backup):+ resp = backup.list_report_jobs()+ assert resp["ReportJobs"] == []+++def test_backup_list_report_plans_empty(backup):+ resp = backup.list_report_plans()+ assert resp["ReportPlans"] == []+++def test_backup_list_frameworks_empty(backup):+ resp = backup.list_frameworks()+ assert resp["Frameworks"] == []+++def test_backup_list_protected_resources_empty(backup):+ resp = backup.list_protected_resources()+ assert resp["Results"] == []+++def test_backup_list_legal_holds_empty(backup):+ resp = backup.list_legal_holds()+ assert resp["LegalHolds"] == []+++def test_backup_list_backup_plan_templates_empty(backup):+ resp = backup.list_backup_plan_templates()+ assert resp["BackupPlanTemplatesList"] == []+++def test_backup_list_restore_testing_plans_empty(backup):+ resp = backup.list_restore_testing_plans()+ assert resp["RestoreTestingPlans"] == []+++def test_backup_list_recovery_points_by_vault_empty(backup):+ name = f"rp-list-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ resp = backup.list_recovery_points_by_backup_vault(BackupVaultName=name)+ assert resp["RecoveryPoints"] == []+++def test_backup_list_recovery_points_by_vault_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.list_recovery_points_by_backup_vault(BackupVaultName="no-such-vault-xyz")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_list_recovery_points_by_resource_empty(backup):+ resp = backup.list_recovery_points_by_resource(+ ResourceArn="arn:aws:dynamodb:us-east-1:000000000000:table/MyTable"+ )+ assert resp["RecoveryPoints"] == []+++def test_backup_list_protected_resources_by_vault_empty(backup):+ name = f"prv-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ resp = backup.list_protected_resources_by_backup_vault(BackupVaultName=name)+ assert resp["Results"] == []+++def test_backup_get_vault_access_policy_not_found(backup):+ name = f"policy-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ with pytest.raises(ClientError) as exc:+ backup.get_backup_vault_access_policy(BackupVaultName=name)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_get_vault_notifications_not_found(backup):+ name = f"notif-vault-{_uid()}"+ backup.create_backup_vault(BackupVaultName=name)+ with pytest.raises(ClientError) as exc:+ backup.get_backup_vault_notifications(BackupVaultName=name)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_describe_copy_job_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.describe_copy_job(CopyJobId="no-such-copy-job")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_describe_framework_not_found(backup):+ with pytest.raises(ClientError) as exc:+ backup.describe_framework(FrameworkName="no-such-framework")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_backup_describe_region_settings(backup):+ resp = backup.describe_region_settings()+ assert resp["ResourceTypeOptInPreference"] == {}+ assert resp["ResourceTypeManagementPreference"] == {}+++def test_backup_describe_global_settings(backup):+ resp = backup.describe_global_settings()+ assert resp["GlobalSettings"] == {}+++def test_backup_get_supported_resource_types(backup):+ resp = backup.get_supported_resource_types()+ assert "DynamoDB" in resp["ResourceTypes"]+ assert "S3" in resp["ResourceTypes"]+++def test_backup_list_scan_jobs_empty(backup):+ resp = backup.list_scan_jobs()+ assert resp["ScanJobs"] == []+++def test_backup_list_tiering_configurations_empty(backup):+ resp = backup.list_tiering_configurations()+ assert resp["TieringConfigurations"] == []+++def test_backup_list_indexed_recovery_points_empty(backup):+ resp = backup.list_indexed_recovery_points()+ assert resp["IndexedRecoveryPoints"] == []+++def test_backup_list_backup_job_summaries_empty(backup):+ resp = backup.list_backup_job_summaries()+ assert resp["BackupJobSummaries"] == []++def test_backup_reset_clears_all_regions():from ministack.core.responses import get_region, set_request_regionfrom ministack.services import backup as backup_servicediff --git a/tests/test_cloudcontrol.py b/tests/test_cloudcontrol.pynew file mode 100644index 00000000..c38f1102--- /dev/null+++ b/tests/test_cloudcontrol.py@@ -0,0 +1,187 @@+"""Direct-handler unit tests for the Cloud Control API emulator.++These call ``ministack.services.cloudcontrol.handle_request`` directly (no+server), asserting botocore-correct shapes: Properties as a JSON string and+ProgressEvent OperationStatus=SUCCESS.+"""++import asyncio+import json++import pytest++from ministack.services import cloudcontrol++TARGET_PREFIX = "CloudApiService"+TYPE_NAME = "AWS::S3::Bucket"+++def _call(action, payload):+ """Invoke the handler for one op and return (status, headers, parsed_body)."""+ headers = {"x-amz-target": f"{TARGET_PREFIX}.{action}"}+ body = json.dumps(payload).encode("utf-8")+ status, resp_headers, resp_body = asyncio.run(+ cloudcontrol.handle_request("POST", "/", headers, body, {})+ )+ return status, resp_headers, json.loads(resp_body)++[email protected](autouse=True)+def _reset():+ cloudcontrol.reset()+ yield+ cloudcontrol.reset()+++def test_create_get_list_update_delete_round_trip():+ # Create+ desired = {"BucketName": "my-bucket", "VersioningConfiguration": {"Status": "Suspended"}}+ status, _, body = _call("CreateResource", {+ "TypeName": TYPE_NAME,+ "DesiredState": json.dumps(desired),+ })+ assert status == 200+ event = body["ProgressEvent"]+ assert event["TypeName"] == TYPE_NAME+ assert event["Operation"] == "CREATE"+ assert event["OperationStatus"] == "SUCCESS"+ assert event["Identifier"] == "my-bucket"+ assert event["RequestToken"]+ assert isinstance(event["EventTime"], int)+ # ResourceModel is a JSON string+ assert isinstance(event["ResourceModel"], str)+ json.loads(event["ResourceModel"])++ # Get+ status, _, body = _call("GetResource", {+ "TypeName": TYPE_NAME,+ "Identifier": "my-bucket",+ })+ assert status == 200+ assert body["TypeName"] == TYPE_NAME+ desc = body["ResourceDescription"]+ assert desc["Identifier"] == "my-bucket"+ # Properties is a JSON string, per botocore+ assert isinstance(desc["Properties"], str)+ assert json.loads(desc["Properties"])["BucketName"] == "my-bucket"++ # List+ status, _, body = _call("ListResources", {"TypeName": TYPE_NAME})+ assert status == 200+ assert body["TypeName"] == TYPE_NAME+ descs = body["ResourceDescriptions"]+ assert len(descs) == 1+ assert descs[0]["Identifier"] == "my-bucket"+ assert isinstance(descs[0]["Properties"], str)++ # Update via RFC 6902 patch+ patch = [{"op": "replace", "path": "/VersioningConfiguration/Status", "value": "Enabled"}]+ status, _, body = _call("UpdateResource", {+ "TypeName": TYPE_NAME,+ "Identifier": "my-bucket",+ "PatchDocument": json.dumps(patch),+ })+ assert status == 200+ uevent = body["ProgressEvent"]+ assert uevent["Operation"] == "UPDATE"+ assert uevent["OperationStatus"] == "SUCCESS"+ props = json.loads(uevent["ResourceModel"])+ assert props["VersioningConfiguration"]["Status"] == "Enabled"++ # Confirm persisted mutation+ _, _, body = _call("GetResource", {"TypeName": TYPE_NAME, "Identifier": "my-bucket"})+ assert json.loads(body["ResourceDescription"]["Properties"])["VersioningConfiguration"]["Status"] == "Enabled"++ # Delete+ status, _, body = _call("DeleteResource", {+ "TypeName": TYPE_NAME,+ "Identifier": "my-bucket",+ })+ assert status == 200+ devent = body["ProgressEvent"]+ assert devent["Operation"] == "DELETE"+ assert devent["OperationStatus"] == "SUCCESS"++ # Gone+ status, _, body = _call("GetResource", {"TypeName": TYPE_NAME, "Identifier": "my-bucket"})+ assert status == 400+ assert body["__type"] == "ResourceNotFoundException"++ # And list is empty+ _, _, body = _call("ListResources", {"TypeName": TYPE_NAME})+ assert body["ResourceDescriptions"] == []+++def test_get_unknown_resource_returns_not_found():+ status, headers, body = _call("GetResource", {+ "TypeName": TYPE_NAME,+ "Identifier": "does-not-exist",+ })+ assert status == 400+ assert body["__type"] == "ResourceNotFoundException"+ assert headers.get("x-amzn-errortype") == "ResourceNotFoundException"+++def test_delete_unknown_resource_returns_not_found():+ status, _, body = _call("DeleteResource", {+ "TypeName": TYPE_NAME,+ "Identifier": "nope",+ })+ assert status == 400+ assert body["__type"] == "ResourceNotFoundException"+++def test_request_tracking_and_status():+ _, _, body = _call("CreateResource", {+ "TypeName": TYPE_NAME,+ "DesiredState": json.dumps({"BucketName": "tracked-bucket"}),+ })+ token = body["ProgressEvent"]["RequestToken"]++ # GetResourceRequestStatus replays the ProgressEvent+ status, _, body = _call("GetResourceRequestStatus", {"RequestToken": token})+ assert status == 200+ assert body["ProgressEvent"]["RequestToken"] == token+ assert body["ProgressEvent"]["OperationStatus"] == "SUCCESS"++ # ListResourceRequests includes it, and filters work+ _, _, body = _call("ListResourceRequests", {})+ tokens = [e["RequestToken"] for e in body["ResourceRequestStatusSummaries"]]+ assert token in tokens++ _, _, body = _call("ListResourceRequests", {+ "ResourceRequestStatusFilter": {"Operations": ["CREATE"]},+ })+ assert all(e["Operation"] == "CREATE" for e in body["ResourceRequestStatusSummaries"])++ _, _, body = _call("ListResourceRequests", {+ "ResourceRequestStatusFilter": {"Operations": ["DELETE"]},+ })+ assert body["ResourceRequestStatusSummaries"] == []+++def test_get_request_status_unknown_token():+ status, _, body = _call("GetResourceRequestStatus", {"RequestToken": "missing"})+ assert status == 400+ assert body["__type"] == "RequestTokenNotFoundException"+++def test_cancel_terminal_request_conflicts():+ _, _, body = _call("CreateResource", {+ "TypeName": TYPE_NAME,+ "DesiredState": json.dumps({"BucketName": "cancel-bucket"}),+ })+ token = body["ProgressEvent"]["RequestToken"]+ # Synchronous requests are already SUCCESS, so cancel must conflict.+ status, _, body = _call("CancelResourceRequest", {"RequestToken": token})+ assert status == 400+ assert body["__type"] == "ConflictException"+++def test_create_duplicate_conflicts():+ payload = {"TypeName": TYPE_NAME, "DesiredState": json.dumps({"BucketName": "dup"})}+ status, _, _ = _call("CreateResource", payload)+ assert status == 200+ status, _, body = _call("CreateResource", payload)+ assert status == 400+ assert body["__type"] == "AlreadyExistsException"diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.pyindex 1f818479..de805fdb 100644--- a/tests/test_cloudfront.py+++ b/tests/test_cloudfront.py@@ -1576,4 +1576,160 @@ def test_cloudfront_response_headers_policy_duplicate_and_list(cloudfront):resp = cloudfront.list_distributions_by_response_headers_policy_id(ResponseHeadersPolicyId=pid)assert resp["DistributionIdList"]["Quantity"] == 0+++# ---------------------------------------------------------------------------+# Read-only list surface — ops previously falling through the path dispatch.+# Shapes verified against botocore cloudfront service-2.json (2020-05-31).+# ---------------------------------------------------------------------------+++def test_cloudfront_list_key_groups_empty(cloudfront):+ resp = cloudfront.list_key_groups()+ lst = resp["KeyGroupList"]+ assert lst["MaxItems"] == 100+ assert lst["Quantity"] == 0+ assert lst.get("Items", []) == []+++def test_cloudfront_list_public_keys_empty(cloudfront):+ resp = cloudfront.list_public_keys()+ lst = resp["PublicKeyList"]+ assert lst["MaxItems"] == 100+ assert lst["Quantity"] == 0+ assert lst.get("Items", []) == []+++def test_cloudfront_list_field_level_encryption_configs_empty(cloudfront):+ resp = cloudfront.list_field_level_encryption_configs()+ lst = resp["FieldLevelEncryptionList"]+ assert lst["MaxItems"] == 100+ assert lst["Quantity"] == 0+ assert lst.get("Items", []) == []+++def test_cloudfront_list_field_level_encryption_profiles_empty(cloudfront):+ resp = cloudfront.list_field_level_encryption_profiles()+ lst = resp["FieldLevelEncryptionProfileList"]+ assert lst["MaxItems"] == 100+ assert lst["Quantity"] == 0+ assert lst.get("Items", []) == []+++def test_cloudfront_list_continuous_deployment_policies_empty(cloudfront):+ resp = cloudfront.list_continuous_deployment_policies()+ lst = resp["ContinuousDeploymentPolicyList"]+ assert lst["MaxItems"] == 100+ assert lst["Quantity"] == 0+ assert lst.get("Items", []) == []+++def test_cloudfront_list_origin_access_identities_empty(cloudfront):+ resp = cloudfront.list_cloud_front_origin_access_identities()+ lst = resp["CloudFrontOriginAccessIdentityList"]+ assert lst["MaxItems"] == 100+ assert lst["IsTruncated"] is False+ assert lst["Quantity"] == 0+ assert lst.get("Items", []) == []+++def test_cloudfront_list_streaming_distributions_empty(cloudfront):+ resp = cloudfront.list_streaming_distributions()+ lst = resp["StreamingDistributionList"]+ assert lst["MaxItems"] == 100+ assert lst["IsTruncated"] is False+ assert lst["Quantity"] == 0+ assert lst.get("Items", []) == []+++def test_cloudfront_list_vpc_origins_empty(cloudfront):+ resp = cloudfront.list_vpc_origins()+ lst = resp["VpcOriginList"]+ assert lst["MaxItems"] == 100+ assert lst["IsTruncated"] is False+ assert lst["Quantity"] == 0+ assert lst.get("Items", []) == []+++def test_cloudfront_list_realtime_log_configs_empty(cloudfront):+ resp = cloudfront.list_realtime_log_configs()+ lst = resp["RealtimeLogConfigs"]+ assert lst["MaxItems"] == 100+ assert lst["IsTruncated"] is False+ assert lst.get("Items", []) == []+++def test_cloudfront_list_anycast_ip_lists_empty(cloudfront):+ resp = cloudfront.list_anycast_ip_lists()+ coll = resp["AnycastIpLists"]+ assert coll["MaxItems"] == 100+ assert coll["IsTruncated"] is False+ assert coll["Quantity"] == 0+ assert coll.get("Items", []) == []+++def test_cloudfront_list_cache_policies_round_trip(cloudfront):+ baseline = cloudfront.list_cache_policies()["CachePolicyList"]["Quantity"]++ name = f"cp-{_uuid_mod.uuid4().hex[:8]}"+ create = cloudfront.create_cache_policy(CachePolicyConfig=_cache_policy_config(name))+ pid = create["CachePolicy"]["Id"]++ listed = cloudfront.list_cache_policies()["CachePolicyList"]+ assert listed["Quantity"] == baseline + 1+ names = [s["CachePolicy"]["CachePolicyConfig"]["Name"] for s in listed["Items"]]+ assert name in names+ types = {s["Type"] for s in listed["Items"]}+ assert types == {"custom"}++ cloudfront.delete_cache_policy(Id=pid, IfMatch=create["ETag"])+++def test_cloudfront_list_origin_request_policies_round_trip(cloudfront):+ baseline = cloudfront.list_origin_request_policies()["OriginRequestPolicyList"]["Quantity"]++ name = f"orp-{_uuid_mod.uuid4().hex[:8]}"+ create = cloudfront.create_origin_request_policy(OriginRequestPolicyConfig=_orp_config(name))+ pid = create["OriginRequestPolicy"]["Id"]++ listed = cloudfront.list_origin_request_policies()["OriginRequestPolicyList"]+ assert listed["Quantity"] == baseline + 1+ names = [s["OriginRequestPolicy"]["OriginRequestPolicyConfig"]["Name"] for s in listed["Items"]]+ assert name in names+ assert {s["Type"] for s in listed["Items"]} == {"custom"}++ cloudfront.delete_origin_request_policy(Id=pid, IfMatch=create["ETag"])+++def test_cloudfront_list_response_headers_policies_round_trip(cloudfront):+ baseline = cloudfront.list_response_headers_policies()["ResponseHeadersPolicyList"]["Quantity"]++ name = f"rhp-{_uuid_mod.uuid4().hex[:8]}"+ create = cloudfront.create_response_headers_policy(ResponseHeadersPolicyConfig=_rhp_config(name))+ pid = create["ResponseHeadersPolicy"]["Id"]++ listed = cloudfront.list_response_headers_policies()["ResponseHeadersPolicyList"]+ assert listed["Quantity"] == baseline + 1+ names = [s["ResponseHeadersPolicy"]["ResponseHeadersPolicyConfig"]["Name"] for s in listed["Items"]]+ assert name in names+ assert {s["Type"] for s in listed["Items"]} == {"custom"}+cloudfront.delete_response_headers_policy(Id=pid, IfMatch=create["ETag"])+++def test_cloudfront_get_monitoring_subscription_errors(cloudfront):+ with pytest.raises(ClientError) as exc:+ cloudfront.get_monitoring_subscription(DistributionId="EDOESNOTEXIST0")+ assert exc.value.response["Error"]["Code"] == "NoSuchDistribution"++ cfg = _custom_origin_distribution_config(f"mon-{_uuid_mod.uuid4().hex[:8]}")+ create = cloudfront.create_distribution(DistributionConfig=cfg)+ dist_id = create["Distribution"]["Id"]+ with pytest.raises(ClientError) as exc:+ cloudfront.get_monitoring_subscription(DistributionId=dist_id)+ assert exc.value.response["Error"]["Code"] == "NoSuchMonitoringSubscription"++ etag = create["ETag"]+ disabled = dict(cfg, Enabled=False)+ upd = cloudfront.update_distribution(DistributionConfig=disabled, Id=dist_id, IfMatch=etag)+ cloudfront.delete_distribution(Id=dist_id, IfMatch=upd["ETag"])diff --git a/tests/test_config.py b/tests/test_config.pynew file mode 100644index 00000000..715a2e29--- /dev/null+++ b/tests/test_config.py@@ -0,0 +1,275 @@+"""+Unit tests for the AWS Config service module (ministack.services.config).++These call the handler directly (no live server / router needed), matching the+direct-dispatch style so they run before the router is wired. Each test sets the+request account + region contextvars, then invokes handle_request with a+JSON-RPC X-Amz-Target header and asserts botocore-verified AWS shapes.+"""++import asyncio+import json++import pytest++from ministack.core.responses import set_request_account_id, set_request_region+from ministack.services import config as config_svc++TARGET_PREFIX = "StarlingDoveService"+++def _call(action, payload):+ set_request_account_id("test") # -> resolves to a stable 12-digit account+ set_request_region("us-east-1")+ headers = {"x-amz-target": f"{TARGET_PREFIX}.{action}"}+ body = json.dumps(payload).encode("utf-8")+ status, resp_headers, resp_body = asyncio.run(+ config_svc.handle_request("POST", "/", headers, body, {})+ )+ parsed = json.loads(resp_body) if resp_body else {}+ return status, parsed++[email protected](autouse=True)+def _reset():+ set_request_account_id("test")+ set_request_region("us-east-1")+ config_svc.reset()+ yield+ config_svc.reset()+++# ── Config Rules ──────────────────────────────────────────────++def test_put_and_describe_config_rule_roundtrip():+ status, _ = _call("PutConfigRule", {+ "ConfigRule": {+ "ConfigRuleName": "s3-bucket-versioning-enabled",+ "Source": {+ "Owner": "AWS",+ "SourceIdentifier": "S3_BUCKET_VERSIONING_ENABLED",+ },+ }+ })+ assert status == 200++ status, out = _call("DescribeConfigRules", {})+ assert status == 200+ assert "ConfigRules" in out+ rules = out["ConfigRules"]+ assert len(rules) == 1+ rule = rules[0]+ assert rule["ConfigRuleName"] == "s3-bucket-versioning-enabled"+ assert rule["ConfigRuleArn"].startswith("arn:aws:config:us-east-1:")+ assert ":config-rule/" in rule["ConfigRuleArn"]+ assert rule["ConfigRuleId"]+ assert rule["ConfigRuleState"] == "ACTIVE"+ assert rule["Source"]["Owner"] == "AWS"+++def test_describe_config_rules_empty():+ status, out = _call("DescribeConfigRules", {})+ assert status == 200+ assert out == {"ConfigRules": []}+++def test_describe_config_rules_unknown_name_errors():+ status, out = _call("DescribeConfigRules", {"ConfigRuleNames": ["nope"]})+ assert status == 400+ assert out["__type"] == "NoSuchConfigRuleException"+++def test_delete_config_rule():+ _call("PutConfigRule", {+ "ConfigRule": {+ "ConfigRuleName": "r1",+ "Source": {"Owner": "AWS", "SourceIdentifier": "X"},+ }+ })+ status, _ = _call("DeleteConfigRule", {"ConfigRuleName": "r1"})+ assert status == 200+ status, out = _call("DescribeConfigRules", {})+ assert out["ConfigRules"] == []+++def test_delete_unknown_config_rule_errors():+ status, out = _call("DeleteConfigRule", {"ConfigRuleName": "ghost"})+ assert status == 400+ assert out["__type"] == "NoSuchConfigRuleException"+++def test_put_config_rule_requires_name():+ status, out = _call("PutConfigRule", {"ConfigRule": {"Source": {"Owner": "AWS"}}})+ assert status == 400+ assert out["__type"] == "InvalidParameterValueException"+++# ── Configuration Recorder ────────────────────────────────────++def test_recorder_put_describe_start_stop():+ status, _ = _call("PutConfigurationRecorder", {+ "ConfigurationRecorder": {+ "name": "default",+ "roleARN": "arn:aws:iam::123456789012:role/config-role",+ "recordingGroup": {"allSupported": True},+ }+ })+ assert status == 200++ status, out = _call("DescribeConfigurationRecorders", {})+ assert status == 200+ recorders = out["ConfigurationRecorders"]+ assert len(recorders) == 1+ assert recorders[0]["name"] == "default"+ assert recorders[0]["roleARN"].endswith("config-role")++ # Status before start: not recording.+ status, out = _call("DescribeConfigurationRecorderStatus", {})+ assert status == 200+ statuses = out["ConfigurationRecordersStatus"]+ assert len(statuses) == 1+ assert statuses[0]["name"] == "default"+ assert statuses[0]["recording"] is False++ status, _ = _call("StartConfigurationRecorder",+ {"ConfigurationRecorderName": "default"})+ assert status == 200+ status, out = _call("DescribeConfigurationRecorderStatus", {})+ st = out["ConfigurationRecordersStatus"][0]+ assert st["recording"] is True+ assert st["lastStatus"] == "Success"+ assert isinstance(st["lastStartTime"], int)++ status, _ = _call("StopConfigurationRecorder",+ {"ConfigurationRecorderName": "default"})+ assert status == 200+ status, out = _call("DescribeConfigurationRecorderStatus", {})+ assert out["ConfigurationRecordersStatus"][0]["recording"] is False+++def test_describe_recorders_empty():+ status, out = _call("DescribeConfigurationRecorders", {})+ assert status == 200+ assert out == {"ConfigurationRecorders": []}+++def test_start_unknown_recorder_errors():+ status, out = _call("StartConfigurationRecorder",+ {"ConfigurationRecorderName": "missing"})+ assert status == 400+ assert out["__type"] == "NoSuchConfigurationRecorderException"+++def test_describe_recorder_status_unknown_name_errors():+ status, out = _call("DescribeConfigurationRecorderStatus",+ {"ConfigurationRecorderNames": ["missing"]})+ assert status == 400+ assert out["__type"] == "NoSuchConfigurationRecorderException"+++# ── Delivery Channel ──────────────────────────────────────────++def test_delivery_channel_put_describe():+ status, _ = _call("PutDeliveryChannel", {+ "DeliveryChannel": {+ "name": "default",+ "s3BucketName": "config-bucket",+ }+ })+ assert status == 200++ status, out = _call("DescribeDeliveryChannels", {})+ assert status == 200+ channels = out["DeliveryChannels"]+ assert len(channels) == 1+ assert channels[0]["name"] == "default"+ assert channels[0]["s3BucketName"] == "config-bucket"++ status, out = _call("DescribeDeliveryChannelStatus", {})+ assert status == 200+ statuses = out["DeliveryChannelsStatus"]+ assert len(statuses) == 1+ assert statuses[0]["name"] == "default"+++def test_describe_delivery_channels_empty():+ status, out = _call("DescribeDeliveryChannels", {})+ assert status == 200+ assert out == {"DeliveryChannels": []}+++def test_describe_delivery_channels_unknown_name_errors():+ status, out = _call("DescribeDeliveryChannels", {"DeliveryChannelNames": ["x"]})+ assert status == 400+ assert out["__type"] == "NoSuchDeliveryChannelException"+++# ── Compliance / evaluation status ────────────────────────────++def test_describe_compliance_by_config_rule():+ _call("PutConfigRule", {+ "ConfigRule": {+ "ConfigRuleName": "r1",+ "Source": {"Owner": "AWS", "SourceIdentifier": "X"},+ }+ })+ status, out = _call("DescribeComplianceByConfigRule", {})+ assert status == 200+ items = out["ComplianceByConfigRules"]+ assert len(items) == 1+ assert items[0]["ConfigRuleName"] == "r1"+ assert items[0]["Compliance"]["ComplianceType"] == "INSUFFICIENT_DATA"+++def test_describe_compliance_unknown_rule_errors():+ status, out = _call("DescribeComplianceByConfigRule",+ {"ConfigRuleNames": ["ghost"]})+ assert status == 400+ assert out["__type"] == "NoSuchConfigRuleException"+++def test_get_compliance_details_by_config_rule():+ _call("PutConfigRule", {+ "ConfigRule": {+ "ConfigRuleName": "r1",+ "Source": {"Owner": "AWS", "SourceIdentifier": "X"},+ }+ })+ status, out = _call("GetComplianceDetailsByConfigRule", {"ConfigRuleName": "r1"})+ assert status == 200+ assert out == {"EvaluationResults": []}+++def test_get_compliance_details_unknown_rule_errors():+ status, out = _call("GetComplianceDetailsByConfigRule", {"ConfigRuleName": "ghost"})+ assert status == 400+ assert out["__type"] == "NoSuchConfigRuleException"+++def test_describe_config_rule_evaluation_status():+ _call("PutConfigRule", {+ "ConfigRule": {+ "ConfigRuleName": "r1",+ "Source": {"Owner": "AWS", "SourceIdentifier": "X"},+ }+ })+ status, out = _call("DescribeConfigRuleEvaluationStatus", {})+ assert status == 200+ items = out["ConfigRulesEvaluationStatus"]+ assert len(items) == 1+ assert items[0]["ConfigRuleName"] == "r1"+ assert items[0]["ConfigRuleArn"].startswith("arn:aws:config:")+ assert items[0]["FirstEvaluationStarted"] is False+++def test_evaluation_status_unknown_rule_errors():+ status, out = _call("DescribeConfigRuleEvaluationStatus",+ {"ConfigRuleNames": ["ghost"]})+ assert status == 400+ assert out["__type"] == "NoSuchConfigRuleException"+++def test_unknown_action_errors():+ status, out = _call("BogusAction", {})+ assert status == 400+ assert out["__type"] == "InvalidAction"diff --git a/tests/test_inspector2.py b/tests/test_inspector2.pyindex d50416d9..0c020d2a 100644--- a/tests/test_inspector2.py+++ b/tests/test_inspector2.py@@ -800,6 +800,99 @@ class TestIntegration:assert "AWS_EC2_INSTANCE" in resource_types+class TestReadOnlyOps:+ """Newly-routed read-only ops return AWS-correct empty/default shapes.++ These are stub-empty in this emulator (no org enrollment, no members,+ no CIS scans, no code-security integrations) so lists are empty and+ singletons return their default/disabled shape. Wire keys verified+ against botocore inspector2 2020-06-08.+ """++ def test_list_members_empty(self, inspector2):+ resp = inspector2.list_members()+ assert resp["members"] == []++ def test_list_delegated_admin_accounts_empty(self, inspector2):+ resp = inspector2.list_delegated_admin_accounts()+ assert resp["delegatedAdminAccounts"] == []++ def test_describe_organization_configuration(self, inspector2):+ resp = inspector2.describe_organization_configuration()+ assert resp["maxAccountLimitReached"] is False+ assert set(resp["autoEnable"].keys()) >= {"ec2", "ecr", "lambda"}++ def test_get_configuration_shape(self, inspector2):+ resp = inspector2.get_configuration()+ assert "ecrConfiguration" in resp+ assert "ec2Configuration" in resp+ assert resp["ecrConfiguration"]["rescanDurationState"]["rescanDuration"] == "LIFETIME"+ assert resp["ec2Configuration"]["scanModeState"]["scanMode"] == "EC2_HYBRID"++ def test_get_ec2_deep_inspection_configuration(self, inspector2):+ resp = inspector2.get_ec2_deep_inspection_configuration()+ assert resp["status"] == "DISABLED"+ assert resp["packagePaths"] == []+ assert resp["orgPackagePaths"] == []++ def test_list_account_permissions_empty(self, inspector2):+ resp = inspector2.list_account_permissions()+ assert resp["permissions"] == []++ def test_list_cis_scans_empty(self, inspector2):+ resp = inspector2.list_cis_scans()+ assert resp["scans"] == []++ def test_list_cis_scan_configurations_empty(self, inspector2):+ resp = inspector2.list_cis_scan_configurations()+ assert resp["scanConfigurations"] == []++ def test_list_usage_totals_default_account(self, inspector2):+ resp = inspector2.list_usage_totals()+ assert resp["totals"][0]["accountId"] == "000000000000"+ assert resp["totals"][0]["usage"] == []++ def test_batch_get_account_status_default_account(self, inspector2):+ inspector2.enable(resourceTypes=["ECR"])+ resp = inspector2.batch_get_account_status()+ accounts = resp["accounts"]+ assert len(accounts) == 1+ acct = accounts[0]+ assert acct["accountId"] == "000000000000"+ assert acct["resourceState"]["ecr"]["status"] == "ENABLED"+ assert resp["failedAccounts"] == []++ def test_batch_get_free_trial_info_default_account(self, inspector2):+ resp = inspector2.batch_get_free_trial_info(accountIds=["000000000000"])+ assert resp["accounts"][0]["accountId"] == "000000000000"+ assert resp["accounts"][0]["freeTrialInfo"] == []+ assert resp["failedAccounts"] == []++ def test_batch_get_member_ec2_deep_inspection_status_empty(self, inspector2):+ resp = inspector2.batch_get_member_ec2_deep_inspection_status(+ accountIds=["111111111111"]+ )+ assert resp["accountIds"] == []+ assert resp["failedAccountIds"] == []++ def test_batch_get_code_snippet_empty(self, inspector2):+ resp = inspector2.batch_get_code_snippet(+ findingArns=["arn:aws:inspector2:us-east-1:000000000000:finding/x"]+ )+ assert resp["codeSnippetResults"] == []+ assert resp["errors"] == []++ def test_get_encryption_key_not_found(self, inspector2):+ with pytest.raises(ClientError) as exc:+ inspector2.get_encryption_key(resourceType="AWS_EC2_INSTANCE", scanType="NETWORK")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++ def test_get_member_not_found(self, inspector2):+ with pytest.raises(ClientError) as exc:+ inspector2.get_member(accountId="111111111111")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++class TestBatchGetFindingDetails:def test_batch_get_finding_details(self, inspector2):inspector2.enable(resourceTypes=["ECR"])diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 61724171..b9505c5d 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -9068,3 +9068,108 @@ def test_lambda_function_url_response_stream_consumes_prelude(lam):assert b"statusCode" not in bodyfinally:lam.delete_function_url_config(FunctionName=fname)+++def _lambda_raw(method, path, body=None):+ """Raw Lambda REST call — needed for params the installed (pre-July)+ botocore rejects client-side, e.g. Code.S3ObjectStorageMode."""+ headers = {+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260806/us-east-1/lambda/aws4_request",+ "Content-Type": "application/json",+ }+ req = _urlreq.Request(+ _endpoint + path,+ data=json.dumps(body).encode() if body is not None else None,+ headers=headers, method=method,+ )+ try:+ return _urlreq.urlopen(req).read()+ except _urlerr.HTTPError as exc:+ return b"ERR " + str(exc.code).encode() + b" " + exc.read()+++def test_lambda_s3_object_storage_mode_reference(lam):+ """July 2026 self-managed code storage: Code.S3ObjectStorageMode=REFERENCE is+ accepted and GetFunction echoes ResolvedS3Object; internal tracking must not+ leak into GetFunctionConfiguration. Driven over raw HTTP because the pinned+ botocore rejects the new field client-side."""+ s3 = boto3.client(+ "s3", endpoint_url=_endpoint, region_name="us-east-1",+ aws_access_key_id="test", aws_secret_access_key="test",+ config=Config(s3={"addressing_style": "path"}),+ )+ suffix = _uuid_mod.uuid4().hex[:8]+ bucket, key, fn = f"lam-ref-bkt-{suffix}", "fn.zip", f"lam-ref-{suffix}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key=key, Body=_make_zip(_LAMBDA_CODE))+ try:+ _lambda_raw("POST", "/2015-03-31/functions/", {+ "FunctionName": fn, "Runtime": "python3.13", "Handler": "index.handler",+ "Role": _LAMBDA_ROLE,+ "Code": {"S3Bucket": bucket, "S3Key": key, "S3ObjectStorageMode": "REFERENCE"},+ })+ gf = json.loads(_lambda_raw("GET", f"/2015-03-31/functions/{fn}"))+ code = gf["Code"]+ assert code["RepositoryType"] == "S3"+ assert code["ResolvedS3Object"] == {"S3Bucket": bucket, "S3Key": key}+ cfg = gf["Configuration"]+ assert not any("s3_object" in k.lower() or "storage_mode" in k.lower() for k in cfg)+ finally:+ lam.delete_function(FunctionName=fn)+++def test_lambda_esm_dynamodb_max_record_age_to_failure_destination(lam, ddb, sqs):+ """July 2026: a DynamoDB-stream ESM enforces MaximumRecordAgeInSeconds — an+ aged-out failing batch is discarded to the OnFailure destination with the+ AWS DDBStreamBatchInfo record (condition=MaxRecordAgeExceeded), so a poison+ batch cannot block the shard. Also asserts CreateEventSourceMapping now+ persists MaximumRecordAgeInSeconds/DestinationConfig."""+ suffix = _uuid_mod.uuid4().hex[:8]+ fn, table = f"esm-age-fn-{suffix}", f"esm-age-tbl-{suffix}"+ lam.create_function(+ FunctionName=fn, Runtime="python3.13", Role=_LAMBDA_ROLE, Handler="index.handler",+ Code={"ZipFile": _make_zip("def handler(e, c):\n raise Exception('always fail')")},+ )+ ddb.create_table(+ TableName=table,+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],+ KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],+ BillingMode="PAY_PER_REQUEST",+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},+ )+ ddb.get_waiter("table_exists").wait(TableName=table)+ stream_arn = ddb.describe_table(TableName=table)["Table"]["LatestStreamArn"]+ q = sqs.create_queue(QueueName=f"esm-onfail-{suffix}")["QueueUrl"]+ qarn = sqs.get_queue_attributes(QueueUrl=q, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ try:+ m = lam.create_event_source_mapping(+ FunctionName=fn, EventSourceArn=stream_arn, BatchSize=1,+ StartingPosition="TRIM_HORIZON", MaximumRecordAgeInSeconds=2,+ DestinationConfig={"OnFailure": {"Destination": qarn}},+ )+ # Create must persist these (previously only Update did).+ got = lam.get_event_source_mapping(UUID=m["UUID"])+ assert got["MaximumRecordAgeInSeconds"] == 2+ assert got["DestinationConfig"]["OnFailure"]["Destination"] == qarn++ ddb.put_item(TableName=table, Item={"id": {"S": "1"}})+ rec = None+ for _ in range(10):+ time.sleep(2)+ msgs = sqs.receive_message(QueueUrl=q, MaxNumberOfMessages=1, WaitTimeSeconds=1).get("Messages", [])+ if msgs:+ rec = json.loads(msgs[0]["Body"])+ break+ assert rec is not None, "no OnFailure record delivered within the age window"+ assert rec["requestContext"]["condition"] == "MaxRecordAgeExceeded"+ assert rec["version"] == "1.0"+ info = rec["DDBStreamBatchInfo"]+ assert info["streamArn"] == stream_arn+ assert info["batchSize"] == 1+ assert info["startSequenceNumber"] and info["endSequenceNumber"]+ finally:+ for esm in lam.list_event_source_mappings(FunctionName=fn).get("EventSourceMappings", []):+ lam.delete_event_source_mapping(UUID=esm["UUID"])+ lam.delete_function(FunctionName=fn)+ ddb.delete_table(TableName=table)diff --git a/tests/test_mediaconnect.py b/tests/test_mediaconnect.pyindex 92126e23..ca564157 100644--- a/tests/test_mediaconnect.py+++ b/tests/test_mediaconnect.py@@ -171,6 +171,81 @@ def test_mediaconnect_list_tags_requires_local_flow_arn(mc, arn, code):assert e.value.response["Error"]["Code"] == code+# ---------------------------------------------------------------------------+# Read-only collections (empty — this stub owns no such resources)+# ---------------------------------------------------------------------------++def test_mediaconnect_list_bridges_empty(mc):+ assert mc.list_bridges()["Bridges"] == []+++def test_mediaconnect_list_entitlements_empty(mc):+ assert mc.list_entitlements()["Entitlements"] == []+++def test_mediaconnect_list_gateways_empty(mc):+ assert mc.list_gateways()["Gateways"] == []+++def test_mediaconnect_list_gateway_instances_empty(mc):+ assert mc.list_gateway_instances()["Instances"] == []+++def test_mediaconnect_list_offerings_empty(mc):+ assert mc.list_offerings()["Offerings"] == []+++def test_mediaconnect_list_reservations_empty(mc):+ assert mc.list_reservations()["Reservations"] == []+++# ---------------------------------------------------------------------------+# Describe-by-ARN for never-owned resources -> NotFoundException+# ---------------------------------------------------------------------------++ ("op", "kwarg", "resource"),+ [+ ("describe_bridge", "BridgeArn", "bridge"),+ ("describe_gateway", "GatewayArn", "gateway"),+ ("describe_gateway_instance", "GatewayInstanceArn", "gateway-instance"),+ ("describe_reservation", "ReservationArn", "reservation"),+ ("describe_offering", "OfferingArn", "offering"),+ ],+)+def test_mediaconnect_describe_unknown_resource_404(mc, op, kwarg, resource):+ bogus = f"arn:aws:mediaconnect:{REGION}:000000000000:{resource}:{uuid.uuid4()}"+ with pytest.raises(ClientError) as e:+ getattr(mc, op)(**{kwarg: bogus})+ assert e.value.response["Error"]["Code"] == "NotFoundException"+++# ---------------------------------------------------------------------------+# DescribeFlowSourceMetadata / DescribeFlowSourceThumbnail+# ---------------------------------------------------------------------------++def test_mediaconnect_describe_flow_source_metadata(mc):+ name = f"flow-meta-{_uid()}"+ flow = mc.create_flow(Name=name, Source=_basic_source())["Flow"]+ resp = mc.describe_flow_source_metadata(FlowArn=flow["FlowArn"])+ assert resp["FlowArn"] == flow["FlowArn"]+ assert resp["Messages"] == []+++def test_mediaconnect_describe_flow_source_metadata_unknown_404(mc):+ bogus = f"arn:aws:mediaconnect:{REGION}:000000000000:flow:{uuid.uuid4()}:nope"+ with pytest.raises(ClientError) as e:+ mc.describe_flow_source_metadata(FlowArn=bogus)+ assert e.value.response["Error"]["Code"] == "NotFoundException"+++def test_mediaconnect_describe_flow_source_thumbnail(mc):+ name = f"flow-thumb-{_uid()}"+ flow = mc.create_flow(Name=name, Source=_basic_source())["Flow"]+ resp = mc.describe_flow_source_thumbnail(FlowArn=flow["FlowArn"])+ assert "ThumbnailDetails" in resp++def test_mediaconnect_flows_are_region_isolated(mc):"""A flow created in us-east-1 must not be visible from us-west-2."""mc_west = boto3.client(diff --git a/tests/test_pipes.py b/tests/test_pipes.pyindex 43da1bc6..9a8bfd04 100644--- a/tests/test_pipes.py+++ b/tests/test_pipes.py@@ -1,6 +1,14 @@+import asyncio+import json+from urllib.parse import quote+import pytest-from ministack.core.responses import _request_region+from ministack.core.responses import (+ _request_region,+ set_request_account_id,+ set_request_region,+)from ministack.services import dynamodb as _ddbfrom ministack.services import pipes as _pipes@@ -412,3 +420,211 @@ def test_pipes_position_is_absolute_across_record_expiry(monkeypatch):_pipes.reset()_ddb._stream_records.clear()_ddb._stream_trimmed.clear()+++# ---------------------------------------------------------------------------+# REST/JSON handler (handle_request) — SDK surface+# ---------------------------------------------------------------------------++ROLE_ARN = "arn:aws:iam::000000000000:role/test-pipe-role"+++def handler_env(monkeypatch):+ _pipes.reset()+ monkeypatch.setattr(_pipes, "_ensure_poller", lambda: None)+ # register_pipe computes an initial stream position from DynamoDB; keep it+ # deterministic and decoupled from the DDB store for handler tests.+ monkeypatch.setattr(_pipes, "_initial_position", lambda pipe: 0)+ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ yield+ _pipes.reset()+++def _req(method, path, body=None, query=None):+ payload = json.dumps(body or {}).encode() if body is not None else b""+ return asyncio.run(_pipes.handle_request(method, path, {}, payload, query or {}))+++def _body(resp):+ return json.loads(resp[2].decode())+++def _create(name, desired="RUNNING", **extra):+ body = {+ "Source": _stream_arn("us-east-1"),+ "Target": _topic_arn("us-east-1"),+ "RoleArn": ROLE_ARN,+ "DesiredState": desired,+ }+ body.update(extra)+ return _req("POST", f"/v1/pipes/{name}", body)+++def test_create_pipe_returns_lifecycle_shape(handler_env):+ status, _hdrs, _b = _create("p1")+ body = _body((status, _hdrs, _b))+ assert status == 200+ assert body["Arn"] == "arn:aws:pipes:us-east-1:000000000000:pipe/p1"+ assert body["Name"] == "p1"+ assert body["DesiredState"] == "RUNNING"+ assert body["CurrentState"] == "RUNNING"+ assert isinstance(body["CreationTime"], int)+ assert isinstance(body["LastModifiedTime"], int)+ # CreatePipeResponse must NOT carry the full describe shape.+ assert "Source" not in body and "Tags" not in body+++def test_create_pipe_reuses_register_pipe(handler_env):+ _create("p1", Tags={"env": "test"}, Description="hi")+ rec = _pipes._pipes.get("p1")+ assert rec is not None+ assert rec["Tags"] == {"env": "test"}+ assert rec["Description"] == "hi"+ assert rec["RoleArn"] == ROLE_ARN+++def test_create_pipe_conflict(handler_env):+ _create("p1")+ status, _hdrs, b = _create("p1")+ assert status == 409+ assert _body((status, _hdrs, b))["__type"] == "ConflictException"+++def test_list_pipes_summary_shape(handler_env):+ _create("alpha")+ _create("beta", desired="STOPPED")+ status, _hdrs, b = _req("GET", "/v1/pipes")+ assert status == 200+ body = _body((status, _hdrs, b))+ names = [p["Name"] for p in body["Pipes"]]+ assert names == ["alpha", "beta"]+ summary = body["Pipes"][0]+ assert set(summary) >= {+ "Name", "Arn", "DesiredState", "CurrentState", "StateReason",+ "CreationTime", "LastModifiedTime", "Source", "Target",+ }+ assert isinstance(summary["CreationTime"], int)+++def test_list_pipes_filters(handler_env):+ _create("alpha")+ _create("beta", desired="STOPPED")+ body = _body(_req("GET", "/v1/pipes", query={"NamePrefix": ["al"]}))+ assert [p["Name"] for p in body["Pipes"]] == ["alpha"]+ body = _body(_req("GET", "/v1/pipes", query={"DesiredState": ["STOPPED"]}))+ assert [p["Name"] for p in body["Pipes"]] == ["beta"]+ body = _body(_req("GET", "/v1/pipes", query={"CurrentState": ["RUNNING"]}))+ assert [p["Name"] for p in body["Pipes"]] == ["alpha"]+++def test_list_pipes_limit_paginates(handler_env):+ for n in ("a", "b", "c"):+ _create(n)+ body = _body(_req("GET", "/v1/pipes", query={"Limit": ["2"]}))+ assert [p["Name"] for p in body["Pipes"]] == ["a", "b"]+ assert body["NextToken"] == "c"+++def test_describe_pipe_full_shape(handler_env):+ _create("p1", Description="desc", Tags={"k": "v"})+ status, _hdrs, b = _req("GET", "/v1/pipes/p1")+ assert status == 200+ body = _body((status, _hdrs, b))+ assert body["Name"] == "p1"+ assert body["Description"] == "desc"+ assert body["RoleArn"] == ROLE_ARN+ assert body["Source"] == _stream_arn("us-east-1")+ assert body["Target"] == _topic_arn("us-east-1")+ assert body["Tags"] == {"k": "v"}+ assert isinstance(body["CreationTime"], int)+++def test_describe_unknown_pipe_not_found(handler_env):+ status, hdrs, b = _req("GET", "/v1/pipes/missing")+ assert status == 404+ body = _body((status, hdrs, b))+ assert body["__type"] == "NotFoundException"+ assert body["message"] == "Pipe missing does not exist."+ assert hdrs["x-amzn-errortype"] == "NotFoundException"+++def test_start_stop_pipe(handler_env):+ _create("p1", desired="STOPPED")+ status, _hdrs, b = _req("POST", "/v1/pipes/p1/start")+ assert status == 200+ body = _body((status, _hdrs, b))+ assert body["DesiredState"] == "RUNNING"+ assert body["CurrentState"] == "RUNNING"+ assert _pipes._pipes.get("p1")["CurrentState"] == "RUNNING"++ body = _body(_req("POST", "/v1/pipes/p1/stop"))+ assert body["DesiredState"] == "STOPPED"+ assert _pipes._pipes.get("p1")["CurrentState"] == "STOPPED"+++def test_start_unknown_pipe_not_found(handler_env):+ status, _hdrs, b = _req("POST", "/v1/pipes/nope/start")+ assert status == 404+ assert _body((status, _hdrs, b))["__type"] == "NotFoundException"+++def test_update_pipe(handler_env):+ _create("p1")+ status, _hdrs, b = _req(+ "PUT", "/v1/pipes/p1", body={"RoleArn": ROLE_ARN, "Description": "new", "DesiredState": "STOPPED"}+ )+ assert status == 200+ assert _body((status, _hdrs, b))["DesiredState"] == "STOPPED"+ rec = _pipes._pipes.get("p1")+ assert rec["Description"] == "new"+ assert rec["CurrentState"] == "STOPPED"+++def test_delete_pipe(handler_env):+ _create("p1")+ status, _hdrs, b = _req("DELETE", "/v1/pipes/p1")+ assert status == 200+ body = _body((status, _hdrs, b))+ assert body["DesiredState"] == "DELETED"+ assert body["CurrentState"] == "DELETING"+ assert _pipes._pipes.get("p1") is None+++def test_delete_unknown_pipe_not_found(handler_env):+ status, _hdrs, b = _req("DELETE", "/v1/pipes/nope")+ assert status == 404+ assert _body((status, _hdrs, b))["__type"] == "NotFoundException"+++def test_lifecycle_create_list_describe_start_stop_delete(handler_env):+ _create("flow", desired="STOPPED")+ assert [p["Name"] for p in _body(_req("GET", "/v1/pipes"))["Pipes"]] == ["flow"]+ assert _body(_req("GET", "/v1/pipes/flow"))["Name"] == "flow"+ assert _body(_req("POST", "/v1/pipes/flow/start"))["CurrentState"] == "RUNNING"+ assert _body(_req("POST", "/v1/pipes/flow/stop"))["CurrentState"] == "STOPPED"+ assert _body(_req("DELETE", "/v1/pipes/flow"))["CurrentState"] == "DELETING"+ assert _body(_req("GET", "/v1/pipes"))["Pipes"] == []+++def test_tag_untag_list_tags(handler_env):+ _create("p1", Tags={"a": "1"})+ arn = "arn:aws:pipes:us-east-1:000000000000:pipe/p1"+ enc = quote(arn, safe="")+ body = _body(_req("GET", f"/tags/{enc}"))+ assert body["tags"] == {"a": "1"}++ status, _hdrs, _b = _req("POST", f"/tags/{enc}", body={"tags": {"b": "2"}})+ assert status == 200+ assert _pipes._pipes.get("p1")["Tags"] == {"a": "1", "b": "2"}++ _req("DELETE", f"/tags/{enc}", query={"tagKeys": ["a"]})+ assert _pipes._pipes.get("p1")["Tags"] == {"b": "2"}+++def test_list_tags_unknown_arn_not_found(handler_env):+ enc = quote("arn:aws:pipes:us-east-1:000000000000:pipe/ghost", safe="")+ status, _hdrs, b = _req("GET", f"/tags/{enc}")+ assert status == 404+ assert _body((status, _hdrs, b))["__type"] == "NotFoundException"diff --git a/tests/test_secretsmanager.py b/tests/test_secretsmanager.pyindex 0ca26409..9cfd45db 100644--- a/tests/test_secretsmanager.py+++ b/tests/test_secretsmanager.py@@ -899,3 +899,39 @@ def test_secretsmanager_arn_shaped_secret_name_does_not_bypass_scope_guard():assert status == 400assert parsed["__type"] == "ResourceNotFoundException"sm.reset()+++def test_secret_label_updated_event_to_eventbridge(sm, eb, sqs):+ """Native 'Secret Label Updated' notification: moving AWSCURRENT (create /+ put / update-with-value) publishes an event to the default EventBridge bus;+ a metadata-only update does not. detail = {name, labelUpdated, versionId}."""+ suffix = _uuid_mod.uuid4().hex[:8]+ name = f"evt-secret-{suffix}"+ q = sqs.create_queue(QueueName=f"sm-evt-{suffix}")["QueueUrl"]+ qarn = sqs.get_queue_attributes(QueueUrl=q, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ eb.put_rule(+ Name=f"sm-rule-{suffix}",+ EventPattern=json.dumps({"source": ["aws.secretsmanager"],+ "detail-type": ["Secret Label Updated"]}),+ )+ eb.put_targets(Rule=f"sm-rule-{suffix}", Targets=[{"Id": "1", "Arn": qarn}])++ sm.create_secret(Name=name, SecretString="v1")+ sm.put_secret_value(SecretId=name, SecretString="v2") # AWSCURRENT moves+ sm.update_secret(SecretId=name, Description="metadata only") # must NOT emit++ time.sleep(1)+ msgs = sqs.receive_message(QueueUrl=q, MaxNumberOfMessages=10, WaitTimeSeconds=2).get("Messages", [])+ events = [json.loads(m["Body"]) for m in msgs]+ label_events = [e for e in events if e.get("detail-type") == "Secret Label Updated"]+ assert label_events, "no Secret Label Updated event delivered"+ for e in label_events:+ assert e["source"] == "aws.secretsmanager"+ d = e["detail"]+ assert d["name"] == name+ assert d["labelUpdated"] == "AWSCURRENT"+ assert d["versionId"]+ # Metadata-only update must not have emitted an extra event beyond the+ # AWSCURRENT moves (create + put); AWSPENDING/AWSPREVIOUS never emit.+ assert all(e["detail"]["labelUpdated"] == "AWSCURRENT" for e in label_events)diff --git a/tests/test_sns.py b/tests/test_sns.pyindex f96ce630..25f277e7 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -587,6 +587,45 @@ def test_sns_filter_policy_blocks_non_matching(sns, sqs):body = json.loads(msgs2["Messages"][0]["Body"])assert body["Message"] == "blue message"+def test_sns_filter_policy_or_operator(sns, sqs):+ """A top-level $or matches when any of its member policies matches; a+ message satisfying neither is filtered out (AWS $or operator)."""+ topic_arn = sns.create_topic(Name="qa-sns-or")["TopicArn"]+ q_url = sqs.create_queue(QueueName="qa-sns-or-q")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ sub_arn = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)["SubscriptionArn"]+ sns.set_subscription_attributes(+ SubscriptionArn=sub_arn,+ AttributeName="FilterPolicy",+ AttributeValue=json.dumps({+ "$or": [+ {"operation": ["event-broadcast"], "environment": ["ENV1"]},+ {"operation": ["session-operation"], "environment": ["ENV1"],+ "session_id": ["abc-123"]},+ ]+ }),+ )++ def _attrs(**kv):+ return {k: {"DataType": "String", "StringValue": v} for k, v in kv.items()}++ # Matches the first $or member.+ sns.publish(TopicArn=topic_arn, Message="first",+ MessageAttributes=_attrs(operation="event-broadcast", environment="ENV1"))+ # Matches the second $or member.+ sns.publish(TopicArn=topic_arn, Message="second",+ MessageAttributes=_attrs(operation="session-operation", environment="ENV1",+ session_id="abc-123"))+ # Matches neither (wrong environment).+ sns.publish(TopicArn=topic_arn, Message="third",+ MessageAttributes=_attrs(operation="event-broadcast", environment="ENV2"))++ received = []+ for _ in range(3):+ resp = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=10, WaitTimeSeconds=1)+ received.extend(json.loads(m["Body"])["Message"] for m in resp.get("Messages", []))+ assert sorted(received) == ["first", "second"]+def test_sns_raw_message_delivery(sns, sqs):"""RawMessageDelivery=true delivers raw message body, not SNS envelope."""topic_arn = sns.create_topic(Name="qa-sns-raw")["TopicArn"]diff --git a/tests/test_sqs.py b/tests/test_sqs.pyindex 2b5be09c..c2733f87 100644--- a/tests/test_sqs.py+++ b/tests/test_sqs.py@@ -1214,10 +1214,10 @@ def test_sqs_messages_endpoint_basic(sqs):assert m["IsVisible"] is True# Subsequent ReceiveMessage still returns both — peek did not mutate.- received = []- for _ in range(2):- resp = sqs.receive_message(QueueUrl=qurl, MaxNumberOfMessages=1, VisibilityTimeout=0)- received.extend(resp.get("Messages", []))+ # (Fetch both in one call: an explicit VisibilityTimeout=0 is now honored,+ # so two single receives would re-return the same immediately-visible message.)+ resp = sqs.receive_message(QueueUrl=qurl, MaxNumberOfMessages=2, WaitTimeSeconds=0)+ received = resp.get("Messages", [])assert sorted(m["Body"] for m in received) == ["hello-peek-1", "hello-peek-2"]sqs.delete_queue(QueueUrl=qurl)