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
initial commit
Nahuel9900537268556b8
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 00000000..3b6980ad--- /dev/null+++ b/.dockerignore@@ -0,0 +1,19 @@+**/__pycache__+**/*.pyc+**/*.pyo+.git+.gitignore+.github+.vscode+tests/+data/+*.md+LICENSE+CONTRIBUTING.md+CHANGELOG.md+SECURITY.md+.env+*.log+docker-compose.yml+Makefile+ministack*.pngdiff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 00000000..850e9818--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,74 @@+name: Bug Report+description: Something isn't working as expected+labels: ["bug"]+body:+ - type: markdown+ attributes:+ value: |+ Thanks for taking the time to report a bug. Please fill out the details below.++ - type: dropdown+ id: service+ attributes:+ label: Affected Service+ options:+ - S3+ - SQS+ - SNS+ - DynamoDB+ - Lambda+ - IAM / STS+ - SecretsManager+ - CloudWatch Logs+ - SSM+ - EventBridge+ - Kinesis+ - CloudWatch Metrics+ - SES+ - Step Functions+ - ECS+ - RDS+ - ElastiCache+ - Glue+ - Athena+ - Router / General+ validations:+ required: true++ - type: textarea+ id: description+ attributes:+ label: What happened?+ description: Describe the bug clearly.+ validations:+ required: true++ - type: textarea+ id: reproduction+ attributes:+ label: Reproduction steps+ description: Minimal code or CLI commands to reproduce.+ render: python+ validations:+ required: true++ - type: textarea+ id: expected+ attributes:+ label: Expected behavior+ validations:+ required: true++ - type: input+ id: version+ attributes:+ label: MiniStack version+ placeholder: "e.g. v0.1.0 or latest"+ validations:+ required: true++ - type: input+ id: sdk+ attributes:+ label: SDK / tool used+ placeholder: "e.g. boto3 1.34, AWS CLI 2.15, Terraform 1.7"diff --git a/.github/ISSUE_TEMPLATE/new_service.yml b/.github/ISSUE_TEMPLATE/new_service.ymlnew file mode 100644index 00000000..20972569--- /dev/null+++ b/.github/ISSUE_TEMPLATE/new_service.yml@@ -0,0 +1,40 @@+name: New Service Request+description: Request emulation for an AWS service not yet supported+labels: ["new-service"]+body:+ - type: input+ id: service+ attributes:+ label: AWS Service name+ placeholder: "e.g. API Gateway, Cognito, Route53"+ validations:+ required: true++ - type: textarea+ id: operations+ attributes:+ label: Operations needed+ description: Which specific API operations do you need? Be specific — this helps prioritize.+ placeholder: |+ - CreateRestApi+ - CreateResource+ - PutMethod+ - CreateDeployment+ validations:+ required: true++ - type: textarea+ id: usecase+ attributes:+ label: Use case+ description: What are you trying to test locally?+ validations:+ required: true++ - type: checkboxes+ id: contribute+ attributes:+ label: Would you like to contribute this?+ options:+ - label: Yes, I'd like to implement this service and open a PR+ - label: I can help review/test an implementationdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 00000000..86d2c8a1--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,43 @@+name: CI++on:+ push:+ branches: [main, master]+ pull_request:+ branches: [main, master]++jobs:+ test:+ runs-on: ubuntu-latest++ services:+ redis:+ image: redis:7-alpine+ ports:+ - 6379:6379+ options: >-+ --health-cmd "redis-cli ping"+ --health-interval 5s+ --health-timeout 3s+ --health-retries 5++ steps:+ - uses: actions/checkout@v4++ - name: Set up Python+ uses: actions/setup-python@v5+ with:+ python-version: "3.12"+ cache: "pip"++ - name: Install dependencies+ run: pip install -r requirements.txt boto3 pytest duckdb docker cbor2++ - name: Start MiniStack+ run: |+ REDIS_HOST=localhost python -m uvicorn app:app --host 0.0.0.0 --port 4566 &+ sleep 3+ curl -sf http://localhost:4566/_localstack/health++ - name: Run tests+ run: pytest tests/ -v --tb=shortdiff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.ymlnew file mode 100644index 00000000..492f08b6--- /dev/null+++ b/.github/workflows/docker-publish.yml@@ -0,0 +1,49 @@+name: Docker Publish++on:+ push:+ tags:+ - "v*.*.*"++env:+ DOCKERHUB_IMAGE: nahuelnucera/ministack++jobs:+ publish:+ runs-on: ubuntu-latest++ steps:+ - uses: actions/checkout@v4++ - name: Set up QEMU (multi-arch)+ uses: docker/setup-qemu-action@v3++ - name: Set up Docker Buildx+ uses: docker/setup-buildx-action@v3++ - name: Log in to Docker Hub+ uses: docker/login-action@v3+ with:+ username: ${{ secrets.DOCKERHUB_USERNAME }}+ password: ${{ secrets.DOCKERHUB_TOKEN }}++ - name: Extract metadata+ id: meta+ uses: docker/metadata-action@v5+ with:+ images: ${{ env.DOCKERHUB_IMAGE }}+ tags: |+ type=semver,pattern={{version}}+ type=semver,pattern={{major}}.{{minor}}+ type=raw,value=latest++ - name: Build and push+ uses: docker/build-push-action@v5+ with:+ context: .+ platforms: linux/amd64,linux/arm64+ push: true+ tags: ${{ steps.meta.outputs.tags }}+ labels: ${{ steps.meta.outputs.labels }}+ cache-from: type=gha+ cache-to: type=gha,mode=maxdiff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..ce335615--- /dev/null+++ b/.gitignore@@ -0,0 +1,52 @@+# Python+__pycache__/+*.py[cod]+*.pyo+*.pyd+.Python+*.egg+*.egg-info/+dist/+build/+eggs/+parts/+var/+sdist/+develop-eggs/+.installed.cfg+lib/+lib64/+.eggs/+*.so++# Virtual environments+.venv/+venv/+env/+ENV/++# Testing+.pytest_cache/+.coverage+coverage.xml+htmlcov/+.tox/++# IDE+.vscode/settings.json+.idea/+*.swp+*.swo+.DS_Store++# Docker+data/++# Secrets / local config+.env+.env.local+*.pem+*.key++# Logs+*.logdiff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 00000000..f9fc4f0b--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,67 @@+# Changelog++All notable changes to MiniStack will be documented here.++Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).+Versioning follows [Semantic Versioning](https://semver.org/).++---++## [0.1.0] — 2024-03-24++Initial public release. Built as a free, open-source alternative to LocalStack.++### Services Added++**Core (9 services)**+- S3 — CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects (batch), optional disk persistence+- SQS — Full queue lifecycle, send/receive/delete, visibility timeout, batch operations, both Query API and JSON protocol+- SNS — Topics, subscriptions, publish+- DynamoDB — Tables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem+- Lambda — CRUD + actual Python function execution via subprocess+- IAM — Users, roles, policies, access keys+- STS — GetCallerIdentity, AssumeRole, GetSessionToken+- SecretsManager — Full secret lifecycle+- CloudWatch Logs — Log groups, streams, PutLogEvents, GetLogEvents, FilterLogEvents++**Extended (6 services)**+- SSM Parameter Store — PutParameter, GetParameter, GetParametersByPath, DeleteParameter+- EventBridge — Event buses, rules, targets, PutEvents+- Kinesis — Streams, shards, PutRecord, PutRecords, GetShardIterator, GetRecords+- CloudWatch Metrics — PutMetricData, GetMetricStatistics, ListMetrics, alarms+- SES — SendEmail, SendRawEmail, identity verification (emails stored, not sent)+- Step Functions — State machines, executions, history++**Infrastructure (5 services)**+- ECS — Clusters, task definitions, services, RunTask with real Docker container execution+- RDS — CreateDBInstance spins up real Postgres/MySQL Docker containers with actual endpoints+- ElastiCache — CreateCacheCluster spins up real Redis/Memcached Docker containers+- Glue — Full Data Catalog (databases, tables, partitions), crawlers, jobs with Python execution+- Athena — Real SQL execution via DuckDB, s3:// path rewriting to local files++### Infrastructure+- Single ASGI app on port 4566 (LocalStack-compatible)+- Docker Compose with Redis sidecar+- Multi-arch Docker image (amd64 + arm64)+- GitHub Actions CI (test on every push/PR)+- GitHub Actions Docker publish (on tag)+- 54 integration tests, all passing+- MIT license++---++## Roadmap++### [0.2.0] — Planned+- API Gateway (REST + HTTP APIs)+- SNS → SQS fan-out delivery+- DynamoDB transactions (TransactWriteItems, TransactGetItems)+- S3 multipart upload+- SQS FIFO queues++### [0.3.0] — Planned+- Cognito (user pools, sign-up/sign-in)+- Step Functions ASL interpreter (actually run state machines)+- Route53 (hosted zones, record sets)+- ACM (certificate management)+- Firehosediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 00000000..92fe0f7a--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,159 @@+# Contributing to MiniStack++Thanks for wanting to contribute. The codebase is intentionally simple — each AWS service is a single self-contained Python file. Adding a new service or fixing a bug should take minutes, not hours.++## Adding a New Service++Every service follows the same 4-step pattern:++### 1. Create `services/myservice.py`++```python+"""+MyService Emulator.+JSON-based API via X-Amz-Target (or Query API).+Supports: OperationOne, OperationTwo, ...+"""++import json+import logging+from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("myservice")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_state: dict = {} # in-memory storage+++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 = {+ "OperationOne": _operation_one,+ "OperationTwo": _operation_two,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown action: {action}", 400)+ return handler(data)+++def _operation_one(data):+ # implement+ return json_response({"result": "ok"})+++def _operation_two(data):+ # implement+ return json_response({})+```++**Protocol guide:**+- JSON services (DynamoDB, SecretsManager, Glue, Athena, etc.) — use `json_response` / `error_response_json`, route via `X-Amz-Target`+- XML services (S3, SQS, SNS, IAM, RDS, ElastiCache) — build XML responses, route via `Action` query param+- REST services (Lambda, ECS) — route via URL path++### 2. Register in `app.py`++```python+from services import myservice++SERVICE_HANDLERS = {+ # ... existing ...+ "myservice": myservice.handle_request,+}+```++### 3. Add detection to `core/router.py`++```python+SERVICE_PATTERNS = {+ # ... existing ...+ "myservice": {+ "target_prefixes": ["AWSMyService"], # for X-Amz-Target routing+ "host_patterns": [r"myservice\."], # for host-based routing+ },+}+```++And add any `Action`-based operations to `action_service_map` in `detect_service()`.++### 4. Add tests to `tests/test_services.py`++```python+@test("MyService: basic operation")+def test_myservice_basic():+ svc = boto3.client("myservice", **kwargs)+ resp = svc.operation_one(Param="value")+ assert resp["result"] == "ok"+```++Add your test function to the `tests` list in `main()`.++---++## Running Tests Locally++```bash+# Start the stack+docker compose up -d++# Install deps+pip install boto3 pytest pytest-cov duckdb++# Run all tests+pytest tests/ -v++# Run a specific test+pytest tests/ -v -k "test_myservice"+```++---++## Code Conventions++- **One file per service** — keep everything for a service in `services/myservice.py`+- **In-memory state** — use module-level dicts (`_things: dict = {}`)+- **No external AWS deps** — no `boto3`, `botocore`, or `aws-sdk` in service code+- **Minimal dependencies** — `duckdb` and `docker` are optional; guard with try/except+- **Error responses** — match real AWS error codes and HTTP status codes as closely as possible+- **Logging** — use `logger = logging.getLogger("servicename")` and log at DEBUG for request details, INFO for significant events, WARNING for degraded behavior++---++## Pull Request Checklist++- [ ] New service file in `services/`+- [ ] Registered in `app.py` SERVICE_HANDLERS+- [ ] Detection patterns added to `core/router.py`+- [ ] Tests added and passing (`pytest tests/ -v`)+- [ ] Service added to the table in `README.md`+- [ ] Entry added to `CHANGELOG.md`++---++## What We're Looking For++High-value contributions right now:++- **API Gateway** — very commonly needed for local dev+- **Cognito** — user pools, sign-up/sign-in flows+- **SNS → SQS fan-out** — publish to a topic and have it deliver to subscribed queues+- **DynamoDB transactions** — `TransactWriteItems`, `TransactGetItems`+- **Step Functions execution** — actually interpret the state machine ASL definition+- **Route53** — basic hosted zones and record sets++---++## Questions?++Open a GitHub Discussion or file an issue with the `question` label.diff --git a/Dockerfile b/Dockerfilenew file mode 100644index 00000000..3f21c8a3--- /dev/null+++ b/Dockerfile@@ -0,0 +1,48 @@+FROM python:3.12-alpine++LABEL maintainer="MiniStack" \+ description="Local AWS Service Emulator — drop-in LocalStack replacement"++# Upgrade all base packages to pick up latest security patches,+# then install nothing extra — curl/unzip removed to eliminate CVEs.+# Upgrade base packages and remove busybox wget (CVE-2025-60876 - HTTP header injection)+# wget is not used in this image; removing it eliminates the attack surface entirely.+RUN apk upgrade --no-cache && rm -f /usr/bin/wget /bin/wget++WORKDIR /opt/ministack++# Upgrade pip to latest to clear pip CVEs, then install app deps.+# httptools/duckdb require C compilation on musl — excluded intentionally.+RUN pip install --no-cache-dir --upgrade pip && \+ pip install --no-cache-dir \+ uvicorn==0.30.6 \+ "cbor2>=5.4.0" \+ "docker>=7.0.0"++COPY core/ core/+COPY services/ services/+COPY app.py .++RUN mkdir -p /tmp/localstack-data/s3++# Run as non-root+RUN addgroup -S ministack && adduser -S ministack -G ministack+USER ministack++ENV GATEWAY_PORT=4566 \+ LOG_LEVEL=INFO \+ S3_PERSIST=0 \+ S3_DATA_DIR=/tmp/localstack-data/s3 \+ REDIS_HOST=redis \+ REDIS_PORT=6379 \+ RDS_BASE_PORT=15432 \+ ELASTICACHE_BASE_PORT=16379 \+ PYTHONUNBUFFERED=1++EXPOSE 4566++# Pure Python healthcheck — no curl dependency+HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \+ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:4566/_localstack/health')" || exit 1++ENTRYPOINT ["python", "-m", "uvicorn", "app:app", "--host", "0.0.0.0", "--port", "4566"]diff --git a/LICENSE b/LICENSEnew file mode 100644index 00000000..4abfb512--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2024 MiniStack Contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/Makefile b/Makefilenew file mode 100644index 00000000..b6d0578a--- /dev/null+++ b/Makefile@@ -0,0 +1,77 @@+.PHONY: build run stop test logs health clean++IMAGE_NAME := ministack+CONTAINER_NAME := ministack+PORT := 4566++build:+ docker build -t $(IMAGE_NAME) .++run: build+ docker run -d --name $(CONTAINER_NAME) -p $(PORT):4566 \+ -e LOG_LEVEL=INFO \+ $(IMAGE_NAME)+ @echo "MiniStack running on http://localhost:$(PORT)"+ @echo "Health: http://localhost:$(PORT)/_localstack/health"++run-compose:+ docker compose up -d --build+ @echo "MiniStack running on http://localhost:$(PORT)"++stop:+ docker stop $(CONTAINER_NAME) 2>/dev/null || true+ docker rm $(CONTAINER_NAME) 2>/dev/null || true++stop-compose:+ docker compose down++logs:+ docker logs -f $(CONTAINER_NAME)++health:+ @curl -s http://localhost:$(PORT)/_localstack/health | python3 -m json.tool++test: run+ @sleep 2+ @echo "=== S3 ==="+ aws --endpoint-url=http://localhost:$(PORT) s3 mb s3://test-bucket+ echo "hello" | aws --endpoint-url=http://localhost:$(PORT) s3 cp - s3://test-bucket/hello.txt+ aws --endpoint-url=http://localhost:$(PORT) s3 ls s3://test-bucket+ aws --endpoint-url=http://localhost:$(PORT) s3 cp s3://test-bucket/hello.txt -+ @echo ""+ @echo "=== SQS ==="+ aws --endpoint-url=http://localhost:$(PORT) sqs create-queue --queue-name test-queue+ aws --endpoint-url=http://localhost:$(PORT) sqs send-message --queue-url http://localhost:$(PORT)/000000000000/test-queue --message-body "hello sqs"+ aws --endpoint-url=http://localhost:$(PORT) sqs receive-message --queue-url http://localhost:$(PORT)/000000000000/test-queue+ @echo ""+ @echo "=== DynamoDB ==="+ aws --endpoint-url=http://localhost:$(PORT) dynamodb create-table \+ --table-name TestTable \+ --attribute-definitions AttributeName=pk,AttributeType=S \+ --key-schema AttributeName=pk,KeyType=HASH \+ --billing-mode PAY_PER_REQUEST+ aws --endpoint-url=http://localhost:$(PORT) dynamodb put-item \+ --table-name TestTable \+ --item '{"pk":{"S":"key1"},"data":{"S":"value1"}}'+ aws --endpoint-url=http://localhost:$(PORT) dynamodb get-item \+ --table-name TestTable \+ --key '{"pk":{"S":"key1"}}'+ @echo ""+ @echo "=== SNS ==="+ aws --endpoint-url=http://localhost:$(PORT) sns create-topic --name test-topic+ aws --endpoint-url=http://localhost:$(PORT) sns list-topics+ @echo ""+ @echo "=== STS ==="+ aws --endpoint-url=http://localhost:$(PORT) sts get-caller-identity+ @echo ""+ @echo "=== SecretsManager ==="+ aws --endpoint-url=http://localhost:$(PORT) secretsmanager create-secret --name test-secret --secret-string '{"user":"admin","pass":"s3cr3t"}'+ aws --endpoint-url=http://localhost:$(PORT) secretsmanager get-secret-value --secret-id test-secret+ @echo ""+ @echo "=== Lambda ==="+ aws --endpoint-url=http://localhost:$(PORT) lambda list-functions+ @echo ""+ @echo "=== All tests passed ==="++clean: stop+ docker rmi $(IMAGE_NAME) 2>/dev/null || truediff --git a/README.md b/README.mdnew file mode 100644index 00000000..b69272bc--- /dev/null+++ b/README.md@@ -0,0 +1,523 @@+# MiniStack — Free, Open-Source Local AWS Emulator++++> **LocalStack is no longer free.** MiniStack is a fully open-source, zero-cost drop-in replacement.+> Single port · No account · No license key · No telemetry · Just AWS APIs, locally.+++++++++++<p align="center">+ <img src="ministack1.png" alt="MiniStack in action" width="700"/>+</p>++---++## Why MiniStack?++LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.++- **20 AWS services** emulated on a single port (4566)+- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK+- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers+- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM+- **Fast startup** — under 2 seconds+- **MIT licensed** — use it, fork it, contribute to it++---++## Quick Start++```bash+# Option 1: Docker Hub (recommended)+docker run -p 4566:4566 nahuelnucera/ministack++# Option 2: Clone and build+git clone https://github.com/Nahuel990/ministack+cd ministack++# Start with Docker Compose (includes Redis sidecar)+docker compose up -d++# Verify+curl http://localhost:4566/_localstack/health+```++That's it. No account, no API key, no sign-up.++---++## Using with AWS CLI++```bash+# Configure a local profile (one-time)+aws configure --profile local+# AWS Access Key ID: test+# AWS Secret Access Key: test+# Default region: us-east-1+# Default output format: json++# Use --endpoint-url on any command+aws --endpoint-url=http://localhost:4566 s3 mb s3://my-bucket+aws --endpoint-url=http://localhost:4566 s3 cp ./file.txt s3://my-bucket/+aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name my-queue+aws --endpoint-url=http://localhost:4566 dynamodb list-tables+aws --endpoint-url=http://localhost:4566 sts get-caller-identity++# Or set the endpoint globally for a session+export AWS_ENDPOINT_URL=http://localhost:4566+aws s3 ls+aws sqs list-queues+```++### awslocal wrapper++```bash+chmod +x bin/awslocal+./bin/awslocal s3 ls+./bin/awslocal dynamodb list-tables+```++---++## Using with boto3++```python+import boto3++# All clients use the same endpoint+def client(service):+ return boto3.client(+ service,+ endpoint_url="http://localhost:4566",+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name="us-east-1",+ )++# S3+s3 = client("s3")+s3.create_bucket(Bucket="my-bucket")+s3.put_object(Bucket="my-bucket", Key="hello.txt", Body=b"Hello, MiniStack!")+obj = s3.get_object(Bucket="my-bucket", Key="hello.txt")+print(obj["Body"].read()) # b'Hello, MiniStack!'++# SQS+sqs = client("sqs")+q = sqs.create_queue(QueueName="my-queue")+sqs.send_message(QueueUrl=q["QueueUrl"], MessageBody="hello")+msgs = sqs.receive_message(QueueUrl=q["QueueUrl"])+print(msgs["Messages"][0]["Body"]) # hello++# DynamoDB+ddb = client("dynamodb")+ddb.create_table(+ TableName="Users",+ KeySchema=[{"AttributeName": "userId", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "userId", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+)+ddb.put_item(TableName="Users", Item={"userId": {"S": "u1"}, "name": {"S": "Alice"}})++# SSM Parameter Store+ssm = client("ssm")+ssm.put_parameter(Name="/app/db/host", Value="localhost", Type="String")+param = ssm.get_parameter(Name="/app/db/host")+print(param["Parameter"]["Value"]) # localhost++# Secrets Manager+sm = client("secretsmanager")+sm.create_secret(Name="db-password", SecretString='{"password":"s3cr3t"}')++# Kinesis+kin = client("kinesis")+kin.create_stream(StreamName="events", ShardCount=1)+kin.put_record(StreamName="events", Data=b'{"event":"click"}', PartitionKey="user1")++# EventBridge+eb = client("events")+eb.put_events(Entries=[{+ "Source": "myapp",+ "DetailType": "UserSignup",+ "Detail": '{"userId": "123"}',+ "EventBusName": "default",+}])++# Step Functions+sfn = client("stepfunctions")+sfn.create_state_machine(+ name="my-workflow",+ definition='{"StartAt":"Hello","States":{"Hello":{"Type":"Pass","End":true}}}',+ roleArn="arn:aws:iam::000000000000:role/role",+)+```++---++## Supported Services++### Core Services++| Service | Operations | Notes |+|---------|-----------|-------|+| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects | Optional disk persistence via `S3_PERSIST=1` |+| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, SendMessageBatch, DeleteMessageBatch | Both Query API and JSON protocol |+| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, Publish | |+| **DynamoDB** | CreateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem | |+| **Lambda** | CreateFunction, DeleteFunction, GetFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration | Python runtimes actually execute; others return mock |+| **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, AttachRolePolicy, PutRolePolicy, CreateAccessKey, ListAccessKeys | |+| **STS** | GetCallerIdentity, AssumeRole, GetSessionToken | |+| **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue | |+| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents | |++### Extended Services++| Service | Operations | Notes |+|---------|-----------|-------|+| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters | Supports String, SecureString, StringList |+| **EventBridge** | CreateEventBus, DeleteEventBus, ListEventBuses, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, PutEvents | |+| **Kinesis** | CreateStream, DeleteStream, DescribeStream, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords | Partition key → shard routing |+| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, ListMetrics, PutMetricAlarm, DescribeAlarms, DeleteAlarms, SetAlarmState | |+| **SES** | SendEmail, SendRawEmail, VerifyEmailIdentity, ListIdentities, GetIdentityVerificationAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics | Emails stored in-memory, not sent |+| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StopExecution, DescribeExecution, ListExecutions, GetExecutionHistory | |++### Infrastructure Services (with real Docker execution)++| Service | Operations | Real Execution |+|---------|-----------|----------------|+| **ECS** | CreateCluster, DeleteCluster, DescribeClusters, ListClusters, RegisterTaskDefinition, DeregisterTaskDefinition, ListTaskDefinitions, CreateService, DeleteService, DescribeServices, UpdateService, ListServices, RunTask, StopTask, DescribeTasks, ListTasks | `RunTask` starts real Docker containers via Docker socket |+| **RDS** | CreateDBInstance, DeleteDBInstance, DescribeDBInstances, StartDBInstance, StopDBInstance, RebootDBInstance, ModifyDBInstance, CreateDBCluster, DeleteDBCluster, DescribeDBClusters, CreateDBSubnetGroup, DescribeDBSubnetGroups, CreateDBParameterGroup, DescribeDBParameterGroups, DescribeDBEngineVersions | `CreateDBInstance` spins up real Postgres/MySQL Docker container, returns actual `host:port` endpoint |+| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, CreateCacheParameterGroup, DescribeCacheParameterGroups, DescribeCacheEngineVersions | `CreateCacheCluster` spins up real Redis/Memcached Docker container |+| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, GetPartitions, BatchCreatePartition, CreateConnection, GetConnections, CreateCrawler, GetCrawler, StartCrawler, CreateJob, GetJob, GetJobs, StartJobRun, GetJobRun, GetJobRuns | Python shell jobs actually execute via subprocess |+| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results |++---++## Real Database Endpoints (RDS)++When you create an RDS instance, MiniStack starts a real database container and returns the actual connection endpoint:++```python+import boto3+import psycopg2 # pip install psycopg2-binary++rds = boto3.client("rds", endpoint_url="http://localhost:4566",+ aws_access_key_id="test", aws_secret_access_key="test", region_name="us-east-1")++resp = rds.create_db_instance(+ DBInstanceIdentifier="mydb",+ DBInstanceClass="db.t3.micro",+ Engine="postgres",+ MasterUsername="admin",+ MasterUserPassword="password",+ DBName="appdb",+ AllocatedStorage=20,+)++endpoint = resp["DBInstance"]["Endpoint"]+# Connect directly — it's a real Postgres instance+conn = psycopg2.connect(+ host=endpoint["Address"], # localhost+ port=endpoint["Port"], # 15432 (auto-assigned)+ user="admin",+ password="password",+ dbname="appdb",+)+```++Supported engines: `postgres`, `mysql`, `mariadb`, `aurora-postgresql`, `aurora-mysql`++---++## Real Redis Endpoints (ElastiCache)++```python+import boto3+import redis # pip install redis++ec = boto3.client("elasticache", endpoint_url="http://localhost:4566",+ aws_access_key_id="test", aws_secret_access_key="test", region_name="us-east-1")++resp = ec.create_cache_cluster(+ CacheClusterId="my-redis",+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+)++node = resp["CacheCluster"]["CacheNodes"][0]["Endpoint"]+r = redis.Redis(host=node["Address"], port=node["Port"])+r.set("key", "value")+print(r.get("key")) # b'value'+```++A Redis sidecar is also always available at `localhost:6379` when using Docker Compose.++---++## Athena with Real SQL++Athena queries run via DuckDB and can query files in your local S3 data directory:++```python+import boto3, time++athena = boto3.client("athena", endpoint_url="http://localhost:4566",+ aws_access_key_id="test", aws_secret_access_key="test", region_name="us-east-1")++# Query runs real SQL via DuckDB+resp = athena.start_query_execution(+ QueryString="SELECT 42 AS answer, 'hello' AS greeting",+ ResultConfiguration={"OutputLocation": "s3://athena-results/"},+)+query_id = resp["QueryExecutionId"]++# Poll for result+while True:+ status = athena.get_query_execution(QueryExecutionId=query_id)+ if status["QueryExecution"]["Status"]["State"] == "SUCCEEDED":+ break+ time.sleep(0.1)++results = athena.get_query_results(QueryExecutionId=query_id)+for row in results["ResultSet"]["Rows"][1:]: # skip header+ print([col["VarCharValue"] for col in row["Data"]])+# ['42', 'hello']+```++---++## ECS with Real Containers++```python+import boto3++ecs = boto3.client("ecs", endpoint_url="http://localhost:4566",+ aws_access_key_id="test", aws_secret_access_key="test", region_name="us-east-1")++ecs.create_cluster(clusterName="dev")++ecs.register_task_definition(+ family="web",+ containerDefinitions=[{+ "name": "nginx",+ "image": "nginx:alpine",+ "cpu": 128,+ "memory": 256,+ "portMappings": [{"containerPort": 80, "hostPort": 8080}],+ }],+)++# This actually runs an nginx container via Docker+resp = ecs.run_task(cluster="dev", taskDefinition="web", count=1)+task_arn = resp["tasks"][0]["taskArn"]++# Stop it (removes the container)+ecs.stop_task(cluster="dev", task=task_arn)+```++---++## Configuration++| Variable | Default | Description |+|----------|---------|-------------|+| `GATEWAY_PORT` | `4566` | Port to listen on |+| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR` |+| `S3_PERSIST` | `0` | Set `1` to persist S3 objects to disk |+| `S3_DATA_DIR` | `/tmp/localstack-data/s3` | S3 persistence directory |+| `REDIS_HOST` | `redis` | Redis host for ElastiCache fallback |+| `REDIS_PORT` | `6379` | Redis port for ElastiCache fallback |+| `RDS_BASE_PORT` | `15432` | Starting host port for RDS containers |+| `ELASTICACHE_BASE_PORT` | `16379` | Starting host port for ElastiCache containers |++---++## Architecture++```+ ┌─────────────────────────────────────────┐+ AWS CLI / boto3 │ ASGI Gateway :4566 │+ Terraform / CDK ──►│ ┌───────────────────────────────────┐ │+ Any AWS SDK │ │ Request Router │ │+ │ │ 1. X-Amz-Target header │ │+ │ │ 2. Authorization credential scope │ │+ │ │ 3. Action query param │ │+ │ │ 4. URL path pattern │ │+ │ │ 5. Host header │ │+ │ │ 6. Default → S3 │ │+ │ └──────────────┬────────────────────┘ │+ │ │ │+ │ ┌──────────────▼──────────────────┐ │+ │ │ Service Handlers │ │+ │ │ │ │+ │ │ S3 SQS SNS DynamoDB │ │+ │ │ Lambda IAM STS Secrets │ │+ │ │ SSM EventBridge Kinesis │ │+ │ │ CloudWatch SES StepFunctions │ │+ │ │ ECS RDS ElastiCache │ │+ │ │ Glue Athena │ │+ │ └──────────────────────────────────┘ │+ │ │+ │ In-Memory Storage + Optional Docker │+ └─────────────────────────────────────────┘+ │+ ┌──────────────┼──────────────┐+ ▼ ▼ ▼+ Redis:6379 Postgres:15432+ MySQL:15433++ (ElastiCache) (RDS) (RDS)+```++---++## Running Tests++```bash+# Install test dependencies+pip install boto3 pytest duckdb docker cbor2++# Start MiniStack+docker compose up -d++# Run the full test suite (54 tests across all 20 services)+pytest tests/ -v+```++Expected output:+```+collected 54 items++tests/test_services.py::test_s3_create_bucket PASSED+tests/test_services.py::test_s3_put_get PASSED+...+tests/test_services.py::test_athena_workgroup PASSED++54 passed in 7.6s+```++---++## Terraform / CDK / Pulumi++### Terraform++```hcl+provider "aws" {+ region = "us-east-1"+ access_key = "test"+ secret_key = "test"+ skip_credentials_validation = true+ skip_metadata_api_check = true+ skip_requesting_account_id = true++ endpoints {+ s3 = "http://localhost:4566"+ sqs = "http://localhost:4566"+ dynamodb = "http://localhost:4566"+ lambda = "http://localhost:4566"+ iam = "http://localhost:4566"+ sts = "http://localhost:4566"+ secretsmanager = "http://localhost:4566"+ ssm = "http://localhost:4566"+ kinesis = "http://localhost:4566"+ sns = "http://localhost:4566"+ rds = "http://localhost:4566"+ ecs = "http://localhost:4566"+ glue = "http://localhost:4566"+ athena = "http://localhost:4566"+ elasticache = "http://localhost:4566"+ stepfunctions = "http://localhost:4566"+ cloudwatch = "http://localhost:4566"+ logs = "http://localhost:4566"+ events = "http://localhost:4566"+ ses = "http://localhost:4566"+ }+}+```++### AWS CDK++```typescript+// cdk.json or in your app+const app = new cdk.App();+// Set endpoint override via environment+process.env.AWS_ENDPOINT_URL = "http://localhost:4566";+```++### Pulumi++```yaml+# Pulumi.dev.yaml+config:+ aws:endpoints:+ - s3: http://localhost:4566+ dynamodb: http://localhost:4566+ # ... etc+```++---++## Comparison++| Feature | MiniStack | LocalStack Free | LocalStack Pro |+|---------|-----------|-----------------|----------------|+| S3, SQS, SNS, DynamoDB | ✅ | ✅ | ✅ |+| Lambda (Python execution) | ✅ | ✅ | ✅ |+| IAM, STS, SecretsManager | ✅ | ✅ | ✅ |+| CloudWatch Logs | ✅ | ✅ | ✅ |+| SSM Parameter Store | ✅ | ✅ | ✅ |+| EventBridge | ✅ | ✅ | ✅ |+| Kinesis | ✅ | ✅ | ✅ |+| SES | ✅ | ✅ | ✅ |+| Step Functions | ✅ | ✅ | ✅ |+| **RDS (real DB containers)** | ✅ | ❌ | ✅ |+| **ElastiCache (real Redis)** | ✅ | ❌ | ✅ |+| **ECS (real Docker containers)** | ✅ | ❌ | ✅ |+| **Athena (real SQL via DuckDB)** | ✅ | ❌ | ✅ |+| **Glue Data Catalog + Jobs** | ✅ | ❌ | ✅ |+| API Gateway | ❌ | ✅ | ✅ |+| Cognito | ❌ | ✅ | ✅ |+| CloudFormation | ❌ | partial | ✅ |+| Cost | **Free** | Was free, now paid | $35+/mo |+| Docker image size | ~150MB | ~1GB | ~1GB |+| Memory at idle | ~30MB | ~500MB | ~500MB |+| Startup time | ~2s | ~15-30s | ~15-30s |+| License | MIT | BSL (restricted) | Proprietary |++---++## Contributing++PRs welcome. The codebase is intentionally simple — each service is a single self-contained Python file in `services/`. Adding a new service means:++1. Create `services/myservice.py` with an `async def handle_request(...)` function+2. Add it to `SERVICE_HANDLERS` in `app.py`+3. Add detection patterns to `core/router.py`+4. Add tests to `tests/test_services.py`++---++## License++MIT — free to use, modify, and distribute. No restrictions.++```+Copyright (c) 2024 MiniStack Contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.+```diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 00000000..139f5a6c--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,28 @@+# Security Policy++## ⚠️ Important: Local Development Only++MiniStack is designed **exclusively for local development and CI/CD testing**.++**Do not expose MiniStack to the internet or any untrusted network.**++- It has no authentication — any request is accepted+- Credentials (`aws_access_key_id`, `aws_secret_access_key`) are ignored+- All data is stored in-memory and is not encrypted+- The Docker socket mount (for ECS/RDS/ElastiCache) gives container-level access to your host++## Reporting a Vulnerability++If you find a security issue that could affect users running MiniStack in a way that exposes their host system or data, please open a GitHub issue tagged `security`.++Since this is a local dev tool with no auth by design, most "vulnerabilities" are intentional trade-offs for simplicity. But if you find something that could cause unintended host compromise (e.g. path traversal in S3 persistence, command injection in Lambda execution), please report it.++## Recommended Usage++```yaml+# docker-compose.yml — bind to localhost only, never 0.0.0.0 on a shared machine+ports:+ - "127.0.0.1:4566:4566"+```++Never run with `S3_PERSIST=1` pointing to sensitive directories.diff --git a/app.py b/app.pynew file mode 100644index 00000000..3b646a27--- /dev/null+++ b/app.py@@ -0,0 +1,166 @@+"""+MiniStack — Local AWS Service Emulator.+Single-port ASGI application on port 4566 (configurable via GATEWAY_PORT).+Routes requests to service handlers based on AWS headers, paths, and query parameters.+Compatible with AWS CLI, boto3, and any AWS SDK via --endpoint-url.+"""++import os+import json+import asyncio+import logging+from urllib.parse import parse_qs, urlparse++from core.router import detect_service, extract_region, extract_account_id+from services import s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwatch_logs+from services import ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctions+from services import ecs, rds, elasticache, glue, athena+from services.iam_sts import handle_iam_request, handle_sts_request++# Configure logging+LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()+logging.basicConfig(+ level=getattr(logging, LOG_LEVEL, logging.INFO),+ format="%(asctime)s %(levelname)s [%(name)s] %(message)s",+ datefmt="%Y-%m-%d %H:%M:%S",+)+logger = logging.getLogger("ministack")++# Service handler mapping+SERVICE_HANDLERS = {+ "s3": s3.handle_request,+ "sqs": sqs.handle_request,+ "sns": sns.handle_request,+ "dynamodb": dynamodb.handle_request,+ "lambda": lambda_svc.handle_request,+ "iam": handle_iam_request,+ "sts": handle_sts_request,+ "secretsmanager": secretsmanager.handle_request,+ "logs": cloudwatch_logs.handle_request,+ "ssm": ssm.handle_request,+ "events": eventbridge.handle_request,+ "kinesis": kinesis.handle_request,+ "monitoring": cloudwatch.handle_request,+ "ses": ses.handle_request,+ "states": stepfunctions.handle_request,+ "ecs": ecs.handle_request,+ "rds": rds.handle_request,+ "elasticache": elasticache.handle_request,+ "glue": glue.handle_request,+ "athena": athena.handle_request,+}++BANNER = r"""+ __ __ _ _ ____ _ _+ | \/ (_)_ __ (_) ___|| |_ __ _ ___| | __+ | |\/| | | '_ \| \___ \| __/ _` |/ __| |/ /+ | | | | | | | | |___) | || (_| | (__| <+ |_| |_|_|_| |_|_|____/ \__\__,_|\___|_|\_\++ Local AWS Service Emulator — Port {port}+ Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,+ SSM, EventBridge, Kinesis, CloudWatch, SES, Step Functions,+ ECS, RDS, ElastiCache, Glue, Athena+"""+++async def app(scope, receive, send):+ """ASGI application entry point."""+ if scope["type"] == "lifespan":+ await _handle_lifespan(scope, receive, send)+ return++ if scope["type"] != "http":+ return++ # Read request+ method = scope["method"]+ path = scope["path"]+ query_string = scope.get("query_string", b"").decode("utf-8")+ query_params = parse_qs(query_string, keep_blank_values=True)++ headers = {}+ for name, value in scope.get("headers", []):+ headers[name.decode("latin-1").lower()] = value.decode("latin-1")++ body = b""+ while True:+ message = await receive()+ body += message.get("body", b"")+ if not message.get("more_body", False):+ break++ # Health check endpoints+ if path in ("/_localstack/health", "/health", "/_ministack/health"):+ await _send_response(send, 200, {"Content-Type": "application/json"},+ json.dumps({"status": "running", "services": {s: "available" for s in SERVICE_HANDLERS}}).encode())+ return++ # Detect target service+ service = detect_service(method, path, headers, query_params)+ region = extract_region(headers)++ logger.debug(f"{method} {path} -> service={service} region={region}")++ handler = SERVICE_HANDLERS.get(service)+ if not handler:+ await _send_response(send, 400, {"Content-Type": "application/json"},+ json.dumps({"error": f"Unsupported service: {service}"}).encode())+ return++ try:+ status, resp_headers, resp_body = await handler(method, path, headers, body, query_params)+ except Exception as e:+ logger.exception(f"Error handling {service} request: {e}")+ await _send_response(send, 500, {"Content-Type": "application/json"},+ json.dumps({"__type": "InternalError", "message": str(e)}).encode())+ return++ # Add CORS headers (same as LocalStack)+ resp_headers.update({+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH",+ "Access-Control-Allow-Headers": "*",+ "Access-Control-Expose-Headers": "*",+ "x-amzn-requestid": headers.get("x-amzn-requestid", ""),+ })++ await _send_response(send, status, resp_headers, resp_body)+++async def _send_response(send, status, headers, body):+ """Send ASGI HTTP response."""+ header_list = [(k.encode("latin-1"), str(v).encode("latin-1")) for k, v in headers.items()]+ await send({+ "type": "http.response.start",+ "status": status,+ "headers": header_list,+ })+ await send({+ "type": "http.response.body",+ "body": body if isinstance(body, bytes) else body.encode("utf-8"),+ })+++async def _handle_lifespan(scope, receive, send):+ """Handle ASGI lifespan events."""+ while True:+ message = await receive()+ if message["type"] == "lifespan.startup":+ port = os.environ.get("GATEWAY_PORT", "4566")+ logger.info(BANNER.format(port=port))+ await send({"type": "lifespan.startup.complete"})+ elif message["type"] == "lifespan.shutdown":+ logger.info("MiniStack shutting down...")+ await send({"type": "lifespan.shutdown.complete"})+ return+++def main():+ import uvicorn+ port = int(os.environ.get("GATEWAY_PORT", "4566"))+ uvicorn.run("app:app", host="0.0.0.0", port=port, log_level=LOG_LEVEL.lower())+++if __name__ == "__main__":+ main()diff --git a/bin/awslocal b/bin/awslocalnew file mode 100755index 00000000..7ed97b15--- /dev/null+++ b/bin/awslocal@@ -0,0 +1,14 @@+#!/usr/bin/env bash+# awslocal — Wrapper around AWS CLI that points to local MiniStack endpoint.+# Usage: ./awslocal s3 ls+# ./awslocal sqs create-queue --queue-name my-queue+# ./awslocal dynamodb list-tables++ENDPOINT_URL="${MINISTACK_ENDPOINT:-http://localhost:4566}"+AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID:-test}"+AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY:-test}"+AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}"++export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION++exec aws --endpoint-url="$ENDPOINT_URL" "$@"diff --git a/core/__init__.py b/core/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/core/responses.py b/core/responses.pynew file mode 100644index 00000000..401db967--- /dev/null+++ b/core/responses.py@@ -0,0 +1,97 @@+"""+AWS Response formatting utilities.+Handles XML responses (S3, SQS, SNS, IAM, STS, CloudWatch) and+JSON responses (DynamoDB, Lambda, SecretsManager, CloudWatch Logs).+"""++import json+import uuid+import hashlib+from datetime import datetime, timezone+from xml.etree.ElementTree import Element, SubElement, tostring+++def xml_response(root_tag: str, namespace: str, children: dict, status: int = 200) -> tuple:+ """Build an AWS-style XML response."""+ root = Element(root_tag, xmlns=namespace)+ _dict_to_xml(root, children)++ # Add RequestId in ResponseMetadata+ metadata = SubElement(root, "ResponseMetadata")+ req_id = SubElement(metadata, "RequestId")+ req_id.text = str(uuid.uuid4())++ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _dict_to_xml(parent: Element, data):+ """Recursively convert dict/list to XML elements."""+ if isinstance(data, dict):+ for key, value in data.items():+ if isinstance(value, list):+ for item in value:+ child = SubElement(parent, key)+ if isinstance(item, dict):+ _dict_to_xml(child, item)+ else:+ child.text = str(item)+ elif isinstance(value, dict):+ child = SubElement(parent, key)+ _dict_to_xml(child, value)+ else:+ child = SubElement(parent, key)+ child.text = str(value) if value is not None else ""+ elif isinstance(data, str):+ parent.text = data+++def json_response(data: dict, status: int = 200) -> tuple:+ """Build an AWS-style JSON response."""+ body = json.dumps(data).encode("utf-8")+ return status, {"Content-Type": "application/x-amz-json-1.0"}, body+++def error_response_xml(code: str, message: str, status: int, namespace: str = "http://s3.amazonaws.com/doc/2006-03-01/") -> tuple:+ """AWS-style XML error response."""+ root = Element("ErrorResponse", xmlns=namespace)+ error = SubElement(root, "Error")+ c = SubElement(error, "Code")+ c.text = code+ m = SubElement(error, "Message")+ m.text = message+ req = SubElement(root, "RequestId")+ req.text = str(uuid.uuid4())++ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def error_response_json(code: str, message: str, status: int = 400) -> tuple:+ """AWS-style JSON error response."""+ data = {+ "__type": code,+ "message": message,+ }+ return json_response(data, status)+++def now_iso() -> str:+ """Current time in AWS ISO format."""+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def now_epoch() -> float:+ return datetime.now(timezone.utc).timestamp()+++def md5_hash(data: bytes) -> str:+ return hashlib.md5(data).hexdigest()+++def sha256_hash(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def new_uuid() -> str:+ return str(uuid.uuid4())diff --git a/core/router.py b/core/router.pynew file mode 100644index 00000000..2f88565c--- /dev/null+++ b/core/router.py@@ -0,0 +1,227 @@+"""+AWS API Request Router.+Routes incoming requests to the correct service handler based on:+ - Authorization header (AWS4-HMAC-SHA256 ... SignedHeaders=host;...)+ - X-Amz-Target header (e.g., DynamoDB_20120810.PutItem)+ - Host header (e.g., sqs.us-east-1.amazonaws.com)+ - URL path patterns (e.g., /2015-03-31/functions for Lambda)+"""++import re+import logging++logger = logging.getLogger("localstack-clone")++# Service detection patterns+SERVICE_PATTERNS = {+ "s3": {+ "host_patterns": [r"s3[\.\-]", r"\.s3\."],+ "path_patterns": [r"^/(?!2\d{3}-)"], # S3 is the fallback for non-API paths+ },+ "sqs": {+ "host_patterns": [r"sqs\."],+ "target_prefixes": ["AmazonSQS"],+ "path_patterns": [r"/queue/", r"Action="],+ },+ "sns": {+ "host_patterns": [r"sns\."],+ "target_prefixes": ["AmazonSNS"],+ },+ "dynamodb": {+ "target_prefixes": ["DynamoDB_20120810"],+ "host_patterns": [r"dynamodb\."],+ },+ "lambda": {+ "path_patterns": [r"^/2015-03-31/functions"],+ "host_patterns": [r"lambda\."],+ },+ "iam": {+ "host_patterns": [r"iam\."],+ "path_patterns": [r"Action=.*(CreateRole|GetRole|ListRoles|PutRolePolicy)"],+ },+ "sts": {+ "host_patterns": [r"sts\."],+ "target_prefixes": ["AWSSecurityTokenService"],+ },+ "secretsmanager": {+ "target_prefixes": ["secretsmanager"],+ "host_patterns": [r"secretsmanager\."],+ },+ "monitoring": {+ "host_patterns": [r"monitoring\."],+ "target_prefixes": ["GraniteServiceVersion20100801"],+ },+ "logs": {+ "target_prefixes": ["Logs_20140328"],+ "host_patterns": [r"logs\."],+ },+ "ssm": {+ "target_prefixes": ["AmazonSSM"],+ "host_patterns": [r"ssm\."],+ },+ "events": {+ "target_prefixes": ["AmazonEventBridge", "AWSEvents"],+ "host_patterns": [r"events\."],+ },+ "kinesis": {+ "target_prefixes": ["Kinesis_20131202"],+ "host_patterns": [r"kinesis\."],+ },+ "ses": {+ "host_patterns": [r"email\."],+ "path_patterns": [r"Action=Send"],+ },+ "states": {+ "target_prefixes": ["AWSStepFunctions"],+ "host_patterns": [r"states\."],+ },+ "ecs": {+ "target_prefixes": ["AmazonEC2ContainerServiceV20141113"],+ "host_patterns": [r"ecs\."],+ "path_patterns": [r"^/clusters", r"^/taskdefinitions", r"^/tasks", r"^/services", r"^/stoptask"],+ },+ "rds": {+ "host_patterns": [r"rds\."],+ "path_patterns": [r"Action=.*DB"],+ },+ "elasticache": {+ "host_patterns": [r"elasticache\."],+ "path_patterns": [r"Action=.*Cache"],+ },+ "glue": {+ "target_prefixes": ["AWSGlue"],+ "host_patterns": [r"glue\."],+ },+ "athena": {+ "target_prefixes": ["AmazonAthena"],+ "host_patterns": [r"athena\."],+ },+}+++def detect_service(method: str, path: str, headers: dict, query_params: dict) -> str:+ """Detect which AWS service a request is targeting."""+ host = headers.get("host", "")+ target = headers.get("x-amz-target", "")+ auth = headers.get("authorization", "")+ content_type = headers.get("content-type", "")++ # 1. Check X-Amz-Target header (most reliable for JSON-based services)+ if target:+ for svc, patterns in SERVICE_PATTERNS.items():+ for prefix in patterns.get("target_prefixes", []):+ if target.startswith(prefix):+ return svc++ # 2. Check Authorization header for service name in credential scope+ if auth:+ match = re.search(r"Credential=[^/]+/[^/]+/[^/]+/([^/]+)/", auth)+ if match:+ svc_name = match.group(1)+ if svc_name in SERVICE_PATTERNS:+ return svc_name+ # Map common credential scope names+ scope_map = {+ "monitoring": "monitoring",+ "execute-api": "lambda",+ "ses": "ses",+ "states": "states",+ "kinesis": "kinesis",+ "events": "events",+ "ssm": "ssm",+ "ecs": "ecs",+ "rds": "rds",+ "elasticache": "elasticache",+ "glue": "glue",+ "athena": "athena",+ }+ if svc_name in scope_map:+ return scope_map[svc_name]++ # 3. Check query parameters for Action-based APIs (SQS, SNS, IAM, STS, CloudWatch)+ action = query_params.get("Action", [""])[0] if isinstance(query_params.get("Action"), list) else query_params.get("Action", "")+ if action:+ action_service_map = {+ # SQS actions+ "SendMessage": "sqs", "ReceiveMessage": "sqs", "DeleteMessage": "sqs",+ "CreateQueue": "sqs", "DeleteQueue": "sqs", "ListQueues": "sqs",+ "GetQueueUrl": "sqs", "GetQueueAttributes": "sqs", "SetQueueAttributes": "sqs",+ "PurgeQueue": "sqs", "ChangeMessageVisibility": "sqs",+ "SendMessageBatch": "sqs", "DeleteMessageBatch": "sqs",+ # SNS actions+ "Publish": "sns", "Subscribe": "sns", "Unsubscribe": "sns",+ "CreateTopic": "sns", "DeleteTopic": "sns", "ListTopics": "sns",+ "ListSubscriptions": "sns", "ConfirmSubscription": "sns",+ "SetTopicAttributes": "sns", "GetTopicAttributes": "sns",+ "ListSubscriptionsByTopic": "sns",+ # IAM actions+ "CreateRole": "iam", "GetRole": "iam", "ListRoles": "iam",+ "DeleteRole": "iam", "CreateUser": "iam", "GetUser": "iam",+ "ListUsers": "iam", "CreatePolicy": "iam", "AttachRolePolicy": "iam",+ "PutRolePolicy": "iam", "CreateAccessKey": "iam",+ # STS actions+ "GetCallerIdentity": "sts", "AssumeRole": "sts",+ "GetSessionToken": "sts",+ # CloudWatch actions+ "PutMetricData": "monitoring", "GetMetricData": "monitoring",+ "ListMetrics": "monitoring", "PutMetricAlarm": "monitoring",+ "DescribeAlarms": "monitoring", "DeleteAlarms": "monitoring",+ "GetMetricStatistics": "monitoring", "SetAlarmState": "monitoring",+ # SES actions+ "SendEmail": "ses", "SendRawEmail": "ses",+ "VerifyEmailIdentity": "ses", "VerifyEmailAddress": "ses",+ "ListIdentities": "ses", "DeleteIdentity": "ses",+ "GetSendQuota": "ses", "GetSendStatistics": "ses",+ "ListVerifiedEmailAddresses": "ses",+ # RDS actions+ "CreateDBInstance": "rds", "DeleteDBInstance": "rds", "DescribeDBInstances": "rds",+ "StartDBInstance": "rds", "StopDBInstance": "rds", "RebootDBInstance": "rds",+ "ModifyDBInstance": "rds", "CreateDBCluster": "rds", "DeleteDBCluster": "rds",+ "DescribeDBClusters": "rds", "CreateDBSubnetGroup": "rds", "DescribeDBSubnetGroups": "rds",+ "CreateDBParameterGroup": "rds", "DescribeDBParameterGroups": "rds",+ "DescribeDBEngineVersions": "rds",+ # ElastiCache actions+ "CreateCacheCluster": "elasticache", "DeleteCacheCluster": "elasticache",+ "DescribeCacheClusters": "elasticache", "ModifyCacheCluster": "elasticache",+ "CreateReplicationGroup": "elasticache", "DeleteReplicationGroup": "elasticache",+ "DescribeReplicationGroups": "elasticache",+ "CreateCacheSubnetGroup": "elasticache", "DescribeCacheSubnetGroups": "elasticache",+ "CreateCacheParameterGroup": "elasticache", "DescribeCacheParameterGroups": "elasticache",+ "DescribeCacheEngineVersions": "elasticache",+ }+ if action in action_service_map:+ return action_service_map[action]++ # 4. Check URL path patterns+ path_lower = path.lower()+ if path_lower.startswith("/2015-03-31/functions"):+ return "lambda"+ if path_lower.startswith(("/clusters", "/taskdefinitions", "/tasks", "/services", "/stoptask")):+ return "ecs"+ # smithy-rpc-v2-cbor path: /service/ServiceName/operation/ActionName+ if "/service/" in path_lower and "/operation/" in path_lower:+ if "granite" in path_lower or "cloudwatch" in path_lower:+ return "monitoring"++ # 5. Check host header patterns+ for svc, patterns in SERVICE_PATTERNS.items():+ for hp in patterns.get("host_patterns", []):+ if re.search(hp, host):+ return svc++ # 6. Default to S3 (same as real LocalStack behavior)+ return "s3"+++def extract_region(headers: dict) -> str:+ """Extract AWS region from the request."""+ auth = headers.get("authorization", "")+ match = re.search(r"Credential=[^/]+/[^/]+/([^/]+)/", auth)+ if match:+ return match.group(1)+ return "us-east-1"+++def extract_account_id(headers: dict) -> str:+ """Extract or generate account ID."""+ return "000000000000"diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 00000000..5f4b58ae--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,59 @@+version: "3.8"++services:+ ministack:+ build: .+ container_name: ministack+ ports:+ - "4566:4566"+ environment:+ - GATEWAY_PORT=4566+ - LOG_LEVEL=INFO+ - S3_PERSIST=0+ - REDIS_HOST=redis+ - REDIS_PORT=6379+ - RDS_BASE_PORT=15432+ - ELASTICACHE_BASE_PORT=16379+ volumes:+ - ./data/s3:/tmp/localstack-data/s3+ - /var/run/docker.sock:/var/run/docker.sock+ depends_on:+ redis:+ condition: service_healthy+ healthcheck:+ test: ["CMD", "curl", "-sf", "http://localhost:4566/_localstack/health"]+ interval: 10s+ timeout: 3s+ retries: 3+ start_period: 5s+ restart: unless-stopped++ redis:+ image: redis:7-alpine+ container_name: ministack-redis+ ports:+ - "6379:6379"+ healthcheck:+ test: ["CMD", "redis-cli", "ping"]+ interval: 5s+ timeout: 3s+ retries: 5+ restart: unless-stopped++ # Optional: Postgres for RDS (always-on, no Docker-in-Docker needed)+ # Uncomment to have a persistent Postgres available at localhost:5432+ # postgres:+ # image: postgres:15-alpine+ # container_name: ministack-postgres+ # ports:+ # - "5432:5432"+ # environment:+ # POSTGRES_USER: admin+ # POSTGRES_PASSWORD: password+ # POSTGRES_DB: mydb+ # healthcheck:+ # test: ["CMD-SHELL", "pg_isready -U admin"]+ # interval: 5s+ # timeout: 3s+ # retries: 5+ # restart: unless-stoppeddiff --git a/ministack-logo.png b/ministack-logo.pngnew file mode 100644index 00000000..d67be7e5Binary files /dev/null and b/ministack-logo.png differdiff --git a/ministack1.png b/ministack1.pngnew file mode 100644index 00000000..689cb23bBinary files /dev/null and b/ministack1.png differdiff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 00000000..928793e8--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,60 @@+[build-system]+requires = ["setuptools>=68", "wheel"]+build-backend = "setuptools.backends.legacy:build"++[project]+name = "ministack"+version = "0.1.0"+description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"+readme = "README.md"+license = { file = "LICENSE" }+requires-python = ">=3.10"+keywords = ["aws", "localstack", "testing", "s3", "sqs", "dynamodb", "local-dev"]+classifiers = [+ "Development Status :: 4 - Beta",+ "Intended Audience :: Developers",+ "License :: OSI Approved :: MIT License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Topic :: Software Development :: Testing",+ "Topic :: Internet",+]+dependencies = [+ "uvicorn[standard]>=0.30.6",+ "httptools>=0.6.1",+]++[project.optional-dependencies]+full = [+ "duckdb>=0.10.0",+ "docker>=7.0.0",+]+dev = [+ "boto3>=1.34",+ "pytest>=8.0",+ "pytest-cov>=5.0",+ "duckdb>=0.10.0",+ "docker>=7.0.0",+]++[project.urls]+Homepage = "https://github.com/Nahuel990/ministack"+Repository = "https://github.com/Nahuel990/ministack"+Issues = "https://github.com/Nahuel990/ministack/issues"++[project.scripts]+ministack = "app:main"++[tool.setuptools.packages.find]+include = ["core*", "services*"]++[tool.pytest.ini_options]+testpaths = ["tests"]+python_files = ["test_*.py"]+python_functions = ["test_*"]++[tool.coverage.run]+source = ["core", "services"]+omit = ["tests/*"]diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 00000000..0c4ab14d--- /dev/null+++ b/requirements.txt@@ -0,0 +1,5 @@+uvicorn[standard]==0.30.6+httptools==0.6.1+duckdb>=0.10.0+docker>=7.0.0+cbor2>=5.4.0diff --git a/services/__init__.py b/services/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/services/athena.py b/services/athena.pynew file mode 100644index 00000000..d1ed3289--- /dev/null+++ b/services/athena.py@@ -0,0 +1,349 @@+"""+Athena Service Emulator.+JSON-based API via X-Amz-Target (AmazonAthena).+Uses DuckDB to actually execute SQL queries against S3 data (CSV/JSON/Parquet).+Supports: StartQueryExecution, GetQueryExecution, GetQueryResults,+ StopQueryExecution, ListQueryExecutions,+ CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups,+ CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries.+"""++import os+import json+import time+import logging+import threading++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("athena")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"+S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/localstack-data/s3")++_executions: dict = {} # query_execution_id -> execution dict+_workgroups: dict = {+ "primary": {+ "Name": "primary",+ "State": "ENABLED",+ "Description": "Primary workgroup",+ "CreationTime": time.time(),+ "Configuration": {"ResultConfiguration": {"OutputLocation": "s3://athena-results/"}},+ }+}+_named_queries: dict = {}++# Try to import DuckDB+try:+ import duckdb+ _duckdb_available = True+ logger.info("Athena: DuckDB available — real SQL execution enabled")+except ImportError:+ _duckdb_available = False+ logger.warning("Athena: DuckDB not available — install with: pip install duckdb")+++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 = {+ "StartQueryExecution": _start_query_execution,+ "GetQueryExecution": _get_query_execution,+ "GetQueryResults": _get_query_results,+ "StopQueryExecution": _stop_query_execution,+ "ListQueryExecutions": _list_query_executions,+ "CreateWorkGroup": _create_workgroup,+ "DeleteWorkGroup": _delete_workgroup,+ "GetWorkGroup": _get_workgroup,+ "ListWorkGroups": _list_workgroups,+ "UpdateWorkGroup": _update_workgroup,+ "CreateNamedQuery": _create_named_query,+ "DeleteNamedQuery": _delete_named_query,+ "GetNamedQuery": _get_named_query,+ "ListNamedQueries": _list_named_queries,+ "BatchGetNamedQuery": _batch_get_named_query,+ "BatchGetQueryExecution": _batch_get_query_execution,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown Athena action: {action}", 400)+ return handler(data)+++def _start_query_execution(data):+ query = data.get("QueryString", "")+ query_id = new_uuid()+ workgroup = data.get("WorkGroup", "primary")+ output_location = (+ data.get("ResultConfiguration", {}).get("OutputLocation")+ or _workgroups.get(workgroup, {}).get("Configuration", {}).get("ResultConfiguration", {}).get("OutputLocation", "s3://athena-results/")+ )+ db = data.get("QueryExecutionContext", {}).get("Database", "default")++ execution = {+ "QueryExecutionId": query_id,+ "Query": query,+ "StatementType": _detect_statement_type(query),+ "ResultConfiguration": {"OutputLocation": f"{output_location}{query_id}.csv"},+ "QueryExecutionContext": {"Database": db},+ "Status": {+ "State": "RUNNING",+ "SubmissionDateTime": time.time(),+ "CompletionDateTime": None,+ "StateChangeReason": "",+ },+ "Statistics": {"EngineExecutionTimeInMillis": 0, "DataScannedInBytes": 0},+ "WorkGroup": workgroup,+ "_results": None,+ "_error": None,+ }+ _executions[query_id] = execution++ # Run query in background thread+ thread = threading.Thread(target=_execute_query, args=(query_id, query, db), daemon=True)+ thread.start()++ return json_response({"QueryExecutionId": query_id})+++def _execute_query(query_id, query, database):+ """Execute query using DuckDB in a background thread."""+ execution = _executions.get(query_id)+ if not execution:+ return++ start = time.time()+ try:+ if _duckdb_available:+ results = _run_duckdb(query, database)+ else:+ results = _mock_query_results(query)++ execution["_results"] = results+ execution["Status"]["State"] = "SUCCEEDED"+ execution["Statistics"]["EngineExecutionTimeInMillis"] = int((time.time() - start) * 1000)+ execution["Statistics"]["DataScannedInBytes"] = sum(+ len(str(row)) for row in results.get("rows", [])+ )+ except Exception as e:+ logger.error(f"Athena query {query_id} failed: {e}")+ execution["Status"]["State"] = "FAILED"+ execution["Status"]["StateChangeReason"] = str(e)+ execution["_error"] = str(e)++ execution["Status"]["CompletionDateTime"] = time.time()+++def _run_duckdb(query, database):+ """Execute SQL via DuckDB, with S3 data directory available."""+ import duckdb++ conn = duckdb.connect(":memory:")++ # Rewrite s3:// paths to local filesystem paths before executing+ rewritten = _rewrite_s3_paths(query)++ try:+ result = conn.execute(rewritten)+ columns = [desc[0] for desc in result.description] if result.description else []+ rows = result.fetchall()+ conn.close()+ return {"columns": columns, "rows": [list(r) for r in rows]}+ except Exception as e:+ conn.close()+ raise e+++def _rewrite_s3_paths(query):+ """Replace s3://bucket/key references with local file paths."""+ import re+ def replace_s3(match):+ s3_path = match.group(1)+ parts = s3_path.lstrip("s3://").split("/", 1)+ bucket = parts[0]+ key = parts[1] if len(parts) > 1 else ""+ local_path = os.path.join(S3_DATA_DIR, bucket, key)+ return f"'{local_path}'"+ return re.sub(r"'(s3://[^']+)'", replace_s3, query)+++def _mock_query_results(query):+ """Return mock results when DuckDB is not available."""+ query_upper = query.strip().upper()+ if query_upper.startswith("SELECT"):+ return {"columns": ["result"], "rows": [["mock_value"]]}+ return {"columns": [], "rows": []}+++def _detect_statement_type(query):+ q = query.strip().upper()+ if q.startswith("SELECT"):+ return "DML"+ if q.startswith(("CREATE", "DROP", "ALTER")):+ return "DDL"+ return "DML"+++def _get_query_execution(data):+ query_id = data.get("QueryExecutionId")+ execution = _executions.get(query_id)+ if not execution:+ return error_response_json("InvalidRequestException", f"Query {query_id} not found", 400)+ return json_response({"QueryExecution": _execution_out(execution)})+++def _get_query_results(data):+ query_id = data.get("QueryExecutionId")+ execution = _executions.get(query_id)+ if not execution:+ return error_response_json("InvalidRequestException", f"Query {query_id} not found", 400)++ if execution["Status"]["State"] != "SUCCEEDED":+ return error_response_json("InvalidRequestException",+ f"Query is in state {execution['Status']['State']}", 400)++ results = execution.get("_results") or {"columns": [], "rows": []}+ columns = results.get("columns", [])+ rows = results.get("rows", [])++ # Format as Athena ResultSet+ result_rows = []+ # Header row+ result_rows.append({"Data": [{"VarCharValue": col} for col in columns]})+ # Data rows+ for row in rows:+ result_rows.append({"Data": [{"VarCharValue": str(v) if v is not None else ""} for v in row]})++ return json_response({+ "QueryExecution": _execution_out(execution),+ "ResultSet": {+ "Rows": result_rows,+ "ResultSetMetadata": {+ "ColumnInfo": [+ {"Name": col, "Type": "varchar", "Label": col, "Nullable": "NULLABLE",+ "CaseSensitive": False, "Precision": 0, "Scale": 0}+ for col in columns+ ]+ },+ },+ "UpdateCount": 0,+ })+++def _stop_query_execution(data):+ query_id = data.get("QueryExecutionId")+ execution = _executions.get(query_id)+ if execution and execution["Status"]["State"] == "RUNNING":+ execution["Status"]["State"] = "CANCELLED"+ execution["Status"]["CompletionDateTime"] = time.time()+ return json_response({})+++def _list_query_executions(data):+ workgroup = data.get("WorkGroup", "primary")+ ids = [qid for qid, ex in _executions.items() if ex.get("WorkGroup") == workgroup]+ return json_response({"QueryExecutionIds": ids})+++def _create_workgroup(data):+ name = data.get("Name")+ if name in _workgroups:+ return error_response_json("InvalidRequestException", f"WorkGroup {name} already exists", 400)+ _workgroups[name] = {+ "Name": name,+ "State": "ENABLED",+ "Description": data.get("Description", ""),+ "CreationTime": time.time(),+ "Configuration": data.get("Configuration", {}),+ }+ return json_response({})+++def _delete_workgroup(data):+ name = data.get("WorkGroup")+ if name == "primary":+ return error_response_json("InvalidRequestException", "Cannot delete primary workgroup", 400)+ _workgroups.pop(name, None)+ return json_response({})+++def _get_workgroup(data):+ name = data.get("WorkGroup")+ wg = _workgroups.get(name)+ if not wg:+ return error_response_json("InvalidRequestException", f"WorkGroup {name} not found", 400)+ return json_response({"WorkGroup": wg})+++def _list_workgroups(data):+ return json_response({"WorkGroups": [{"Name": wg["Name"], "State": wg["State"]} for wg in _workgroups.values()]})+++def _update_workgroup(data):+ name = data.get("WorkGroup")+ wg = _workgroups.get(name)+ if not wg:+ return error_response_json("InvalidRequestException", f"WorkGroup {name} not found", 400)+ if "ConfigurationUpdates" in data:+ wg["Configuration"].update(data["ConfigurationUpdates"])+ if "Description" in data:+ wg["Description"] = data["Description"]+ return json_response({})+++def _create_named_query(data):+ query_id = new_uuid()+ _named_queries[query_id] = {+ "NamedQueryId": query_id,+ "Name": data.get("Name", ""),+ "Description": data.get("Description", ""),+ "Database": data.get("Database", "default"),+ "QueryString": data.get("QueryString", ""),+ "WorkGroup": data.get("WorkGroup", "primary"),+ }+ return json_response({"NamedQueryId": query_id})+++def _delete_named_query(data):+ _named_queries.pop(data.get("NamedQueryId"), None)+ return json_response({})+++def _get_named_query(data):+ query_id = data.get("NamedQueryId")+ nq = _named_queries.get(query_id)+ if not nq:+ return error_response_json("InvalidRequestException", f"Named query {query_id} not found", 400)+ return json_response({"NamedQuery": nq})+++def _list_named_queries(data):+ workgroup = data.get("WorkGroup", "primary")+ ids = [qid for qid, nq in _named_queries.items() if nq.get("WorkGroup") == workgroup]+ return json_response({"NamedQueryIds": ids})+++def _batch_get_named_query(data):+ ids = data.get("NamedQueryIds", [])+ queries = [_named_queries[qid] for qid in ids if qid in _named_queries]+ unprocessed = [qid for qid in ids if qid not in _named_queries]+ return json_response({"NamedQueries": queries, "UnprocessedNamedQueryIds": unprocessed})+++def _batch_get_query_execution(data):+ ids = data.get("QueryExecutionIds", [])+ execs = [_execution_out(_executions[qid]) for qid in ids if qid in _executions]+ unprocessed = [qid for qid in ids if qid not in _executions]+ return json_response({"QueryExecutions": execs, "UnprocessedQueryExecutionIds": unprocessed})+++def _execution_out(ex):+ return {k: v for k, v in ex.items() if not k.startswith("_")}diff --git a/services/cloudwatch.py b/services/cloudwatch.pynew file mode 100644index 00000000..fd3141a9--- /dev/null+++ b/services/cloudwatch.py@@ -0,0 +1,398 @@+"""+CloudWatch Metrics Service Emulator.+Supports legacy Query API (form-encoded), smithy-rpc-v2-cbor (botocore 1.42+),+and JSON/X-Amz-Target protocol (botocore 1.42 with endpoint_url).+Operations: PutMetricData, GetMetricStatistics, ListMetrics,+ PutMetricAlarm, DescribeAlarms, DeleteAlarms,+ EnableAlarmActions, DisableAlarmActions, SetAlarmState.+"""++import re+import json+import time+import logging+from urllib.parse import parse_qs+from collections import defaultdict++from core.responses import new_uuid++logger = logging.getLogger("cloudwatch")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_metrics: dict = defaultdict(list)+_alarms: dict = {}+++async def handle_request(method, path, headers, body, query_params):+ content_type = headers.get("content-type", "")+ target = headers.get("x-amz-target", "")+ is_cbor = "cbor" in content_type or "cbor" in headers.get("smithy-protocol", "")+ is_json = (not is_cbor) and ("json" in content_type or bool(target))++ params = dict(query_params)+ cbor_data = {}++ if body:+ if is_cbor:+ try:+ import cbor2+ cbor_data = cbor2.loads(body) or {}+ except Exception as e:+ logger.error(f"CBOR decode error: {e}")+ cbor_data = {}+ elif is_json:+ try:+ cbor_data = json.loads(body) or {}+ except Exception as e:+ logger.error(f"JSON decode error: {e}")+ cbor_data = {}+ else:+ for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():+ params[k] = v++ # Extract action: X-Amz-Target first, then URL path, then form params+ action = ""+ if target and "." in target:+ action = target.split(".")[-1]+ if not action:+ m = re.search(r"/operation/([^/?]+)", path)+ if m:+ action = m.group(1)+ if not action:+ action = _p(params, "Action")++ handlers = {+ "PutMetricData": _put_metric_data,+ "GetMetricStatistics": _get_metric_statistics,+ "ListMetrics": _list_metrics,+ "PutMetricAlarm": _put_metric_alarm,+ "DescribeAlarms": _describe_alarms,+ "DeleteAlarms": _delete_alarms,+ "EnableAlarmActions": _enable_alarm_actions,+ "DisableAlarmActions": _disable_alarm_actions,+ "SetAlarmState": _set_alarm_state,+ }++ handler = handlers.get(action)+ if not handler:+ return _error("InvalidAction", f"Unknown action: {action}", 400, is_cbor or is_json)+ return handler(params, cbor_data, is_cbor, is_json)+++def _put_metric_data(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ namespace = cbor_data.get("Namespace", "")+ for md in cbor_data.get("MetricData", []):+ metric_name = md.get("MetricName", "")+ value = float(md.get("Value", 0))+ unit = md.get("Unit", "None")+ ts = time.time()+ dims = {d["Name"]: d["Value"] for d in md.get("Dimensions", [])}+ _metrics[(namespace, metric_name, _dims_key(dims))].append(+ {"Timestamp": ts, "Value": value, "Unit": unit, "Dimensions": dims}+ )+ else:+ namespace = _p(params, "Namespace")+ i = 1+ while _p(params, f"MetricData.member.{i}.MetricName"):+ metric_name = _p(params, f"MetricData.member.{i}.MetricName")+ value = float(_p(params, f"MetricData.member.{i}.Value") or "0")+ unit = _p(params, f"MetricData.member.{i}.Unit") or "None"+ ts_str = _p(params, f"MetricData.member.{i}.Timestamp")+ ts = float(ts_str) if ts_str else time.time()+ dims = {}+ j = 1+ while _p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Name"):+ dims[_p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Name")] = \+ _p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Value")+ j += 1+ _metrics[(namespace, metric_name, _dims_key(dims))].append(+ {"Timestamp": ts, "Value": value, "Unit": unit, "Dimensions": dims}+ )+ i += 1++ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "PutMetricDataResponse", "")+++def _list_metrics(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ namespace = cbor_data.get("Namespace")+ metric_name = cbor_data.get("MetricName")+ else:+ namespace = _p(params, "Namespace")+ metric_name = _p(params, "MetricName")++ seen = set()+ result = []+ for (ns, mn, dk), points in _metrics.items():+ if namespace and ns != namespace:+ continue+ if metric_name and mn != metric_name:+ continue+ key = (ns, mn, dk)+ if key in seen:+ continue+ seen.add(key)+ dims = [{"Name": k, "Value": v} for k, v in (points[0].get("Dimensions", {}) if points else {}).items()]+ result.append({"Namespace": ns, "MetricName": mn, "Dimensions": dims})++ if is_cbor:+ return _cbor_ok({"Metrics": result})+ if is_json:+ return _json_ok({"Metrics": result})++ members = ""+ for item in result:+ dims_xml = "".join(f"<member><Name>{d['Name']}</Name><Value>{d['Value']}</Value></member>"+ for d in item["Dimensions"])+ members += f"<member><Namespace>{item['Namespace']}</Namespace><MetricName>{item['MetricName']}</MetricName><Dimensions>{dims_xml}</Dimensions></member>"+ return _xml(200, "ListMetricsResponse", f"<ListMetricsResult><Metrics>{members}</Metrics></ListMetricsResult>")+++def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ namespace = cbor_data.get("Namespace")+ metric_name = cbor_data.get("MetricName")+ period = int(cbor_data.get("Period") or 60)+ else:+ namespace = _p(params, "Namespace")+ metric_name = _p(params, "MetricName")+ period = int(_p(params, "Period") or 60)++ all_points = []+ for (ns, mn, dk), points in _metrics.items():+ if ns == namespace and mn == metric_name:+ all_points.extend(points)++ if is_cbor or is_json:+ datapoints = []+ buckets = defaultdict(list)+ for pt in all_points:+ buckets[int(pt["Timestamp"] // period) * period].append(pt["Value"])+ for ts, values in sorted(buckets.items()):+ datapoints.append({+ "Timestamp": ts, "SampleCount": len(values),+ "Sum": sum(values), "Average": sum(values) / len(values),+ "Minimum": min(values), "Maximum": max(values),+ "Unit": all_points[0]["Unit"] if all_points else "None",+ })+ if is_cbor:+ return _cbor_ok({"Datapoints": datapoints, "Label": metric_name})+ return _json_ok({"Datapoints": datapoints, "Label": metric_name})++ if not all_points:+ return _xml(200, "GetMetricStatisticsResponse",+ f"<GetMetricStatisticsResult><Datapoints/><Label>{metric_name}</Label></GetMetricStatisticsResult>")+ buckets = defaultdict(list)+ for pt in all_points:+ buckets[int(pt["Timestamp"] // period) * period].append(pt["Value"])+ dps = ""+ for ts, values in sorted(buckets.items()):+ dps += (f"<member><Timestamp>{ts}</Timestamp><SampleCount>{len(values)}</SampleCount>"+ f"<Sum>{sum(values)}</Sum><Average>{sum(values)/len(values):.6f}</Average>"+ f"<Minimum>{min(values)}</Minimum><Maximum>{max(values)}</Maximum>"+ f"<Unit>{all_points[0]['Unit']}</Unit></member>")+ return _xml(200, "GetMetricStatisticsResponse",+ f"<GetMetricStatisticsResult><Datapoints>{dps}</Datapoints><Label>{metric_name}</Label></GetMetricStatisticsResult>")+++def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ name = cbor_data.get("AlarmName", "")+ alarm = {+ "AlarmName": name,+ "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{name}",+ "AlarmDescription": cbor_data.get("AlarmDescription"),+ "MetricName": cbor_data.get("MetricName"),+ "Namespace": cbor_data.get("Namespace"),+ "Statistic": cbor_data.get("Statistic", "Average"),+ "Period": int(cbor_data.get("Period", 60)),+ "EvaluationPeriods": int(cbor_data.get("EvaluationPeriods", 1)),+ "Threshold": float(cbor_data.get("Threshold", 0)),+ "ComparisonOperator": cbor_data.get("ComparisonOperator"),+ "StateValue": "OK",+ "StateReason": "Threshold Crossed",+ "ActionsEnabled": cbor_data.get("ActionsEnabled", True),+ }+ else:+ name = _p(params, "AlarmName")+ alarm = {+ "AlarmName": name,+ "AlarmArn": f"arn:aws:cloudwatch:{REGION}:{ACCOUNT_ID}:alarm:{name}",+ "AlarmDescription": _p(params, "AlarmDescription"),+ "MetricName": _p(params, "MetricName"),+ "Namespace": _p(params, "Namespace"),+ "Statistic": _p(params, "Statistic") or "Average",+ "Period": int(_p(params, "Period") or "60"),+ "EvaluationPeriods": int(_p(params, "EvaluationPeriods") or "1"),+ "Threshold": float(_p(params, "Threshold") or "0"),+ "ComparisonOperator": _p(params, "ComparisonOperator"),+ "StateValue": "OK",+ "StateReason": "Threshold Crossed",+ "ActionsEnabled": _p(params, "ActionsEnabled") != "false",+ }+ _alarms[name] = alarm+ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "PutMetricAlarmResponse", "")+++def _describe_alarms(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ names = cbor_data.get("AlarmNames", [])+ prefix = cbor_data.get("AlarmNamePrefix")+ state = cbor_data.get("StateValue")+ else:+ names = [_p(params, f"AlarmNames.member.{i}") for i in range(1, 100)+ if _p(params, f"AlarmNames.member.{i}")]+ prefix = _p(params, "AlarmNamePrefix")+ state = _p(params, "StateValue")++ result = []+ for name, alarm in _alarms.items():+ if names and name not in names:+ continue+ if prefix and not name.startswith(prefix):+ continue+ if state and alarm["StateValue"] != state:+ continue+ result.append(alarm)++ if is_cbor:+ return _cbor_ok({"MetricAlarms": result})+ if is_json:+ return _json_ok({"MetricAlarms": result})++ members = "".join(+ f"<member><AlarmName>{a['AlarmName']}</AlarmName><AlarmArn>{a['AlarmArn']}</AlarmArn>"+ f"<StateValue>{a['StateValue']}</StateValue><MetricName>{a['MetricName']}</MetricName>"+ f"<Namespace>{a['Namespace']}</Namespace><Threshold>{a['Threshold']}</Threshold>"+ f"<ComparisonOperator>{a['ComparisonOperator']}</ComparisonOperator></member>"+ for a in result+ )+ return _xml(200, "DescribeAlarmsResponse",+ f"<DescribeAlarmsResult><MetricAlarms>{members}</MetricAlarms></DescribeAlarmsResult>")+++def _delete_alarms(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ for name in cbor_data.get("AlarmNames", []):+ _alarms.pop(name, None)+ else:+ i = 1+ while _p(params, f"AlarmNames.member.{i}"):+ _alarms.pop(_p(params, f"AlarmNames.member.{i}"), None)+ i += 1+ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "DeleteAlarmsResponse", "")+++def _enable_alarm_actions(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ names = cbor_data.get("AlarmNames", [])+ else:+ names = [_p(params, f"AlarmNames.member.{i}") for i in range(1, 100)+ if _p(params, f"AlarmNames.member.{i}")]+ for name in names:+ if name in _alarms:+ _alarms[name]["ActionsEnabled"] = True+ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "EnableAlarmActionsResponse", "")+++def _disable_alarm_actions(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ names = cbor_data.get("AlarmNames", [])+ else:+ names = [_p(params, f"AlarmNames.member.{i}") for i in range(1, 100)+ if _p(params, f"AlarmNames.member.{i}")]+ for name in names:+ if name in _alarms:+ _alarms[name]["ActionsEnabled"] = False+ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "DisableAlarmActionsResponse", "")+++def _set_alarm_state(params, cbor_data, is_cbor, is_json=False):+ if is_cbor or is_json:+ name = cbor_data.get("AlarmName", "")+ state = cbor_data.get("StateValue", "")+ reason = cbor_data.get("StateReason", "")+ else:+ name = _p(params, "AlarmName")+ state = _p(params, "StateValue")+ reason = _p(params, "StateReason")+ if name in _alarms:+ _alarms[name]["StateValue"] = state+ _alarms[name]["StateReason"] = reason+ if is_cbor:+ return _cbor_ok({})+ if is_json:+ return _json_ok({})+ return _xml(200, "SetAlarmStateResponse", "")+++# --- Helpers ---++def _dims_key(dims: dict) -> str:+ return "|".join(f"{k}={v}" for k, v in sorted(dims.items()))+++def _p(params, key, default=""):+ val = params.get(key, [default])+ return val[0] if isinstance(val, list) else val+++def _cbor_ok(data: dict):+ try:+ import cbor2+ body = cbor2.dumps(data)+ except Exception:+ body = json.dumps(data).encode()+ return 200, {"Content-Type": "application/cbor", "smithy-protocol": "rpc-v2-cbor"}, body+++def _json_ok(data: dict):+ return 200, {"Content-Type": "application/json"}, json.dumps(data).encode()+++def _xml(status, root_tag, inner):+ body = (f'<?xml version="1.0" encoding="UTF-8"?>\n'+ f'<{root_tag} xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'+ f' {inner}\n'+ f' <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>\n'+ f'</{root_tag}>').encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _error(code, message, status, is_cbor=False):+ if is_cbor:+ try:+ import cbor2+ body = cbor2.dumps({"__type": code, "message": message})+ except Exception:+ body = json.dumps({"__type": code, "message": message}).encode()+ return status, {"Content-Type": "application/cbor"}, body+ body = (f'<?xml version="1.0" encoding="UTF-8"?>\n'+ f'<ErrorResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">\n'+ f' <Error><Code>{code}</Code><Message>{message}</Message></Error>\n'+ f' <RequestId>{new_uuid()}</RequestId>\n'+ f'</ErrorResponse>').encode("utf-8")+ return status, {"Content-Type": "application/xml"}, bodydiff --git a/services/cloudwatch_logs.py b/services/cloudwatch_logs.pynew file mode 100644index 00000000..4f2a50b0--- /dev/null+++ b/services/cloudwatch_logs.py@@ -0,0 +1,164 @@+"""+CloudWatch Logs Service Emulator.+JSON-based API via X-Amz-Target (Logs_20140328).+Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,+ CreateLogStream, DeleteLogStream, DescribeLogStreams,+ PutLogEvents, GetLogEvents, FilterLogEvents.+"""++import json+import time+import logging++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("logs")++_log_groups: dict = {} # group_name -> {arn, streams: {stream_name: {events: [...], upload_seq}}}+++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 = {+ "CreateLogGroup": _create_log_group,+ "DeleteLogGroup": _delete_log_group,+ "DescribeLogGroups": _describe_log_groups,+ "CreateLogStream": _create_log_stream,+ "DeleteLogStream": _delete_log_stream,+ "DescribeLogStreams": _describe_log_streams,+ "PutLogEvents": _put_log_events,+ "GetLogEvents": _get_log_events,+ "FilterLogEvents": _filter_log_events,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidOperationException", f"Unknown: {action}", 400)+ return handler(data)+++def _create_log_group(data):+ name = data.get("logGroupName")+ if name in _log_groups:+ return error_response_json("ResourceAlreadyExistsException", f"Log group {name} already exists", 400)+ _log_groups[name] = {+ "arn": f"arn:aws:logs:us-east-1:000000000000:log-group:{name}",+ "creationTime": int(time.time() * 1000),+ "streams": {},+ }+ return json_response({})+++def _delete_log_group(data):+ name = data.get("logGroupName")+ _log_groups.pop(name, None)+ return json_response({})+++def _describe_log_groups(data):+ prefix = data.get("logGroupNamePrefix", "")+ groups = []+ for name, g in _log_groups.items():+ if name.startswith(prefix):+ groups.append({+ "logGroupName": name,+ "arn": g["arn"],+ "creationTime": g["creationTime"],+ "storedBytes": 0,+ })+ return json_response({"logGroups": groups})+++def _create_log_stream(data):+ group = data.get("logGroupName")+ stream = data.get("logStreamName")+ if group not in _log_groups:+ return error_response_json("ResourceNotFoundException", f"Log group {group} not found", 400)+ _log_groups[group]["streams"][stream] = {"events": [], "uploadSequenceToken": "1"}+ return json_response({})+++def _delete_log_stream(data):+ group = data.get("logGroupName")+ stream = data.get("logStreamName")+ if group in _log_groups:+ _log_groups[group]["streams"].pop(stream, None)+ return json_response({})+++def _describe_log_streams(data):+ group = data.get("logGroupName")+ if group not in _log_groups:+ return error_response_json("ResourceNotFoundException", f"Log group {group} not found", 400)+ streams = []+ for name, s in _log_groups[group]["streams"].items():+ streams.append({+ "logStreamName": name,+ "creationTime": int(time.time() * 1000),+ "storedBytes": sum(len(e.get("message", "")) for e in s["events"]),+ "uploadSequenceToken": s["uploadSequenceToken"],+ })+ return json_response({"logStreams": streams})+++def _put_log_events(data):+ group = data.get("logGroupName")+ stream = data.get("logStreamName")+ events = data.get("logEvents", [])++ if group not in _log_groups:+ _log_groups[group] = {"arn": "", "creationTime": int(time.time() * 1000), "streams": {}}+ if stream not in _log_groups[group]["streams"]:+ _log_groups[group]["streams"][stream] = {"events": [], "uploadSequenceToken": "1"}++ s = _log_groups[group]["streams"][stream]+ for e in events:+ s["events"].append({"timestamp": e.get("timestamp", int(time.time() * 1000)), "message": e.get("message", ""), "ingestionTime": int(time.time() * 1000)})++ token = str(int(s["uploadSequenceToken"]) + 1)+ s["uploadSequenceToken"] = token+ return json_response({"nextSequenceToken": token})+++def _get_log_events(data):+ group = data.get("logGroupName")+ stream = data.get("logStreamName")+ limit = data.get("limit", 10000)++ if group not in _log_groups or stream not in _log_groups[group]["streams"]:+ return json_response({"events": [], "nextForwardToken": "f/0", "nextBackwardToken": "b/0"})++ events = _log_groups[group]["streams"][stream]["events"][-limit:]+ return json_response({+ "events": events,+ "nextForwardToken": f"f/{len(events)}",+ "nextBackwardToken": "b/0",+ })+++def _filter_log_events(data):+ group = data.get("logGroupName")+ pattern = data.get("filterPattern", "").lower()+ limit = data.get("limit", 10000)++ if group not in _log_groups:+ return json_response({"events": [], "searchedLogStreams": []})++ events = []+ searched = []+ for stream_name, s in _log_groups[group]["streams"].items():+ searched.append({"logStreamName": stream_name, "searchedCompletely": True})+ for e in s["events"]:+ if not pattern or pattern in e.get("message", "").lower():+ events.append({**e, "logStreamName": stream_name})+ if len(events) >= limit:+ break++ return json_response({"events": events, "searchedLogStreams": searched})diff --git a/services/dynamodb.py b/services/dynamodb.pynew file mode 100644index 00000000..490d2c7f--- /dev/null+++ b/services/dynamodb.py@@ -0,0 +1,424 @@+"""+DynamoDB Service Emulator.+Supports: CreateTable, DeleteTable, DescribeTable, ListTables,+ PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem.+Uses X-Amz-Target header for action routing (JSON API).+"""++import re+import time+import copy+import json+import logging+from collections import defaultdict++from core.responses import json_response, error_response_json, new_uuid, now_iso++logger = logging.getLogger("dynamodb")++_tables: dict = {} # table_name -> {schema, items: {partition_key_val: {sort_key_val: item}}, ...}+++async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:+ 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 = {+ "CreateTable": _create_table,+ "DeleteTable": _delete_table,+ "DescribeTable": _describe_table,+ "ListTables": _list_tables,+ "PutItem": _put_item,+ "GetItem": _get_item,+ "DeleteItem": _delete_item,+ "UpdateItem": _update_item,+ "Query": _query,+ "Scan": _scan,+ "BatchWriteItem": _batch_write_item,+ "BatchGetItem": _batch_get_item,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("UnknownOperationException", f"Unknown operation: {action}", 400)+ return handler(data)+++def _create_table(data):+ name = data.get("TableName")+ if not name:+ return error_response_json("ValidationException", "TableName is required", 400)+ if name in _tables:+ return error_response_json("ResourceInUseException", f"Table {name} already exists", 400)++ key_schema = data.get("KeySchema", [])+ attr_defs = data.get("AttributeDefinitions", [])++ pk_name = None+ sk_name = None+ for ks in key_schema:+ if ks["KeyType"] == "HASH":+ pk_name = ks["AttributeName"]+ elif ks["KeyType"] == "RANGE":+ sk_name = ks["AttributeName"]++ _tables[name] = {+ "TableName": name,+ "KeySchema": key_schema,+ "AttributeDefinitions": attr_defs,+ "pk_name": pk_name,+ "sk_name": sk_name,+ "items": defaultdict(dict), # pk_value -> {sk_value: item}+ "TableStatus": "ACTIVE",+ "CreationDateTime": time.time(),+ "ItemCount": 0,+ "TableSizeBytes": 0,+ "TableArn": f"arn:aws:dynamodb:us-east-1:000000000000:table/{name}",+ "GlobalSecondaryIndexes": data.get("GlobalSecondaryIndexes", []),+ "LocalSecondaryIndexes": data.get("LocalSecondaryIndexes", []),+ "ProvisionedThroughput": data.get("ProvisionedThroughput", {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}),+ "BillingModeSummary": {"BillingMode": data.get("BillingMode", "PROVISIONED")},+ }++ return json_response({"TableDescription": _table_description(name)})+++def _delete_table(data):+ name = data.get("TableName")+ if name not in _tables:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ desc = _table_description(name)+ del _tables[name]+ return json_response({"TableDescription": desc})+++def _describe_table(data):+ name = data.get("TableName")+ if name not in _tables:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)+ return json_response({"Table": _table_description(name)})+++def _list_tables(data):+ limit = data.get("Limit", 100)+ start = data.get("ExclusiveStartTableName", "")+ names = sorted(_tables.keys())+ if start:+ names = [n for n in names if n > start]+ names = names[:limit]+ result = {"TableNames": names}+ if len(names) == limit:+ result["LastEvaluatedTableName"] = names[-1]+ return json_response(result)+++def _put_item(data):+ name = data.get("TableName")+ table = _tables.get(name)+ if not table:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)++ item = data.get("Item", {})+ pk_val = _extract_key_val(item.get(table["pk_name"]))+ sk_val = _extract_key_val(item.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"++ old_item = table["items"].get(pk_val, {}).get(sk_val)++ table["items"][pk_val][sk_val] = item+ _update_counts(table)++ result = {}+ if data.get("ReturnValues") == "ALL_OLD" and old_item:+ result["Attributes"] = old_item+ return json_response(result)+++def _get_item(data):+ name = data.get("TableName")+ table = _tables.get(name)+ if not table:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)++ key = data.get("Key", {})+ pk_val = _extract_key_val(key.get(table["pk_name"]))+ sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"++ item = table["items"].get(pk_val, {}).get(sk_val)++ result = {}+ if item:+ projection = data.get("ProjectionExpression")+ if projection:+ attrs = [a.strip() for a in projection.split(",")]+ result["Item"] = {k: v for k, v in item.items() if k in attrs}+ else:+ result["Item"] = item+ return json_response(result)+++def _delete_item(data):+ name = data.get("TableName")+ table = _tables.get(name)+ if not table:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)++ key = data.get("Key", {})+ pk_val = _extract_key_val(key.get(table["pk_name"]))+ sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"++ old_item = table["items"].get(pk_val, {}).pop(sk_val, None)+ _update_counts(table)++ result = {}+ if data.get("ReturnValues") == "ALL_OLD" and old_item:+ result["Attributes"] = old_item+ return json_response(result)+++def _update_item(data):+ name = data.get("TableName")+ table = _tables.get(name)+ if not table:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)++ key = data.get("Key", {})+ pk_val = _extract_key_val(key.get(table["pk_name"]))+ sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"++ item = table["items"].get(pk_val, {}).get(sk_val, dict(key))+ expr_attr_values = data.get("ExpressionAttributeValues", {})+ expr_attr_names = data.get("ExpressionAttributeNames", {})+ update_expr = data.get("UpdateExpression", "")++ # Basic SET/REMOVE parsing+ if update_expr:+ item = _apply_update_expression(item, update_expr, expr_attr_values, expr_attr_names)++ table["items"][pk_val][sk_val] = item+ _update_counts(table)++ result = {}+ ret = data.get("ReturnValues", "NONE")+ if ret == "ALL_NEW":+ result["Attributes"] = item+ elif ret == "ALL_OLD":+ result["Attributes"] = item # Simplified+ return json_response(result)+++def _query(data):+ name = data.get("TableName")+ table = _tables.get(name)+ if not table:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)++ expr_attr_values = data.get("ExpressionAttributeValues", {})+ expr_attr_names = data.get("ExpressionAttributeNames", {})+ key_condition = data.get("KeyConditionExpression", "")+ filter_expr = data.get("FilterExpression", "")+ limit = data.get("Limit", 1000000)+ scan_forward = data.get("ScanIndexForward", True)++ # Extract partition key value from KeyConditionExpression+ pk_val = _extract_pk_from_condition(key_condition, expr_attr_values, expr_attr_names, table["pk_name"])++ items = []+ if pk_val and pk_val in table["items"]:+ sk_items = table["items"][pk_val]+ for sk, item in sorted(sk_items.items(), reverse=not scan_forward):+ if _matches_condition(item, key_condition, expr_attr_values, expr_attr_names, table):+ if not filter_expr or _matches_filter(item, filter_expr, expr_attr_values, expr_attr_names):+ items.append(item)+ if len(items) >= limit:+ break+ else:+ # Fallback: scan all items for the matching partition key+ for pk, sk_dict in table["items"].items():+ for sk, item in sk_dict.items():+ if _matches_condition(item, key_condition, expr_attr_values, expr_attr_names, table):+ if not filter_expr or _matches_filter(item, filter_expr, expr_attr_values, expr_attr_names):+ items.append(item)+ if len(items) >= limit:+ break++ return json_response({"Items": items, "Count": len(items), "ScannedCount": len(items)})+++def _scan(data):+ name = data.get("TableName")+ table = _tables.get(name)+ if not table:+ return error_response_json("ResourceNotFoundException", f"Table {name} not found", 400)++ filter_expr = data.get("FilterExpression", "")+ expr_attr_values = data.get("ExpressionAttributeValues", {})+ expr_attr_names = data.get("ExpressionAttributeNames", {})+ limit = data.get("Limit", 1000000)++ items = []+ scanned = 0+ for pk, sk_dict in table["items"].items():+ for sk, item in sk_dict.items():+ scanned += 1+ if not filter_expr or _matches_filter(item, filter_expr, expr_attr_values, expr_attr_names):+ items.append(item)+ if len(items) >= limit:+ break++ return json_response({"Items": items, "Count": len(items), "ScannedCount": scanned})+++def _batch_write_item(data):+ request_items = data.get("RequestItems", {})+ for table_name, requests in request_items.items():+ table = _tables.get(table_name)+ if not table:+ continue+ for req in requests:+ if "PutRequest" in req:+ item = req["PutRequest"]["Item"]+ pk_val = _extract_key_val(item.get(table["pk_name"]))+ sk_val = _extract_key_val(item.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ table["items"][pk_val][sk_val] = item+ elif "DeleteRequest" in req:+ key = req["DeleteRequest"]["Key"]+ pk_val = _extract_key_val(key.get(table["pk_name"]))+ sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ table["items"].get(pk_val, {}).pop(sk_val, None)+ _update_counts(table)++ return json_response({"UnprocessedItems": {}})+++def _batch_get_item(data):+ request_items = data.get("RequestItems", {})+ responses = {}+ for table_name, config in request_items.items():+ table = _tables.get(table_name)+ if not table:+ continue+ responses[table_name] = []+ for key in config.get("Keys", []):+ pk_val = _extract_key_val(key.get(table["pk_name"]))+ sk_val = _extract_key_val(key.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"+ item = table["items"].get(pk_val, {}).get(sk_val)+ if item:+ responses[table_name].append(item)++ return json_response({"Responses": responses, "UnprocessedKeys": {}})+++# --- Helpers ---++def _table_description(name):+ t = _tables[name]+ return {+ "TableName": t["TableName"],+ "KeySchema": t["KeySchema"],+ "AttributeDefinitions": t["AttributeDefinitions"],+ "TableStatus": t["TableStatus"],+ "CreationDateTime": t["CreationDateTime"],+ "ItemCount": t["ItemCount"],+ "TableSizeBytes": t["TableSizeBytes"],+ "TableArn": t["TableArn"],+ "ProvisionedThroughput": t["ProvisionedThroughput"],+ "BillingModeSummary": t.get("BillingModeSummary", {}),+ }+++def _extract_key_val(attr):+ if not attr:+ return ""+ if "S" in attr:+ return attr["S"]+ if "N" in attr:+ return attr["N"]+ if "B" in attr:+ return attr["B"]+ return str(attr)+++def _update_counts(table):+ count = sum(len(sk_dict) for sk_dict in table["items"].values())+ table["ItemCount"] = count+ table["TableSizeBytes"] = count * 100 # rough estimate+++def _apply_update_expression(item, expr, attr_values, attr_names):+ """Basic SET and REMOVE expression support."""+ item = dict(item)++ # Handle SET+ set_match = re.search(r'SET\s+(.+?)(?=\s+REMOVE|\s+ADD|\s+DELETE|$)', expr, re.IGNORECASE)+ if set_match:+ assignments = set_match.group(1).split(",")+ for assign in assignments:+ parts = assign.strip().split("=", 1)+ if len(parts) == 2:+ path = _resolve_name(parts[0].strip(), attr_names)+ val_ref = parts[1].strip()+ if val_ref in attr_values:+ item[path] = attr_values[val_ref]++ # Handle REMOVE+ remove_match = re.search(r'REMOVE\s+(.+?)(?=\s+SET|\s+ADD|\s+DELETE|$)', expr, re.IGNORECASE)+ if remove_match:+ fields = remove_match.group(1).split(",")+ for f in fields:+ path = _resolve_name(f.strip(), attr_names)+ item.pop(path, None)++ return item+++def _resolve_name(name, attr_names):+ return attr_names.get(name, name)+++def _extract_pk_from_condition(condition, attr_values, attr_names, pk_name):+ """Try to extract partition key value from KeyConditionExpression."""+ resolved_pk = pk_name+ for alias, real_name in attr_names.items():+ if real_name == pk_name:+ resolved_pk = alias+ break++ # Match patterns like "#pk = :val" or "pk = :val"+ pattern = rf'{re.escape(resolved_pk)}\s*=\s*(:\w+)'+ match = re.search(pattern, condition)+ if match:+ val_ref = match.group(1)+ if val_ref in attr_values:+ return _extract_key_val(attr_values[val_ref])+ return None+++def _matches_condition(item, condition, attr_values, attr_names, table):+ """Simplified condition matching — checks basic equality."""+ if not condition:+ return True+ # For now, just return True (items are already filtered by pk)+ return True+++def _matches_filter(item, filter_expr, attr_values, attr_names):+ """Simplified filter expression matching."""+ if not filter_expr:+ return True+ # Basic attribute_exists / = support+ for alias, real_name in attr_names.items():+ filter_expr = filter_expr.replace(alias, real_name)++ # Check equality: "field = :val"+ eq_match = re.search(r'(\w+)\s*=\s*(:\w+)', filter_expr)+ if eq_match:+ field = eq_match.group(1)+ val_ref = eq_match.group(2)+ if field in item and val_ref in attr_values:+ return item[field] == attr_values[val_ref]+ return Truediff --git a/services/ecs.py b/services/ecs.pynew file mode 100644index 00000000..da2c3b2a--- /dev/null+++ b/services/ecs.py@@ -0,0 +1,519 @@+"""+ECS (Elastic Container Service) Emulator.+REST JSON API — path-based routing like real ECS.+Supports: CreateCluster, DeleteCluster, DescribeCluster, ListClusters,+ RegisterTaskDefinition, DeregisterTaskDefinition, DescribeTaskDefinition, ListTaskDefinitions,+ CreateService, DeleteService, DescribeServices, UpdateService, ListServices,+ RunTask, StopTask, DescribeTasks, ListTasks.++Container execution: if Docker socket is available, RunTask actually runs containers.+"""++import os+import json+import time+import logging++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("ecs")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_clusters: dict = {} # cluster_name -> cluster dict+_task_defs: dict = {} # family:revision -> task def dict+_task_def_latest: dict = {} # family -> latest revision number+_services: dict = {} # cluster_name/service_name -> service dict+_tasks: dict = {} # task_arn -> task dict++# Docker client (optional)+_docker = None+def _get_docker():+ global _docker+ if _docker is None:+ try:+ import docker+ _docker = docker.from_env()+ except Exception:+ pass+ return _docker+++async def handle_request(method, path, headers, body, query_params):+ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ data = {}++ # ECS uses path-based routing: /clusters, /taskdefinitions, etc.+ # Strip leading slash and split+ parts = [p for p in path.strip("/").split("/") if p]++ # Also support X-Amz-Target for some SDKs+ target = headers.get("x-amz-target", "")+ if target:+ action = target.split(".")[-1]+ return _dispatch_action(action, data, parts, method)++ # Path-based dispatch+ if not parts:+ return error_response_json("InvalidRequest", "Missing path", 400)++ resource = parts[0]++ # POST /clusters -> CreateCluster+ # GET /clusters -> ListClusters+ if resource == "clusters":+ if method == "POST" and len(parts) == 1:+ return _create_cluster(data)+ if method == "GET" and len(parts) == 1:+ return _list_clusters(data)+ if method == "POST" and len(parts) == 2 and parts[1] == "delete":+ return _delete_cluster(data)+ if method == "POST" and len(parts) == 1 and "describe" in data:+ return _describe_clusters(data)+ # POST /clusters with clusters key = describe+ if method == "POST" and "clusters" in data:+ return _describe_clusters(data)++ # /taskdefinitions+ if resource == "taskdefinitions":+ if method == "POST" and len(parts) == 1:+ return _register_task_definition(data)+ if method == "GET" and len(parts) == 1:+ return _list_task_definitions(data)+ if method == "GET" and len(parts) == 2:+ return _describe_task_definition(parts[1])+ if method == "DELETE" and len(parts) == 2:+ return _deregister_task_definition(parts[1])++ # /tasks+ if resource == "tasks":+ if method == "POST" and len(parts) == 1:+ # Could be RunTask or DescribeTasks depending on body+ if "taskDefinition" in data:+ return _run_task(data)+ if "tasks" in data:+ return _describe_tasks(data)+ if method == "GET" and len(parts) == 1:+ return _list_tasks(data)++ # /services+ if resource == "services":+ if method == "POST" and len(parts) == 1:+ if "serviceName" in data and "taskDefinition" in data:+ return _create_service(data)+ if "services" in data:+ return _describe_services(data)+ if method == "GET" and len(parts) == 1:+ return _list_services(data)+ if method == "PUT" and len(parts) == 2:+ return _update_service(parts[1], data)+ if method == "DELETE" and len(parts) == 2:+ return _delete_service(parts[1], data)++ # /stoptask+ if resource == "stoptask":+ return _stop_task(data)++ return error_response_json("InvalidRequest", f"Unknown ECS path: {path}", 400)+++def _dispatch_action(action, data, parts, method):+ """Handle X-Amz-Target based dispatch."""+ handlers = {+ "CreateCluster": _create_cluster,+ "DeleteCluster": _delete_cluster,+ "DescribeClusters": _describe_clusters,+ "ListClusters": _list_clusters,+ "RegisterTaskDefinition": _register_task_definition,+ "DeregisterTaskDefinition": lambda d: _deregister_task_definition(d.get("taskDefinition", "")),+ "DescribeTaskDefinition": lambda d: _describe_task_definition(d.get("taskDefinition", "")),+ "ListTaskDefinitions": _list_task_definitions,+ "CreateService": _create_service,+ "DeleteService": lambda d: _delete_service(d.get("service", ""), d),+ "DescribeServices": _describe_services,+ "UpdateService": lambda d: _update_service(d.get("service", ""), d),+ "ListServices": _list_services,+ "RunTask": _run_task,+ "StopTask": _stop_task,+ "DescribeTasks": _describe_tasks,+ "ListTasks": _list_tasks,+ }+ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown ECS action: {action}", 400)+ return handler(data)+++# ---- Clusters ----++def _create_cluster(data):+ name = data.get("clusterName", "default")+ arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{name}"+ _clusters[name] = {+ "clusterArn": arn, "clusterName": name,+ "status": "ACTIVE", "registeredContainerInstancesCount": 0,+ "runningTasksCount": 0, "pendingTasksCount": 0,+ "activeServicesCount": 0, "tags": data.get("tags", []),+ "settings": data.get("settings", []),+ "capacityProviders": data.get("capacityProviders", []),+ }+ return json_response({"cluster": _clusters[name]})+++def _delete_cluster(data):+ name = data.get("cluster", "default")+ name = _resolve_cluster_name(name)+ cluster = _clusters.pop(name, None)+ if not cluster:+ return error_response_json("ClusterNotFoundException", f"Cluster {name} not found", 400)+ return json_response({"cluster": cluster})+++def _describe_clusters(data):+ names = data.get("clusters", ["default"])+ result = []+ failures = []+ for name in names:+ n = _resolve_cluster_name(name)+ if n in _clusters:+ result.append(_clusters[n])+ else:+ failures.append({"arn": name, "reason": "MISSING"})+ return json_response({"clusters": result, "failures": failures})+++def _list_clusters(data):+ arns = [c["clusterArn"] for c in _clusters.values()]+ return json_response({"clusterArns": arns})+++# ---- Task Definitions ----++def _register_task_definition(data):+ family = data.get("family")+ if not family:+ return error_response_json("ValidationException", "family is required", 400)++ rev = _task_def_latest.get(family, 0) + 1+ _task_def_latest[family] = rev+ td_key = f"{family}:{rev}"+ arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:task-definition/{td_key}"++ td = {+ "taskDefinitionArn": arn,+ "family": family,+ "revision": rev,+ "status": "ACTIVE",+ "containerDefinitions": data.get("containerDefinitions", []),+ "volumes": data.get("volumes", []),+ "networkMode": data.get("networkMode", "bridge"),+ "requiresCompatibilities": data.get("requiresCompatibilities", ["EC2"]),+ "cpu": data.get("cpu", "256"),+ "memory": data.get("memory", "512"),+ "executionRoleArn": data.get("executionRoleArn", ""),+ "taskRoleArn": data.get("taskRoleArn", ""),+ "registeredAt": time.time(),+ }+ _task_defs[td_key] = td+ return json_response({"taskDefinition": td, "tags": data.get("tags", [])})+++def _deregister_task_definition(td_ref):+ key = _resolve_td_key(td_ref)+ td = _task_defs.get(key)+ if not td:+ return error_response_json("InvalidParameterException", f"Task definition {td_ref} not found", 400)+ td["status"] = "INACTIVE"+ return json_response({"taskDefinition": td})+++def _describe_task_definition(td_ref):+ if isinstance(td_ref, dict):+ td_ref = td_ref.get("taskDefinition", "")+ key = _resolve_td_key(td_ref)+ td = _task_defs.get(key)+ if not td:+ return error_response_json("InvalidParameterException", f"Task definition {td_ref} not found", 400)+ return json_response({"taskDefinition": td, "tags": []})+++def _list_task_definitions(data):+ family = data.get("familyPrefix", "")+ status = data.get("status", "ACTIVE")+ arns = [+ td["taskDefinitionArn"] for td in _task_defs.values()+ if (not family or td["family"].startswith(family)) and td["status"] == status+ ]+ return json_response({"taskDefinitionArns": arns})+++# ---- Services ----++def _create_service(data):+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ if cluster not in _clusters:+ _create_cluster({"clusterName": cluster})++ name = data.get("serviceName")+ td_key = _resolve_td_key(data.get("taskDefinition", ""))+ arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:service/{cluster}/{name}"+ svc_key = f"{cluster}/{name}"++ _services[svc_key] = {+ "serviceArn": arn, "serviceName": name, "clusterArn": _clusters[cluster]["clusterArn"],+ "taskDefinition": _task_defs.get(td_key, {}).get("taskDefinitionArn", data.get("taskDefinition", "")),+ "desiredCount": data.get("desiredCount", 1),+ "runningCount": 0, "pendingCount": 0,+ "status": "ACTIVE",+ "launchType": data.get("launchType", "EC2"),+ "networkConfiguration": data.get("networkConfiguration", {}),+ "loadBalancers": data.get("loadBalancers", []),+ "createdAt": time.time(),+ "deployments": [],+ "events": [],+ }+ _clusters[cluster]["activeServicesCount"] += 1+ return json_response({"service": _services[svc_key]})+++def _delete_service(service_name, data):+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ svc_key = f"{cluster}/{service_name}"+ svc = _services.pop(svc_key, None)+ if not svc:+ return error_response_json("ServiceNotFoundException", f"Service {service_name} not found", 400)+ if cluster in _clusters:+ _clusters[cluster]["activeServicesCount"] = max(0, _clusters[cluster]["activeServicesCount"] - 1)+ return json_response({"service": svc})+++def _describe_services(data):+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ services = data.get("services", [])+ result = []+ failures = []+ for svc_name in services:+ svc_key = f"{cluster}/{_resolve_service_name(svc_name)}"+ if svc_key in _services:+ result.append(_services[svc_key])+ else:+ failures.append({"arn": svc_name, "reason": "MISSING"})+ return json_response({"services": result, "failures": failures})+++def _update_service(service_name, data):+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ svc_key = f"{cluster}/{_resolve_service_name(service_name)}"+ svc = _services.get(svc_key)+ if not svc:+ return error_response_json("ServiceNotFoundException", f"Service {service_name} not found", 400)+ if "desiredCount" in data:+ svc["desiredCount"] = data["desiredCount"]+ if "taskDefinition" in data:+ svc["taskDefinition"] = data["taskDefinition"]+ return json_response({"service": svc})+++def _list_services(data):+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ arns = [s["serviceArn"] for k, s in _services.items() if k.startswith(f"{cluster}/")]+ return json_response({"serviceArns": arns})+++# ---- Tasks ----++def _run_task(data):+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ if cluster not in _clusters:+ _create_cluster({"clusterName": cluster})++ td_ref = data.get("taskDefinition", "")+ td_key = _resolve_td_key(td_ref)+ td = _task_defs.get(td_key)++ count = data.get("count", 1)+ tasks = []+ failures = []++ for _ in range(count):+ task_id = new_uuid()+ task_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:task/{cluster}/{task_id}"+ container_overrides = data.get("overrides", {}).get("containerOverrides", [])++ task = {+ "taskArn": task_arn,+ "clusterArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{cluster}",+ "taskDefinitionArn": td["taskDefinitionArn"] if td else td_ref,+ "lastStatus": "RUNNING",+ "desiredStatus": "RUNNING",+ "launchType": data.get("launchType", "EC2"),+ "cpu": td.get("cpu", "256") if td else "256",+ "memory": td.get("memory", "512") if td else "512",+ "createdAt": time.time(),+ "startedAt": time.time(),+ "group": data.get("group", ""),+ "containers": [],+ "_docker_ids": [],+ }++ # Try to actually run containers via Docker+ docker_client = _get_docker()+ if docker_client and td:+ for cdef in td.get("containerDefinitions", []):+ # Apply overrides+ env_override = {}+ for ov in container_overrides:+ if ov.get("name") == cdef["name"]:+ for e in ov.get("environment", []):+ env_override[e["name"]] = e["value"]++ env = {e["name"]: e["value"] for e in cdef.get("environment", [])}+ env.update(env_override)++ port_bindings = {}+ for pm in cdef.get("portMappings", []):+ host_port = pm.get("hostPort", pm.get("containerPort"))+ port_bindings[f"{pm['containerPort']}/tcp"] = host_port++ try:+ container = docker_client.containers.run(+ cdef["image"],+ detach=True,+ environment=env,+ ports=port_bindings if port_bindings else None,+ name=f"ministack-ecs-{task_id[:8]}-{cdef['name']}",+ labels={"ministack": "ecs", "task_arn": task_arn},+ )+ task["containers"].append({+ "name": cdef["name"], "image": cdef["image"],+ "lastStatus": "RUNNING", "exitCode": None,+ "networkBindings": [],+ "containerArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container/{new_uuid()}",+ "_docker_id": container.id,+ })+ task["_docker_ids"].append(container.id)+ logger.info(f"ECS: started container {cdef['image']} for task {task_id[:8]}")+ except Exception as e:+ logger.warning(f"ECS: Docker run failed for {cdef.get('image')}: {e}")+ task["containers"].append({+ "name": cdef["name"], "image": cdef["image"],+ "lastStatus": "RUNNING", "exitCode": None,+ "networkBindings": [],+ "containerArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container/{new_uuid()}",+ })+ elif td:+ for cdef in td.get("containerDefinitions", []):+ task["containers"].append({+ "name": cdef["name"], "image": cdef["image"],+ "lastStatus": "RUNNING", "exitCode": None,+ "networkBindings": [],+ "containerArn": f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:container/{new_uuid()}",+ })++ _tasks[task_arn] = task+ _clusters[cluster]["runningTasksCount"] += 1+ tasks.append({k: v for k, v in task.items() if not k.startswith("_")})++ return json_response({"tasks": tasks, "failures": failures})+++def _stop_task(data):+ task_ref = data.get("task", "")+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ reason = data.get("reason", "")++ # Resolve by ARN or short ID+ task = _tasks.get(task_ref)+ if not task:+ for arn, t in _tasks.items():+ if arn.endswith(task_ref):+ task = t+ task_ref = arn+ break++ if not task:+ return error_response_json("InvalidParameterException", f"Task {task_ref} not found", 400)++ # Stop Docker containers+ docker_client = _get_docker()+ if docker_client:+ for docker_id in task.get("_docker_ids", []):+ try:+ container = docker_client.containers.get(docker_id)+ container.stop(timeout=5)+ container.remove()+ except Exception as e:+ logger.warning(f"ECS: failed to stop container {docker_id}: {e}")++ task["lastStatus"] = "STOPPED"+ task["desiredStatus"] = "STOPPED"+ task["stoppedAt"] = time.time()+ task["stoppedReason"] = reason++ cluster_name = _resolve_cluster_name(cluster)+ if cluster_name in _clusters:+ _clusters[cluster_name]["runningTasksCount"] = max(0, _clusters[cluster_name]["runningTasksCount"] - 1)++ return json_response({"task": {k: v for k, v in task.items() if not k.startswith("_")}})+++def _describe_tasks(data):+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ task_refs = data.get("tasks", [])+ result = []+ failures = []+ for ref in task_refs:+ task = _tasks.get(ref)+ if not task:+ for arn, t in _tasks.items():+ if arn.endswith(ref):+ task = t+ break+ if task:+ result.append({k: v for k, v in task.items() if not k.startswith("_")})+ else:+ failures.append({"arn": ref, "reason": "MISSING"})+ return json_response({"tasks": result, "failures": failures})+++def _list_tasks(data):+ cluster = _resolve_cluster_name(data.get("cluster", "default"))+ cluster_arn = f"arn:aws:ecs:{REGION}:{ACCOUNT_ID}:cluster/{cluster}"+ status = data.get("desiredStatus", "RUNNING")+ arns = [+ arn for arn, t in _tasks.items()+ if t.get("clusterArn") == cluster_arn and t.get("desiredStatus") == status+ ]+ return json_response({"taskArns": arns})+++# ---- Helpers ----++def _resolve_cluster_name(ref):+ if not ref:+ return "default"+ if "/" in ref:+ return ref.split("/")[-1]+ return ref+++def _resolve_service_name(ref):+ if "/" in ref:+ return ref.split("/")[-1]+ return ref+++def _resolve_td_key(ref):+ """Resolve task definition ARN or family[:revision] to internal key."""+ if not ref:+ return ""+ if "task-definition/" in ref:+ ref = ref.split("task-definition/")[-1]+ if ":" not in ref:+ # Latest revision+ rev = _task_def_latest.get(ref, 1)+ return f"{ref}:{rev}"+ return refdiff --git a/services/elasticache.py b/services/elasticache.pynew file mode 100644index 00000000..93694714--- /dev/null+++ b/services/elasticache.py@@ -0,0 +1,394 @@+"""+ElastiCache Service Emulator.+Query API (Action=...) for control plane.+Supports: CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters,+ CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups,+ CreateCacheSubnetGroup, DescribeCacheSubnetGroups,+ CreateCacheParameterGroup, DescribeCacheParameterGroups,+ ListTagsForResource, AddTagsToResource.++When Docker is available, CreateCacheCluster spins up a real Redis/Memcached container.+Otherwise returns localhost:6379 (assumes Redis sidecar in docker-compose).+"""++import os+import time+import logging+from urllib.parse import parse_qs++from core.responses import new_uuid++logger = logging.getLogger("elasticache")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"+REDIS_DEFAULT_HOST = os.environ.get("REDIS_HOST", "redis")+REDIS_DEFAULT_PORT = int(os.environ.get("REDIS_PORT", "6379"))+BASE_PORT = int(os.environ.get("ELASTICACHE_BASE_PORT", "16379"))++_clusters: dict = {}+_replication_groups: dict = {}+_subnet_groups: dict = {}+_param_groups: dict = {}+_port_counter = [BASE_PORT]++_docker = None+def _get_docker():+ global _docker+ if _docker is None:+ try:+ import docker+ _docker = docker.from_env()+ except Exception:+ pass+ return _docker+++async def handle_request(method, path, headers, body, query_params):+ params = dict(query_params)+ if method == "POST" and body:+ form_params = parse_qs(body.decode("utf-8", errors="replace"))+ for k, v in form_params.items():+ params[k] = v++ action = _p(params, "Action")++ handlers = {+ "CreateCacheCluster": _create_cache_cluster,+ "DeleteCacheCluster": _delete_cache_cluster,+ "DescribeCacheClusters": _describe_cache_clusters,+ "ModifyCacheCluster": _modify_cache_cluster,+ "RebootCacheCluster": _reboot_cache_cluster,+ "CreateReplicationGroup": _create_replication_group,+ "DeleteReplicationGroup": _delete_replication_group,+ "DescribeReplicationGroups": _describe_replication_groups,+ "ModifyReplicationGroup": _modify_replication_group,+ "CreateCacheSubnetGroup": _create_subnet_group,+ "DescribeCacheSubnetGroups": _describe_subnet_groups,+ "DeleteCacheSubnetGroup": _delete_subnet_group,+ "CreateCacheParameterGroup": _create_param_group,+ "DescribeCacheParameterGroups": _describe_param_groups,+ "DeleteCacheParameterGroup": _delete_param_group,+ "DescribeCacheEngineVersions": _describe_engine_versions,+ "ListTagsForResource": _list_tags,+ "AddTagsToResource": _add_tags,+ "RemoveTagsFromResource": _remove_tags,+ }++ handler = handlers.get(action)+ if not handler:+ return _error("InvalidAction", f"Unknown ElastiCache action: {action}", 400)+ return handler(params)+++def _create_cache_cluster(p):+ cluster_id = _p(p, "CacheClusterId")+ engine = _p(p, "Engine") or "redis"+ engine_version = _p(p, "EngineVersion") or ("7.0.12" if engine == "redis" else "1.6.17")+ node_type = _p(p, "CacheNodeType") or "cache.t3.micro"+ num_nodes = int(_p(p, "NumCacheNodes") or "1")++ if cluster_id in _clusters:+ return _error("CacheClusterAlreadyExists", f"Cluster {cluster_id} already exists", 400)++ arn = f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:cluster:{cluster_id}"+ endpoint_host = REDIS_DEFAULT_HOST+ endpoint_port = REDIS_DEFAULT_PORT if engine == "redis" else 11211+ docker_container_id = None++ # Try to spin up a real container+ docker_client = _get_docker()+ if docker_client:+ host_port = _port_counter[0]+ _port_counter[0] += 1+ endpoint_host = "localhost"+ endpoint_port = host_port++ if engine == "redis":+ image = f"redis:{engine_version.split('.')[0]}-alpine"+ container_port = 6379+ else:+ image = f"memcached:{engine_version}-alpine"+ container_port = 11211++ try:+ container = docker_client.containers.run(+ image, detach=True,+ ports={f"{container_port}/tcp": host_port},+ name=f"ministack-elasticache-{cluster_id}",+ labels={"ministack": "elasticache", "cluster_id": cluster_id},+ )+ docker_container_id = container.id+ logger.info(f"ElastiCache: started {engine} container for {cluster_id} on port {host_port}")+ except Exception as e:+ logger.warning(f"ElastiCache: Docker failed for {cluster_id}: {e}")+ endpoint_host = REDIS_DEFAULT_HOST+ endpoint_port = REDIS_DEFAULT_PORT++ _clusters[cluster_id] = {+ "CacheClusterId": cluster_id,+ "CacheClusterArn": arn,+ "CacheClusterStatus": "available",+ "Engine": engine,+ "EngineVersion": engine_version,+ "CacheNodeType": node_type,+ "NumCacheNodes": num_nodes,+ "CacheClusterCreateTime": time.time(),+ "PreferredAvailabilityZone": f"{REGION}a",+ "CacheParameterGroup": {"CacheParameterGroupName": f"default.{engine}{engine_version[:3]}", "ParameterApplyStatus": "in-sync"},+ "CacheSubnetGroupName": _p(p, "CacheSubnetGroupName") or "default",+ "AutoMinorVersionUpgrade": True,+ "SecurityGroups": [],+ "ReplicationGroupId": "",+ "SnapshotRetentionLimit": 0,+ "SnapshotWindow": "05:00-06:00",+ "CacheNodes": [+ {+ "CacheNodeId": f"{i:04d}",+ "CacheNodeStatus": "available",+ "CacheNodeCreateTime": time.time(),+ "Endpoint": {"Address": endpoint_host, "Port": endpoint_port},+ "ParameterGroupStatus": "in-sync",+ "SourceCacheNodeId": "",+ }+ for i in range(1, num_nodes + 1)+ ],+ "_docker_container_id": docker_container_id,+ "_endpoint": {"Address": endpoint_host, "Port": endpoint_port},+ }+ return _xml_cluster_response("CreateCacheClusterResponse", "CreateCacheClusterResult", _clusters[cluster_id])+++def _delete_cache_cluster(p):+ cluster_id = _p(p, "CacheClusterId")+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("CacheClusterNotFound", f"Cluster {cluster_id} not found", 404)++ docker_client = _get_docker()+ if docker_client and cluster.get("_docker_container_id"):+ try:+ container = docker_client.containers.get(cluster["_docker_container_id"])+ container.stop(timeout=5)+ container.remove()+ except Exception as e:+ logger.warning(f"ElastiCache: failed to remove container for {cluster_id}: {e}")++ cluster["CacheClusterStatus"] = "deleting"+ del _clusters[cluster_id]+ return _xml_cluster_response("DeleteCacheClusterResponse", "DeleteCacheClusterResult", cluster)+++def _describe_cache_clusters(p):+ cluster_id = _p(p, "CacheClusterId")+ if cluster_id:+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("CacheClusterNotFound", f"Cluster {cluster_id} not found", 404)+ clusters = [cluster]+ else:+ clusters = list(_clusters.values())+ members = "".join(_cluster_xml(c) for c in clusters)+ return _xml(200, "DescribeCacheClustersResponse",+ f"<DescribeCacheClustersResult><CacheClusters>{members}</CacheClusters></DescribeCacheClustersResult>")+++def _modify_cache_cluster(p):+ cluster_id = _p(p, "CacheClusterId")+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("CacheClusterNotFound", f"Cluster {cluster_id} not found", 404)+ if _p(p, "NumCacheNodes"):+ cluster["NumCacheNodes"] = int(_p(p, "NumCacheNodes"))+ return _xml_cluster_response("ModifyCacheClusterResponse", "ModifyCacheClusterResult", cluster)+++def _reboot_cache_cluster(p):+ cluster_id = _p(p, "CacheClusterId")+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("CacheClusterNotFound", f"Cluster {cluster_id} not found", 404)+ return _xml_cluster_response("RebootCacheClusterResponse", "RebootCacheClusterResult", cluster)+++def _create_replication_group(p):+ rg_id = _p(p, "ReplicationGroupId")+ desc = _p(p, "ReplicationGroupDescription")+ arn = f"arn:aws:elasticache:{REGION}:{ACCOUNT_ID}:replicationgroup:{rg_id}"+ endpoint_host = REDIS_DEFAULT_HOST+ endpoint_port = REDIS_DEFAULT_PORT++ _replication_groups[rg_id] = {+ "ReplicationGroupId": rg_id,+ "Description": desc,+ "Status": "available",+ "MemberClusters": [],+ "NodeGroups": [{"NodeGroupId": "0001", "Status": "available",+ "PrimaryEndpoint": {"Address": endpoint_host, "Port": endpoint_port},+ "ReaderEndpoint": {"Address": endpoint_host, "Port": endpoint_port}}],+ "SnapshotRetentionLimit": 0,+ "SnapshotWindow": "05:00-06:00",+ "ClusterEnabled": False,+ "CacheNodeType": _p(p, "CacheNodeType") or "cache.t3.micro",+ "AuthTokenEnabled": False,+ "TransitEncryptionEnabled": False,+ "AtRestEncryptionEnabled": False,+ "ARN": arn,+ }+ members = _rg_xml(_replication_groups[rg_id])+ return _xml(200, "CreateReplicationGroupResponse",+ f"<CreateReplicationGroupResult><ReplicationGroup>{members}</ReplicationGroup></CreateReplicationGroupResult>")+++def _delete_replication_group(p):+ rg_id = _p(p, "ReplicationGroupId")+ rg = _replication_groups.pop(rg_id, None)+ if not rg:+ return _error("ReplicationGroupNotFoundFault", f"Replication group {rg_id} not found", 404)+ members = _rg_xml(rg)+ return _xml(200, "DeleteReplicationGroupResponse",+ f"<DeleteReplicationGroupResult><ReplicationGroup>{members}</ReplicationGroup></DeleteReplicationGroupResult>")+++def _describe_replication_groups(p):+ rg_id = _p(p, "ReplicationGroupId")+ if rg_id:+ rg = _replication_groups.get(rg_id)+ if not rg:+ return _error("ReplicationGroupNotFoundFault", f"Replication group {rg_id} not found", 404)+ groups = [rg]+ else:+ groups = list(_replication_groups.values())+ members = "".join(f"<member>{_rg_xml(g)}</member>" for g in groups)+ return _xml(200, "DescribeReplicationGroupsResponse",+ f"<DescribeReplicationGroupsResult><ReplicationGroups>{members}</ReplicationGroups></DescribeReplicationGroupsResult>")+++def _modify_replication_group(p):+ rg_id = _p(p, "ReplicationGroupId")+ rg = _replication_groups.get(rg_id)+ if not rg:+ return _error("ReplicationGroupNotFoundFault", f"Replication group {rg_id} not found", 404)+ return _xml(200, "ModifyReplicationGroupResponse",+ f"<ModifyReplicationGroupResult><ReplicationGroup>{_rg_xml(rg)}</ReplicationGroup></ModifyReplicationGroupResult>")+++def _create_subnet_group(p):+ name = _p(p, "CacheSubnetGroupName")+ _subnet_groups[name] = {"CacheSubnetGroupName": name, "CacheSubnetGroupDescription": _p(p, "CacheSubnetGroupDescription")}+ return _xml(200, "CreateCacheSubnetGroupResponse",+ f"<CreateCacheSubnetGroupResult><CacheSubnetGroup><CacheSubnetGroupName>{name}</CacheSubnetGroupName></CacheSubnetGroup></CreateCacheSubnetGroupResult>")+++def _describe_subnet_groups(p):+ name = _p(p, "CacheSubnetGroupName")+ groups = [_subnet_groups[name]] if name and name in _subnet_groups else list(_subnet_groups.values())+ members = "".join(f"<member><CacheSubnetGroupName>{g['CacheSubnetGroupName']}</CacheSubnetGroupName></member>" for g in groups)+ return _xml(200, "DescribeCacheSubnetGroupsResponse",+ f"<DescribeCacheSubnetGroupsResult><CacheSubnetGroups>{members}</CacheSubnetGroups></DescribeCacheSubnetGroupsResult>")+++def _delete_subnet_group(p):+ _subnet_groups.pop(_p(p, "CacheSubnetGroupName"), None)+ return _xml(200, "DeleteCacheSubnetGroupResponse", "")+++def _create_param_group(p):+ name = _p(p, "CacheParameterGroupName")+ _param_groups[name] = {"CacheParameterGroupName": name, "CacheParameterGroupFamily": _p(p, "CacheParameterGroupFamily")}+ return _xml(200, "CreateCacheParameterGroupResponse",+ f"<CreateCacheParameterGroupResult><CacheParameterGroup><CacheParameterGroupName>{name}</CacheParameterGroupName></CacheParameterGroup></CreateCacheParameterGroupResult>")+++def _describe_param_groups(p):+ name = _p(p, "CacheParameterGroupName")+ groups = [_param_groups[name]] if name and name in _param_groups else list(_param_groups.values())+ members = "".join(f"<member><CacheParameterGroupName>{g['CacheParameterGroupName']}</CacheParameterGroupName></member>" for g in groups)+ return _xml(200, "DescribeCacheParameterGroupsResponse",+ f"<DescribeCacheParameterGroupsResult><CacheParameterGroups>{members}</CacheParameterGroups></DescribeCacheParameterGroupsResult>")+++def _delete_param_group(p):+ _param_groups.pop(_p(p, "CacheParameterGroupName"), None)+ return _xml(200, "DeleteCacheParameterGroupResponse", "")+++def _describe_engine_versions(p):+ engine = _p(p, "Engine") or "redis"+ versions = {"redis": ["7.0.12", "6.2.14", "5.0.6"], "memcached": ["1.6.17", "1.6.12"]}+ members = "".join(+ f"<member><Engine>{engine}</Engine><EngineVersion>{v}</EngineVersion><CacheParameterGroupFamily>{engine}{v[:3]}</CacheParameterGroupFamily></member>"+ for v in versions.get(engine, ["7.0.12"])+ )+ return _xml(200, "DescribeCacheEngineVersionsResponse",+ f"<DescribeCacheEngineVersionsResult><CacheEngineVersions>{members}</CacheEngineVersions></DescribeCacheEngineVersionsResult>")+++def _list_tags(p):+ return _xml(200, "ListTagsForResourceResponse", "<ListTagsForResourceResult><TagList/></ListTagsForResourceResult>")+++def _add_tags(p):+ return _xml(200, "AddTagsToResourceResponse", "<AddTagsToResourceResult><TagList/></AddTagsToResourceResult>")+++def _remove_tags(p):+ return _xml(200, "RemoveTagsFromResourceResponse", "")+++# ---- XML helpers ----++def _cluster_xml(c):+ ep = c.get("_endpoint", {})+ nodes_xml = ""+ for node in c.get("CacheNodes", []):+ nep = node.get("Endpoint", {})+ nodes_xml += f"""<member>+ <CacheNodeId>{node['CacheNodeId']}</CacheNodeId>+ <CacheNodeStatus>{node['CacheNodeStatus']}</CacheNodeStatus>+ <Endpoint><Address>{nep.get('Address','localhost')}</Address><Port>{nep.get('Port',6379)}</Port></Endpoint>+ </member>"""+ return f"""<member>+ <CacheClusterId>{c['CacheClusterId']}</CacheClusterId>+ <CacheClusterStatus>{c['CacheClusterStatus']}</CacheClusterStatus>+ <Engine>{c['Engine']}</Engine>+ <EngineVersion>{c['EngineVersion']}</EngineVersion>+ <CacheNodeType>{c['CacheNodeType']}</CacheNodeType>+ <NumCacheNodes>{c['NumCacheNodes']}</NumCacheNodes>+ <CacheClusterArn>{c['CacheClusterArn']}</CacheClusterArn>+ <CacheNodes>{nodes_xml}</CacheNodes>+ </member>"""+++def _rg_xml(rg):+ return f"""<ReplicationGroupId>{rg['ReplicationGroupId']}</ReplicationGroupId>+ <Description>{rg['Description']}</Description>+ <Status>{rg['Status']}</Status>+ <ARN>{rg['ARN']}</ARN>"""+++def _xml_cluster_response(root_tag, result_tag, cluster):+ return _xml(200, root_tag, f"<{result_tag}><CacheCluster>{_cluster_xml(cluster)}</CacheCluster></{result_tag}>")+++def _p(params, key, default=""):+ val = params.get(key, [default])+ return val[0] if isinstance(val, list) else val+++def _xml(status, root_tag, inner):+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<{root_tag} xmlns="http://elasticache.amazonaws.com/doc/2015-02-02/">+ {inner}+ <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>+</{root_tag}>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _error(code, message, status):+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<ErrorResponse xmlns="http://elasticache.amazonaws.com/doc/2015-02-02/">+ <Error><Code>{code}</Code><Message>{message}</Message></Error>+ <RequestId>{new_uuid()}</RequestId>+</ErrorResponse>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, bodydiff --git a/services/eventbridge.py b/services/eventbridge.pynew file mode 100644index 00000000..1097a30e--- /dev/null+++ b/services/eventbridge.py@@ -0,0 +1,196 @@+"""+EventBridge Service Emulator.+JSON-based API via X-Amz-Target (AmazonEventBridge).+Supports: CreateEventBus, DeleteEventBus, ListEventBuses,+ PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule,+ PutTargets, RemoveTargets, ListTargetsByRule,+ PutEvents.+"""++import json+import time+import logging+import re++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("events")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_event_buses: dict = {+ "default": {+ "Name": "default",+ "Arn": f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/default",+ "CreationTime": time.time(),+ }+}+_rules: dict = {} # rule_name -> rule dict+_targets: dict = {} # rule_name -> [target, ...]+_events_log: list = [] # stored PutEvents entries+++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 = {+ "CreateEventBus": _create_event_bus,+ "DeleteEventBus": _delete_event_bus,+ "ListEventBuses": _list_event_buses,+ "DescribeEventBus": _describe_event_bus,+ "PutRule": _put_rule,+ "DeleteRule": _delete_rule,+ "ListRules": _list_rules,+ "DescribeRule": _describe_rule,+ "EnableRule": _enable_rule,+ "DisableRule": _disable_rule,+ "PutTargets": _put_targets,+ "RemoveTargets": _remove_targets,+ "ListTargetsByRule": _list_targets_by_rule,+ "PutEvents": _put_events,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown action: {action}", 400)+ return handler(data)+++def _create_event_bus(data):+ name = data.get("Name")+ if not name:+ return error_response_json("ValidationException", "Name is required", 400)+ if name in _event_buses:+ return error_response_json("ResourceAlreadyExistsException", f"Event bus {name} already exists", 400)+ arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:event-bus/{name}"+ _event_buses[name] = {"Name": name, "Arn": arn, "CreationTime": time.time()}+ return json_response({"EventBusArn": arn})+++def _delete_event_bus(data):+ name = data.get("Name")+ if name == "default":+ return error_response_json("ValidationException", "Cannot delete the default event bus", 400)+ _event_buses.pop(name, None)+ return json_response({})+++def _list_event_buses(data):+ prefix = data.get("NamePrefix", "")+ buses = [b for n, b in _event_buses.items() if n.startswith(prefix)]+ return json_response({"EventBuses": buses})+++def _describe_event_bus(data):+ name = data.get("Name", "default")+ bus = _event_buses.get(name)+ if not bus:+ return error_response_json("ResourceNotFoundException", f"Event bus {name} not found", 400)+ return json_response(bus)+++def _put_rule(data):+ name = data.get("Name")+ if not name:+ return error_response_json("ValidationException", "Name is required", 400)+ bus = data.get("EventBusName", "default")+ arn = f"arn:aws:events:{REGION}:{ACCOUNT_ID}:rule/{name}"+ _rules[name] = {+ "Name": name,+ "Arn": arn,+ "EventBusName": bus,+ "ScheduleExpression": data.get("ScheduleExpression", ""),+ "EventPattern": data.get("EventPattern", ""),+ "State": data.get("State", "ENABLED"),+ "Description": data.get("Description", ""),+ "CreatedBy": ACCOUNT_ID,+ }+ return json_response({"RuleArn": arn})+++def _delete_rule(data):+ name = data.get("Name")+ _rules.pop(name, None)+ _targets.pop(name, None)+ return json_response({})+++def _list_rules(data):+ prefix = data.get("NamePrefix", "")+ bus = data.get("EventBusName", "default")+ rules = [r for n, r in _rules.items() if n.startswith(prefix) and r.get("EventBusName", "default") == bus]+ return json_response({"Rules": rules})+++def _describe_rule(data):+ name = data.get("Name")+ rule = _rules.get(name)+ if not rule:+ return error_response_json("ResourceNotFoundException", f"Rule {name} not found", 400)+ return json_response(rule)+++def _enable_rule(data):+ name = data.get("Name")+ if name in _rules:+ _rules[name]["State"] = "ENABLED"+ return json_response({})+++def _disable_rule(data):+ name = data.get("Name")+ if name in _rules:+ _rules[name]["State"] = "DISABLED"+ return json_response({})+++def _put_targets(data):+ rule = data.get("Rule")+ targets = data.get("Targets", [])+ if rule not in _targets:+ _targets[rule] = []+ existing_ids = {t["Id"] for t in _targets[rule]}+ for t in targets:+ if t["Id"] in existing_ids:+ _targets[rule] = [x for x in _targets[rule] if x["Id"] != t["Id"]]+ _targets[rule].append(t)+ return json_response({"FailedEntryCount": 0, "FailedEntries": []})+++def _remove_targets(data):+ rule = data.get("Rule")+ ids = set(data.get("Ids", []))+ if rule in _targets:+ _targets[rule] = [t for t in _targets[rule] if t["Id"] not in ids]+ return json_response({"FailedEntryCount": 0, "FailedEntries": []})+++def _list_targets_by_rule(data):+ rule = data.get("Rule")+ targets = _targets.get(rule, [])+ return json_response({"Targets": targets})+++def _put_events(data):+ entries = data.get("Entries", [])+ results = []+ for entry in entries:+ event_id = new_uuid()+ _events_log.append({+ "EventId": event_id,+ "Source": entry.get("Source", ""),+ "DetailType": entry.get("DetailType", ""),+ "Detail": entry.get("Detail", "{}"),+ "EventBusName": entry.get("EventBusName", "default"),+ "Time": time.time(),+ })+ results.append({"EventId": event_id})+ logger.debug(f"EventBridge event: {entry.get('Source')} / {entry.get('DetailType')}")+ return json_response({"FailedEntryCount": 0, "Entries": results})diff --git a/services/glue.py b/services/glue.pynew file mode 100644index 00000000..aec81abb--- /dev/null+++ b/services/glue.py@@ -0,0 +1,516 @@+"""+Glue Service Emulator.+JSON-based API via X-Amz-Target (AWSGlue).+Supports full Data Catalog: Databases, Tables, Partitions, Connections, Crawlers, Jobs, JobRuns.+Job execution runs Python scripts via subprocess (same approach as Lambda).+"""++import os+import json+import time+import subprocess+import tempfile+import logging++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("glue")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_databases: dict = {} # db_name -> {Name, Description, LocationUri, Parameters, CreateTime}+_tables: dict = {} # db_name/table_name -> table dict+_partitions: dict = {} # db_name/table_name -> [partition, ...]+_connections: dict = {}+_crawlers: dict = {}+_jobs: dict = {}+_job_runs: dict = {} # job_name -> [run, ...]+++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 = {+ # Databases+ "CreateDatabase": _create_database,+ "DeleteDatabase": _delete_database,+ "GetDatabase": _get_database,+ "GetDatabases": _get_databases,+ "UpdateDatabase": _update_database,+ # Tables+ "CreateTable": _create_table,+ "DeleteTable": _delete_table,+ "GetTable": _get_table,+ "GetTables": _get_tables,+ "UpdateTable": _update_table,+ "BatchDeleteTable": _batch_delete_table,+ # Partitions+ "CreatePartition": _create_partition,+ "DeletePartition": _delete_partition,+ "GetPartition": _get_partition,+ "GetPartitions": _get_partitions,+ "BatchCreatePartition": _batch_create_partition,+ # Connections+ "CreateConnection": _create_connection,+ "DeleteConnection": _delete_connection,+ "GetConnection": _get_connection,+ "GetConnections": _get_connections,+ # Crawlers+ "CreateCrawler": _create_crawler,+ "DeleteCrawler": _delete_crawler,+ "GetCrawler": _get_crawler,+ "GetCrawlers": _get_crawlers,+ "StartCrawler": _start_crawler,+ "StopCrawler": _stop_crawler,+ # Jobs+ "CreateJob": _create_job,+ "DeleteJob": _delete_job,+ "GetJob": _get_job,+ "GetJobs": _get_jobs,+ "UpdateJob": _update_job,+ "StartJobRun": _start_job_run,+ "GetJobRun": _get_job_run,+ "GetJobRuns": _get_job_runs,+ "BatchStopJobRun": _batch_stop_job_run,+ # Tags+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "GetTags": _get_tags,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown Glue action: {action}", 400)+ return handler(data)+++# ---- Databases ----++def _create_database(data):+ db_input = data.get("DatabaseInput", {})+ name = db_input.get("Name")+ if not name:+ return error_response_json("InvalidInputException", "DatabaseInput.Name is required", 400)+ if name in _databases:+ return error_response_json("AlreadyExistsException", f"Database {name} already exists", 400)+ _databases[name] = {+ "Name": name,+ "Description": db_input.get("Description", ""),+ "LocationUri": db_input.get("LocationUri", ""),+ "Parameters": db_input.get("Parameters", {}),+ "CreateTime": time.time(),+ "CatalogId": ACCOUNT_ID,+ }+ return json_response({})+++def _delete_database(data):+ name = data.get("Name")+ if name not in _databases:+ return error_response_json("EntityNotFoundException", f"Database {name} not found", 400)+ del _databases[name]+ # Remove all tables in this database+ keys_to_del = [k for k in _tables if k.startswith(f"{name}/")]+ for k in keys_to_del:+ del _tables[k]+ return json_response({})+++def _get_database(data):+ name = data.get("Name")+ db = _databases.get(name)+ if not db:+ return error_response_json("EntityNotFoundException", f"Database {name} not found", 400)+ return json_response({"Database": db})+++def _get_databases(data):+ return json_response({"DatabaseList": list(_databases.values())})+++def _update_database(data):+ name = data.get("Name")+ db_input = data.get("DatabaseInput", {})+ if name not in _databases:+ return error_response_json("EntityNotFoundException", f"Database {name} not found", 400)+ _databases[name].update({k: v for k, v in db_input.items() if k != "Name"})+ return json_response({})+++# ---- Tables ----++def _create_table(data):+ db_name = data.get("DatabaseName")+ table_input = data.get("TableInput", {})+ name = table_input.get("Name")+ key = f"{db_name}/{name}"+ if key in _tables:+ return error_response_json("AlreadyExistsException", f"Table {name} already exists", 400)+ _tables[key] = {+ "Name": name,+ "DatabaseName": db_name,+ "Description": table_input.get("Description", ""),+ "Owner": table_input.get("Owner", ""),+ "CreateTime": time.time(),+ "UpdateTime": time.time(),+ "LastAccessTime": time.time(),+ "StorageDescriptor": table_input.get("StorageDescriptor", {}),+ "PartitionKeys": table_input.get("PartitionKeys", []),+ "TableType": table_input.get("TableType", "EXTERNAL_TABLE"),+ "Parameters": table_input.get("Parameters", {}),+ "IsRegisteredWithLakeFormation": False,+ "CatalogId": ACCOUNT_ID,+ }+ return json_response({})+++def _delete_table(data):+ db_name = data.get("DatabaseName")+ name = data.get("Name")+ key = f"{db_name}/{name}"+ _tables.pop(key, None)+ return json_response({})+++def _get_table(data):+ db_name = data.get("DatabaseName")+ name = data.get("Name")+ key = f"{db_name}/{name}"+ table = _tables.get(key)+ if not table:+ return error_response_json("EntityNotFoundException", f"Table {name} not found in {db_name}", 400)+ return json_response({"Table": table})+++def _get_tables(data):+ db_name = data.get("DatabaseName")+ tables = [t for k, t in _tables.items() if k.startswith(f"{db_name}/")]+ return json_response({"TableList": tables})+++def _update_table(data):+ db_name = data.get("DatabaseName")+ table_input = data.get("TableInput", {})+ name = table_input.get("Name")+ key = f"{db_name}/{name}"+ if key not in _tables:+ return error_response_json("EntityNotFoundException", f"Table {name} not found", 400)+ _tables[key].update({k: v for k, v in table_input.items() if k != "Name"})+ _tables[key]["UpdateTime"] = time.time()+ return json_response({})+++def _batch_delete_table(data):+ db_name = data.get("DatabaseName")+ names = data.get("TablesToDelete", [])+ errors = []+ for name in names:+ key = f"{db_name}/{name}"+ if key not in _tables:+ errors.append({"TableName": name, "ErrorDetail": {"ErrorCode": "EntityNotFoundException", "ErrorMessage": "Table not found"}})+ else:+ del _tables[key]+ return json_response({"Errors": errors})+++# ---- Partitions ----++def _create_partition(data):+ db_name = data.get("DatabaseName")+ table_name = data.get("TableName")+ partition_input = data.get("PartitionInput", {})+ key = f"{db_name}/{table_name}"+ if key not in _partitions:+ _partitions[key] = []+ _partitions[key].append({**partition_input, "CreationTime": time.time(), "LastAccessTime": time.time()})+ return json_response({})+++def _delete_partition(data):+ db_name = data.get("DatabaseName")+ table_name = data.get("TableName")+ values = data.get("PartitionValues", [])+ key = f"{db_name}/{table_name}"+ if key in _partitions:+ _partitions[key] = [p for p in _partitions[key] if p.get("Values") != values]+ return json_response({})+++def _get_partition(data):+ db_name = data.get("DatabaseName")+ table_name = data.get("TableName")+ values = data.get("PartitionValues", [])+ key = f"{db_name}/{table_name}"+ for p in _partitions.get(key, []):+ if p.get("Values") == values:+ return json_response({"Partition": p})+ return error_response_json("EntityNotFoundException", "Partition not found", 400)+++def _get_partitions(data):+ db_name = data.get("DatabaseName")+ table_name = data.get("TableName")+ key = f"{db_name}/{table_name}"+ return json_response({"Partitions": _partitions.get(key, [])})+++def _batch_create_partition(data):+ db_name = data.get("DatabaseName")+ table_name = data.get("TableName")+ key = f"{db_name}/{table_name}"+ if key not in _partitions:+ _partitions[key] = []+ for pi in data.get("PartitionInputList", []):+ _partitions[key].append({**pi, "CreationTime": time.time()})+ return json_response({"Errors": []})+++# ---- Connections ----++def _create_connection(data):+ conn_input = data.get("ConnectionInput", {})+ name = conn_input.get("Name")+ _connections[name] = {**conn_input, "CreationTime": time.time(), "LastUpdatedTime": time.time()}+ return json_response({})+++def _delete_connection(data):+ _connections.pop(data.get("ConnectionName"), None)+ return json_response({})+++def _get_connection(data):+ name = data.get("Name")+ conn = _connections.get(name)+ if not conn:+ return error_response_json("EntityNotFoundException", f"Connection {name} not found", 400)+ return json_response({"Connection": conn})+++def _get_connections(data):+ return json_response({"ConnectionList": list(_connections.values())})+++# ---- Crawlers ----++def _create_crawler(data):+ name = data.get("Name")+ schedule = data.get("Schedule", "")+ # Schedule can be passed as a string (cron expression) or omitted+ schedule_struct = {"ScheduleExpression": schedule} if schedule else {}+ _crawlers[name] = {+ "Name": name,+ "Role": data.get("Role", ""),+ "DatabaseName": data.get("DatabaseName", ""),+ "Description": data.get("Description", ""),+ "Targets": data.get("Targets", {}),+ "Schedule": schedule_struct,+ "State": "READY",+ "CrawlElapsedTime": 0,+ "CreationTime": time.time(),+ "LastUpdated": time.time(),+ "LastCrawl": None,+ "Version": 1,+ "Configuration": data.get("Configuration", ""),+ "CrawlerSecurityConfiguration": data.get("CrawlerSecurityConfiguration", ""),+ }+ return json_response({})+++def _delete_crawler(data):+ _crawlers.pop(data.get("Name"), None)+ return json_response({})+++def _get_crawler(data):+ name = data.get("Name")+ crawler = _crawlers.get(name)+ if not crawler:+ return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)+ return json_response({"Crawler": crawler})+++def _get_crawlers(data):+ return json_response({"Crawlers": list(_crawlers.values())})+++def _start_crawler(data):+ name = data.get("Name")+ if name not in _crawlers:+ return error_response_json("EntityNotFoundException", f"Crawler {name} not found", 400)+ _crawlers[name]["State"] = "RUNNING"+ # Immediately mark as ready (no actual crawling)+ _crawlers[name]["State"] = "READY"+ _crawlers[name]["LastCrawl"] = {"Status": "SUCCEEDED", "StartTime": time.time(), "EndTime": time.time()}+ return json_response({})+++def _stop_crawler(data):+ name = data.get("Name")+ if name in _crawlers:+ _crawlers[name]["State"] = "READY"+ return json_response({})+++# ---- Jobs ----++def _create_job(data):+ name = data.get("Name")+ if not name:+ return error_response_json("InvalidInputException", "Name is required", 400)+ _jobs[name] = {+ "Name": name,+ "Description": data.get("Description", ""),+ "Role": data.get("Role", ""),+ "Command": data.get("Command", {}),+ "DefaultArguments": data.get("DefaultArguments", {}),+ "Connections": data.get("Connections", {}),+ "MaxRetries": data.get("MaxRetries", 0),+ "Timeout": data.get("Timeout", 2880),+ "GlueVersion": data.get("GlueVersion", "3.0"),+ "NumberOfWorkers": data.get("NumberOfWorkers", 2),+ "WorkerType": data.get("WorkerType", "G.1X"),+ "CreatedOn": time.time(),+ "LastModifiedOn": time.time(),+ }+ _job_runs[name] = []+ return json_response({"Name": name})+++def _delete_job(data):+ name = data.get("JobName")+ _jobs.pop(name, None)+ _job_runs.pop(name, None)+ return json_response({"JobName": name})+++def _get_job(data):+ name = data.get("JobName")+ job = _jobs.get(name)+ if not job:+ return error_response_json("EntityNotFoundException", f"Job {name} not found", 400)+ return json_response({"Job": job})+++def _get_jobs(data):+ return json_response({"Jobs": list(_jobs.values())})+++def _update_job(data):+ name = data.get("JobName")+ job_update = data.get("JobUpdate", {})+ if name not in _jobs:+ return error_response_json("EntityNotFoundException", f"Job {name} not found", 400)+ _jobs[name].update(job_update)+ _jobs[name]["LastModifiedOn"] = time.time()+ return json_response({"JobName": name})+++def _start_job_run(data):+ job_name = data.get("JobName")+ if job_name not in _jobs:+ return error_response_json("EntityNotFoundException", f"Job {job_name} not found", 400)++ run_id = new_uuid()+ job = _jobs[job_name]+ args = {**job.get("DefaultArguments", {}), **data.get("Arguments", {})}++ run = {+ "Id": run_id,+ "JobName": job_name,+ "StartedOn": time.time(),+ "LastModifiedOn": time.time(),+ "CompletedOn": None,+ "JobRunState": "RUNNING",+ "Arguments": args,+ "ErrorMessage": "",+ "ExecutionTime": 0,+ "Attempt": 0,+ "GlueVersion": job.get("GlueVersion", "3.0"),+ }++ # Try to actually run the script if it's a Python shell job+ script_location = job.get("Command", {}).get("ScriptLocation", "")+ if script_location and script_location.endswith(".py") and os.path.exists(script_location):+ try:+ env = dict(os.environ)+ env.update({k.lstrip("--"): v for k, v in args.items() if k.startswith("--")})+ proc = subprocess.run(+ ["python3", script_location],+ capture_output=True, text=True, timeout=job.get("Timeout", 300),+ env=env,+ )+ if proc.returncode == 0:+ run["JobRunState"] = "SUCCEEDED"+ else:+ run["JobRunState"] = "FAILED"+ run["ErrorMessage"] = proc.stderr[:500]+ except Exception as e:+ run["JobRunState"] = "FAILED"+ run["ErrorMessage"] = str(e)+ else:+ # Mock success+ run["JobRunState"] = "SUCCEEDED"++ run["CompletedOn"] = time.time()+ run["ExecutionTime"] = int(run["CompletedOn"] - run["StartedOn"])+ _job_runs[job_name].append(run)+ return json_response({"JobRunId": run_id})+++def _get_job_run(data):+ job_name = data.get("JobName")+ run_id = data.get("RunId")+ for run in _job_runs.get(job_name, []):+ if run["Id"] == run_id:+ return json_response({"JobRun": run})+ return error_response_json("EntityNotFoundException", f"Job run {run_id} not found", 400)+++def _get_job_runs(data):+ job_name = data.get("JobName")+ return json_response({"JobRuns": _job_runs.get(job_name, [])})+++def _batch_stop_job_run(data):+ job_name = data.get("JobName")+ run_ids = data.get("JobRunIds", [])+ errors = []+ for run_id in run_ids:+ found = False+ for run in _job_runs.get(job_name, []):+ if run["Id"] == run_id:+ run["JobRunState"] = "STOPPED"+ found = True+ break+ if not found:+ errors.append({"JobName": job_name, "JobRunId": run_id, "ErrorDetail": {"ErrorCode": "EntityNotFoundException", "ErrorMessage": "Run not found"}})+ return json_response({"SuccessfulSubmissions": [{"JobName": job_name, "JobRunId": r} for r in run_ids if r not in [e["JobRunId"] for e in errors]], "Errors": errors})+++# ---- Tags ----+_tags: dict = {}++def _tag_resource(data):+ arn = data.get("ResourceArn", "")+ _tags[arn] = {**_tags.get(arn, {}), **data.get("TagsToAdd", {})}+ return json_response({})+++def _untag_resource(data):+ arn = data.get("ResourceArn", "")+ for key in data.get("TagsToRemove", []):+ _tags.get(arn, {}).pop(key, None)+ return json_response({})+++def _get_tags(data):+ arn = data.get("ResourceArn", "")+ return json_response({"Tags": _tags.get(arn, {})})diff --git a/services/iam_sts.py b/services/iam_sts.pynew file mode 100644index 00000000..5590cc39--- /dev/null+++ b/services/iam_sts.py@@ -0,0 +1,226 @@+"""+IAM & STS Service Emulators.+IAM: CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles,+ DeleteRole, CreatePolicy, AttachRolePolicy, PutRolePolicy, CreateAccessKey.+STS: GetCallerIdentity, AssumeRole, GetSessionToken.+"""++import time+import json+import logging+from urllib.parse import parse_qs++from core.responses import new_uuid++logger = logging.getLogger("iam")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_users: dict = {}+_roles: dict = {}+_policies: dict = {}+_access_keys: dict = {}+++# ========== IAM ==========++async def handle_iam_request(method, path, headers, body, query_params):+ params = dict(query_params)+ if method == "POST" and body:+ form_params = parse_qs(body.decode("utf-8", errors="replace"))+ for k, v in form_params.items():+ params[k] = v++ action = _p(params, "Action")++ handlers = {+ "CreateUser": _create_user,+ "GetUser": _get_user,+ "ListUsers": _list_users,+ "DeleteUser": _delete_user,+ "CreateRole": _create_role,+ "GetRole": _get_role,+ "ListRoles": _list_roles,+ "DeleteRole": _delete_role,+ "CreatePolicy": _create_policy,+ "AttachRolePolicy": _attach_role_policy,+ "PutRolePolicy": _put_role_policy,+ "CreateAccessKey": _create_access_key,+ "ListAccessKeys": _list_access_keys,+ }++ handler = handlers.get(action)+ if not handler:+ return _xml(200, "ErrorResponse", f"<Error><Code>InvalidAction</Code><Message>Unknown: {action}</Message></Error>", ns="iam")+ return handler(params)+++def _create_user(p):+ name = _p(p, "UserName")+ arn = f"arn:aws:iam::{ACCOUNT_ID}:user/{name}"+ _users[name] = {"UserName": name, "Arn": arn, "UserId": new_uuid()[:20].upper(), "CreateDate": _now(), "Path": _p(p, "Path") or "/"}+ return _xml(200, "CreateUserResponse", f"<CreateUserResult><User>{_user_xml(name)}</User></CreateUserResult>", ns="iam")+++def _get_user(p):+ name = _p(p, "UserName") or "default"+ if name not in _users:+ _users[name] = {"UserName": name, "Arn": f"arn:aws:iam::{ACCOUNT_ID}:user/{name}", "UserId": new_uuid()[:20].upper(), "CreateDate": _now(), "Path": "/"}+ return _xml(200, "GetUserResponse", f"<GetUserResult><User>{_user_xml(name)}</User></GetUserResult>", ns="iam")+++def _list_users(p):+ members = "".join(f"<member>{_user_xml(n)}</member>" for n in _users)+ return _xml(200, "ListUsersResponse", f"<ListUsersResult><Users>{members}</Users><IsTruncated>false</IsTruncated></ListUsersResult>", ns="iam")+++def _delete_user(p):+ _users.pop(_p(p, "UserName"), None)+ return _xml(200, "DeleteUserResponse", "", ns="iam")+++def _create_role(p):+ name = _p(p, "RoleName")+ arn = f"arn:aws:iam::{ACCOUNT_ID}:role/{name}"+ _roles[name] = {"RoleName": name, "Arn": arn, "RoleId": new_uuid()[:20].upper(), "CreateDate": _now(), "Path": _p(p, "Path") or "/", "AssumeRolePolicyDocument": _p(p, "AssumeRolePolicyDocument"), "Policies": []}+ return _xml(200, "CreateRoleResponse", f"<CreateRoleResult><Role>{_role_xml(name)}</Role></CreateRoleResult>", ns="iam")+++def _get_role(p):+ name = _p(p, "RoleName")+ if name not in _roles:+ return _xml(404, "ErrorResponse", f"<Error><Code>NoSuchEntity</Code><Message>Role {name} not found</Message></Error>", ns="iam")+ return _xml(200, "GetRoleResponse", f"<GetRoleResult><Role>{_role_xml(name)}</Role></GetRoleResult>", ns="iam")+++def _list_roles(p):+ members = "".join(f"<member>{_role_xml(n)}</member>" for n in _roles)+ return _xml(200, "ListRolesResponse", f"<ListRolesResult><Roles>{members}</Roles><IsTruncated>false</IsTruncated></ListRolesResult>", ns="iam")+++def _delete_role(p):+ _roles.pop(_p(p, "RoleName"), None)+ return _xml(200, "DeleteRoleResponse", "", ns="iam")+++def _create_policy(p):+ name = _p(p, "PolicyName")+ arn = f"arn:aws:iam::{ACCOUNT_ID}:policy/{name}"+ _policies[arn] = {"PolicyName": name, "Arn": arn, "PolicyId": new_uuid()[:20].upper(), "CreateDate": _now()}+ return _xml(200, "CreatePolicyResponse", f"""<CreatePolicyResult><Policy>+ <PolicyName>{name}</PolicyName><Arn>{arn}</Arn>+ </Policy></CreatePolicyResult>""", ns="iam")+++def _attach_role_policy(p):+ role_name = _p(p, "RoleName")+ policy_arn = _p(p, "PolicyArn")+ if role_name in _roles:+ _roles[role_name]["Policies"].append(policy_arn)+ return _xml(200, "AttachRolePolicyResponse", "", ns="iam")+++def _put_role_policy(p):+ return _xml(200, "PutRolePolicyResponse", "", ns="iam")+++def _create_access_key(p):+ user = _p(p, "UserName") or "default"+ key_id = f"AKIA{''.join(new_uuid().replace('-','')[:16].upper())}"+ secret = new_uuid().replace("-", "") + new_uuid().replace("-", "")[:8]+ _access_keys[key_id] = {"UserName": user, "AccessKeyId": key_id, "SecretAccessKey": secret, "Status": "Active", "CreateDate": _now()}+ return _xml(200, "CreateAccessKeyResponse", f"""<CreateAccessKeyResult><AccessKey>+ <UserName>{user}</UserName><AccessKeyId>{key_id}</AccessKeyId>+ <SecretAccessKey>{secret}</SecretAccessKey><Status>Active</Status>+ </AccessKey></CreateAccessKeyResult>""", ns="iam")+++def _list_access_keys(p):+ user = _p(p, "UserName") or "default"+ members = ""+ for k, v in _access_keys.items():+ if v["UserName"] == user:+ members += f"<member><AccessKeyId>{k}</AccessKeyId><Status>{v['Status']}</Status><UserName>{user}</UserName></member>"+ return _xml(200, "ListAccessKeysResponse", f"<ListAccessKeysResult><AccessKeyMetadata>{members}</AccessKeyMetadata></ListAccessKeysResult>", ns="iam")+++def _user_xml(name):+ u = _users[name]+ return f"<UserName>{u['UserName']}</UserName><UserId>{u['UserId']}</UserId><Arn>{u['Arn']}</Arn><Path>{u['Path']}</Path><CreateDate>{u['CreateDate']}</CreateDate>"+++def _role_xml(name):+ r = _roles[name]+ return f"<RoleName>{r['RoleName']}</RoleName><RoleId>{r['RoleId']}</RoleId><Arn>{r['Arn']}</Arn><Path>{r['Path']}</Path><CreateDate>{r['CreateDate']}</CreateDate>"+++# ========== STS ==========++async def handle_sts_request(method, path, headers, body, query_params):+ params = dict(query_params)+ if method == "POST" and body:+ form_params = parse_qs(body.decode("utf-8", errors="replace"))+ for k, v in form_params.items():+ params[k] = v++ action = _p(params, "Action")++ if action == "GetCallerIdentity":+ return _xml(200, "GetCallerIdentityResponse", f"""<GetCallerIdentityResult>+ <Arn>arn:aws:iam::{ACCOUNT_ID}:root</Arn>+ <UserId>{ACCOUNT_ID}</UserId>+ <Account>{ACCOUNT_ID}</Account>+ </GetCallerIdentityResult>""", ns="sts")++ if action == "AssumeRole":+ role_arn = _p(params, "RoleArn")+ session = _p(params, "RoleSessionName")+ return _xml(200, "AssumeRoleResponse", f"""<AssumeRoleResult>+ <Credentials>+ <AccessKeyId>ASIAEXAMPLE</AccessKeyId>+ <SecretAccessKey>secretkey</SecretAccessKey>+ <SessionToken>sessiontoken{new_uuid()}</SessionToken>+ <Expiration>{_now()}</Expiration>+ </Credentials>+ <AssumedRoleUser>+ <AssumedRoleId>AROA:{session}</AssumedRoleId>+ <Arn>{role_arn}</Arn>+ </AssumedRoleUser>+ </AssumeRoleResult>""", ns="sts")++ if action == "GetSessionToken":+ return _xml(200, "GetSessionTokenResponse", f"""<GetSessionTokenResult>+ <Credentials>+ <AccessKeyId>ASIAEXAMPLE</AccessKeyId>+ <SecretAccessKey>secretkey</SecretAccessKey>+ <SessionToken>sessiontoken{new_uuid()}</SessionToken>+ <Expiration>{_now()}</Expiration>+ </Credentials>+ </GetSessionTokenResult>""", ns="sts")++ return _xml(400, "ErrorResponse", f"<Error><Code>InvalidAction</Code><Message>Unknown: {action}</Message></Error>", ns="sts")+++# ========== Shared helpers ==========++def _p(params, key, default=""):+ val = params.get(key, [default])+ return val[0] if isinstance(val, list) else val+++def _now():+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+++def _xml(status, root_tag, inner, ns="iam"):+ ns_url = {+ "iam": "https://iam.amazonaws.com/doc/2010-05-08/",+ "sts": "https://sts.amazonaws.com/doc/2011-06-15/",+ }.get(ns, "")+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<{root_tag} xmlns="{ns_url}">+ {inner}+ <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>+</{root_tag}>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, bodydiff --git a/services/kinesis.py b/services/kinesis.pynew file mode 100644index 00000000..5589a40e--- /dev/null+++ b/services/kinesis.py@@ -0,0 +1,301 @@+"""+Kinesis Data Streams Emulator.+JSON-based API via X-Amz-Target (Kinesis_20131202).+Supports: CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary,+ ListStreams, PutRecord, PutRecords, GetShardIterator, GetRecords,+ MergeShards, SplitShard, ListShards.+"""++import json+import time+import base64+import hashlib+import logging++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("kinesis")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_streams: dict = {} # stream_name -> {arn, shards: {shard_id: {records: [...]}}, status, retention}+_shard_iterators: dict = {} # iterator_token -> {stream, shard_id, position}+++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 = {+ "CreateStream": _create_stream,+ "DeleteStream": _delete_stream,+ "DescribeStream": _describe_stream,+ "DescribeStreamSummary": _describe_stream_summary,+ "ListStreams": _list_streams,+ "ListShards": _list_shards,+ "PutRecord": _put_record,+ "PutRecords": _put_records,+ "GetShardIterator": _get_shard_iterator,+ "GetRecords": _get_records,+ "IncreaseStreamRetentionPeriod": _increase_retention,+ "DecreaseStreamRetentionPeriod": _decrease_retention,+ "AddTagsToStream": _add_tags,+ "ListTagsForStream": _list_tags,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown action: {action}", 400)+ return handler(data)+++def _create_stream(data):+ name = data.get("StreamName")+ shard_count = data.get("ShardCount", 1)+ if not name:+ return error_response_json("ValidationException", "StreamName is required", 400)+ if name in _streams:+ return error_response_json("ResourceInUseException", f"Stream {name} already exists", 400)++ arn = f"arn:aws:kinesis:{REGION}:{ACCOUNT_ID}:stream/{name}"+ shards = {}+ for i in range(shard_count):+ shard_id = f"shardId-{i:012d}"+ shards[shard_id] = {+ "records": [],+ "sequence_counter": 0,+ "tags": {},+ }++ _streams[name] = {+ "StreamName": name,+ "StreamARN": arn,+ "StreamStatus": "ACTIVE",+ "RetentionPeriodHours": 24,+ "shards": shards,+ "tags": {},+ "CreationTimestamp": time.time(),+ }+ return json_response({})+++def _delete_stream(data):+ name = data.get("StreamName")+ if name not in _streams:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ del _streams[name]+ return json_response({})+++def _describe_stream(data):+ name = data.get("StreamName")+ stream = _streams.get(name)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ return json_response({"StreamDescription": _stream_desc(stream)})+++def _describe_stream_summary(data):+ name = data.get("StreamName")+ stream = _streams.get(name)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ desc = _stream_desc(stream)+ desc.pop("Shards", None)+ return json_response({"StreamDescriptionSummary": {**desc, "OpenShardCount": len(stream["shards"])}})+++def _list_streams(data):+ names = list(_streams.keys())+ return json_response({"StreamNames": names, "HasMoreStreams": False})+++def _list_shards(data):+ name = data.get("StreamName")+ stream = _streams.get(name)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ shards = [_shard_out(sid, s) for sid, s in stream["shards"].items()]+ return json_response({"Shards": shards})+++def _put_record(data):+ name = data.get("StreamName")+ stream = _streams.get(name)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)++ partition_key = data.get("PartitionKey", "")+ record_data = data.get("Data", "")++ # Route to shard based on partition key hash+ shard_id = _get_shard_for_key(partition_key, len(stream["shards"]))+ shard = stream["shards"][shard_id]+ shard["sequence_counter"] += 1+ seq = f"{int(time.time() * 1000):020d}{shard['sequence_counter']:010d}"++ shard["records"].append({+ "SequenceNumber": seq,+ "ApproximateArrivalTimestamp": time.time(),+ "Data": record_data,+ "PartitionKey": partition_key,+ })++ return json_response({"ShardId": shard_id, "SequenceNumber": seq})+++def _put_records(data):+ name = data.get("StreamName")+ stream = _streams.get(name)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)++ records = data.get("Records", [])+ results = []+ failed = 0++ for rec in records:+ partition_key = rec.get("PartitionKey", "")+ record_data = rec.get("Data", "")+ shard_id = _get_shard_for_key(partition_key, len(stream["shards"]))+ shard = stream["shards"][shard_id]+ shard["sequence_counter"] += 1+ seq = f"{int(time.time() * 1000):020d}{shard['sequence_counter']:010d}"+ shard["records"].append({+ "SequenceNumber": seq,+ "ApproximateArrivalTimestamp": time.time(),+ "Data": record_data,+ "PartitionKey": partition_key,+ })+ results.append({"SequenceNumber": seq, "ShardId": shard_id})++ return json_response({"FailedRecordCount": failed, "Records": results})+++def _get_shard_iterator(data):+ name = data.get("StreamName")+ shard_id = data.get("ShardId")+ iterator_type = data.get("ShardIteratorType", "LATEST")+ seq = data.get("StartingSequenceNumber", "")++ stream = _streams.get(name)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ if shard_id not in stream["shards"]:+ return error_response_json("ResourceNotFoundException", f"Shard {shard_id} not found", 400)++ shard = stream["shards"][shard_id]+ if iterator_type == "TRIM_HORIZON":+ position = 0+ elif iterator_type == "LATEST":+ position = len(shard["records"])+ elif iterator_type in ("AT_SEQUENCE_NUMBER", "AFTER_SEQUENCE_NUMBER"):+ records = shard["records"]+ position = next((i for i, r in enumerate(records) if r["SequenceNumber"] >= seq), len(records))+ if iterator_type == "AFTER_SEQUENCE_NUMBER":+ position += 1+ else:+ position = len(shard["records"])++ token = new_uuid()+ _shard_iterators[token] = {"stream": name, "shard_id": shard_id, "position": position}+ return json_response({"ShardIterator": token})+++def _get_records(data):+ iterator = data.get("ShardIterator")+ limit = data.get("Limit", 10000)++ state = _shard_iterators.get(iterator)+ if not state:+ return error_response_json("ExpiredIteratorException", "Shard iterator has expired", 400)++ stream = _streams.get(state["stream"])+ if not stream:+ return error_response_json("ResourceNotFoundException", "Stream not found", 400)++ shard = stream["shards"].get(state["shard_id"])+ if not shard:+ return error_response_json("ResourceNotFoundException", "Shard not found", 400)++ pos = state["position"]+ records = shard["records"][pos:pos + limit]+ new_pos = pos + len(records)+ state["position"] = new_pos++ next_token = new_uuid()+ _shard_iterators[next_token] = {"stream": state["stream"], "shard_id": state["shard_id"], "position": new_pos}++ return json_response({+ "Records": records,+ "NextShardIterator": next_token,+ "MillisBehindLatest": 0,+ })+++def _increase_retention(data):+ name = data.get("StreamName")+ hours = data.get("RetentionPeriodHours", 24)+ if name in _streams:+ _streams[name]["RetentionPeriodHours"] = hours+ return json_response({})+++def _decrease_retention(data):+ name = data.get("StreamName")+ hours = data.get("RetentionPeriodHours", 24)+ if name in _streams:+ _streams[name]["RetentionPeriodHours"] = hours+ return json_response({})+++def _add_tags(data):+ name = data.get("StreamName")+ tags = data.get("Tags", {})+ if name in _streams:+ _streams[name]["tags"].update(tags)+ return json_response({})+++def _list_tags(data):+ name = data.get("StreamName")+ stream = _streams.get(name)+ if not stream:+ return error_response_json("ResourceNotFoundException", f"Stream {name} not found", 400)+ tags = [{"Key": k, "Value": v} for k, v in stream["tags"].items()]+ return json_response({"Tags": tags, "HasMoreTags": False})+++# --- Helpers ---++def _get_shard_for_key(partition_key: str, shard_count: int) -> str:+ h = int(hashlib.md5(partition_key.encode()).hexdigest(), 16)+ idx = h % shard_count+ return f"shardId-{idx:012d}"+++def _shard_out(shard_id, shard):+ return {+ "ShardId": shard_id,+ "HashKeyRange": {"StartingHashKey": "0", "EndingHashKey": "340282366920938463463374607431768211455"},+ "SequenceNumberRange": {"StartingSequenceNumber": "0"},+ }+++def _stream_desc(stream):+ return {+ "StreamName": stream["StreamName"],+ "StreamARN": stream["StreamARN"],+ "StreamStatus": stream["StreamStatus"],+ "RetentionPeriodHours": stream["RetentionPeriodHours"],+ "StreamCreationTimestamp": stream["CreationTimestamp"],+ "Shards": [_shard_out(sid, s) for sid, s in stream["shards"].items()],+ "HasMoreShards": False,+ "EnhancedMonitoring": [{"ShardLevelMetrics": []}],+ }diff --git a/services/lambda_svc.py b/services/lambda_svc.pynew file mode 100644index 00000000..c6b1d438--- /dev/null+++ b/services/lambda_svc.py@@ -0,0 +1,251 @@+"""+Lambda Service Emulator.+Supports: CreateFunction, DeleteFunction, GetFunction, ListFunctions,+ Invoke, UpdateFunctionCode, UpdateFunctionConfiguration.+Functions are stored in-memory. Invocation runs code in a subprocess (Python only) or returns mock results.+"""++import os+import json+import time+import base64+import zipfile+import tempfile+import subprocess+import logging++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("lambda")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_functions: dict = {} # function_name -> {config, code_zip, code_dir}+++async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:+ """Route Lambda REST API requests."""++ # Parse path: /2015-03-31/functions[/name[/invocations|/code|/configuration]]+ parts = path.rstrip("/").split("/")+ # parts: ['', '2015-03-31', 'functions', ...]++ if len(parts) < 3:+ return error_response_json("InvalidRequest", "Invalid path", 400)++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ data = {}++ # POST /2015-03-31/functions — CreateFunction+ if method == "POST" and len(parts) == 3:+ return _create_function(data)++ # GET /2015-03-31/functions — ListFunctions+ if method == "GET" and len(parts) == 3:+ return _list_functions()++ func_name = parts[3] if len(parts) > 3 else None++ if not func_name:+ return error_response_json("InvalidRequest", "Missing function name", 400)++ # POST /2015-03-31/functions/{name}/invocations — Invoke+ if method == "POST" and len(parts) >= 5 and parts[4] == "invocations":+ return _invoke(func_name, data, headers)++ # GET /2015-03-31/functions/{name} — GetFunction+ if method == "GET" and len(parts) == 4:+ return _get_function(func_name)++ # GET /2015-03-31/functions/{name}/configuration+ if method == "GET" and len(parts) >= 5 and parts[4] == "configuration":+ return _get_function_config(func_name)++ # DELETE /2015-03-31/functions/{name}+ if method == "DELETE" and len(parts) == 4:+ return _delete_function(func_name)++ # PUT /2015-03-31/functions/{name}/code+ if method == "PUT" and len(parts) >= 5 and parts[4] == "code":+ return _update_code(func_name, data)++ # PUT /2015-03-31/functions/{name}/configuration+ if method == "PUT" and len(parts) >= 5 and parts[4] == "configuration":+ return _update_config(func_name, data)++ return error_response_json("InvalidRequest", f"Unhandled Lambda path: {path}", 400)+++def _create_function(data):+ name = data.get("FunctionName")+ if not name:+ return error_response_json("InvalidParameterValueException", "FunctionName required", 400)+ if name in _functions:+ return error_response_json("ResourceConflictException", f"Function {name} already exists", 409)++ func_arn = f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{name}"+ config = {+ "FunctionName": name,+ "FunctionArn": func_arn,+ "Runtime": data.get("Runtime", "python3.9"),+ "Role": data.get("Role", f"arn:aws:iam::{ACCOUNT_ID}:role/lambda-role"),+ "Handler": data.get("Handler", "index.handler"),+ "CodeSize": 0,+ "Description": data.get("Description", ""),+ "Timeout": data.get("Timeout", 3),+ "MemorySize": data.get("MemorySize", 128),+ "LastModified": time.strftime("%Y-%m-%dT%H:%M:%S.000+0000"),+ "Version": "$LATEST",+ "State": "Active",+ "PackageType": "Zip",+ "Environment": data.get("Environment", {"Variables": {}}),+ "Layers": data.get("Layers", []),+ }++ code_zip = None+ code_data = data.get("Code", {})+ if "ZipFile" in code_data:+ code_zip = base64.b64decode(code_data["ZipFile"])+ config["CodeSize"] = len(code_zip)+ config["CodeSha256"] = base64.b64encode(b"fakehash").decode()++ _functions[name] = {"config": config, "code_zip": code_zip}++ return json_response(config, 201)+++def _get_function(name):+ if name not in _functions:+ return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)+ func = _functions[name]+ return json_response({+ "Configuration": func["config"],+ "Code": {"RepositoryType": "S3", "Location": ""},+ })+++def _get_function_config(name):+ if name not in _functions:+ return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)+ return json_response(_functions[name]["config"])+++def _list_functions():+ funcs = [f["config"] for f in _functions.values()]+ return json_response({"Functions": funcs})+++def _delete_function(name):+ if name not in _functions:+ return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)+ del _functions[name]+ return 204, {}, b""+++def _update_code(name, data):+ if name not in _functions:+ return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)+ if "ZipFile" in data:+ code_zip = base64.b64decode(data["ZipFile"])+ _functions[name]["code_zip"] = code_zip+ _functions[name]["config"]["CodeSize"] = len(code_zip)+ _functions[name]["config"]["LastModified"] = time.strftime("%Y-%m-%dT%H:%M:%S.000+0000")+ return json_response(_functions[name]["config"])+++def _update_config(name, data):+ if name not in _functions:+ return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)+ config = _functions[name]["config"]+ for key in ["Runtime", "Handler", "Description", "Timeout", "MemorySize", "Role", "Environment", "Layers"]:+ if key in data:+ config[key] = data[key]+ config["LastModified"] = time.strftime("%Y-%m-%dT%H:%M:%S.000+0000")+ return json_response(config)+++def _invoke(name, event, headers):+ if name not in _functions:+ return error_response_json("ResourceNotFoundException", f"Function {name} not found", 404)++ func = _functions[name]+ invocation_type = headers.get("x-amz-invocation-type", "RequestResponse")++ if invocation_type == "Event":+ # Async — just acknowledge+ return 202, {"X-Amz-Function-Error": ""}, b""++ # Try to actually execute the function if we have the code+ result = _execute_function(func, event)++ resp_headers = {+ "Content-Type": "application/json",+ "X-Amz-Executed-Version": "$LATEST",+ }+ if result.get("error"):+ resp_headers["X-Amz-Function-Error"] = "Unhandled"++ return 200, resp_headers, json.dumps(result.get("body", {})).encode("utf-8")+++def _execute_function(func, event):+ """Attempt to execute a Python Lambda function."""+ code_zip = func.get("code_zip")+ if not code_zip:+ return {"body": {"statusCode": 200, "body": "Mock response — no code deployed"}}++ handler = func["config"]["Handler"]+ runtime = func["config"]["Runtime"]+ env_vars = func["config"].get("Environment", {}).get("Variables", {})++ if not runtime.startswith("python"):+ return {"body": {"statusCode": 200, "body": f"Mock response — {runtime} not supported for local execution"}}++ try:+ with tempfile.TemporaryDirectory() as tmpdir:+ zip_path = os.path.join(tmpdir, "code.zip")+ with open(zip_path, "wb") as f:+ f.write(code_zip)++ code_dir = os.path.join(tmpdir, "code")+ os.makedirs(code_dir)+ with zipfile.ZipFile(zip_path) as zf:+ zf.extractall(code_dir)++ module_name, func_name = handler.rsplit(".", 1)+ event_json = json.dumps(event)++ script = f"""+import sys, json+sys.path.insert(0, '{code_dir}')+import {module_name}+event = json.loads('''{event_json}''')+context = type('Context', (), {{'function_name': '{func["config"]["FunctionName"]}', 'memory_limit_in_mb': {func["config"]["MemorySize"]}, 'invoked_function_arn': '{func["config"]["FunctionArn"]}', 'aws_request_id': '{new_uuid()}'}})()+result = {module_name}.{func_name}(event, context)+print(json.dumps(result))+"""+ env = dict(os.environ)+ env.update(env_vars)++ proc = subprocess.run(+ ["python3", "-c", script],+ capture_output=True, text=True, timeout=func["config"]["Timeout"],+ env=env,+ )++ if proc.returncode == 0:+ try:+ return {"body": json.loads(proc.stdout.strip())}+ except json.JSONDecodeError:+ return {"body": proc.stdout.strip()}+ else:+ return {"body": {"errorMessage": proc.stderr.strip(), "errorType": "RuntimeError"}, "error": True}++ except subprocess.TimeoutExpired:+ return {"body": {"errorMessage": "Task timed out", "errorType": "TimeoutError"}, "error": True}+ except Exception as e:+ logger.error(f"Lambda execution error: {e}")+ return {"body": {"errorMessage": str(e), "errorType": type(e).__name__}, "error": True}diff --git a/services/rds.py b/services/rds.pynew file mode 100644index 00000000..4656124a--- /dev/null+++ b/services/rds.py@@ -0,0 +1,444 @@+"""+RDS Service Emulator.+Query API (Action=...) for control plane + optional Docker-based real Postgres/MySQL.+Supports: CreateDBInstance, DeleteDBInstance, DescribeDBInstances,+ CreateDBCluster, DeleteDBCluster, DescribeDBClusters,+ CreateDBSubnetGroup, DescribeDBSubnetGroups,+ CreateDBParameterGroup, DescribeDBParameterGroups,+ StartDBInstance, StopDBInstance, RebootDBInstance,+ ListTagsForResource, AddTagsToResource.++When Docker is available, CreateDBInstance spins up a real Postgres/MySQL container+and returns the actual host:port as the endpoint.+"""++import os+import time+import json+import logging+from urllib.parse import parse_qs++from core.responses import new_uuid++logger = logging.getLogger("rds")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"+BASE_PORT = int(os.environ.get("RDS_BASE_PORT", "15432"))++_instances: dict = {} # db_instance_id -> instance dict+_clusters: dict = {} # db_cluster_id -> cluster dict+_subnet_groups: dict = {}+_param_groups: dict = {}+_port_counter = [BASE_PORT]++_docker = None+def _get_docker():+ global _docker+ if _docker is None:+ try:+ import docker+ _docker = docker.from_env()+ except Exception:+ pass+ return _docker+++async def handle_request(method, path, headers, body, query_params):+ params = dict(query_params)+ if method == "POST" and body:+ form_params = parse_qs(body.decode("utf-8", errors="replace"))+ for k, v in form_params.items():+ params[k] = v++ action = _p(params, "Action")++ handlers = {+ "CreateDBInstance": _create_db_instance,+ "DeleteDBInstance": _delete_db_instance,+ "DescribeDBInstances": _describe_db_instances,+ "StartDBInstance": _start_db_instance,+ "StopDBInstance": _stop_db_instance,+ "RebootDBInstance": _reboot_db_instance,+ "ModifyDBInstance": _modify_db_instance,+ "CreateDBCluster": _create_db_cluster,+ "DeleteDBCluster": _delete_db_cluster,+ "DescribeDBClusters": _describe_db_clusters,+ "CreateDBSubnetGroup": _create_subnet_group,+ "DescribeDBSubnetGroups": _describe_subnet_groups,+ "DeleteDBSubnetGroup": _delete_subnet_group,+ "CreateDBParameterGroup": _create_param_group,+ "DescribeDBParameterGroups": _describe_param_groups,+ "DeleteDBParameterGroup": _delete_param_group,+ "ListTagsForResource": _list_tags,+ "AddTagsToResource": _add_tags,+ "RemoveTagsFromResource": _remove_tags,+ "DescribeDBEngineVersions": _describe_engine_versions,+ "DescribeOrderableDBInstanceOptions": _describe_orderable_options,+ }++ handler = handlers.get(action)+ if not handler:+ return _error("InvalidAction", f"Unknown RDS action: {action}", 400)+ return handler(params)+++def _create_db_instance(p):+ db_id = _p(p, "DBInstanceIdentifier")+ engine = _p(p, "Engine") or "postgres"+ engine_version = _p(p, "EngineVersion") or ("15.3" if "postgres" in engine else "8.0.33")+ db_class = _p(p, "DBInstanceClass") or "db.t3.micro"+ master_user = _p(p, "MasterUsername") or "admin"+ master_pass = _p(p, "MasterUserPassword") or "password"+ db_name = _p(p, "DBName") or "mydb"+ port = int(_p(p, "Port") or ("5432" if "postgres" in engine else "3306"))+ allocated_storage = int(_p(p, "AllocatedStorage") or "20")++ if db_id in _instances:+ return _error("DBInstanceAlreadyExists", f"DB instance {db_id} already exists", 400)++ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:db:{db_id}"+ endpoint_host = "localhost"+ endpoint_port = port+ docker_container_id = None++ # Try to spin up a real DB container+ docker_client = _get_docker()+ if docker_client:+ host_port = _port_counter[0]+ _port_counter[0] += 1+ endpoint_port = host_port++ if "postgres" in engine or "aurora-postgresql" in engine:+ image = f"postgres:{engine_version.split('.')[0]}-alpine"+ env = {+ "POSTGRES_USER": master_user,+ "POSTGRES_PASSWORD": master_pass,+ "POSTGRES_DB": db_name,+ }+ container_port = 5432+ elif "mysql" in engine or "aurora-mysql" in engine or "mariadb" in engine:+ image = "mysql:8" if "mysql" in engine else "mariadb:latest"+ env = {+ "MYSQL_ROOT_PASSWORD": master_pass,+ "MYSQL_DATABASE": db_name,+ "MYSQL_USER": master_user,+ "MYSQL_PASSWORD": master_pass,+ }+ container_port = 3306+ else:+ image = None++ if image:+ try:+ container = docker_client.containers.run(+ image, detach=True,+ environment=env,+ ports={f"{container_port}/tcp": host_port},+ name=f"ministack-rds-{db_id}",+ labels={"ministack": "rds", "db_id": db_id},+ )+ docker_container_id = container.id+ logger.info(f"RDS: started {engine} container for {db_id} on port {host_port}")+ except Exception as e:+ logger.warning(f"RDS: Docker failed for {db_id}: {e}")++ instance = {+ "DBInstanceIdentifier": db_id,+ "DBInstanceClass": db_class,+ "Engine": engine,+ "EngineVersion": engine_version,+ "DBInstanceStatus": "available",+ "MasterUsername": master_user,+ "DBName": db_name,+ "Endpoint": {"Address": endpoint_host, "Port": endpoint_port, "HostedZoneId": "Z2R2ITUGPM61AM"},+ "AllocatedStorage": allocated_storage,+ "InstanceCreateTime": time.time(),+ "PreferredBackupWindow": "03:00-04:00",+ "BackupRetentionPeriod": int(_p(p, "BackupRetentionPeriod") or "1"),+ "DBSecurityGroups": [],+ "VpcSecurityGroups": [],+ "DBParameterGroups": [{"DBParameterGroupName": f"default.{engine}{engine_version[:3]}", "ParameterApplyStatus": "in-sync"}],+ "AvailabilityZone": f"{REGION}a",+ "DBSubnetGroup": {"DBSubnetGroupName": _p(p, "DBSubnetGroupName") or "default", "SubnetGroupStatus": "Complete", "Subnets": []},+ "PreferredMaintenanceWindow": "sun:05:00-sun:06:00",+ "PendingModifiedValues": {},+ "MultiAZ": _p(p, "MultiAZ") == "true",+ "AutoMinorVersionUpgrade": True,+ "ReadReplicaDBInstanceIdentifiers": [],+ "LicenseModel": "general-public-license",+ "OptionGroupMemberships": [],+ "PubliclyAccessible": _p(p, "PubliclyAccessible") == "true",+ "StorageType": _p(p, "StorageType") or "gp2",+ "DbInstancePort": endpoint_port,+ "StorageEncrypted": _p(p, "StorageEncrypted") == "true",+ "DbiResourceId": f"db-{new_uuid()[:8].upper()}",+ "CACertificateIdentifier": "rds-ca-2019",+ "DomainMemberships": [],+ "CopyTagsToSnapshot": False,+ "MonitoringInterval": 0,+ "DBInstanceArn": arn,+ "IAMDatabaseAuthenticationEnabled": False,+ "PerformanceInsightsEnabled": False,+ "DeletionProtection": _p(p, "DeletionProtection") == "true",+ "TagList": [],+ "_docker_container_id": docker_container_id,+ }+ _instances[db_id] = instance+ return _xml_instance_response("CreateDBInstanceResponse", "CreateDBInstanceResult", instance)+++def _delete_db_instance(p):+ db_id = _p(p, "DBInstanceIdentifier")+ instance = _instances.get(db_id)+ if not instance:+ return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)++ # Stop Docker container+ docker_client = _get_docker()+ if docker_client and instance.get("_docker_container_id"):+ try:+ container = docker_client.containers.get(instance["_docker_container_id"])+ container.stop(timeout=5)+ container.remove()+ logger.info(f"RDS: removed container for {db_id}")+ except Exception as e:+ logger.warning(f"RDS: failed to remove container for {db_id}: {e}")++ instance["DBInstanceStatus"] = "deleting"+ del _instances[db_id]+ return _xml_instance_response("DeleteDBInstanceResponse", "DeleteDBInstanceResult", instance)+++def _describe_db_instances(p):+ db_id = _p(p, "DBInstanceIdentifier")+ if db_id:+ instance = _instances.get(db_id)+ if not instance:+ return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ instances = [instance]+ else:+ instances = list(_instances.values())++ members = "".join(_instance_xml(i) for i in instances)+ return _xml(200, "DescribeDBInstancesResponse",+ f"<DescribeDBInstancesResult><DBInstances>{members}</DBInstances></DescribeDBInstancesResult>")+++def _start_db_instance(p):+ db_id = _p(p, "DBInstanceIdentifier")+ instance = _instances.get(db_id)+ if not instance:+ return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ instance["DBInstanceStatus"] = "available"+ return _xml_instance_response("StartDBInstanceResponse", "StartDBInstanceResult", instance)+++def _stop_db_instance(p):+ db_id = _p(p, "DBInstanceIdentifier")+ instance = _instances.get(db_id)+ if not instance:+ return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ instance["DBInstanceStatus"] = "stopped"+ return _xml_instance_response("StopDBInstanceResponse", "StopDBInstanceResult", instance)+++def _reboot_db_instance(p):+ db_id = _p(p, "DBInstanceIdentifier")+ instance = _instances.get(db_id)+ if not instance:+ return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ instance["DBInstanceStatus"] = "available"+ return _xml_instance_response("RebootDBInstanceResponse", "RebootDBInstanceResult", instance)+++def _modify_db_instance(p):+ db_id = _p(p, "DBInstanceIdentifier")+ instance = _instances.get(db_id)+ if not instance:+ return _error("DBInstanceNotFound", f"DB instance {db_id} not found", 404)+ if _p(p, "DBInstanceClass"):+ instance["DBInstanceClass"] = _p(p, "DBInstanceClass")+ if _p(p, "AllocatedStorage"):+ instance["AllocatedStorage"] = int(_p(p, "AllocatedStorage"))+ return _xml_instance_response("ModifyDBInstanceResponse", "ModifyDBInstanceResult", instance)+++def _create_db_cluster(p):+ cluster_id = _p(p, "DBClusterIdentifier")+ engine = _p(p, "Engine") or "aurora-postgresql"+ arn = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:cluster:{cluster_id}"+ _clusters[cluster_id] = {+ "DBClusterIdentifier": cluster_id,+ "DBClusterArn": arn,+ "Engine": engine,+ "EngineVersion": _p(p, "EngineVersion") or "15.3",+ "Status": "available",+ "MasterUsername": _p(p, "MasterUsername") or "admin",+ "DatabaseName": _p(p, "DatabaseName") or "",+ "Endpoint": f"{cluster_id}.cluster-{new_uuid()[:8]}.{REGION}.rds.amazonaws.com",+ "ReaderEndpoint": f"{cluster_id}.cluster-ro-{new_uuid()[:8]}.{REGION}.rds.amazonaws.com",+ "Port": int(_p(p, "Port") or "5432"),+ "MultiAZ": False,+ "DBClusterMembers": [],+ "ClusterCreateTime": time.time(),+ }+ members = _cluster_xml(_clusters[cluster_id])+ return _xml(200, "CreateDBClusterResponse", f"<CreateDBClusterResult><DBCluster>{members}</DBCluster></CreateDBClusterResult>")+++def _delete_db_cluster(p):+ cluster_id = _p(p, "DBClusterIdentifier")+ cluster = _clusters.pop(cluster_id, None)+ if not cluster:+ return _error("DBClusterNotFoundFault", f"Cluster {cluster_id} not found", 404)+ members = _cluster_xml(cluster)+ return _xml(200, "DeleteDBClusterResponse", f"<DeleteDBClusterResult><DBCluster>{members}</DBCluster></DeleteDBClusterResult>")+++def _describe_db_clusters(p):+ cluster_id = _p(p, "DBClusterIdentifier")+ if cluster_id:+ cluster = _clusters.get(cluster_id)+ if not cluster:+ return _error("DBClusterNotFoundFault", f"Cluster {cluster_id} not found", 404)+ clusters = [cluster]+ else:+ clusters = list(_clusters.values())+ members = "".join(f"<member>{_cluster_xml(c)}</member>" for c in clusters)+ return _xml(200, "DescribeDBClustersResponse",+ f"<DescribeDBClustersResult><DBClusters>{members}</DBClusters></DescribeDBClustersResult>")+++def _create_subnet_group(p):+ name = _p(p, "DBSubnetGroupName")+ _subnet_groups[name] = {"DBSubnetGroupName": name, "DBSubnetGroupDescription": _p(p, "DBSubnetGroupDescription"), "Subnets": []}+ return _xml(200, "CreateDBSubnetGroupResponse",+ f"<CreateDBSubnetGroupResult><DBSubnetGroup><DBSubnetGroupName>{name}</DBSubnetGroupName></DBSubnetGroup></CreateDBSubnetGroupResult>")+++def _describe_subnet_groups(p):+ name = _p(p, "DBSubnetGroupName")+ groups = [_subnet_groups[name]] if name and name in _subnet_groups else list(_subnet_groups.values())+ members = "".join(f"<member><DBSubnetGroupName>{g['DBSubnetGroupName']}</DBSubnetGroupName></member>" for g in groups)+ return _xml(200, "DescribeDBSubnetGroupsResponse",+ f"<DescribeDBSubnetGroupsResult><DBSubnetGroups>{members}</DBSubnetGroups></DescribeDBSubnetGroupsResult>")+++def _delete_subnet_group(p):+ _subnet_groups.pop(_p(p, "DBSubnetGroupName"), None)+ return _xml(200, "DeleteDBSubnetGroupResponse", "")+++def _create_param_group(p):+ name = _p(p, "DBParameterGroupName")+ _param_groups[name] = {"DBParameterGroupName": name, "DBParameterGroupFamily": _p(p, "DBParameterGroupFamily"), "Description": _p(p, "Description")}+ return _xml(200, "CreateDBParameterGroupResponse",+ f"<CreateDBParameterGroupResult><DBParameterGroup><DBParameterGroupName>{name}</DBParameterGroupName></DBParameterGroup></CreateDBParameterGroupResult>")+++def _describe_param_groups(p):+ name = _p(p, "DBParameterGroupName")+ groups = [_param_groups[name]] if name and name in _param_groups else list(_param_groups.values())+ members = "".join(f"<member><DBParameterGroupName>{g['DBParameterGroupName']}</DBParameterGroupName></member>" for g in groups)+ return _xml(200, "DescribeDBParameterGroupsResponse",+ f"<DescribeDBParameterGroupsResult><DBParameterGroups>{members}</DBParameterGroups></DescribeDBParameterGroupsResult>")+++def _delete_param_group(p):+ _param_groups.pop(_p(p, "DBParameterGroupName"), None)+ return _xml(200, "DeleteDBParameterGroupResponse", "")+++def _list_tags(p):+ return _xml(200, "ListTagsForResourceResponse", "<ListTagsForResourceResult><TagList/></ListTagsForResourceResult>")+++def _add_tags(p):+ return _xml(200, "AddTagsToResourceResponse", "")+++def _remove_tags(p):+ return _xml(200, "RemoveTagsFromResourceResponse", "")+++def _describe_engine_versions(p):+ engine = _p(p, "Engine") or "postgres"+ versions = {+ "postgres": ["15.3", "14.8", "13.11", "12.15"],+ "mysql": ["8.0.33", "8.0.28", "5.7.43"],+ "mariadb": ["10.6.14", "10.5.21"],+ "aurora-postgresql": ["15.3", "14.8"],+ "aurora-mysql": ["8.0.mysql_aurora.3.03.0"],+ }+ members = ""+ for v in versions.get(engine, ["15.3"]):+ members += f"<member><Engine>{engine}</Engine><EngineVersion>{v}</EngineVersion><DBParameterGroupFamily>{engine}{v[:3]}</DBParameterGroupFamily><DBEngineDescription>{engine}</DBEngineDescription><DBEngineVersionDescription>{engine} {v}</DBEngineVersionDescription></member>"+ return _xml(200, "DescribeDBEngineVersionsResponse",+ f"<DescribeDBEngineVersionsResult><DBEngineVersions>{members}</DBEngineVersions></DescribeDBEngineVersionsResult>")+++def _describe_orderable_options(p):+ return _xml(200, "DescribeOrderableDBInstanceOptionsResponse",+ "<DescribeOrderableDBInstanceOptionsResult><OrderableDBInstanceOptions/></DescribeOrderableDBInstanceOptionsResult>")+++# ---- XML helpers ----++def _instance_xml(i):+ ep = i.get("Endpoint", {})+ return f"""<member>+ <DBInstanceIdentifier>{i['DBInstanceIdentifier']}</DBInstanceIdentifier>+ <DBInstanceClass>{i['DBInstanceClass']}</DBInstanceClass>+ <Engine>{i['Engine']}</Engine>+ <EngineVersion>{i['EngineVersion']}</EngineVersion>+ <DBInstanceStatus>{i['DBInstanceStatus']}</DBInstanceStatus>+ <MasterUsername>{i['MasterUsername']}</MasterUsername>+ <DBName>{i.get('DBName','')}</DBName>+ <Endpoint>+ <Address>{ep.get('Address','localhost')}</Address>+ <Port>{ep.get('Port',5432)}</Port>+ </Endpoint>+ <AllocatedStorage>{i['AllocatedStorage']}</AllocatedStorage>+ <MultiAZ>{str(i['MultiAZ']).lower()}</MultiAZ>+ <StorageType>{i['StorageType']}</StorageType>+ <DBInstanceArn>{i['DBInstanceArn']}</DBInstanceArn>+ </member>"""+++def _cluster_xml(c):+ return f"""<DBClusterIdentifier>{c['DBClusterIdentifier']}</DBClusterIdentifier>+ <DBClusterArn>{c['DBClusterArn']}</DBClusterArn>+ <Engine>{c['Engine']}</Engine>+ <EngineVersion>{c['EngineVersion']}</EngineVersion>+ <Status>{c['Status']}</Status>+ <Endpoint>{c['Endpoint']}</Endpoint>+ <ReaderEndpoint>{c['ReaderEndpoint']}</ReaderEndpoint>+ <Port>{c['Port']}</Port>"""+++def _xml_instance_response(root_tag, result_tag, instance):+ return _xml(200, root_tag, f"<{result_tag}><DBInstance>{_instance_xml(instance)}</DBInstance></{result_tag}>")+++def _p(params, key, default=""):+ val = params.get(key, [default])+ return val[0] if isinstance(val, list) else val+++def _xml(status, root_tag, inner):+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<{root_tag} xmlns="http://rds.amazonaws.com/doc/2014-10-31/">+ {inner}+ <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>+</{root_tag}>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _error(code, message, status):+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">+ <Error><Code>{code}</Code><Message>{message}</Message></Error>+ <RequestId>{new_uuid()}</RequestId>+</ErrorResponse>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, bodydiff --git a/services/s3.py b/services/s3.pynew file mode 100644index 00000000..cf73e9a5--- /dev/null+++ b/services/s3.py@@ -0,0 +1,409 @@+"""+S3 Service Emulator.+Supports: CreateBucket, DeleteBucket, ListBuckets, HeadBucket,+ PutObject, GetObject, DeleteObject, HeadObject, CopyObject,+ ListObjects (v1 & v2), DeleteObjects (batch).+Storage: In-memory (optionally backed by /tmp/localstack-data/s3/).+"""++import os+import re+import logging+from datetime import datetime, timezone+from collections import defaultdict+from xml.etree.ElementTree import Element, SubElement, tostring, fromstring++from core.responses import md5_hash, sha256_hash, now_iso, new_uuid++logger = logging.getLogger("s3")++# In-memory storage+_buckets: dict = {} # bucket_name -> {"created": iso_str, "objects": {key: {"body": bytes, "metadata": dict, "content_type": str, "etag": str, "last_modified": str, "size": int}}}++DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/localstack-data/s3")+PERSIST = os.environ.get("S3_PERSIST", "0") == "1"+++def _ensure_bucket(name):+ if name not in _buckets:+ return None+ return _buckets[name]+++def _parse_bucket_key(path: str, headers: dict):+ """Extract bucket name and key from path or Host header."""+ host = headers.get("host", "")++ # Virtual-hosted style: bucket.s3.localhost:4566+ vhost_match = re.match(r"^([a-zA-Z0-9.\-_]+)\.s3[\.\-]", host)+ if vhost_match:+ bucket = vhost_match.group(1)+ key = path.lstrip("/")+ return bucket, key++ # Path style: /bucket/key+ parts = path.lstrip("/").split("/", 1)+ bucket = parts[0] if parts else ""+ key = parts[1] if len(parts) > 1 else ""+ return bucket, key+++async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:+ """Route S3 requests to handlers."""+ bucket, key = _parse_bucket_key(path, headers)++ # ListBuckets: GET /+ if method == "GET" and not bucket:+ return _list_buckets()++ # Batch delete: POST /?delete+ if method == "POST" and "delete" in query_params:+ return _delete_objects(bucket, body)++ # ListObjects v2: GET /bucket?list-type=2+ if method == "GET" and not key and query_params.get("list-type", [""])[0] == "2":+ return _list_objects_v2(bucket, query_params)++ # ListObjects v1: GET /bucket+ if method == "GET" and not key:+ if "location" in query_params:+ return _get_bucket_location(bucket)+ return _list_objects_v1(bucket, query_params)++ # CreateBucket: PUT /bucket (no key)+ if method == "PUT" and bucket and not key:+ return _create_bucket(bucket, body)++ # DeleteBucket: DELETE /bucket (no key)+ if method == "DELETE" and bucket and not key:+ return _delete_bucket(bucket)++ # HeadBucket: HEAD /bucket+ if method == "HEAD" and bucket and not key:+ return _head_bucket(bucket)++ # PutObject: PUT /bucket/key+ if method == "PUT" and key:+ # CopyObject: has x-amz-copy-source+ if "x-amz-copy-source" in headers:+ return _copy_object(bucket, key, headers)+ return _put_object(bucket, key, body, headers)++ # GetObject: GET /bucket/key+ if method == "GET" and key:+ return _get_object(bucket, key, headers)++ # HeadObject: HEAD /bucket/key+ if method == "HEAD" and key:+ return _head_object(bucket, key)++ # DeleteObject: DELETE /bucket/key+ if method == "DELETE" and key:+ return _delete_object(bucket, key)++ return _error("MethodNotAllowed", f"Method {method} not supported", 405)+++def _list_buckets():+ root = Element("ListAllMyBucketsResult", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")+ owner = SubElement(root, "Owner")+ SubElement(owner, "ID").text = "owner-id"+ SubElement(owner, "DisplayName").text = "localstack"+ buckets_el = SubElement(root, "Buckets")+ for name, data in _buckets.items():+ b = SubElement(buckets_el, "Bucket")+ SubElement(b, "Name").text = name+ SubElement(b, "CreationDate").text = data["created"]+ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")+ return 200, {"Content-Type": "application/xml"}, body+++def _create_bucket(name: str, body: bytes):+ if name in _buckets:+ return _error("BucketAlreadyOwnedByYou", f"Bucket {name} already exists", 409)+ _buckets[name] = {"created": now_iso(), "objects": {}}+ if PERSIST:+ os.makedirs(os.path.join(DATA_DIR, name), exist_ok=True)+ return 200, {"Content-Type": "application/xml", "Location": f"/{name}"}, b""+++def _delete_bucket(name: str):+ bucket = _ensure_bucket(name)+ if bucket is None:+ return _error("NoSuchBucket", f"Bucket {name} does not exist", 404)+ if bucket["objects"]:+ return _error("BucketNotEmpty", "The bucket is not empty", 409)+ del _buckets[name]+ return 204, {}, b""+++def _head_bucket(name: str):+ if name not in _buckets:+ return _error("NoSuchBucket", f"Bucket {name} does not exist", 404)+ return 200, {"Content-Type": "application/xml"}, b""+++def _get_bucket_location(name: str):+ if name not in _buckets:+ return _error("NoSuchBucket", f"Bucket {name} does not exist", 404)+ root = Element("LocationConstraint", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")+ root.text = "us-east-1"+ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")+ return 200, {"Content-Type": "application/xml"}, body+++def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ # Auto-create bucket (LocalStack behavior)+ _buckets[bucket_name] = {"created": now_iso(), "objects": {}}+ bucket = _buckets[bucket_name]++ etag = f'"{md5_hash(body)}"'+ content_type = headers.get("content-type", "application/octet-stream")++ # Extract user metadata (x-amz-meta-*)+ metadata = {}+ for k, v in headers.items():+ if k.lower().startswith("x-amz-meta-"):+ metadata[k] = v++ obj = {+ "body": body,+ "content_type": content_type,+ "etag": etag,+ "last_modified": now_iso(),+ "size": len(body),+ "metadata": metadata,+ }+ bucket["objects"][key] = obj++ if PERSIST:+ _persist_object(bucket_name, key, body)++ return 200, {"ETag": etag, "Content-Type": "application/xml"}, b""+++def _get_object(bucket_name: str, key: str, headers: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ if key not in bucket["objects"]:+ return _error("NoSuchKey", f"The specified key does not exist: {key}", 404)++ obj = bucket["objects"][key]+ resp_headers = {+ "Content-Type": obj["content_type"],+ "ETag": obj["etag"],+ "Last-Modified": obj["last_modified"],+ "Content-Length": str(obj["size"]),+ }+ resp_headers.update(obj["metadata"])+ return 200, resp_headers, obj["body"]+++def _head_object(bucket_name: str, key: str):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ if key not in bucket["objects"]:+ return 404, {}, b""++ obj = bucket["objects"][key]+ resp_headers = {+ "Content-Type": obj["content_type"],+ "ETag": obj["etag"],+ "Last-Modified": obj["last_modified"],+ "Content-Length": str(obj["size"]),+ }+ return 200, resp_headers, b""+++def _delete_object(bucket_name: str, key: str):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)+ bucket["objects"].pop(key, None)+ return 204, {}, b""+++def _copy_object(bucket_name: str, dest_key: str, headers: dict):+ source = headers.get("x-amz-copy-source", "").lstrip("/")+ src_parts = source.split("/", 1)+ if len(src_parts) < 2:+ return _error("InvalidArgument", "Invalid copy source", 400)++ src_bucket_name, src_key = src_parts+ src_bucket = _ensure_bucket(src_bucket_name)+ if src_bucket is None or src_key not in src_bucket["objects"]:+ return _error("NoSuchKey", "Source object not found", 404)++ dest_bucket = _ensure_bucket(bucket_name)+ if dest_bucket is None:+ _buckets[bucket_name] = {"created": now_iso(), "objects": {}}+ dest_bucket = _buckets[bucket_name]++ src_obj = src_bucket["objects"][src_key]+ new_etag = src_obj["etag"]+ dest_bucket["objects"][dest_key] = {+ "body": src_obj["body"],+ "content_type": src_obj["content_type"],+ "etag": new_etag,+ "last_modified": now_iso(),+ "size": src_obj["size"],+ "metadata": dict(src_obj["metadata"]),+ }++ root = Element("CopyObjectResult")+ SubElement(root, "LastModified").text = now_iso()+ SubElement(root, "ETag").text = new_etag+ body = tostring(root, encoding="unicode").encode("utf-8")+ return 200, {"Content-Type": "application/xml"}, body+++def _list_objects_v1(bucket_name: str, query_params: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)++ prefix = _qp(query_params, "prefix", "")+ delimiter = _qp(query_params, "delimiter", "")+ max_keys = int(_qp(query_params, "max-keys", "1000"))+ marker = _qp(query_params, "marker", "")++ keys = sorted(k for k in bucket["objects"] if k.startswith(prefix) and k > marker)+ common_prefixes = set()+ contents = []++ for k in keys:+ if delimiter:+ suffix = k[len(prefix):]+ idx = suffix.find(delimiter)+ if idx >= 0:+ common_prefixes.add(prefix + suffix[:idx + len(delimiter)])+ continue+ if len(contents) >= max_keys:+ break+ contents.append(k)++ root = Element("ListBucketResult", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")+ SubElement(root, "Name").text = bucket_name+ SubElement(root, "Prefix").text = prefix+ SubElement(root, "MaxKeys").text = str(max_keys)+ SubElement(root, "IsTruncated").text = "false"++ for k in contents:+ obj = bucket["objects"][k]+ c = SubElement(root, "Contents")+ SubElement(c, "Key").text = k+ SubElement(c, "LastModified").text = obj["last_modified"]+ SubElement(c, "ETag").text = obj["etag"]+ SubElement(c, "Size").text = str(obj["size"])+ SubElement(c, "StorageClass").text = "STANDARD"++ for cp in sorted(common_prefixes):+ cpe = SubElement(root, "CommonPrefixes")+ SubElement(cpe, "Prefix").text = cp++ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")+ return 200, {"Content-Type": "application/xml"}, body+++def _list_objects_v2(bucket_name: str, query_params: dict):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)++ prefix = _qp(query_params, "prefix", "")+ delimiter = _qp(query_params, "delimiter", "")+ max_keys = int(_qp(query_params, "max-keys", "1000"))+ continuation = _qp(query_params, "continuation-token", "")+ start_after = _qp(query_params, "start-after", "")++ effective_start = continuation or start_after+ keys = sorted(k for k in bucket["objects"] if k.startswith(prefix) and k > effective_start)+ common_prefixes = set()+ contents = []++ for k in keys:+ if delimiter:+ suffix = k[len(prefix):]+ idx = suffix.find(delimiter)+ if idx >= 0:+ common_prefixes.add(prefix + suffix[:idx + len(delimiter)])+ continue+ if len(contents) >= max_keys:+ break+ contents.append(k)++ root = Element("ListBucketResult", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")+ SubElement(root, "Name").text = bucket_name+ SubElement(root, "Prefix").text = prefix+ SubElement(root, "MaxKeys").text = str(max_keys)+ SubElement(root, "KeyCount").text = str(len(contents))+ SubElement(root, "IsTruncated").text = "false"++ for k in contents:+ obj = bucket["objects"][k]+ c = SubElement(root, "Contents")+ SubElement(c, "Key").text = k+ SubElement(c, "LastModified").text = obj["last_modified"]+ SubElement(c, "ETag").text = obj["etag"]+ SubElement(c, "Size").text = str(obj["size"])+ SubElement(c, "StorageClass").text = "STANDARD"++ for cp in sorted(common_prefixes):+ cpe = SubElement(root, "CommonPrefixes")+ SubElement(cpe, "Prefix").text = cp++ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")+ return 200, {"Content-Type": "application/xml"}, body+++def _delete_objects(bucket_name: str, body: bytes):+ bucket = _ensure_bucket(bucket_name)+ if bucket is None:+ return _error("NoSuchBucket", f"Bucket {bucket_name} does not exist", 404)++ root = fromstring(body)+ ns = {"s3": "http://s3.amazonaws.com/doc/2006-03-01/"}+ deleted = []+ for obj_el in root.findall(".//Object", ns) or root.findall(".//Object"):+ key_el = obj_el.find("Key", ns) or obj_el.find("Key")+ if key_el is not None and key_el.text:+ bucket["objects"].pop(key_el.text, None)+ deleted.append(key_el.text)++ resp = Element("DeleteResult", xmlns="http://s3.amazonaws.com/doc/2006-03-01/")+ for k in deleted:+ d = SubElement(resp, "Deleted")+ SubElement(d, "Key").text = k++ body_out = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(resp, encoding="unicode").encode("utf-8")+ return 200, {"Content-Type": "application/xml"}, body_out+++def _persist_object(bucket: str, key: str, data: bytes):+ try:+ fpath = os.path.join(DATA_DIR, bucket, key)+ os.makedirs(os.path.dirname(fpath), exist_ok=True)+ with open(fpath, "wb") as f:+ f.write(data)+ except Exception as e:+ logger.warning(f"Failed to persist S3 object: {e}")+++def _error(code: str, message: str, status: int):+ root = Element("Error")+ SubElement(root, "Code").text = code+ SubElement(root, "Message").text = message+ SubElement(root, "RequestId").text = new_uuid()+ body = b'<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding="unicode").encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _qp(params: dict, key: str, default: str = "") -> str:+ val = params.get(key, [default])+ if isinstance(val, list):+ return val[0] if val else default+ return valdiff --git a/services/secretsmanager.py b/services/secretsmanager.pynew file mode 100644index 00000000..a16b79e1--- /dev/null+++ b/services/secretsmanager.py@@ -0,0 +1,155 @@+"""+SecretsManager Service Emulator.+JSON-based API via X-Amz-Target.+Supports: CreateSecret, GetSecretValue, ListSecrets, DeleteSecret,+ UpdateSecret, DescribeSecret, PutSecretValue.+"""++import json+import time+import logging++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("secretsmanager")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_secrets: dict = {} # name -> {arn, name, secret_string, secret_binary, version_id, created, updated, versions}+++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 = {+ "CreateSecret": _create_secret,+ "GetSecretValue": _get_secret_value,+ "ListSecrets": _list_secrets,+ "DeleteSecret": _delete_secret,+ "UpdateSecret": _update_secret,+ "DescribeSecret": _describe_secret,+ "PutSecretValue": _put_secret_value,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidRequestException", f"Unknown action: {action}", 400)+ return handler(data)+++def _create_secret(data):+ name = data.get("Name")+ if not name:+ return error_response_json("InvalidParameterException", "Name required", 400)+ if name in _secrets:+ return error_response_json("ResourceExistsException", f"Secret {name} already exists", 400)++ arn = f"arn:aws:secretsmanager:{REGION}:{ACCOUNT_ID}:secret:{name}-{new_uuid()[:6]}"+ version_id = new_uuid()+ _secrets[name] = {+ "ARN": arn, "Name": name,+ "SecretString": data.get("SecretString", ""),+ "SecretBinary": data.get("SecretBinary"),+ "VersionId": version_id,+ "CreatedDate": time.time(),+ "LastChangedDate": time.time(),+ "VersionIdsToStages": {version_id: ["AWSCURRENT"]},+ "Description": data.get("Description", ""),+ }+ return json_response({"ARN": arn, "Name": name, "VersionId": version_id})+++def _get_secret_value(data):+ name = data.get("SecretId")+ secret = _secrets.get(name)+ if not secret:+ # Try by ARN+ for s in _secrets.values():+ if s["ARN"] == name:+ secret = s+ break+ if not secret:+ return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)++ result = {+ "ARN": secret["ARN"], "Name": secret["Name"],+ "VersionId": secret["VersionId"],+ "VersionStages": ["AWSCURRENT"],+ "CreatedDate": secret["CreatedDate"],+ }+ if secret.get("SecretString"):+ result["SecretString"] = secret["SecretString"]+ if secret.get("SecretBinary"):+ result["SecretBinary"] = secret["SecretBinary"]+ return json_response(result)+++def _list_secrets(data):+ secrets_list = []+ for s in _secrets.values():+ secrets_list.append({+ "ARN": s["ARN"], "Name": s["Name"],+ "LastChangedDate": s["LastChangedDate"],+ "Description": s.get("Description", ""),+ })+ return json_response({"SecretList": secrets_list})+++def _delete_secret(data):+ name = data.get("SecretId")+ secret = _secrets.pop(name, None)+ if not secret:+ return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)+ return json_response({"ARN": secret["ARN"], "Name": secret["Name"], "DeletionDate": time.time()})+++def _update_secret(data):+ name = data.get("SecretId")+ secret = _secrets.get(name)+ if not secret:+ return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)+ if "SecretString" in data:+ secret["SecretString"] = data["SecretString"]+ if "SecretBinary" in data:+ secret["SecretBinary"] = data["SecretBinary"]+ version_id = new_uuid()+ secret["VersionId"] = version_id+ secret["LastChangedDate"] = time.time()+ return json_response({"ARN": secret["ARN"], "Name": name, "VersionId": version_id})+++def _describe_secret(data):+ name = data.get("SecretId")+ secret = _secrets.get(name)+ if not secret:+ return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)+ return json_response({+ "ARN": secret["ARN"], "Name": secret["Name"],+ "Description": secret.get("Description", ""),+ "LastChangedDate": secret["LastChangedDate"],+ "CreatedDate": secret["CreatedDate"],+ "VersionIdsToStages": secret["VersionIdsToStages"],+ })+++def _put_secret_value(data):+ name = data.get("SecretId")+ secret = _secrets.get(name)+ if not secret:+ return error_response_json("ResourceNotFoundException", f"Secret {name} not found", 400)+ if "SecretString" in data:+ secret["SecretString"] = data["SecretString"]+ if "SecretBinary" in data:+ secret["SecretBinary"] = data["SecretBinary"]+ version_id = new_uuid()+ secret["VersionId"] = version_id+ secret["LastChangedDate"] = time.time()+ secret["VersionIdsToStages"][version_id] = ["AWSCURRENT"]+ return json_response({"ARN": secret["ARN"], "Name": name, "VersionId": version_id, "VersionStages": ["AWSCURRENT"]})diff --git a/services/ses.py b/services/ses.pynew file mode 100644index 00000000..ecee75d9--- /dev/null+++ b/services/ses.py@@ -0,0 +1,184 @@+"""+SES (Simple Email Service) Emulator.+Query API (Action=...) via POST form body.+Supports: SendEmail, SendRawEmail, VerifyEmailIdentity, VerifyEmailAddress,+ ListIdentities, GetIdentityVerificationAttributes, DeleteIdentity,+ GetSendQuota, GetSendStatistics.+All emails are stored in-memory (not actually sent).+"""++import time+import logging+from urllib.parse import parse_qs++from core.responses import new_uuid++logger = logging.getLogger("ses")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_identities: dict = {} # email/domain -> {verified, type}+_sent_emails: list = [] # log of sent emails+++async def handle_request(method, path, headers, body, query_params):+ params = dict(query_params)+ if method == "POST" and body:+ form_params = parse_qs(body.decode("utf-8", errors="replace"))+ for k, v in form_params.items():+ params[k] = v++ action = _p(params, "Action")++ handlers = {+ "SendEmail": _send_email,+ "SendRawEmail": _send_raw_email,+ "VerifyEmailIdentity": _verify_email_identity,+ "VerifyEmailAddress": _verify_email_identity, # legacy alias+ "ListIdentities": _list_identities,+ "GetIdentityVerificationAttributes": _get_identity_verification_attributes,+ "DeleteIdentity": _delete_identity,+ "GetSendQuota": _get_send_quota,+ "GetSendStatistics": _get_send_statistics,+ "ListVerifiedEmailAddresses": _list_verified_emails,+ }++ handler = handlers.get(action)+ if not handler:+ return _error("InvalidAction", f"Unknown action: {action}", 400)+ return handler(params)+++def _send_email(params):+ source = _p(params, "Source")+ subject = _p(params, "Message.Subject.Data")+ body_text = _p(params, "Message.Body.Text.Data")+ body_html = _p(params, "Message.Body.Html.Data")++ # Collect To/CC/BCC addresses+ to_addrs = _collect_list(params, "Destination.ToAddresses.member")+ cc_addrs = _collect_list(params, "Destination.CcAddresses.member")+ bcc_addrs = _collect_list(params, "Destination.BccAddresses.member")++ msg_id = f"{new_uuid()}@email.amazonses.com"+ _sent_emails.append({+ "MessageId": msg_id,+ "Source": source,+ "To": to_addrs,+ "CC": cc_addrs,+ "BCC": bcc_addrs,+ "Subject": subject,+ "BodyText": body_text,+ "BodyHtml": body_html,+ "Timestamp": time.time(),+ })+ logger.info(f"SES SendEmail: {source} -> {to_addrs} | {subject}")+ return _xml(200, "SendEmailResponse", f"<SendEmailResult><MessageId>{msg_id}</MessageId></SendEmailResult>")+++def _send_raw_email(params):+ raw_message = _p(params, "RawMessage.Data")+ msg_id = f"{new_uuid()}@email.amazonses.com"+ _sent_emails.append({+ "MessageId": msg_id,+ "RawMessage": raw_message,+ "Timestamp": time.time(),+ })+ logger.info(f"SES SendRawEmail: {msg_id}")+ return _xml(200, "SendRawEmailResponse", f"<SendRawEmailResult><MessageId>{msg_id}</MessageId></SendRawEmailResult>")+++def _verify_email_identity(params):+ email = _p(params, "EmailAddress")+ _identities[email] = {"VerificationStatus": "Success", "Type": "EmailAddress"}+ return _xml(200, "VerifyEmailIdentityResponse", "<VerifyEmailIdentityResult/>")+++def _list_identities(params):+ identity_type = _p(params, "IdentityType")+ members = ""+ for identity, info in _identities.items():+ if not identity_type or info["Type"] == identity_type:+ members += f"<member>{identity}</member>"+ return _xml(200, "ListIdentitiesResponse", f"<ListIdentitiesResult><Identities>{members}</Identities></ListIdentitiesResult>")+++def _get_identity_verification_attributes(params):+ identities = _collect_list(params, "Identities.member")+ entries = ""+ for identity in identities:+ info = _identities.get(identity, {"VerificationStatus": "Pending"})+ entries += f"""<entry>+ <key>{identity}</key>+ <value><VerificationStatus>{info['VerificationStatus']}</VerificationStatus></value>+ </entry>"""+ return _xml(200, "GetIdentityVerificationAttributesResponse",+ f"<GetIdentityVerificationAttributesResult><VerificationAttributes>{entries}</VerificationAttributes></GetIdentityVerificationAttributesResult>")+++def _delete_identity(params):+ identity = _p(params, "Identity")+ _identities.pop(identity, None)+ return _xml(200, "DeleteIdentityResponse", "")+++def _get_send_quota(params):+ return _xml(200, "GetSendQuotaResponse", """<GetSendQuotaResult>+ <Max24HourSend>50000.0</Max24HourSend>+ <MaxSendRate>14.0</MaxSendRate>+ <SentLast24Hours>0.0</SentLast24Hours>+ </GetSendQuotaResult>""")+++def _get_send_statistics(params):+ members = ""+ for email in _sent_emails[-100:]:+ members += f"""<member>+ <Timestamp>{email['Timestamp']}</Timestamp>+ <DeliveryAttempts>1</DeliveryAttempts>+ <Bounces>0</Bounces>+ <Complaints>0</Complaints>+ <Rejects>0</Rejects>+ </member>"""+ return _xml(200, "GetSendStatisticsResponse", f"<GetSendStatisticsResult><SendDataPoints>{members}</SendDataPoints></GetSendStatisticsResult>")+++def _list_verified_emails(params):+ members = "".join(f"<member>{e}</member>" for e in _identities if _identities[e]["Type"] == "EmailAddress")+ return _xml(200, "ListVerifiedEmailAddressesResponse",+ f"<ListVerifiedEmailAddressesResult><VerifiedEmailAddresses>{members}</VerifiedEmailAddresses></ListVerifiedEmailAddressesResult>")+++# --- Helpers ---++def _collect_list(params, prefix):+ result = []+ i = 1+ while _p(params, f"{prefix}.{i}"):+ result.append(_p(params, f"{prefix}.{i}"))+ i += 1+ return result+++def _p(params, key, default=""):+ val = params.get(key, [default])+ return val[0] if isinstance(val, list) else val+++def _xml(status, root_tag, inner):+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<{root_tag} xmlns="http://ses.amazonaws.com/doc/2010-12-01/">+ {inner}+ <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>+</{root_tag}>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _error(code, message, status):+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">+ <Error><Code>{code}</Code><Message>{message}</Message></Error>+ <RequestId>{new_uuid()}</RequestId>+</ErrorResponse>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, bodydiff --git a/services/sns.py b/services/sns.pynew file mode 100644index 00000000..9c38e753--- /dev/null+++ b/services/sns.py@@ -0,0 +1,196 @@+"""+SNS Service Emulator.+Supports: CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes,+ Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, Publish.+"""++import time+import hashlib+import logging+from urllib.parse import parse_qs++from core.responses import new_uuid++logger = logging.getLogger("sns")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_topics: dict = {} # arn -> {name, attributes, subscriptions: [{arn, protocol, endpoint, confirmed}]}+_sub_arn_to_topic: dict = {}+++async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:+ params = dict(query_params)+ if method == "POST" and body:+ form_params = parse_qs(body.decode("utf-8", errors="replace"))+ for k, v in form_params.items():+ params[k] = v++ action = _p(params, "Action")+ handlers = {+ "CreateTopic": _create_topic,+ "DeleteTopic": _delete_topic,+ "ListTopics": _list_topics,+ "GetTopicAttributes": _get_topic_attributes,+ "SetTopicAttributes": _set_topic_attributes,+ "Subscribe": _subscribe,+ "Unsubscribe": _unsubscribe,+ "ListSubscriptions": _list_subscriptions,+ "ListSubscriptionsByTopic": _list_subscriptions_by_topic,+ "Publish": _publish,+ }++ handler = handlers.get(action)+ if not handler:+ return _error("InvalidAction", f"Unknown action: {action}", 400)+ return handler(params)+++def _create_topic(params):+ name = _p(params, "Name")+ if not name:+ return _error("InvalidParameter", "Name is required", 400)+ arn = f"arn:aws:sns:{REGION}:{ACCOUNT_ID}:{name}"+ if arn not in _topics:+ _topics[arn] = {+ "name": name, "arn": arn,+ "attributes": {+ "TopicArn": arn,+ "DisplayName": name,+ "SubscriptionsConfirmed": "0",+ "SubscriptionsPending": "0",+ "SubscriptionsDeleted": "0",+ },+ "subscriptions": [],+ "messages": [],+ }+ return _xml(200, "CreateTopicResponse", f"<CreateTopicResult><TopicArn>{arn}</TopicArn></CreateTopicResult>")+++def _delete_topic(params):+ arn = _p(params, "TopicArn")+ _topics.pop(arn, None)+ return _xml(200, "DeleteTopicResponse", "")+++def _list_topics(params):+ members = "".join(f"<member><TopicArn>{arn}</TopicArn></member>" for arn in _topics)+ return _xml(200, "ListTopicsResponse", f"<ListTopicsResult><Topics>{members}</Topics></ListTopicsResult>")+++def _get_topic_attributes(params):+ arn = _p(params, "TopicArn")+ topic = _topics.get(arn)+ if not topic:+ return _error("NotFound", "Topic not found", 404)+ attrs = "".join(f"<entry><key>{k}</key><value>{v}</value></entry>" for k, v in topic["attributes"].items())+ return _xml(200, "GetTopicAttributesResponse", f"<GetTopicAttributesResult><Attributes>{attrs}</Attributes></GetTopicAttributesResult>")+++def _set_topic_attributes(params):+ arn = _p(params, "TopicArn")+ topic = _topics.get(arn)+ if not topic:+ return _error("NotFound", "Topic not found", 404)+ attr_name = _p(params, "AttributeName")+ attr_val = _p(params, "AttributeValue")+ topic["attributes"][attr_name] = attr_val+ return _xml(200, "SetTopicAttributesResponse", "")+++def _subscribe(params):+ topic_arn = _p(params, "TopicArn")+ protocol = _p(params, "Protocol")+ endpoint = _p(params, "Endpoint")++ topic = _topics.get(topic_arn)+ if not topic:+ return _error("NotFound", "Topic not found", 404)++ sub_arn = f"{topic_arn}:{new_uuid()}"+ sub = {"arn": sub_arn, "protocol": protocol, "endpoint": endpoint, "confirmed": True, "topic_arn": topic_arn}+ topic["subscriptions"].append(sub)+ _sub_arn_to_topic[sub_arn] = topic_arn+ topic["attributes"]["SubscriptionsConfirmed"] = str(len([s for s in topic["subscriptions"] if s["confirmed"]]))++ return _xml(200, "SubscribeResponse", f"<SubscribeResult><SubscriptionArn>{sub_arn}</SubscriptionArn></SubscribeResult>")+++def _unsubscribe(params):+ sub_arn = _p(params, "SubscriptionArn")+ topic_arn = _sub_arn_to_topic.get(sub_arn)+ if topic_arn and topic_arn in _topics:+ _topics[topic_arn]["subscriptions"] = [s for s in _topics[topic_arn]["subscriptions"] if s["arn"] != sub_arn]+ _sub_arn_to_topic.pop(sub_arn, None)+ return _xml(200, "UnsubscribeResponse", "")+++def _list_subscriptions(params):+ members = ""+ for topic in _topics.values():+ for sub in topic["subscriptions"]:+ members += f"""<member>+ <SubscriptionArn>{sub['arn']}</SubscriptionArn>+ <TopicArn>{sub['topic_arn']}</TopicArn>+ <Protocol>{sub['protocol']}</Protocol>+ <Endpoint>{sub['endpoint']}</Endpoint>+ </member>"""+ return _xml(200, "ListSubscriptionsResponse", f"<ListSubscriptionsResult><Subscriptions>{members}</Subscriptions></ListSubscriptionsResult>")+++def _list_subscriptions_by_topic(params):+ topic_arn = _p(params, "TopicArn")+ topic = _topics.get(topic_arn)+ if not topic:+ return _error("NotFound", "Topic not found", 404)+ members = ""+ for sub in topic["subscriptions"]:+ members += f"""<member>+ <SubscriptionArn>{sub['arn']}</SubscriptionArn>+ <TopicArn>{topic_arn}</TopicArn>+ <Protocol>{sub['protocol']}</Protocol>+ <Endpoint>{sub['endpoint']}</Endpoint>+ </member>"""+ return _xml(200, "ListSubscriptionsByTopicResponse", f"<ListSubscriptionsByTopicResult><Subscriptions>{members}</Subscriptions></ListSubscriptionsByTopicResult>")+++def _publish(params):+ topic_arn = _p(params, "TopicArn") or _p(params, "TargetArn")+ message = _p(params, "Message")+ subject = _p(params, "Subject")++ msg_id = new_uuid()++ if topic_arn and topic_arn in _topics:+ _topics[topic_arn]["messages"].append({+ "id": msg_id, "message": message, "subject": subject,+ "timestamp": time.time(),+ })+ # In real LocalStack, this would fan out to subscribers+ logger.info(f"SNS publish to {topic_arn}: {message[:100]}")++ return _xml(200, "PublishResponse", f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")+++def _p(params, key, default=""):+ val = params.get(key, [default])+ return val[0] if isinstance(val, list) else val+++def _xml(status, root_tag, inner):+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<{root_tag} xmlns="http://sns.amazonaws.com/doc/2010-03-31/">+ {inner}+ <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>+</{root_tag}>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _error(code, message, status):+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">+ <Error><Code>{code}</Code><Message>{message}</Message></Error>+ <RequestId>{new_uuid()}</RequestId>+</ErrorResponse>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, bodydiff --git a/services/sqs.py b/services/sqs.pynew file mode 100644index 00000000..b2874ade--- /dev/null+++ b/services/sqs.py@@ -0,0 +1,603 @@+"""+SQS Service Emulator.+Supports: CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes,+ SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage,+ ChangeMessageVisibility, SendMessageBatch, DeleteMessageBatch.+"""++import time+import json+import hashlib+import logging+from collections import defaultdict+from urllib.parse import parse_qs++from core.responses import new_uuid, now_iso, md5_hash++logger = logging.getLogger("sqs")++# In-memory queues+# queue_url -> {name, attributes, messages: [{id, body, md5, receipt_handle, sent_at, visible_at, receive_count}], ...}+_queues: dict = {}+_queue_name_to_url: dict = {}++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"+DEFAULT_HOST = "localhost"+DEFAULT_PORT = "4566"+++def _queue_url(name: str) -> str:+ host = DEFAULT_HOST+ port = DEFAULT_PORT+ return f"http://{host}:{port}/{ACCOUNT_ID}/{name}"+++async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:+ """Handle SQS requests — supports both legacy Query API and modern JSON API."""+ target = headers.get("x-amz-target", "")++ # Modern JSON protocol (boto3 default since ~2023): X-Amz-Target: AmazonSQS.CreateQueue+ if target.startswith("AmazonSQS."):+ action = target.split(".")[-1]+ try:+ data = json.loads(body) if body else {}+ except Exception:+ data = {}+ return _handle_json_action(action, data, path)++ # Legacy Query API: Action=CreateQueue in form body or query string+ params = dict(query_params)+ if method == "POST" and body:+ form_params = parse_qs(body.decode("utf-8", errors="replace"))+ for k, v in form_params.items():+ params[k] = v++ action = _p(params, "Action")++ handlers = {+ "CreateQueue": _create_queue,+ "DeleteQueue": _delete_queue,+ "ListQueues": _list_queues,+ "GetQueueUrl": _get_queue_url,+ "GetQueueAttributes": _get_queue_attributes,+ "SetQueueAttributes": _set_queue_attributes,+ "PurgeQueue": _purge_queue,+ "SendMessage": _send_message,+ "ReceiveMessage": _receive_message,+ "DeleteMessage": _delete_message,+ "ChangeMessageVisibility": _change_visibility,+ "SendMessageBatch": _send_message_batch,+ "DeleteMessageBatch": _delete_message_batch,+ }++ handler = handlers.get(action)+ if handler is None:+ return _error("InvalidAction", f"Unknown action: {action}", 400)++ return handler(params, path)+++def _handle_json_action(action: str, data: dict, path: str):+ """Handle modern JSON-protocol SQS actions."""++ if action == "CreateQueue":+ name = data.get("QueueName", "")+ if not name:+ return _json_error("MissingParameter", "QueueName is required", 400)+ url = _queue_url(name)+ if url not in _queues:+ _queues[url] = {+ "name": name, "url": url,+ "attributes": {+ "QueueArn": f"arn:aws:sqs:{REGION}:{ACCOUNT_ID}:{name}",+ "CreatedTimestamp": str(int(time.time())),+ "LastModifiedTimestamp": str(int(time.time())),+ "VisibilityTimeout": "30",+ "MaximumMessageSize": "262144",+ "MessageRetentionPeriod": "345600",+ "DelaySeconds": "0",+ "ReceiveMessageWaitTimeSeconds": "0",+ "ApproximateNumberOfMessages": "0",+ "ApproximateNumberOfMessagesNotVisible": "0",+ },+ "messages": [], "delayed": [],+ }+ attrs = data.get("Attributes") or data.get("attributes") or {}+ for k, v in attrs.items():+ _queues[url]["attributes"][k] = v+ _queue_name_to_url[name] = url+ return _json_resp({"QueueUrl": url})++ if action == "DeleteQueue":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ if url in _queues:+ name = _queues[url]["name"]+ del _queues[url]+ _queue_name_to_url.pop(name, None)+ return _json_resp({})++ if action == "ListQueues":+ prefix = data.get("QueueNamePrefix", "")+ urls = [u for u, q in _queues.items() if not prefix or q["name"].startswith(prefix)]+ return _json_resp({"QueueUrls": urls})++ if action == "GetQueueUrl":+ name = data.get("QueueName", "")+ url = _queue_name_to_url.get(name)+ if not url:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", f"Queue {name} not found", 400)+ return _json_resp({"QueueUrl": url})++ if action == "SendMessage":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ body_text = data.get("MessageBody", "")+ delay = int(data.get("DelaySeconds", 0) or queue["attributes"].get("DelaySeconds", "0"))+ msg_id = new_uuid()+ md5 = hashlib.md5(body_text.encode()).hexdigest()+ msg = {+ "id": msg_id, "body": body_text, "md5": md5,+ "receipt_handle": None, "sent_at": time.time(),+ "visible_at": time.time() + delay, "receive_count": 0,+ "attributes": {},+ }+ # Parse message attributes+ for attr_name, attr_val in (data.get("MessageAttributes") or {}).items():+ msg["attributes"][attr_name] = attr_val+ queue["messages"].append(msg)+ return _json_resp({"MessageId": msg_id, "MD5OfMessageBody": md5})++ if action == "ReceiveMessage":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ max_msgs = int(data.get("MaxNumberOfMessages", 1))+ vis_timeout = int(data.get("VisibilityTimeout", queue["attributes"].get("VisibilityTimeout", "30")))+ now = time.time()+ visible = [m for m in queue["messages"] if m["visible_at"] <= now]+ to_return = visible[:max_msgs]+ messages = []+ for msg in to_return:+ receipt = new_uuid()+ msg["receipt_handle"] = receipt+ msg["visible_at"] = now + vis_timeout+ msg["receive_count"] += 1+ m = {+ "MessageId": msg["id"],+ "ReceiptHandle": receipt,+ "MD5OfBody": msg["md5"],+ "Body": msg["body"],+ }+ if msg["attributes"]:+ m["MessageAttributes"] = msg["attributes"]+ messages.append(m)+ return _json_resp({"Messages": messages} if messages else {})++ if action == "DeleteMessage":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ receipt = data.get("ReceiptHandle", "")+ queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") != receipt]+ return _json_resp({})++ if action == "PurgeQueue":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ queue["messages"].clear()+ return _json_resp({})++ if action == "GetQueueAttributes":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ now = time.time()+ visible = sum(1 for m in queue["messages"] if m["visible_at"] <= now)+ not_visible = sum(1 for m in queue["messages"] if m["visible_at"] > now)+ queue["attributes"]["ApproximateNumberOfMessages"] = str(visible)+ queue["attributes"]["ApproximateNumberOfMessagesNotVisible"] = str(not_visible)+ requested = data.get("AttributeNames", ["All"])+ attrs = {}+ for k, v in queue["attributes"].items():+ if "All" in requested or k in requested:+ attrs[k] = v+ return _json_resp({"Attributes": attrs})++ if action == "SetQueueAttributes":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ for k, v in (data.get("Attributes") or {}).items():+ queue["attributes"][k] = v+ return _json_resp({})++ if action == "ChangeMessageVisibility":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ receipt = data.get("ReceiptHandle", "")+ timeout = int(data.get("VisibilityTimeout", 30))+ for msg in queue["messages"]:+ if msg.get("receipt_handle") == receipt:+ msg["visible_at"] = time.time() + timeout+ break+ return _json_resp({})++ if action == "SendMessageBatch":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ results = []+ for entry in data.get("Entries", []):+ body_text = entry.get("MessageBody", "")+ delay = int(entry.get("DelaySeconds", 0))+ msg_id = new_uuid()+ md5 = hashlib.md5(body_text.encode()).hexdigest()+ queue["messages"].append({+ "id": msg_id, "body": body_text, "md5": md5,+ "receipt_handle": None, "sent_at": time.time(),+ "visible_at": time.time() + delay, "receive_count": 0, "attributes": {},+ })+ results.append({"Id": entry.get("Id"), "MessageId": msg_id, "MD5OfMessageBody": md5})+ return _json_resp({"Successful": results, "Failed": []})++ if action == "DeleteMessageBatch":+ url = data.get("QueueUrl", "") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _json_error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ results = []+ for entry in data.get("Entries", []):+ receipt = entry.get("ReceiptHandle", "")+ queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") != receipt]+ results.append({"Id": entry.get("Id")})+ return _json_resp({"Successful": results, "Failed": []})++ return _json_error("InvalidAction", f"Unknown action: {action}", 400)+++def _json_resp(data: dict, status: int = 200) -> tuple:+ body = json.dumps(data).encode("utf-8")+ return status, {"Content-Type": "application/x-amz-json-1.0"}, body+++def _json_error(code: str, message: str, status: int) -> tuple:+ body = json.dumps({"__type": code, "message": message}).encode("utf-8")+ return status, {"Content-Type": "application/x-amz-json-1.0"}, body+++def _create_queue(params: dict, path: str):+ name = _p(params, "QueueName")+ if not name:+ return _error("MissingParameter", "QueueName is required", 400)++ url = _queue_url(name)+ if url not in _queues:+ _queues[url] = {+ "name": name,+ "url": url,+ "attributes": {+ "QueueArn": f"arn:aws:sqs:{REGION}:{ACCOUNT_ID}:{name}",+ "CreatedTimestamp": str(int(time.time())),+ "LastModifiedTimestamp": str(int(time.time())),+ "VisibilityTimeout": "30",+ "MaximumMessageSize": "262144",+ "MessageRetentionPeriod": "345600",+ "DelaySeconds": "0",+ "ReceiveMessageWaitTimeSeconds": "0",+ "ApproximateNumberOfMessages": "0",+ "ApproximateNumberOfMessagesNotVisible": "0",+ },+ "messages": [],+ "delayed": [],+ }+ # Apply any attributes from the request+ i = 1+ while _p(params, f"Attribute.{i}.Name"):+ attr_name = _p(params, f"Attribute.{i}.Name")+ attr_val = _p(params, f"Attribute.{i}.Value")+ _queues[url]["attributes"][attr_name] = attr_val+ i += 1+ _queue_name_to_url[name] = url++ return _xml(200, "CreateQueueResponse", f"""+ <CreateQueueResult>+ <QueueUrl>{url}</QueueUrl>+ </CreateQueueResult>""")+++def _delete_queue(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ if url in _queues:+ name = _queues[url]["name"]+ del _queues[url]+ _queue_name_to_url.pop(name, None)+ return _xml(200, "DeleteQueueResponse", "")+++def _list_queues(params: dict, path: str):+ prefix = _p(params, "QueueNamePrefix")+ urls = []+ for url, q in _queues.items():+ if not prefix or q["name"].startswith(prefix):+ urls.append(url)++ members = "".join(f"<QueueUrl>{u}</QueueUrl>" for u in urls)+ return _xml(200, "ListQueuesResponse", f"""+ <ListQueuesResult>+ {members}+ </ListQueuesResult>""")+++def _get_queue_url(params: dict, path: str):+ name = _p(params, "QueueName")+ url = _queue_name_to_url.get(name)+ if not url:+ return _error("AWS.SimpleQueueService.NonExistentQueue", f"Queue {name} not found", 400)+ return _xml(200, "GetQueueUrlResponse", f"""+ <GetQueueUrlResult>+ <QueueUrl>{url}</QueueUrl>+ </GetQueueUrlResult>""")+++def _get_queue_attributes(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)++ # Update approximate counts+ now = time.time()+ visible = sum(1 for m in queue["messages"] if m["visible_at"] <= now)+ not_visible = sum(1 for m in queue["messages"] if m["visible_at"] > now)+ queue["attributes"]["ApproximateNumberOfMessages"] = str(visible)+ queue["attributes"]["ApproximateNumberOfMessagesNotVisible"] = str(not_visible)++ attrs = ""+ # Check which attributes are requested+ requested = set()+ i = 1+ while _p(params, f"AttributeName.{i}"):+ requested.add(_p(params, f"AttributeName.{i}"))+ i += 1++ for k, v in queue["attributes"].items():+ if not requested or "All" in requested or k in requested:+ attrs += f"<Attribute><Name>{k}</Name><Value>{v}</Value></Attribute>"++ return _xml(200, "GetQueueAttributesResponse", f"""+ <GetQueueAttributesResult>+ {attrs}+ </GetQueueAttributesResult>""")+++def _set_queue_attributes(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)++ i = 1+ while _p(params, f"Attribute.{i}.Name"):+ attr_name = _p(params, f"Attribute.{i}.Name")+ attr_val = _p(params, f"Attribute.{i}.Value")+ queue["attributes"][attr_name] = attr_val+ i += 1++ return _xml(200, "SetQueueAttributesResponse", "")+++def _purge_queue(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)+ queue["messages"].clear()+ return _xml(200, "PurgeQueueResponse", "")+++def _send_message(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)++ body_text = _p(params, "MessageBody")+ delay = int(_p(params, "DelaySeconds") or queue["attributes"].get("DelaySeconds", "0"))+ msg_id = new_uuid()+ md5 = hashlib.md5(body_text.encode()).hexdigest()++ msg = {+ "id": msg_id,+ "body": body_text,+ "md5": md5,+ "receipt_handle": None,+ "sent_at": time.time(),+ "visible_at": time.time() + delay,+ "receive_count": 0,+ "attributes": {},+ }++ # Parse message attributes+ i = 1+ while _p(params, f"MessageAttribute.{i}.Name"):+ attr_name = _p(params, f"MessageAttribute.{i}.Name")+ attr_type = _p(params, f"MessageAttribute.{i}.Value.DataType")+ attr_val = _p(params, f"MessageAttribute.{i}.Value.StringValue")+ msg["attributes"][attr_name] = {"DataType": attr_type, "StringValue": attr_val}+ i += 1++ queue["messages"].append(msg)++ return _xml(200, "SendMessageResponse", f"""+ <SendMessageResult>+ <MessageId>{msg_id}</MessageId>+ <MD5OfMessageBody>{md5}</MD5OfMessageBody>+ </SendMessageResult>""")+++def _receive_message(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)++ max_msgs = int(_p(params, "MaxNumberOfMessages") or "1")+ vis_timeout = int(_p(params, "VisibilityTimeout") or queue["attributes"].get("VisibilityTimeout", "30"))+ wait_time = int(_p(params, "WaitTimeSeconds") or "0")++ now = time.time()+ visible = [m for m in queue["messages"] if m["visible_at"] <= now]+ to_return = visible[:max_msgs]++ messages_xml = ""+ for msg in to_return:+ receipt = new_uuid()+ msg["receipt_handle"] = receipt+ msg["visible_at"] = now + vis_timeout+ msg["receive_count"] += 1++ attrs_xml = ""+ for attr_name, attr_val in msg["attributes"].items():+ attrs_xml += f"""<MessageAttribute>+ <Name>{attr_name}</Name>+ <Value>+ <DataType>{attr_val['DataType']}</DataType>+ <StringValue>{attr_val['StringValue']}</StringValue>+ </Value>+ </MessageAttribute>"""++ messages_xml += f"""<Message>+ <MessageId>{msg['id']}</MessageId>+ <ReceiptHandle>{receipt}</ReceiptHandle>+ <MD5OfBody>{msg['md5']}</MD5OfBody>+ <Body>{msg['body']}</Body>+ {attrs_xml}+ </Message>"""++ return _xml(200, "ReceiveMessageResponse", f"""+ <ReceiveMessageResult>+ {messages_xml}+ </ReceiveMessageResult>""")+++def _delete_message(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)++ receipt = _p(params, "ReceiptHandle")+ queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") != receipt]+ return _xml(200, "DeleteMessageResponse", "")+++def _change_visibility(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)++ receipt = _p(params, "ReceiptHandle")+ timeout = int(_p(params, "VisibilityTimeout") or "30")++ for msg in queue["messages"]:+ if msg.get("receipt_handle") == receipt:+ msg["visible_at"] = time.time() + timeout+ break++ return _xml(200, "ChangeMessageVisibilityResponse", "")+++def _send_message_batch(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)++ results = ""+ i = 1+ while _p(params, f"SendMessageBatchRequestEntry.{i}.Id"):+ entry_id = _p(params, f"SendMessageBatchRequestEntry.{i}.Id")+ body_text = _p(params, f"SendMessageBatchRequestEntry.{i}.MessageBody")+ delay = int(_p(params, f"SendMessageBatchRequestEntry.{i}.DelaySeconds") or "0")+ msg_id = new_uuid()+ md5 = hashlib.md5(body_text.encode()).hexdigest()++ queue["messages"].append({+ "id": msg_id, "body": body_text, "md5": md5,+ "receipt_handle": None, "sent_at": time.time(),+ "visible_at": time.time() + delay, "receive_count": 0, "attributes": {},+ })+ results += f"""<SendMessageBatchResultEntry>+ <Id>{entry_id}</Id><MessageId>{msg_id}</MessageId>+ <MD5OfMessageBody>{md5}</MD5OfMessageBody>+ </SendMessageBatchResultEntry>"""+ i += 1++ return _xml(200, "SendMessageBatchResponse", f"<SendMessageBatchResult>{results}</SendMessageBatchResult>")+++def _delete_message_batch(params: dict, path: str):+ url = _p(params, "QueueUrl") or _url_from_path(path)+ queue = _queues.get(url)+ if not queue:+ return _error("AWS.SimpleQueueService.NonExistentQueue", "Queue not found", 400)++ results = ""+ i = 1+ while _p(params, f"DeleteMessageBatchRequestEntry.{i}.Id"):+ entry_id = _p(params, f"DeleteMessageBatchRequestEntry.{i}.Id")+ receipt = _p(params, f"DeleteMessageBatchRequestEntry.{i}.ReceiptHandle")+ queue["messages"] = [m for m in queue["messages"] if m.get("receipt_handle") != receipt]+ results += f"<DeleteMessageBatchResultEntry><Id>{entry_id}</Id></DeleteMessageBatchResultEntry>"+ i += 1++ return _xml(200, "DeleteMessageBatchResponse", f"<DeleteMessageBatchResult>{results}</DeleteMessageBatchResult>")+++# --- Helpers ---++def _p(params: dict, key: str, default: str = "") -> str:+ val = params.get(key, [default])+ if isinstance(val, list):+ return val[0] if val else default+ return val+++def _url_from_path(path: str) -> str:+ """Extract queue URL from path like /000000000000/queue-name."""+ parts = path.strip("/").split("/")+ if len(parts) >= 2:+ name = parts[-1]+ return _queue_url(name)+ return ""+++def _xml(status: int, root_tag: str, inner: str) -> tuple:+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<{root_tag} xmlns="http://queue.amazonaws.com/doc/2012-11-05/">+ {inner}+ <ResponseMetadata><RequestId>{new_uuid()}</RequestId></ResponseMetadata>+</{root_tag}>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, body+++def _error(code: str, message: str, status: int) -> tuple:+ body = f"""<?xml version="1.0" encoding="UTF-8"?>+<ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">+ <Error><Code>{code}</Code><Message>{message}</Message></Error>+ <RequestId>{new_uuid()}</RequestId>+</ErrorResponse>""".encode("utf-8")+ return status, {"Content-Type": "application/xml"}, bodydiff --git a/services/ssm.py b/services/ssm.pynew file mode 100644index 00000000..a4597ce3--- /dev/null+++ b/services/ssm.py@@ -0,0 +1,164 @@+"""+SSM Parameter Store Emulator.+JSON-based API via X-Amz-Target (AmazonSSM).+Supports: PutParameter, GetParameter, GetParameters, GetParametersByPath,+ DeleteParameter, DeleteParameters, DescribeParameters.+"""++import json+import time+import logging++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("ssm")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_parameters: dict = {} # name -> {Name, Value, Type, Version, ARN, LastModifiedDate, DataType}+++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 = {+ "PutParameter": _put_parameter,+ "GetParameter": _get_parameter,+ "GetParameters": _get_parameters,+ "GetParametersByPath": _get_parameters_by_path,+ "DeleteParameter": _delete_parameter,+ "DeleteParameters": _delete_parameters,+ "DescribeParameters": _describe_parameters,+ "GetParameterHistory": _get_parameter_history,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown action: {action}", 400)+ return handler(data)+++def _put_parameter(data):+ name = data.get("Name")+ if not name:+ return error_response_json("ValidationException", "Name is required", 400)++ overwrite = data.get("Overwrite", False)+ if name in _parameters and not overwrite:+ return error_response_json("ParameterAlreadyExists", f"Parameter {name} already exists", 400)++ version = (_parameters[name]["Version"] + 1) if name in _parameters else 1+ arn = f"arn:aws:ssm:{REGION}:{ACCOUNT_ID}:parameter{name}"+ _parameters[name] = {+ "Name": name,+ "Value": data.get("Value", ""),+ "Type": data.get("Type", "String"),+ "Version": version,+ "ARN": arn,+ "LastModifiedDate": time.time(),+ "DataType": data.get("DataType", "text"),+ "Description": data.get("Description", ""),+ "Tier": data.get("Tier", "Standard"),+ }+ return json_response({"Version": version, "Tier": "Standard"})+++def _get_parameter(data):+ name = data.get("Name")+ param = _parameters.get(name)+ if not param:+ return error_response_json("ParameterNotFound", f"Parameter {name} not found", 400)+ return json_response({"Parameter": _param_out(param)})+++def _get_parameters(data):+ names = data.get("Names", [])+ params = []+ invalid = []+ for name in names:+ p = _parameters.get(name)+ if p:+ params.append(_param_out(p))+ else:+ invalid.append(name)+ return json_response({"Parameters": params, "InvalidParameters": invalid})+++def _get_parameters_by_path(data):+ path = data.get("Path", "/")+ recursive = data.get("Recursive", False)+ results = []+ for name, param in _parameters.items():+ if recursive:+ if name.startswith(path):+ results.append(_param_out(param))+ else:+ # Non-recursive: only direct children (no further slashes after path)+ if name.startswith(path):+ suffix = name[len(path):]+ if "/" not in suffix.lstrip("/"):+ results.append(_param_out(param))+ return json_response({"Parameters": results})+++def _delete_parameter(data):+ name = data.get("Name")+ if name not in _parameters:+ return error_response_json("ParameterNotFound", f"Parameter {name} not found", 400)+ del _parameters[name]+ return json_response({})+++def _delete_parameters(data):+ names = data.get("Names", [])+ deleted = []+ invalid = []+ for name in names:+ if name in _parameters:+ del _parameters[name]+ deleted.append(name)+ else:+ invalid.append(name)+ return json_response({"DeletedParameters": deleted, "InvalidParameters": invalid})+++def _describe_parameters(data):+ filters = data.get("ParameterFilters", [])+ results = []+ for name, param in _parameters.items():+ results.append({+ "Name": param["Name"],+ "Type": param["Type"],+ "Version": param["Version"],+ "LastModifiedDate": param["LastModifiedDate"],+ "ARN": param["ARN"],+ "DataType": param["DataType"],+ })+ return json_response({"Parameters": results})+++def _get_parameter_history(data):+ name = data.get("Name")+ param = _parameters.get(name)+ if not param:+ return error_response_json("ParameterNotFound", f"Parameter {name} not found", 400)+ return json_response({"Parameters": [_param_out(param)]})+++def _param_out(param):+ return {+ "Name": param["Name"],+ "Type": param["Type"],+ "Value": param["Value"],+ "Version": param["Version"],+ "ARN": param["ARN"],+ "LastModifiedDate": param["LastModifiedDate"],+ "DataType": param["DataType"],+ }diff --git a/services/stepfunctions.py b/services/stepfunctions.pynew file mode 100644index 00000000..ff09d330--- /dev/null+++ b/services/stepfunctions.py@@ -0,0 +1,193 @@+"""+Step Functions Service Emulator.+JSON-based API via X-Amz-Target (AWSStepFunctions).+Supports: CreateStateMachine, DeleteStateMachine, DescribeStateMachine, ListStateMachines,+ StartExecution, StopExecution, DescribeExecution, ListExecutions,+ GetExecutionHistory.+Executions are stored in-memory; no actual state machine logic is run.+"""++import json+import time+import logging++from core.responses import json_response, error_response_json, new_uuid++logger = logging.getLogger("states")++ACCOUNT_ID = "000000000000"+REGION = "us-east-1"++_state_machines: dict = {} # arn -> state machine dict+_executions: dict = {} # arn -> execution dict+++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 = {+ "CreateStateMachine": _create_state_machine,+ "DeleteStateMachine": _delete_state_machine,+ "DescribeStateMachine": _describe_state_machine,+ "UpdateStateMachine": _update_state_machine,+ "ListStateMachines": _list_state_machines,+ "StartExecution": _start_execution,+ "StopExecution": _stop_execution,+ "DescribeExecution": _describe_execution,+ "ListExecutions": _list_executions,+ "GetExecutionHistory": _get_execution_history,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("InvalidAction", f"Unknown action: {action}", 400)+ return handler(data)+++def _create_state_machine(data):+ name = data.get("name")+ if not name:+ return error_response_json("ValidationException", "name is required", 400)++ arn = f"arn:aws:states:{REGION}:{ACCOUNT_ID}:stateMachine:{name}"+ if arn in _state_machines:+ return error_response_json("StateMachineAlreadyExists", f"State machine {name} already exists", 400)++ _state_machines[arn] = {+ "stateMachineArn": arn,+ "name": name,+ "definition": data.get("definition", "{}"),+ "roleArn": data.get("roleArn", f"arn:aws:iam::{ACCOUNT_ID}:role/StepFunctionsRole"),+ "type": data.get("type", "STANDARD"),+ "creationDate": time.time(),+ "status": "ACTIVE",+ "loggingConfiguration": data.get("loggingConfiguration", {"level": "OFF", "includeExecutionData": False}),+ "tags": data.get("tags", []),+ }+ return json_response({"stateMachineArn": arn, "creationDate": time.time()})+++def _delete_state_machine(data):+ arn = data.get("stateMachineArn")+ if arn not in _state_machines:+ return error_response_json("StateMachineDoesNotExist", f"State machine {arn} not found", 400)+ del _state_machines[arn]+ return json_response({})+++def _describe_state_machine(data):+ arn = data.get("stateMachineArn")+ sm = _state_machines.get(arn)+ if not sm:+ return error_response_json("StateMachineDoesNotExist", f"State machine {arn} not found", 400)+ return json_response(sm)+++def _update_state_machine(data):+ arn = data.get("stateMachineArn")+ sm = _state_machines.get(arn)+ if not sm:+ return error_response_json("StateMachineDoesNotExist", f"State machine {arn} not found", 400)+ if "definition" in data:+ sm["definition"] = data["definition"]+ if "roleArn" in data:+ sm["roleArn"] = data["roleArn"]+ return json_response({"updateDate": time.time()})+++def _list_state_machines(data):+ machines = [+ {"stateMachineArn": sm["stateMachineArn"], "name": sm["name"],+ "type": sm["type"], "creationDate": sm["creationDate"]}+ for sm in _state_machines.values()+ ]+ return json_response({"stateMachines": machines})+++def _start_execution(data):+ sm_arn = data.get("stateMachineArn")+ if sm_arn not in _state_machines:+ return error_response_json("StateMachineDoesNotExist", f"State machine {sm_arn} not found", 400)++ name = data.get("name") or new_uuid()+ exec_arn = f"arn:aws:states:{REGION}:{ACCOUNT_ID}:execution:{_state_machines[sm_arn]['name']}:{name}"++ _executions[exec_arn] = {+ "executionArn": exec_arn,+ "stateMachineArn": sm_arn,+ "name": name,+ "status": "RUNNING",+ "startDate": time.time(),+ "stopDate": None,+ "input": data.get("input", "{}"),+ "output": None,+ "events": [+ {"id": 1, "type": "ExecutionStarted", "timestamp": time.time(),+ "executionStartedEventDetails": {"input": data.get("input", "{}")}},+ ],+ }+ logger.info(f"Step Functions execution started: {exec_arn}")+ return json_response({"executionArn": exec_arn, "startDate": time.time()})+++def _stop_execution(data):+ exec_arn = data.get("executionArn")+ execution = _executions.get(exec_arn)+ if not execution:+ return error_response_json("ExecutionDoesNotExist", f"Execution {exec_arn} not found", 400)+ execution["status"] = "ABORTED"+ execution["stopDate"] = time.time()+ execution["events"].append({+ "id": len(execution["events"]) + 1,+ "type": "ExecutionAborted",+ "timestamp": time.time(),+ "executionAbortedEventDetails": {+ "error": data.get("error", ""),+ "cause": data.get("cause", ""),+ },+ })+ return json_response({"stopDate": execution["stopDate"]})+++def _describe_execution(data):+ exec_arn = data.get("executionArn")+ execution = _executions.get(exec_arn)+ if not execution:+ return error_response_json("ExecutionDoesNotExist", f"Execution {exec_arn} not found", 400)+ result = dict(execution)+ result.pop("events", None)+ return json_response(result)+++def _list_executions(data):+ sm_arn = data.get("stateMachineArn")+ status_filter = data.get("statusFilter")+ execs = []+ for exec_arn, ex in _executions.items():+ if sm_arn and ex["stateMachineArn"] != sm_arn:+ continue+ if status_filter and ex["status"] != status_filter:+ continue+ execs.append({+ "executionArn": ex["executionArn"],+ "stateMachineArn": ex["stateMachineArn"],+ "name": ex["name"],+ "status": ex["status"],+ "startDate": ex["startDate"],+ "stopDate": ex.get("stopDate"),+ })+ return json_response({"executions": execs})+++def _get_execution_history(data):+ exec_arn = data.get("executionArn")+ execution = _executions.get(exec_arn)+ if not execution:+ return error_response_json("ExecutionDoesNotExist", f"Execution {exec_arn} not found", 400)+ return json_response({"events": execution["events"]})diff --git a/tests/conftest.py b/tests/conftest.pynew file mode 100644index 00000000..baaaffe2--- /dev/null+++ b/tests/conftest.py@@ -0,0 +1,103 @@+"""+Pytest fixtures for MiniStack integration tests.+"""+import os+import pytest+import boto3+from botocore.config import Config++ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+REGION = "us-east-1"++_kwargs = dict(+ endpoint_url=ENDPOINT,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name=REGION,+ config=Config(region_name=REGION, retries={"max_attempts": 0}),+)+++def make_client(service):+ return boto3.client(service, **_kwargs)++[email protected](scope="session")+def s3():+ return make_client("s3")+[email protected](scope="session")+def sqs():+ return make_client("sqs")+[email protected](scope="session")+def sns():+ return make_client("sns")+[email protected](scope="session")+def ddb():+ return make_client("dynamodb")+[email protected](scope="session")+def sts():+ return make_client("sts")+[email protected](scope="session")+def sm():+ return make_client("secretsmanager")+[email protected](scope="session")+def logs():+ return make_client("logs")+[email protected](scope="session")+def lam():+ return make_client("lambda")+[email protected](scope="session")+def iam():+ return make_client("iam")+[email protected](scope="session")+def ssm():+ return make_client("ssm")+[email protected](scope="session")+def eb():+ return make_client("events")+[email protected](scope="session")+def kin():+ return make_client("kinesis")+[email protected](scope="session")+def cw():+ return make_client("cloudwatch")+[email protected](scope="session")+def ses():+ return make_client("ses")+[email protected](scope="session")+def sfn():+ return make_client("stepfunctions")+[email protected](scope="session")+def ecs():+ return make_client("ecs")+[email protected](scope="session")+def rds():+ return make_client("rds")+[email protected](scope="session")+def ec():+ return make_client("elasticache")+[email protected](scope="session")+def glue():+ return make_client("glue")+[email protected](scope="session")+def athena():+ return make_client("athena")diff --git a/tests/test_services.py b/tests/test_services.pynew file mode 100644index 00000000..e6e8c43f--- /dev/null+++ b/tests/test_services.py@@ -0,0 +1,624 @@+"""+MiniStack Integration Tests — pytest edition.+Run: pytest tests/ -v+Requires: pip install boto3 pytest+"""++import io+import json+import time+import zipfile+++# ========== S3 ==========++def test_s3_create_bucket(s3):+ s3.create_bucket(Bucket="test-bucket-1")+ buckets = s3.list_buckets()["Buckets"]+ assert any(b["Name"] == "test-bucket-1" for b in buckets)+++def test_s3_put_get(s3):+ s3.create_bucket(Bucket="test-bucket-2")+ s3.put_object(Bucket="test-bucket-2", Key="hello.txt", Body=b"Hello, MiniStack!")+ resp = s3.get_object(Bucket="test-bucket-2", Key="hello.txt")+ assert resp["Body"].read() == b"Hello, MiniStack!"+++def test_s3_list(s3):+ s3.create_bucket(Bucket="test-bucket-3")+ for i in range(5):+ s3.put_object(Bucket="test-bucket-3", Key=f"file-{i}.txt", Body=f"content-{i}".encode())+ resp = s3.list_objects_v2(Bucket="test-bucket-3")+ assert resp["KeyCount"] == 5+++def test_s3_delete(s3):+ s3.create_bucket(Bucket="test-bucket-4")+ s3.put_object(Bucket="test-bucket-4", Key="to-delete.txt", Body=b"bye")+ s3.delete_object(Bucket="test-bucket-4", Key="to-delete.txt")+ resp = s3.list_objects_v2(Bucket="test-bucket-4")+ assert resp["KeyCount"] == 0+++def test_s3_copy(s3):+ s3.create_bucket(Bucket="test-bucket-5a")+ s3.create_bucket(Bucket="test-bucket-5b")+ s3.put_object(Bucket="test-bucket-5a", Key="original.txt", Body=b"original content")+ s3.copy_object(+ CopySource={"Bucket": "test-bucket-5a", "Key": "original.txt"},+ Bucket="test-bucket-5b", Key="copied.txt",+ )+ resp = s3.get_object(Bucket="test-bucket-5b", Key="copied.txt")+ assert resp["Body"].read() == b"original content"+++def test_s3_head(s3):+ s3.create_bucket(Bucket="test-bucket-6")+ s3.put_object(Bucket="test-bucket-6", Key="meta.txt", Body=b"12345")+ resp = s3.head_object(Bucket="test-bucket-6", Key="meta.txt")+ assert resp["ContentLength"] == 5+++# ========== SQS ==========++def test_sqs_basic(sqs):+ resp = sqs.create_queue(QueueName="test-queue-1")+ url = resp["QueueUrl"]+ sqs.send_message(QueueUrl=url, MessageBody="hello sqs")+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)+ assert len(msgs.get("Messages", [])) == 1+ assert msgs["Messages"][0]["Body"] == "hello sqs"+++def test_sqs_delete_msg(sqs):+ resp = sqs.create_queue(QueueName="test-queue-2")+ url = resp["QueueUrl"]+ sqs.send_message(QueueUrl=url, MessageBody="to delete")+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1)+ receipt = msgs["Messages"][0]["ReceiptHandle"]+ sqs.delete_message(QueueUrl=url, ReceiptHandle=receipt)+++def test_sqs_list(sqs):+ sqs.create_queue(QueueName="test-queue-list-1")+ sqs.create_queue(QueueName="test-queue-list-2")+ resp = sqs.list_queues()+ assert len(resp.get("QueueUrls", [])) >= 2+++def test_sqs_batch(sqs):+ resp = sqs.create_queue(QueueName="test-queue-batch")+ url = resp["QueueUrl"]+ sqs.send_message_batch(+ QueueUrl=url,+ Entries=[{"Id": str(i), "MessageBody": f"msg{i}"} for i in range(3)],+ )+ msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10)+ assert len(msgs.get("Messages", [])) >= 1+++# ========== SNS ==========++def test_sns_basic(sns):+ resp = sns.create_topic(Name="test-topic-1")+ arn = resp["TopicArn"]+ assert "test-topic-1" in arn+ pub = sns.publish(TopicArn=arn, Message="hello sns", Subject="Test")+ assert "MessageId" in pub+++def test_sns_subscribe(sns):+ resp = sns.create_topic(Name="test-topic-2")+ arn = resp["TopicArn"]+ sub = sns.subscribe(TopicArn=arn, Protocol="email", Endpoint="[email protected]")+ assert "SubscriptionArn" in sub+ subs = sns.list_subscriptions_by_topic(TopicArn=arn)+ assert len(subs.get("Subscriptions", [])) >= 1+++# ========== DynamoDB ==========++def test_dynamodb_basic(ddb):+ try:+ ddb.delete_table(TableName="TestTable1")+ except Exception:+ pass+ ddb.create_table(+ TableName="TestTable1",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.put_item(TableName="TestTable1", Item={"pk": {"S": "key1"}, "data": {"S": "value1"}})+ resp = ddb.get_item(TableName="TestTable1", Key={"pk": {"S": "key1"}})+ assert resp["Item"]["data"]["S"] == "value1"+ ddb.delete_item(TableName="TestTable1", Key={"pk": {"S": "key1"}})+ resp = ddb.get_item(TableName="TestTable1", Key={"pk": {"S": "key1"}})+ assert "Item" not in resp+++def test_dynamodb_scan(ddb):+ try:+ ddb.delete_table(TableName="ScanTable")+ except Exception:+ pass+ ddb.create_table(+ TableName="ScanTable",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ for i in range(10):+ ddb.put_item(TableName="ScanTable", Item={"pk": {"S": f"key{i}"}, "val": {"N": str(i)}})+ resp = ddb.scan(TableName="ScanTable")+ assert resp["Count"] == 10+++def test_dynamodb_batch(ddb):+ try:+ ddb.delete_table(TableName="BatchTable")+ except Exception:+ pass+ ddb.create_table(+ TableName="BatchTable",+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.batch_write_item(RequestItems={+ "BatchTable": [+ {"PutRequest": {"Item": {"pk": {"S": f"bk{i}"}, "v": {"S": f"bv{i}"}}}}+ for i in range(5)+ ]+ })+ resp = ddb.scan(TableName="BatchTable")+ assert resp["Count"] == 5+++# ========== STS ==========++def test_sts_get_caller_identity(sts):+ resp = sts.get_caller_identity()+ assert resp["Account"] == "000000000000"+++# ========== SecretsManager ==========++def test_secrets_create_get(sm):+ sm.create_secret(Name="test-secret-1", SecretString='{"user":"admin"}')+ resp = sm.get_secret_value(SecretId="test-secret-1")+ assert json.loads(resp["SecretString"])["user"] == "admin"+++def test_secrets_update_list(sm):+ sm.create_secret(Name="test-secret-2", SecretString="original")+ sm.update_secret(SecretId="test-secret-2", SecretString="updated")+ resp = sm.get_secret_value(SecretId="test-secret-2")+ assert resp["SecretString"] == "updated"+ listed = sm.list_secrets()+ assert any(s["Name"] == "test-secret-2" for s in listed["SecretList"])+++# ========== CloudWatch Logs ==========++def test_logs_put_get(logs):+ logs.create_log_group(logGroupName="/test/ministack")+ logs.create_log_stream(logGroupName="/test/ministack", logStreamName="stream1")+ logs.put_log_events(+ logGroupName="/test/ministack",+ logStreamName="stream1",+ logEvents=[+ {"timestamp": int(time.time() * 1000), "message": "Hello from MiniStack"},+ {"timestamp": int(time.time() * 1000), "message": "Second log line"},+ ],+ )+ resp = logs.get_log_events(logGroupName="/test/ministack", logStreamName="stream1")+ assert len(resp["events"]) == 2+++def test_logs_filter(logs):+ resp = logs.filter_log_events(logGroupName="/test/ministack", filterPattern="MiniStack")+ assert len(resp["events"]) >= 1+++# ========== Lambda ==========++def test_lambda_create_invoke(lam):+ code = b'def handler(event, context):\n return {"statusCode": 200, "body": "Hello!", "event": event}\n'+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName="test-func-1",+ Runtime="python3.9",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )+ funcs = lam.list_functions()+ assert any(f["FunctionName"] == "test-func-1" for f in funcs["Functions"])+ resp = lam.invoke(FunctionName="test-func-1", Payload=json.dumps({"key": "value"}))+ payload = json.loads(resp["Payload"].read())+ assert payload["statusCode"] == 200+++# ========== IAM ==========++def test_iam_role_user(iam):+ iam.create_role(+ RoleName="test-role",+ AssumeRolePolicyDocument=json.dumps({"Version": "2012-10-17", "Statement": []}),+ )+ roles = iam.list_roles()+ assert any(r["RoleName"] == "test-role" for r in roles.get("Roles", []))+ iam.create_user(UserName="test-user")+ users = iam.list_users()+ assert any(u["UserName"] == "test-user" for u in users.get("Users", []))+++# ========== SSM ==========++def test_ssm_put_get(ssm):+ ssm.put_parameter(Name="/app/db/host", Value="localhost", Type="String")+ resp = ssm.get_parameter(Name="/app/db/host")+ assert resp["Parameter"]["Value"] == "localhost"+++def test_ssm_get_by_path(ssm):+ ssm.put_parameter(Name="/app/config/key1", Value="val1", Type="String")+ ssm.put_parameter(Name="/app/config/key2", Value="val2", Type="String")+ resp = ssm.get_parameters_by_path(Path="/app/config", Recursive=True)+ assert len(resp["Parameters"]) >= 2+++def test_ssm_overwrite(ssm):+ ssm.put_parameter(Name="/app/overwrite", Value="v1", Type="String")+ ssm.put_parameter(Name="/app/overwrite", Value="v2", Type="String", Overwrite=True)+ resp = ssm.get_parameter(Name="/app/overwrite")+ assert resp["Parameter"]["Value"] == "v2"+++# ========== EventBridge ==========++def test_eventbridge_bus_rule(eb):+ eb.create_event_bus(Name="test-bus")+ eb.put_rule(Name="test-rule", EventBusName="test-bus", ScheduleExpression="rate(5 minutes)", State="ENABLED")+ rules = eb.list_rules(EventBusName="test-bus")+ assert any(r["Name"] == "test-rule" for r in rules["Rules"])+++def test_eventbridge_put_events(eb):+ resp = eb.put_events(Entries=[+ {"Source": "myapp", "DetailType": "UserSignup", "Detail": json.dumps({"userId": "123"}), "EventBusName": "default"},+ {"Source": "myapp", "DetailType": "OrderPlaced", "Detail": json.dumps({"orderId": "456"}), "EventBusName": "default"},+ ])+ assert resp["FailedEntryCount"] == 0+ assert len(resp["Entries"]) == 2+++def test_eventbridge_targets(eb):+ eb.put_rule(Name="target-rule", ScheduleExpression="rate(1 minute)", State="ENABLED")+ eb.put_targets(Rule="target-rule", Targets=[+ {"Id": "1", "Arn": "arn:aws:lambda:us-east-1:000000000000:function:my-func"},+ ])+ resp = eb.list_targets_by_rule(Rule="target-rule")+ assert len(resp["Targets"]) == 1+++# ========== Kinesis ==========++def test_kinesis_put_get(kin):+ kin.create_stream(StreamName="test-stream", ShardCount=1)+ kin.put_record(StreamName="test-stream", Data=b"hello kinesis", PartitionKey="pk1")+ kin.put_record(StreamName="test-stream", Data=b"second record", PartitionKey="pk2")+ desc = kin.describe_stream(StreamName="test-stream")+ shard_id = desc["StreamDescription"]["Shards"][0]["ShardId"]+ it = kin.get_shard_iterator(StreamName="test-stream", ShardId=shard_id, ShardIteratorType="TRIM_HORIZON")+ records = kin.get_records(ShardIterator=it["ShardIterator"])+ assert len(records["Records"]) == 2+++def test_kinesis_batch(kin):+ kin.create_stream(StreamName="test-stream-batch", ShardCount=1)+ resp = kin.put_records(+ StreamName="test-stream-batch",+ Records=[{"Data": f"record-{i}".encode(), "PartitionKey": f"pk{i}"} for i in range(5)],+ )+ assert resp["FailedRecordCount"] == 0+ assert len(resp["Records"]) == 5+++def test_kinesis_list(kin):+ resp = kin.list_streams()+ assert "test-stream" in resp["StreamNames"]+++# ========== CloudWatch Metrics ==========++def test_cloudwatch_metrics(cw):+ cw.put_metric_data(+ Namespace="MyApp",+ MetricData=[+ {"MetricName": "RequestCount", "Value": 42.0, "Unit": "Count"},+ {"MetricName": "Latency", "Value": 123.5, "Unit": "Milliseconds"},+ ],+ )+ resp = cw.list_metrics(Namespace="MyApp")+ names = [m["MetricName"] for m in resp["Metrics"]]+ assert "RequestCount" in names+ assert "Latency" in names+++def test_cloudwatch_alarm(cw):+ cw.put_metric_alarm(+ AlarmName="high-latency",+ MetricName="Latency",+ Namespace="MyApp",+ Statistic="Average",+ Period=60,+ EvaluationPeriods=1,+ Threshold=500.0,+ ComparisonOperator="GreaterThanThreshold",+ )+ resp = cw.describe_alarms(AlarmNames=["high-latency"])+ assert len(resp["MetricAlarms"]) == 1+++# ========== SES ==========++def test_ses_send(ses):+ ses.verify_email_identity(EmailAddress="[email protected]")+ resp = ses.send_email(+ Source="[email protected]",+ Destination={"ToAddresses": ["[email protected]"]},+ Message={+ "Subject": {"Data": "Test Subject"},+ "Body": {"Text": {"Data": "Hello from MiniStack SES"}},+ },+ )+ assert "MessageId" in resp+++def test_ses_list_identities(ses):+ ses.verify_email_identity(EmailAddress="[email protected]")+ resp = ses.list_identities()+ assert "[email protected]" in resp["Identities"]+++def test_ses_quota(ses):+ resp = ses.get_send_quota()+ assert resp["Max24HourSend"] == 50000.0+++# ========== Step Functions ==========++def test_sfn_create_execute(sfn):+ definition = json.dumps({+ "Comment": "Simple state machine",+ "StartAt": "HelloWorld",+ "States": {"HelloWorld": {"Type": "Pass", "End": True}},+ })+ resp = sfn.create_state_machine(+ name="test-machine",+ definition=definition,+ roleArn="arn:aws:iam::000000000000:role/StepFunctionsRole",+ )+ sm_arn = resp["stateMachineArn"]+ exec_resp = sfn.start_execution(stateMachineArn=sm_arn, input=json.dumps({"key": "value"}))+ exec_arn = exec_resp["executionArn"]+ desc = sfn.describe_execution(executionArn=exec_arn)+ assert desc["status"] == "RUNNING"+++def test_sfn_list(sfn):+ machines = sfn.list_state_machines()+ assert any(m["name"] == "test-machine" for m in machines["stateMachines"])+ sm_arn = next(m["stateMachineArn"] for m in machines["stateMachines"] if m["name"] == "test-machine")+ execs = sfn.list_executions(stateMachineArn=sm_arn)+ assert len(execs["executions"]) >= 1+++# ========== ECS ==========++def test_ecs_cluster(ecs):+ ecs.create_cluster(clusterName="test-cluster")+ clusters = ecs.list_clusters()+ assert any("test-cluster" in arn for arn in clusters["clusterArns"])+++def test_ecs_task_def(ecs):+ resp = ecs.register_task_definition(+ family="test-task",+ containerDefinitions=[{+ "name": "web",+ "image": "nginx:alpine",+ "cpu": 128,+ "memory": 256,+ "portMappings": [{"containerPort": 80, "hostPort": 8080}],+ }],+ requiresCompatibilities=["EC2"],+ cpu="256",+ memory="512",+ )+ assert resp["taskDefinition"]["family"] == "test-task"+ assert resp["taskDefinition"]["revision"] == 1+++def test_ecs_list_task_defs(ecs):+ resp = ecs.list_task_definitions(familyPrefix="test-task")+ assert len(resp["taskDefinitionArns"]) >= 1+++def test_ecs_service(ecs):+ ecs.create_service(+ cluster="test-cluster",+ serviceName="test-service",+ taskDefinition="test-task",+ desiredCount=1,+ )+ resp = ecs.describe_services(cluster="test-cluster", services=["test-service"])+ assert len(resp["services"]) == 1+ assert resp["services"][0]["serviceName"] == "test-service"+++# ========== RDS ==========++def test_rds_create(rds):+ rds.create_db_instance(+ DBInstanceIdentifier="test-db",+ DBInstanceClass="db.t3.micro",+ Engine="postgres",+ MasterUsername="admin",+ MasterUserPassword="password123",+ DBName="testdb",+ AllocatedStorage=20,+ )+ resp = rds.describe_db_instances(DBInstanceIdentifier="test-db")+ instances = resp["DBInstances"]+ assert len(instances) == 1+ assert instances[0]["DBInstanceIdentifier"] == "test-db"+ assert instances[0]["Engine"] == "postgres"+ assert "Address" in instances[0]["Endpoint"]+++def test_rds_engines(rds):+ resp = rds.describe_db_engine_versions(Engine="postgres")+ assert len(resp["DBEngineVersions"]) > 0+++def test_rds_cluster(rds):+ rds.create_db_cluster(+ DBClusterIdentifier="test-cluster",+ Engine="aurora-postgresql",+ MasterUsername="admin",+ MasterUserPassword="password123",+ )+ resp = rds.describe_db_clusters(DBClusterIdentifier="test-cluster")+ assert resp["DBClusters"][0]["DBClusterIdentifier"] == "test-cluster"+++# ========== ElastiCache ==========++def test_elasticache_create(ec):+ ec.create_cache_cluster(+ CacheClusterId="test-redis",+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ resp = ec.describe_cache_clusters(CacheClusterId="test-redis")+ clusters = resp["CacheClusters"]+ assert len(clusters) == 1+ assert clusters[0]["CacheClusterId"] == "test-redis"+ assert clusters[0]["Engine"] == "redis"+++def test_elasticache_replication_group(ec):+ ec.create_replication_group(+ ReplicationGroupId="test-rg",+ ReplicationGroupDescription="Test replication group",+ CacheNodeType="cache.t3.micro",+ )+ resp = ec.describe_replication_groups(ReplicationGroupId="test-rg")+ assert resp["ReplicationGroups"][0]["ReplicationGroupId"] == "test-rg"+++def test_elasticache_engines(ec):+ resp = ec.describe_cache_engine_versions(Engine="redis")+ assert len(resp["CacheEngineVersions"]) > 0+++# ========== Glue ==========++def test_glue_catalog(glue):+ glue.create_database(DatabaseInput={"Name": "test_db", "Description": "Test database"})+ glue.create_table(+ DatabaseName="test_db",+ TableInput={+ "Name": "test_table",+ "StorageDescriptor": {+ "Columns": [+ {"Name": "id", "Type": "int"},+ {"Name": "name", "Type": "string"},+ ],+ "Location": "s3://my-bucket/data/",+ "InputFormat": "org.apache.hadoop.mapred.TextInputFormat",+ "OutputFormat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",+ "SerdeInfo": {"SerializationLibrary": "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"},+ },+ "TableType": "EXTERNAL_TABLE",+ },+ )+ resp = glue.get_table(DatabaseName="test_db", Name="test_table")+ assert resp["Table"]["Name"] == "test_table"+++def test_glue_list(glue):+ dbs = glue.get_databases()+ assert any(d["Name"] == "test_db" for d in dbs["DatabaseList"])+ tables = glue.get_tables(DatabaseName="test_db")+ assert any(t["Name"] == "test_table" for t in tables["TableList"])+++def test_glue_job(glue):+ glue.create_job(+ Name="test-job",+ Role="arn:aws:iam::000000000000:role/GlueRole",+ Command={"Name": "glueetl", "ScriptLocation": "s3://my-bucket/scripts/etl.py"},+ GlueVersion="3.0",+ )+ resp = glue.start_job_run(JobName="test-job")+ assert "JobRunId" in resp+ runs = glue.get_job_runs(JobName="test-job")+ assert len(runs["JobRuns"]) == 1+++def test_glue_crawler(glue):+ glue.create_crawler(+ Name="test-crawler",+ Role="arn:aws:iam::000000000000:role/GlueRole",+ DatabaseName="test_db",+ Targets={"S3Targets": [{"Path": "s3://my-bucket/data/"}]},+ )+ resp = glue.get_crawler(Name="test-crawler")+ assert resp["Crawler"]["Name"] == "test-crawler"+ glue.start_crawler(Name="test-crawler")+++# ========== Athena ==========++def test_athena_query(athena):+ resp = athena.start_query_execution(+ QueryString="SELECT 1 AS num, 'hello' AS greeting",+ QueryExecutionContext={"Database": "default"},+ ResultConfiguration={"OutputLocation": "s3://athena-results/"},+ )+ query_id = resp["QueryExecutionId"]+ state = None+ for _ in range(10):+ status = athena.get_query_execution(QueryExecutionId=query_id)+ state = status["QueryExecution"]["Status"]["State"]+ if state in ("SUCCEEDED", "FAILED", "CANCELLED"):+ break+ time.sleep(0.2)+ assert state == "SUCCEEDED", f"Query ended in state: {state}"+ results = athena.get_query_results(QueryExecutionId=query_id)+ assert len(results["ResultSet"]["Rows"]) >= 1+++def test_athena_workgroup(athena):+ athena.create_work_group(+ Name="test-wg",+ Description="Test workgroup",+ Configuration={"ResultConfiguration": {"OutputLocation": "s3://athena-results/test/"}},+ )+ wgs = athena.list_work_groups()+ assert any(wg["Name"] == "test-wg" for wg in wgs["WorkGroups"])+ resp = athena.create_named_query(+ Name="my-query",+ Database="default",+ QueryString="SELECT * FROM my_table LIMIT 10",+ WorkGroup="test-wg",+ )+ assert "NamedQueryId" in resp