firt commit

This commit is contained in:
Hector Ventura committed 2026-03-15 17:43:56 -05:00
commit 61433f59ab
313 files changed
+51266

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
target/
data/
.git/
.idea/
.DS_Store
*.md
+36
View File
@@ -0,0 +1,36 @@
---
name: Bug report
about: An AWS API call returns wrong behavior or an error
title: '[BUG] '
labels: bug
assignees: ''
---
## Service
<!-- e.g. SQS, DynamoDB, Lambda -->
## AWS API Action
<!-- e.g. SendMessage, PutItem, CreateFunction -->
## Expected behavior
<!-- What the real AWS SDK/CLI returns -->
## Actual behavior
<!-- What Floci returns — include the full error message or response body -->
## Reproduction
```bash
# Minimal AWS CLI or SDK snippet that triggers the issue
aws --endpoint-url http://localhost:4566 sqs send-message ...
```
## Environment
- Floci version / image tag:
- Java SDK version (if applicable):
- How you're running Floci (Docker / native / `mvn quarkus:dev`):
+28
View File
@@ -0,0 +1,28 @@
---
name: Feature request
about: Missing AWS API action or service
title: '[FEAT] '
labels: enhancement
assignees: ''
---
## Service
<!-- e.g. S3, Kinesis, CloudWatch -->
## API Action / Feature
<!-- e.g. S3 Object Tagging, Kinesis GetShardIterator -->
## AWS Documentation
<!-- Link to the AWS API reference for this action -->
## Why is this needed?
<!-- Describe your use case — what breaks without it? -->
## Are you willing to contribute a PR?
- [ ] Yes
- [ ] No
+21
View File
@@ -0,0 +1,21 @@
## Summary
<!-- What does this PR do? Link any related issues with "Closes #N" -->
## Type of change
- [ ] Bug fix (`fix:`)
- [ ] New feature (`feat:`)
- [ ] Breaking change (`feat!:` or `fix!:`)
- [ ] Docs / chore
## AWS Compatibility
<!-- For new actions: which SDK version and AWS CLI version were used to verify the wire protocol? -->
<!-- For bug fixes: what was the incorrect behavior? -->
## Checklist
- [ ] `mvn test` passes locally
- [ ] New or updated integration test added
- [ ] Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/)
+63
View File
@@ -0,0 +1,63 @@
name: Docker
on:
push:
tags:
- '*.*.*'
permissions:
contents: read
jobs:
build:
name: Build & Push Docker Images
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Extract version from tag
id: version
run: echo "version=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
- name: Set up QEMU
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: Build and push native image
uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile.native
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/floci:latest
${{ secrets.DOCKERHUB_USERNAME }}/floci:${{ steps.version.outputs.version }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
VERSION=${{ steps.version.outputs.version }}
- name: Build and push JVM image
uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/floci:latest-jvm
${{ secrets.DOCKERHUB_USERNAME }}/floci:${{ steps.version.outputs.version }}-jvm
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
VERSION=${{ steps.version.outputs.version }}
+29
View File
@@ -0,0 +1,29 @@
name: Publish Docs
on:
push:
branches:
- main
paths:
- "docs/**"
- "mkdocs.yml"
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: Install MkDocs
run: pip install -r docs/requirements.txt
- name: Deploy to GitHub Pages
run: mkdocs gh-deploy --force
+30
View File
@@ -0,0 +1,30 @@
name: Release
on:
push:
branches:
- main
permissions:
contents: write
jobs:
release:
name: Semantic Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Semantic Release
uses: cycjimmy/semantic-release-action@v4
with:
extra_plugins: |
@semantic-release/changelog
@semantic-release/git
@semantic-release/exec
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+15
View File
@@ -0,0 +1,15 @@
target/
data/
*.class
*.jar
*.war
.idea/
*.iml
.settings/
.project
.classpath
.vscode/
.DS_Store
CLAUDE.md
.claude
+28
View File
@@ -0,0 +1,28 @@
{
"tagFormat": "${version}",
"branches": ["main"],
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
[
"@semantic-release/changelog",
{
"changelogFile": "CHANGELOG.md"
}
],
[
"@semantic-release/exec",
{
"prepareCmd": "mvn versions:set -DnewVersion=${nextRelease.version} -DgenerateBackupPoms=false && sed -i 's/ENV FLOCI_VERSION=.*/ENV FLOCI_VERSION=${nextRelease.version}/' Dockerfile.native"
}
],
[
"@semantic-release/git",
{
"assets": ["pom.xml", "Dockerfile.native", "CHANGELOG.md"],
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
}
],
"@semantic-release/github"
]
}
+31
View File
@@ -0,0 +1,31 @@
# Code of Conduct
## Our Pledge
We as members, contributors, and maintainers pledge to make participation in Floci a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
**Positive behavior includes:**
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
**Unacceptable behavior includes:**
- The use of sexualized language or imagery
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening a GitHub issue or contacting the maintainers directly. All complaints will be reviewed and investigated promptly and fairly.
Maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, issues, and other contributions that are not aligned with this Code of Conduct.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1.
+81
View File
@@ -0,0 +1,81 @@
# Contributing to Floci
Thank you for your interest in contributing! Floci is a community-driven project and all contributions are welcome.
## Ways to Contribute
- **Bug reports** — open an issue with a minimal reproduction
- **Feature requests** — open an issue describing the AWS behavior you need
- **Pull requests** — bug fixes, new service implementations, or improvements
- **Compatibility tests** — add cases to `../floci-compatibility-tests`
## Getting Started
### Prerequisites
- Java 25+
- Maven 3.9+
- Docker (for integration tests that spin up Lambda/RDS/ElastiCache)
### Build & Run
```bash
git clone https://github.com/hectorvent/floci.git
cd floci
mvn quarkus:dev # hot reload on port 4566
```
### Run Tests
```bash
mvn test # all tests
mvn test -Dtest=SsmIntegrationTest # single class
mvn test -Dtest=SsmIntegrationTest#putParameter # single method
```
## Commit Message Format
This project uses [Conventional Commits](https://www.conventionalcommits.org/) — semantic-release reads these to generate the changelog and version bumps automatically.
| Prefix | When to use | Version bump |
|--------|-------------|--------------|
| `feat:` | New AWS API action or service | minor |
| `fix:` | Bug fix or AWS compatibility correction | patch |
| `perf:` | Performance improvement | patch |
| `docs:` | Documentation only | none |
| `chore:` | Build, CI, dependencies | none |
| `BREAKING CHANGE:` | Footer or `!` suffix — incompatible change | major |
**Examples:**
```
feat: add SQS SendMessageBatch action
fix: correct DynamoDB QueryFilter comparison operators
feat!: change default storage mode to persistent
```
## Architecture
See [CLAUDE.md](CLAUDE.md) for a detailed description of the three-layer architecture (Controller → Service → Storage), the AWS wire protocol mapping, and conventions for adding new services.
## Adding a New AWS Service
1. Create a package under `src/main/java/.../services/<service>/`
2. Add a Controller (follow the correct protocol — Query, JSON 1.1, REST JSON, or REST XML)
3. Add a Service (`@ApplicationScoped`) and model POJOs
4. Register in `ServiceRegistry`
5. Add config entries in `EmulatorConfig.java` and `application.yml`
6. Add integration tests in `*IntegrationTest.java`
Always implement the **real AWS wire protocol** — never invent custom endpoints. The AWS SDK must work against Floci without modification.
## Pull Request Guidelines
- Keep PRs focused — one feature or fix per PR
- Add or update tests for any changed behavior
- Ensure `mvn test` passes before opening the PR
- Reference any related issues in the PR description
## Reporting Security Issues
Please do **not** open public issues for security vulnerabilities. Report them privately by emailing the maintainer or using [GitHub private vulnerability reporting](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/privately-reporting-a-security-vulnerability).
+27
View File
@@ -0,0 +1,27 @@
# Stage 1: Build
FROM eclipse-temurin:25-jdk AS build
WORKDIR /build
RUN apt-get update && apt-get install -y maven && rm -rf /var/lib/apt/lists/*
COPY pom.xml .
RUN mvn dependency:go-offline -q
COPY src/ src/
RUN mvn clean package -DskipTests -q
# Stage 2: Runtime
FROM eclipse-temurin:25-jre-alpine
WORKDIR /app
COPY --from=build /build/target/quarkus-app/ quarkus-app/
RUN mkdir -p /app/data
VOLUME /app/data
EXPOSE 4566 6379-6399
ARG VERSION=latest
ENV FLOCI_VERSION=${VERSION}
ENTRYPOINT ["java", "-jar", "quarkus-app/quarkus-run.jar"]
+30
View File
@@ -0,0 +1,30 @@
# Stage 1: Build native executable
FROM quay.io/quarkus/ubi-quarkus-mandrel-builder-image:jdk-24 AS build
USER root
WORKDIR /app
# Install Maven 3.9.x (system Maven is too old for Quarkus 3.31)
RUN curl -fsSL https://archive.apache.org/dist/maven/maven-3/3.9.12/binaries/apache-maven-3.9.12-bin.tar.gz | tar xz -C /opt \
&& ln -sf /opt/apache-maven-3.9.12/bin/mvn /usr/local/bin/mvn
COPY pom.xml .
RUN mvn dependency:go-offline -B
COPY src ./src
RUN mvn clean package -Dnative -DskipTests -B
# Stage 2: Minimal runtime
FROM quay.io/quarkus/quarkus-micro-image:2.0
WORKDIR /app
VOLUME /app/data
EXPOSE 4566
ARG VERSION=latest
ENV FLOCI_VERSION=${VERSION}
COPY --from=build /app/target/*-runner /app/application
RUN chmod +x /app/application
ENTRYPOINT ["/app/application"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Hector Ventura
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.
+965
View File
@@ -0,0 +1,965 @@
<p align="center">
<img src="logo.svg" alt="Floci" width="400" />
</p>
<h3 align="center">🍿☁️ Light, fluffy, and always free</h3>
<p align="center">
<em>Named after <a href="https://en.wikipedia.org/wiki/Cirrocumulus_floccus">floccus</a> — the cloud formation that looks exactly like popcorn.</em>
</p>
A fast, free, and open-source local AWS service emulator built for developers who need reliable AWS services in
development without the cost, complexity, or vendor lock-in.
Floci runs as a single binary on port 4566 and emulates SSM Parameter Store, SQS, SNS, S3, DynamoDB, DynamoDB Streams,
Lambda, API Gateway (REST and HTTP), Cognito, KMS, Kinesis, Secrets Manager, CloudFormation, Step Functions, IAM, STS,
ElastiCache, RDS, EventBridge, and CloudWatch with full AWS CLI and SDK compatibility.
## Why Floci?
**No account required.** No auth tokens, no sign-ups, no telemetry. Pull the image and start building.
**No feature gates.** Every feature is available to everyone. SSM, SQS, SNS, S3, DynamoDB, DynamoDB Streams, Lambda, API
Gateway (REST and HTTP), Cognito, KMS, Kinesis, Secrets Manager, CloudFormation, Step Functions, IAM, STS, ElastiCache (
Redis with IAM auth), RDS (PostgreSQL and MySQL with IAM auth), EventBridge, CloudWatch Logs and Metrics — all included,
all free, forever.
**No CI restrictions.** Run Floci in your CI pipeline with zero limitations. No credits, no quotas, no paid tiers for
automated testing.
**Truly open source.** MIT licensed. Fork it, extend it, embed it. No "community edition" sunset coming.
> With LocalStack's community
> edition [sunsetting in March 2026](https://blog.localstack.cloud/the-road-ahead-for-localstack/) -- requiring auth
> tokens, dropping CI support from the free tier, and ceasing security updates -- Floci offers a stable,
> no-strings-attached alternative for teams that need local AWS services without commercial dependencies.
## Quick Start
### Docker (Recommended)
`latest` is the native image — sub-second startup, minimal memory:
```yaml
# docker-compose.yml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
volumes:
- ./data:/app/data
```
```bash
docker compose up
```
All services are available at `http://localhost:4566`.
### JVM Image
For broader platform compatibility, use the JVM image:
```yaml
services:
floci:
image: hectorvent/floci:latest-jvm
ports:
- "4566:4566"
volumes:
- ./data:/app/data
```
### Image Tags
| Tag | Description |
|---|---|
| `latest` | Native image — sub-second startup (**default**) |
| `x.y.z` | Native image — pinned release |
| `latest-jvm` | JVM image — most compatible |
| `x.y.z-jvm` | JVM image — pinned release |
### Build from Source
```bash
git clone https://github.com/hectorvent/floci.git
cd floci
mvn quarkus:dev # Dev mode with hot reload on port 4566
```
## Usage
Point any AWS CLI or SDK to Floci using `--endpoint-url`:
```bash
export AWS_ENDPOINT=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
```
### SSM Parameter Store
```bash
aws ssm put-parameter --endpoint-url $AWS_ENDPOINT \
--name /app/db/host --value "localhost" --type String
aws ssm get-parameter --endpoint-url $AWS_ENDPOINT \
--name /app/db/host
aws ssm get-parameters-by-path --endpoint-url $AWS_ENDPOINT \
--path /app/ --recursive
```
### SQS
```bash
aws sqs create-queue --endpoint-url $AWS_ENDPOINT \
--queue-name my-queue
aws sqs send-message --endpoint-url $AWS_ENDPOINT \
--queue-url $AWS_ENDPOINT/000000000000/my-queue \
--message-body '{"event":"order.created"}'
aws sqs receive-message --endpoint-url $AWS_ENDPOINT \
--queue-url $AWS_ENDPOINT/000000000000/my-queue
```
### S3
```bash
aws s3 mb s3://my-bucket --endpoint-url $AWS_ENDPOINT
aws s3 cp myfile.txt s3://my-bucket/ --endpoint-url $AWS_ENDPOINT
aws s3 ls s3://my-bucket --endpoint-url $AWS_ENDPOINT
```
### DynamoDB
```bash
aws dynamodb create-table --endpoint-url $AWS_ENDPOINT \
--table-name Users \
--attribute-definitions AttributeName=userId,AttributeType=S \
--key-schema AttributeName=userId,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
aws dynamodb put-item --endpoint-url $AWS_ENDPOINT \
--table-name Users \
--item '{"userId":{"S":"u1"},"name":{"S":"Alice"}}'
aws dynamodb get-item --endpoint-url $AWS_ENDPOINT \
--table-name Users --key '{"userId":{"S":"u1"}}'
```
### IAM
```bash
aws iam create-user --endpoint-url $AWS_ENDPOINT --user-name alice
aws iam create-role --endpoint-url $AWS_ENDPOINT \
--role-name my-role \
--assume-role-policy-document '{"Version":"2012-10-17","Statement":[]}'
aws iam attach-role-policy --endpoint-url $AWS_ENDPOINT \
--role-name my-role --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess
```
### STS
```bash
aws sts get-caller-identity --endpoint-url $AWS_ENDPOINT
aws sts assume-role --endpoint-url $AWS_ENDPOINT \
--role-arn arn:aws:iam::000000000000:role/my-role \
--role-session-name my-session
```
## SDK Integration
```java
// Java (AWS SDK v2)
DynamoDbClient client = DynamoDbClient.builder()
.endpointOverride(URI.create("http://localhost:4566"))
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test")))
.build();
```
```python
# Python (boto3)
import boto3
client = boto3.client('ssm',
endpoint_url='http://localhost:4566',
region_name='us-east-1',
aws_access_key_id='test',
aws_secret_access_key='test')
```
```javascript
// Node.js (AWS SDK v3)
import {SSMClient} from "@aws-sdk/client-ssm";
const client = new SSMClient({
endpoint: "http://localhost:4566",
region: "us-east-1",
credentials: {accessKeyId: "test", secretAccessKey: "test"},
});
```
## Supported Operations
### SSM Parameter Store (12 operations)
| Operation | Description |
|--------------------------|---------------------------------------|
| `PutParameter` | Create or update a parameter |
| `GetParameter` | Retrieve a single parameter |
| `GetParameters` | Retrieve multiple parameters by name |
| `GetParametersByPath` | Retrieve parameters by path hierarchy |
| `GetParameterHistory` | Get version history of a parameter |
| `LabelParameterVersion` | Attach labels to a parameter version |
| `DescribeParameters` | List parameters with optional filters |
| `DeleteParameter` | Delete a single parameter |
| `DeleteParameters` | Delete multiple parameters |
| `AddTagsToResource` | Tag a parameter |
| `ListTagsForResource` | List parameter tags |
| `RemoveTagsFromResource` | Remove parameter tags |
### SQS (17 operations)
| Operation | Description |
|--------------------------------|------------------------------------------|
| `CreateQueue` | Create a standard or FIFO queue |
| `DeleteQueue` | Delete a queue |
| `ListQueues` | List all queues |
| `GetQueueUrl` | Get queue URL by name |
| `GetQueueAttributes` | Get queue attributes |
| `SetQueueAttributes` | Set queue attributes |
| `SendMessage` | Send a message (FIFO supported) |
| `SendMessageBatch` | Send up to 10 messages in one request |
| `ReceiveMessage` | Receive messages with visibility timeout |
| `DeleteMessage` | Delete a message by receipt handle |
| `DeleteMessageBatch` | Delete up to 10 messages in one request |
| `ChangeMessageVisibility` | Change message visibility timeout |
| `ChangeMessageVisibilityBatch` | Change visibility for multiple messages |
| `PurgeQueue` | Delete all messages in a queue |
| `TagQueue` | Tag a queue |
| `UntagQueue` | Remove queue tags |
| `ListQueueTags` | List queue tags |
### SNS (13 operations)
| Operation | Description |
|----------------------------|----------------------------------|
| `CreateTopic` | Create a topic |
| `DeleteTopic` | Delete a topic |
| `GetTopicAttributes` | Get topic attributes |
| `SetTopicAttributes` | Set topic attributes |
| `ListTopics` | List all topics |
| `Subscribe` | Subscribe an endpoint to a topic |
| `Unsubscribe` | Remove a subscription |
| `ListSubscriptions` | List all subscriptions |
| `ListSubscriptionsByTopic` | List subscriptions for a topic |
| `Publish` | Publish a message to a topic |
| `TagResource` | Tag a topic |
| `UntagResource` | Remove topic tags |
| `ListTagsForResource` | List topic tags |
### S3 (30 operations)
| Operation | Description |
|--------------------------------------|-----------------------------------------------------|
| `CreateBucket` | Create a bucket (with optional Object Lock) |
| `DeleteBucket` | Delete a bucket |
| `ListBuckets` | List all buckets |
| `HeadBucket` | Check bucket existence |
| `GetBucketLocation` | Get bucket region |
| `PutObject` | Upload an object |
| `GetObject` | Download an object |
| `HeadObject` | Get object metadata |
| `DeleteObject` | Delete an object |
| `DeleteObjects` | Delete multiple objects in one request |
| `CopyObject` | Copy an object within or between buckets |
| `ListObjects` / `ListObjectsV2` | List objects with prefix/delimiter support |
| `PutBucketTagging` | Tag a bucket |
| `GetBucketTagging` | Get bucket tags |
| `DeleteBucketTagging` | Remove bucket tags |
| `PutObjectTagging` | Tag an object |
| `GetObjectTagging` | Get object tags |
| `DeleteObjectTagging` | Remove object tags |
| `PutBucketVersioning` | Enable or suspend versioning |
| `GetBucketVersioning` | Get versioning status |
| `ListObjectVersions` | List object versions |
| `InitiateMultipartUpload` | Start a multipart upload |
| `UploadPart` | Upload a part |
| `CompleteMultipartUpload` | Complete a multipart upload |
| `AbortMultipartUpload` | Abort a multipart upload |
| `ListMultipartUploads` | List active multipart uploads |
| `PutBucketNotificationConfiguration` | Configure S3 event notifications (SQS/SNS) |
| `GetBucketNotificationConfiguration` | Get notification configuration |
| `PutObjectLockConfiguration` | Set default retention policy on a bucket |
| `GetObjectLockConfiguration` | Get bucket-level Object Lock config |
| `PutObjectRetention` | Set COMPLIANCE or GOVERNANCE retention on an object |
| `GetObjectRetention` | Get per-object retention settings |
| `PutObjectLegalHold` | Apply or lift a legal hold on an object |
| `GetObjectLegalHold` | Get legal hold status |
| Pre-signed URLs | Generate time-limited GET/PUT URLs (AWS Sig V4) |
### DynamoDB (22 operations)
| Operation | Description |
|----------------------|-----------------------------------------------------------|
| `CreateTable` | Create a table with key schema, GSIs, and LSIs |
| `DeleteTable` | Delete a table |
| `DescribeTable` | Get table metadata |
| `ListTables` | List all tables |
| `UpdateTable` | Modify throughput and table settings |
| `DescribeTimeToLive` | Get TTL configuration |
| `UpdateTimeToLive` | Enable or disable TTL on a table |
| `PutItem` | Insert or replace an item |
| `GetItem` | Retrieve a single item by key |
| `DeleteItem` | Delete an item by key |
| `UpdateItem` | Update item (UpdateExpression supported) |
| `Query` | Query with key conditions and filters (GSI/LSI supported) |
| `Scan` | Scan with filter expressions |
| `BatchWriteItem` | Put or delete up to 25 items |
| `BatchGetItem` | Get up to 100 items across tables |
| `TransactWriteItems` | Execute multiple write operations atomically |
| `TransactGetItems` | Get multiple items atomically |
| `TagResource` | Tag a table |
| `UntagResource` | Remove table tags |
| `ListTagsOfResource` | List table tags |
### DynamoDB Streams (5 operations)
| Operation | Description |
|--------------------|---------------------------------------------------|
| `ListStreams` | List streams for a table |
| `DescribeStream` | Get stream metadata and shard info |
| `GetShardIterator` | Get a shard iterator |
| `GetRecords` | Read records from a stream shard |
| Stream triggers | DynamoDB Streams as a Lambda event source mapping |
### Lambda (25 operations)
| Operation | Description |
|-------------------------------|----------------------------------------------------------------------------|
| `CreateFunction` | Create a function (Node.js, Python, Java runtimes) |
| `GetFunction` | Get function metadata and code location |
| `GetFunctionConfiguration` | Get function configuration |
| `ListFunctions` | List all functions |
| `UpdateFunctionCode` | Update function code |
| `UpdateFunctionConfiguration` | Update environment, memory, timeout, and other settings |
| `DeleteFunction` | Delete a function |
| `Invoke` | Invoke synchronously (RequestResponse), asynchronously (Event), or dry-run |
| `CreateAlias` | Create a function alias pointing to a version |
| `GetAlias` | Get alias details |
| `ListAliases` | List all aliases for a function |
| `UpdateAlias` | Update alias target version |
| `DeleteAlias` | Delete an alias |
| `CreateFunctionUrlConfig` | Create an HTTP URL for a function |
| `GetFunctionUrlConfig` | Get function URL configuration |
| `UpdateFunctionUrlConfig` | Update function URL settings |
| `DeleteFunctionUrlConfig` | Delete a function URL |
| `ListFunctionUrlConfigs` | List function URLs |
| `CreateEventSourceMapping` | Map SQS, Kinesis, or DynamoDB Streams to trigger a function |
| `GetEventSourceMapping` | Get mapping details |
| `ListEventSourceMappings` | List all mappings |
| `UpdateEventSourceMapping` | Change batch size or state |
| `DeleteEventSourceMapping` | Remove a mapping |
### API Gateway (24 operations)
| Operation | Description |
|---------------------------------------------|----------------------------------------------------|
| `CreateRestApi` | Create a REST API |
| `GetRestApi` / `GetRestApis` | Get one or all REST APIs |
| `DeleteRestApi` | Delete a REST API |
| `CreateResource` | Add a resource path |
| `GetResource` / `GetResources` | Get one or all resources |
| `DeleteResource` | Delete a resource |
| `PutMethod` | Add an HTTP method to a resource |
| `GetMethod` | Get method configuration |
| `PutMethodResponse` | Configure method response |
| `PutIntegration` | Set backend integration (MOCK or AWS_PROXY/Lambda) |
| `GetIntegration` | Get integration details |
| `PutIntegrationResponse` | Configure integration response |
| `GetIntegrationResponse` | Get integration response |
| `CreateDeployment` | Deploy an API snapshot |
| `CreateStage` | Create a named stage |
| `GetStage` / `GetStages` | Get one or all stages |
| `UpdateStage` | Update stage variables or settings |
| `DeleteStage` | Delete a stage |
| `TagResource` / `UntagResource` / `GetTags` | Tag management |
| Stage invocation | Execute APIs via `/{stage}/{path}` routing |
### IAM (65+ operations)
| Category | Operations |
|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Users | `CreateUser`, `GetUser`, `ListUsers`, `UpdateUser`, `DeleteUser`, `TagUser`, `UntagUser`, `ListUserTags` |
| Access Keys | `CreateAccessKey`, `ListAccessKeys`, `UpdateAccessKey`, `DeleteAccessKey` |
| Groups | `CreateGroup`, `GetGroup`, `ListGroups`, `DeleteGroup`, `AddUserToGroup`, `RemoveUserFromGroup`, `ListGroupsForUser` |
| Roles | `CreateRole`, `GetRole`, `ListRoles`, `UpdateRole`, `DeleteRole`, `UpdateAssumeRolePolicy`, `TagRole`, `UntagRole`, `ListRoleTags` |
| Policies | `CreatePolicy`, `GetPolicy`, `ListPolicies`, `DeletePolicy`, `CreatePolicyVersion`, `GetPolicyVersion`, `ListPolicyVersions`, `DeletePolicyVersion`, `SetDefaultPolicyVersion`, `TagPolicy`, `UntagPolicy`, `ListPolicyTags` |
| Policy Attachments | `AttachRolePolicy`, `DetachRolePolicy`, `ListAttachedRolePolicies`, `AttachUserPolicy`, `DetachUserPolicy`, `ListAttachedUserPolicies`, `AttachGroupPolicy`, `DetachGroupPolicy`, `ListAttachedGroupPolicies` |
| Inline Policies | `PutRolePolicy`, `GetRolePolicy`, `ListRolePolicies`, `DeleteRolePolicy`, `PutUserPolicy`, `GetUserPolicy`, `ListUserPolicies`, `DeleteUserPolicy`, `PutGroupPolicy`, `GetGroupPolicy`, `ListGroupPolicies`, `DeleteGroupPolicy` |
| Instance Profiles | `CreateInstanceProfile`, `GetInstanceProfile`, `ListInstanceProfiles`, `DeleteInstanceProfile`, `AddRoleToInstanceProfile`, `RemoveRoleFromInstanceProfile`, `ListInstanceProfilesForRole` |
### STS (7 operations)
| Operation | Description |
|------------------------------|-------------------------------------------------------|
| `GetCallerIdentity` | Return account ID, user ID, and ARN |
| `AssumeRole` | Return temporary credentials for a role |
| `AssumeRoleWithWebIdentity` | Assume a role via OIDC/web identity token |
| `AssumeRoleWithSAML` | Assume a role via SAML assertion |
| `GetSessionToken` | Return temporary credentials for the current identity |
| `GetFederationToken` | Return credentials for a federated user |
| `DecodeAuthorizationMessage` | Decode an encoded authorization failure message |
### ElastiCache (9 operations + Redis protocol)
| Operation | Description |
|-----------------------------|---------------------------------------------------------------------------------------------|
| `CreateReplicationGroup` | Create a Redis replication group |
| `DescribeReplicationGroups` | List replication groups |
| `DeleteReplicationGroup` | Delete a replication group |
| `CreateUser` | Create a Redis user with password or IAM auth |
| `DescribeUsers` | List Redis users |
| `ModifyUser` | Update user passwords or access string |
| `DeleteUser` | Delete a Redis user |
| `GenerateIamAuthToken` | Generate a Sig V4 token for Redis IAM auth |
| `ValidateIamAuthToken` | Validate a previously generated token |
| Redis protocol | Full Redis command support via TCP (SET, GET, PING, AUTH, etc.) using real Redis containers |
### RDS (14 operations + JDBC connectivity)
| Operation | Description |
|-----------------------------|-----------------------------------------------------------------------------------------------|
| `CreateDBInstance` | Create a PostgreSQL or MySQL DB instance |
| `DescribeDBInstances` | List DB instances |
| `ModifyDBInstance` | Modify instance settings (e.g., enable IAM auth) |
| `RebootDBInstance` | Reboot an instance |
| `DeleteDBInstance` | Delete an instance |
| `CreateDBCluster` | Create a MySQL/Aurora-compatible cluster |
| `DescribeDBClusters` | List DB clusters |
| `ModifyDBCluster` | Modify cluster settings |
| `DeleteDBCluster` | Delete a cluster |
| `CreateDBParameterGroup` | Create a parameter group |
| `DescribeDBParameterGroups` | List parameter groups |
| `DescribeDBParameters` | List parameters in a group |
| `ModifyDBParameterGroup` | Update parameter values |
| `DeleteDBParameterGroup` | Delete a parameter group |
| IAM Auth | Generate and validate RDS IAM authentication tokens |
| JDBC | Real PostgreSQL and MySQL containers launched on demand, accessible via standard JDBC drivers |
### EventBridge (14 operations)
| Operation | Description |
|------------------------------|---------------------------------------------|
| `CreateEventBus` | Create a custom event bus |
| `DescribeEventBus` | Get event bus details |
| `ListEventBuses` | List all event buses |
| `DeleteEventBus` | Delete an event bus |
| `PutRule` | Create or update an event rule |
| `DescribeRule` | Get rule details |
| `ListRules` | List rules on an event bus |
| `EnableRule` / `DisableRule` | Control whether a rule is active |
| `DeleteRule` | Delete a rule |
| `PutTargets` | Attach targets (SQS, SNS, Lambda) to a rule |
| `ListTargetsByRule` | List rule targets |
| `RemoveTargets` | Detach targets from a rule |
| `PutEvents` | Publish custom events to an event bus |
### CloudWatch Logs (14 operations)
| Operation | Description |
|------------------------------------------------------|-----------------------------------------|
| `CreateLogGroup` | Create a log group |
| `DeleteLogGroup` | Delete a log group |
| `DescribeLogGroups` | List log groups |
| `PutRetentionPolicy` | Set log retention (days) |
| `DeleteRetentionPolicy` | Remove a retention policy |
| `TagLogGroup` / `UntagLogGroup` / `ListTagsLogGroup` | Tag management |
| `CreateLogStream` | Create a log stream within a group |
| `DeleteLogStream` | Delete a log stream |
| `DescribeLogStreams` | List streams in a group |
| `PutLogEvents` | Ingest log events |
| `GetLogEvents` | Retrieve log events with time filtering |
| `FilterLogEvents` | Search log events by pattern |
### CloudWatch Metrics (5 operations)
| Operation | Description |
|-----------------------|-----------------------------------------------------|
| `PutMetricData` | Publish custom metrics with optional dimensions |
| `ListMetrics` | List metrics by namespace, name, or dimension |
| `GetMetricStatistics` | Retrieve statistics (Sum, Average, Count, Min, Max) |
| `GetMetricData` | Query metrics with metric math expressions |
| `PutMetricAlarm` | Create or update a metric alarm |
### API Gateway v2 / HTTP API (16 operations)
| Operation | Description |
|--------------------------------------|-----------------------------------|
| `CreateApi` | Create an HTTP API |
| `GetApi` / `GetApis` | Get one or all HTTP APIs |
| `DeleteApi` | Delete an HTTP API |
| `CreateRoute` | Add a route to an API |
| `GetRoute` / `GetRoutes` | Get one or all routes |
| `DeleteRoute` | Delete a route |
| `CreateIntegration` | Set a backend integration |
| `GetIntegration` / `GetIntegrations` | Get one or all integrations |
| `DeleteIntegration` | Delete an integration |
| `CreateAuthorizer` | Create a JWT or Lambda authorizer |
| `GetAuthorizer` / `GetAuthorizers` | Get one or all authorizers |
| `DeleteAuthorizer` | Delete an authorizer |
| `CreateStage` | Create a named deployment stage |
| `GetStage` / `GetStages` | Get one or all stages |
| `UpdateStage` | Update stage settings |
| `DeleteStage` | Delete a stage |
### Cognito (20 operations)
| Operation | Description |
|-----------------------------|------------------------------------------------------------|
| `CreateUserPool` | Create a user pool |
| `DescribeUserPool` | Get user pool details |
| `ListUserPools` | List all user pools |
| `DeleteUserPool` | Delete a user pool |
| `CreateUserPoolClient` | Create an app client |
| `DescribeUserPoolClient` | Get app client details |
| `ListUserPoolClients` | List app clients for a pool |
| `DeleteUserPoolClient` | Delete an app client |
| `AdminCreateUser` | Create a user in a pool |
| `AdminGetUser` | Get a user by username |
| `AdminDeleteUser` | Delete a user |
| `AdminSetUserPassword` | Set a user's password |
| `AdminUpdateUserAttributes` | Update user attributes |
| `ListUsers` | List users in a pool |
| `SignUp` | Register a new user |
| `InitiateAuth` | Start an authentication flow |
| `AdminInitiateAuth` | Admin-initiated authentication |
| `RespondToAuthChallenge` | Respond to an auth challenge |
| Well-known endpoints | JWKS and OpenID configuration endpoints for JWT validation |
### KMS (15 operations)
| Operation | Description |
|-----------------------------------|---------------------------------------------------------|
| `CreateKey` | Create a KMS key |
| `DescribeKey` | Get key metadata |
| `ListKeys` | List all keys |
| `ScheduleKeyDeletion` | Schedule a key for deletion |
| `CancelKeyDeletion` | Cancel a pending deletion |
| `Encrypt` | Encrypt plaintext data |
| `Decrypt` | Decrypt ciphertext |
| `ReEncrypt` | Re-encrypt data under a different key |
| `GenerateDataKey` | Generate a data encryption key (plaintext + ciphertext) |
| `GenerateDataKeyWithoutPlaintext` | Generate a data key (ciphertext only) |
| `Sign` | Create a digital signature |
| `Verify` | Verify a digital signature |
| `CreateAlias` | Create a friendly alias for a key |
| `DeleteAlias` | Delete an alias |
| `ListAliases` | List all aliases |
### Kinesis (15 operations)
| Operation | Description |
|------------------------------------------------------------------|--------------------------------------------|
| `CreateStream` | Create a data stream |
| `DeleteStream` | Delete a stream |
| `ListStreams` | List all streams |
| `DescribeStream` | Get stream details and shard info |
| `DescribeStreamSummary` | Get a summary of stream metadata |
| `PutRecord` | Write a single record |
| `PutRecords` | Write up to 500 records in one request |
| `GetShardIterator` | Get a position marker for a shard |
| `GetRecords` | Read records from a shard |
| `SplitShard` | Split a shard into two |
| `MergeShards` | Merge two adjacent shards |
| `RegisterStreamConsumer` | Register an enhanced fan-out consumer |
| `DeregisterStreamConsumer` | Remove a consumer |
| `SubscribeToShard` | Subscribe to a shard with enhanced fan-out |
| `AddTagsToStream` / `RemoveTagsFromStream` / `ListTagsForStream` | Tag management |
### Secrets Manager (10 operations)
| Operation | Description |
|--------------------------------------------------------------------|-------------------------------------------------|
| `CreateSecret` | Create a new secret |
| `GetSecretValue` | Retrieve a secret value by name or ARN |
| `PutSecretValue` | Store a new version of a secret |
| `UpdateSecret` | Update secret metadata |
| `DescribeSecret` | Get secret details and version info |
| `ListSecrets` | List all secrets |
| `DeleteSecret` | Delete a secret (with optional recovery window) |
| `ListSecretVersionIds` | List versions of a secret |
| `TagResource` / `UntagResource` | Tag management |
| `GetResourcePolicy` / `PutResourcePolicy` / `DeleteResourcePolicy` | Resource-based policies |
### CloudFormation (12 operations)
| Operation | Description |
|-------------------------|------------------------------------------|
| `CreateStack` | Create a stack from a template |
| `UpdateStack` | Update an existing stack |
| `DeleteStack` | Delete a stack and its resources |
| `DescribeStacks` | Get stack status and outputs |
| `ListStacks` | List stacks with optional status filter |
| `DescribeStackEvents` | Get the event history of a stack |
| `ListStackResources` | List resources in a stack |
| `DescribeStackResource` | Get details of a specific stack resource |
| `CreateChangeSet` | Preview changes before applying |
| `DescribeChangeSet` | Get change set details |
| `ExecuteChangeSet` | Apply a change set to a stack |
| `ListChangeSets` | List change sets for a stack |
### Step Functions (11 operations)
| Operation | Description |
|-------------------------------------------------------------|-----------------------------------------------|
| `CreateStateMachine` | Create a state machine from an ASL definition |
| `DescribeStateMachine` | Get state machine metadata |
| `ListStateMachines` | List all state machines |
| `UpdateStateMachine` | Update the ASL definition or role |
| `DeleteStateMachine` | Delete a state machine |
| `StartExecution` | Start a new execution |
| `DescribeExecution` | Get execution status and output |
| `ListExecutions` | List executions for a state machine |
| `StopExecution` | Stop a running execution |
| `GetExecutionHistory` | Get the event history of an execution |
| `SendTaskSuccess` / `SendTaskFailure` / `SendTaskHeartbeat` | Respond to task tokens |
## Configuration
All settings can be overridden via environment variables. Floci uses the Quarkus convention: dots become underscores,
names become uppercase (e.g., `floci.default-region` becomes `FLOCI_DEFAULT_REGION`).
### General
| Variable | Default | Description |
|----------------------------|----------------|------------------------|
| `QUARKUS_HTTP_PORT` | `4566` | HTTP port |
| `FLOCI_DEFAULT_REGION` | `us-east-1` | Default AWS region |
| `FLOCI_DEFAULT_ACCOUNT_ID` | `000000000000` | Default AWS account ID |
### Storage
Floci supports 4 storage modes, configurable globally or per service:
| Mode | Description | Best for |
|--------------|------------------------------------------|---------------------------|
| `memory` | In-memory only, data lost on restart | CI, throwaway tests |
| `persistent` | Immediate disk writes on every change | Data safety |
| `hybrid` | In-memory with async flush to disk | Development (default) |
| `wal` | Write-ahead log with periodic compaction | High-throughput workloads |
| Variable | Default | Description |
|--------------------------------------------|----------|------------------------------|
| `FLOCI_STORAGE_MODE` | `hybrid` | Global storage mode |
| `FLOCI_STORAGE_PERSISTENT_PATH` | `./data` | Data directory |
| `FLOCI_STORAGE_WAL_COMPACTION_INTERVAL_MS` | `30000` | WAL compaction interval (ms) |
#### Per-Service Storage Overrides
Override the global mode for individual services:
| Variable | Default | Description |
|-----------------------------------------------------------------|---------------|--------------------------------------|
| `FLOCI_STORAGE_SERVICES_SSM_MODE` | `memory` | SSM storage mode |
| `FLOCI_STORAGE_SERVICES_SSM_FLUSH_INTERVAL_MS` | `5000` | SSM flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_SQS_MODE` | `memory` | SQS storage mode |
| `FLOCI_STORAGE_SERVICES_SQS_PERSIST_ON_SHUTDOWN` | `true` | Flush SQS messages to disk on shutdown |
| `FLOCI_STORAGE_SERVICES_S3_MODE` | `hybrid` | S3 storage mode |
| `FLOCI_STORAGE_SERVICES_S3_CACHE_SIZE_MB` | `100` | S3 in-memory cache size (MB) |
| `FLOCI_STORAGE_SERVICES_DYNAMODB_MODE` | `memory` | DynamoDB storage mode |
| `FLOCI_STORAGE_SERVICES_DYNAMODB_FLUSH_INTERVAL_MS` | `5000` | DynamoDB flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_SNS_MODE` | `memory` | SNS storage mode |
| `FLOCI_STORAGE_SERVICES_SNS_FLUSH_INTERVAL_MS` | `5000` | SNS flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_LAMBDA_MODE` | `memory` | Lambda storage mode |
| `FLOCI_STORAGE_SERVICES_LAMBDA_FLUSH_INTERVAL_MS` | `5000` | Lambda flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_APIGATEWAY_MODE` | `memory` | API Gateway (v1) storage mode |
| `FLOCI_STORAGE_SERVICES_APIGATEWAY_FLUSH_INTERVAL_MS` | `5000` | API Gateway (v1) flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_APIGATEWAYV2_MODE` | `memory` | API Gateway (v2) storage mode |
| `FLOCI_STORAGE_SERVICES_APIGATEWAYV2_FLUSH_INTERVAL_MS` | `5000` | API Gateway (v2) flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_IAM_MODE` | `memory` | IAM storage mode |
| `FLOCI_STORAGE_SERVICES_IAM_FLUSH_INTERVAL_MS` | `5000` | IAM flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_RDS_MODE` | `memory` | RDS storage mode |
| `FLOCI_STORAGE_SERVICES_RDS_FLUSH_INTERVAL_MS` | `5000` | RDS flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_EVENTBRIDGE_MODE` | `memory` | EventBridge storage mode |
| `FLOCI_STORAGE_SERVICES_EVENTBRIDGE_FLUSH_INTERVAL_MS` | `5000` | EventBridge flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_CLOUDWATCHLOGS_MODE` | `memory` | CloudWatch Logs storage mode |
| `FLOCI_STORAGE_SERVICES_CLOUDWATCHLOGS_FLUSH_INTERVAL_MS` | `5000` | CloudWatch Logs flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_CLOUDWATCHMETRICS_MODE` | `memory` | CloudWatch Metrics storage mode |
| `FLOCI_STORAGE_SERVICES_CLOUDWATCHMETRICS_FLUSH_INTERVAL_MS` | `5000` | CloudWatch Metrics flush interval (ms) |
| `FLOCI_STORAGE_SERVICES_SECRETSMANAGER_MODE` | `memory` | Secrets Manager storage mode |
| `FLOCI_STORAGE_SERVICES_SECRETSMANAGER_FLUSH_INTERVAL_MS` | `5000` | Secrets Manager flush interval (ms) |
### Auth
| Variable | Default | Description |
|----------------------------------|-------------------------|---------------------------------|
| `FLOCI_AUTH_VALIDATE_SIGNATURES` | `false` | Validate AWS request signatures |
| `FLOCI_AUTH_REQUIRE_CREDENTIALS` | `false` | Require AWS credentials |
| `FLOCI_AUTH_PRESIGN_SECRET` | `local-emulator-secret` | Secret for S3 pre-signed URLs |
### Service Limits
| Variable | Default | Description |
|----------------------------------------------------|----------|------------------------------|
| `FLOCI_SERVICES_SSM_MAX_PARAMETER_HISTORY` | `5` | Max parameter versions kept |
| `FLOCI_SERVICES_SQS_DEFAULT_VISIBILITY_TIMEOUT` | `30` | Visibility timeout (seconds) |
| `FLOCI_SERVICES_SQS_MAX_MESSAGE_SIZE` | `262144` | Max message size (bytes) |
| `FLOCI_SERVICES_SQS_MAX_RECEIVE_COUNT` | `10` | Max receive count |
| `FLOCI_SERVICES_S3_MAX_MULTIPART_PARTS` | `10000` | Max parts per upload |
| `FLOCI_SERVICES_S3_DEFAULT_PRESIGN_EXPIRY_SECONDS` | `3600` | Pre-signed URL expiry |
| `FLOCI_SERVICES_DYNAMODB_MAX_ITEM_SIZE` | `400000` | Max item size (bytes) |
| `FLOCI_SERVICES_DOCKER_NETWORK` | | Shared Docker network for Lambda, RDS, ElastiCache containers |
## Docker Compose for Developers
### Development (with persistence)
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
volumes:
- ./data:/app/data
environment:
FLOCI_STORAGE_MODE: hybrid
FLOCI_STORAGE_PERSISTENT_PATH: /app/data
```
### CI / Testing (ephemeral)
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
environment:
FLOCI_STORAGE_MODE: memory
```
### Full-Stack Development
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
volumes:
- floci-data:/app/data
environment:
FLOCI_STORAGE_MODE: hybrid
FLOCI_STORAGE_PERSISTENT_PATH: /app/data
api:
build: ./api
depends_on:
- floci
environment:
AWS_ENDPOINT_URL: http://floci:4566
AWS_DEFAULT_REGION: us-east-1
AWS_ACCESS_KEY_ID: test
AWS_SECRET_ACCESS_KEY: test
worker:
build: ./worker
depends_on:
- floci
environment:
AWS_ENDPOINT_URL: http://floci:4566
AWS_DEFAULT_REGION: us-east-1
AWS_ACCESS_KEY_ID: test
AWS_SECRET_ACCESS_KEY: test
volumes:
floci-data:
```
### Custom Region and Account
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
volumes:
- ./data:/app/data
environment:
FLOCI_DEFAULT_REGION: eu-west-1
FLOCI_DEFAULT_ACCOUNT_ID: "123456789012"
FLOCI_STORAGE_MODE: hybrid
FLOCI_STORAGE_PERSISTENT_PATH: /app/data
# Use persistent storage for SSM, memory for SQS
FLOCI_STORAGE_SERVICES_SSM_MODE: persistent
FLOCI_STORAGE_SERVICES_SQS_MODE: memory
```
## Data Persistence
When using `persistent` or `hybrid` mode, data is stored as human-readable JSON files:
```
data/
ssm-parameters.json # SSM parameters
ssm-history.json # Parameter version history
sqs-queues.json # Queue definitions
sqs-messages.json # Queue messages
s3-buckets.json # Bucket metadata
s3-objects.json # Object metadata
s3/ # Object binary data
dynamodb-tables.json # Table definitions
dynamodb-items.json # Table items
```
You can inspect, edit, or seed these files directly -- they're plain JSON.
## Region Isolation
SSM, SQS, SNS, DynamoDB, DynamoDB Streams, Lambda, API Gateway, Cognito, KMS, Kinesis, Secrets Manager, CloudFormation,
Step Functions, EventBridge, and CloudWatch resources are isolated by region. Different regions maintain separate
namespaces, matching AWS behavior. S3 buckets and IAM are global.
## Building
```bash
mvn clean package # Build JAR
mvn clean package -DskipTests # Build without tests
mvn test # Run all tests
# Docker images
docker build -t floci:latest-jvm . # JVM image
docker build -f Dockerfile.native -t floci:native . # Native image (~152MB)
```
## Performance
Benchmarks run against the AWS SDK v2 test suite on Apple Silicon M-series host.
### JVM vs Native — Startup & Memory
| | JVM | Native | Delta |
|-------------------|----------|------------|------------|
| Startup time | 684 ms | **24 ms** | 28× faster |
| Idle memory | 78 MiB | **13 MiB** | −83% |
| Memory under load | 176 MiB | **80 MiB** | −55% |
### JVM vs Native — Lambda Invocation Latency (110 sequential calls)
| | JVM | Native | Delta |
|--------------|----------|------------|-------------|
| Cold start | 1000 ms | **158 ms** | 6.3× faster |
| Warm average | 3 ms | **2 ms** | 1.5× faster |
| Warm minimum | 2 ms | **1 ms** | |
| Warm maximum | 15 ms | **6 ms** | |
### JVM vs Native — Throughput (10,000 invocations / 10 threads)
| | JVM | Native | Delta |
|-------------|-----------|---------------|--------|
| Throughput | 280 req/s | **289 req/s** | +3.2% |
| Latency avg | 13 ms | **12 ms** | |
| Failures | 0 | **0** | |
Both runtimes pass all 408 SDK tests. Throughput is roughly equivalent because both are I/O bound on Lambda Docker containers — the native advantage shows most clearly in startup time and memory footprint.
## Floci vs LocalStack Community
Benchmarks run against both emulators using the same AWS SDK v2 test suite (408 checks covering SQS, SQS→Lambda ESM, SNS, S3, S3 Object Lock, S3 Advanced, SSM, DynamoDB, DynamoDB Advanced, DynamoDB LSI, DynamoDB Streams, Lambda, API Gateway REST, API Gateway v2, S3 Event Notifications, IAM, STS, IAM Performance, EventBridge, CloudWatch Logs, CloudWatch Metrics, Secrets Manager, KMS, Cognito, Step Functions, Kinesis, ElastiCache, and RDS). LocalStack 4.14.0 community, Floci native 1.0.0.
### Test Results
| Test Suite | Floci Native | LocalStack 4.14.0 |
|---------------------------------------|---------------|-------------------------------------------------------------------------------------------------------------|
| SQS (22 checks) | ✅ 22/22 | ✅ 22/22 |
| SQS → Lambda ESM (12 checks) | ✅ 12/12 | ⚠️ 10/12 — `CreateEventSourceMapping` response mismatch; non-existent function returns wrong error code |
| SNS (12 checks) | ✅ 12/12 | ✅ 12/12 |
| S3 (23 checks) | ✅ 23/23 | ⚠️ 22/23 — `DeleteBucketTagging` returns error when tag set is empty |
| S3 Object Lock (30 checks) | ✅ 30/30 | ⚠️ 24/30 — COMPLIANCE/GOVERNANCE enforcement and legal holds not blocking deletes |
| S3 Advanced (13 checks) | ✅ 13/13 | ⚠️ 10/13 — ACL put/get and RestoreObject not supported |
| SSM (12 checks) | ✅ 12/12 | ✅ 12/12 |
| DynamoDB (18 checks) | ✅ 18/18 | ✅ 18/18 |
| DynamoDB Advanced (18 checks) | ✅ 18/18 | ⚠️ 16/18 — TTL expiry not enforced (items remain visible after TTL passes) |
| DynamoDB LSI (4 checks) | ✅ 4/4 | ✅ 4/4 |
| DynamoDB Streams (12 checks) | ✅ 12/12 | ⚠️ 8/12 — DescribeStream returns incorrect shard info; KEYS_ONLY and stream disable not working |
| Lambda CRUD (10 checks) | ✅ 10/10 | ✅ 10/10 |
| Lambda Invoke (4 checks) | ✅ 4/4 | ✅ 4/4 |
| Lambda HTTP (8 checks) | ✅ 8/8 | ✅ 8/8 |
| Lambda Warm Pool (3 checks) | ✅ 3/3 | ✅ 3/3 |
| Lambda Concurrent (3 checks) | ✅ 3/3 | ✅ 3/3 |
| API Gateway REST (43 checks) | ✅ 43/43 | ⚠️ 42/43 — `/_api` stage invocation route not mapped |
| API Gateway v2 / HTTP API (5 checks) | ✅ 5/5 | ❌ 0/5 — `CreateApi` fails; HTTP APIs not available in community edition |
| S3 Event Notifications (11 checks) | ✅ 11/11 | ❌ 0/11 — SNS→SQS subscription fails; event notifications not delivered |
| IAM (32 checks) | ✅ 32/32 | ⚠️ 27/32 — inline policies (`PutRolePolicy`/`GetRolePolicy`/`ListRolePolicies`) and access key creation differ |
| STS (18 checks) | ✅ 18/18 | ⚠️ 6/18 — `AssumeRoleWithWebIdentity`, `AssumeRoleWithSAML`, `GetFederationToken`, `DecodeAuthorizationMessage` not implemented |
| IAM Performance (3 checks) | ✅ 3/3 | ✅ 3/3 |
| EventBridge (14 checks) | ✅ 14/14 | ⚠️ 13/14 — `DisableRule` does not immediately halt event delivery |
| CloudWatch Logs (12 checks) | ✅ 12/12 | ⚠️ 9/12 — tag operations (`TagLogGroup`/`UntagLogGroup`) and `FilterLogEvents` not supported |
| CloudWatch Metrics (14 checks) | ✅ 14/14 | ✅ 14/14 |
| Secrets Manager (15 checks) | ✅ 15/15 | ⚠️ 13/15 — `DescribeSecret` missing version stages in response; `RotateSecret` not supported |
| KMS (16 checks) | ✅ 16/16 | ⚠️ 12/16 — `ReEncrypt` and `Sign`/`Verify` not available |
| Cognito (8 checks) | ✅ 8/8 | ❌ 0/8 — not available in community edition |
| Step Functions (7 checks) | ✅ 7/7 | ⚠️ 6/7 — `DescribeExecution` missing output field until execution fully completes |
| Kinesis (15 checks) | ✅ 15/15 | ⚠️ 8/15 — `PutRecord`/`GetRecords`, encryption, `SplitShard`, and enhanced fan-out (EFO) not working |
| ElastiCache (21 checks) | ✅ 21/21 | ❌ Not available in community edition |
| RDS (50 checks) | ✅ 50/50 | ❌ Not available in community edition |
| **Total** | ✅ **408/408** | ⚠️ **305/383 (80%) on overlapping tests; many services unavailable** |
### Performance
| | Floci Native | LocalStack 4.14.0 | Delta |
|--------------------------------------|---------------|-------------------|--------------------|
| Startup time | **~24 ms** | ~3.3 s | 138× faster |
| Idle memory | **~13 MiB** | ~143 MiB | −91% |
| Memory after full test run | **~80 MiB** | ~827 MiB | −90% |
| Lambda warm latency (avg) | **2 ms** | 10 ms | 5× faster |
| Lambda warm latency (max) | **6 ms** | 68 ms | 11.3× faster |
| Lambda throughput (10k / 10 threads) | **289 req/s** | 120 req/s | 2.4× more req/s |
| Lambda failures (10k calls) | **0** | 0 | — |
### Feature Coverage
| Feature | Floci | LocalStack Community |
|----------------------------------------------------------------|----------------|------------------------------------------------------------|
| Auth token required | No | Yes (since March 2026) |
| CI/CD support | Unlimited | Requires paid plan |
| Security updates | Yes | No (community edition frozen) |
| SSM, SQS, SNS, S3, DynamoDB | ✅ All included | ✅ All included |
| S3 Object Lock (COMPLIANCE, GOVERNANCE, legal holds) | ✅ | ⚠️ Partial — enforcement not blocking deletes |
| DynamoDB Streams | ✅ | ⚠️ Partial — DescribeStream and KEYS_ONLY mode broken |
| Lambda execution | ✅ | ✅ |
| Lambda Event Source Mapping (SQS, Kinesis, DynamoDB Streams) | ✅ | ⚠️ Partial |
| Lambda Function URLs | ✅ | ⚠️ Partial |
| API Gateway REST (stage execution) | ✅ | ⚠️ Partial — `/_api` route not mapped |
| API Gateway v2 / HTTP API | ✅ | ❌ Not available |
| S3 Event Notifications → SNS/SQS | ✅ | ❌ SNS subscription fails |
| IAM (full — users, roles, policies, groups, instance profiles) | ✅ | ⚠️ Partial — inline policies differ |
| STS (7 operations incl. SAML, WebIdentity, federation) | ✅ | ⚠️ Partial — 4 of 7 operations missing |
| Cognito (user pools, auth flows, JWT well-known endpoints) | ✅ | ❌ Not available |
| KMS (encrypt, decrypt, sign, verify, data keys) | ✅ | ⚠️ Partial — ReEncrypt, Sign, Verify not working |
| Kinesis (streams, shards, enhanced fan-out) | ✅ | ⚠️ Partial — PutRecord/GetRecords and EFO not working |
| Secrets Manager (versioning, resource policies) | ✅ | ⚠️ Partial — RotateSecret missing |
| CloudFormation (stacks, change sets, resource provisioning) | ✅ | ⚠️ Partial — basic operations only |
| Step Functions (ASL executor, executions, task tokens) | ✅ | ⚠️ Partial — DescribeExecution missing output |
| ElastiCache (Redis + IAM auth + Lettuce) | ✅ | ❌ Not available |
| RDS (PostgreSQL + MySQL + IAM auth + JDBC) | ✅ | ❌ Not available |
| EventBridge (rules, targets, event delivery) | ✅ | ⚠️ Partial — DisableRule timing issue |
| CloudWatch Logs (groups, streams, filter, query) | ✅ | ⚠️ Partial — tagging and FilterLogEvents missing |
| CloudWatch Metrics (put, list, statistics, alarms) | ✅ | ✅ All included |
| License | MIT | Restricted |
| Native binary option | ✅ ~40 MB | ❌ |
| Docker image size | **~90 MB** | ~1.0 GB |
| Startup time | ~24 ms | ~3.3 s |
## License
MIT -- use it however you want.
+92
View File
@@ -0,0 +1,92 @@
services:
sdk-test:
build:
context: ./sdk-test
dockerfile: Dockerfile
environment:
FLOCI_ENDPOINT: http://floci:4566
depends_on:
- floci
profiles:
- test
sdk-test-node:
build:
context: ./sdk-test-node
dockerfile: Dockerfile
environment:
FLOCI_ENDPOINT: http://floci:4566
depends_on:
- floci
profiles:
- test
compat-cdk:
build:
context: ./compat-cdk
dockerfile: Dockerfile
environment:
FLOCI_ENDPOINT: http://floci:4566
depends_on:
- floci
profiles:
- test
compat-opentofu:
build:
context: ./compat-opentofu
dockerfile: Dockerfile
environment:
FLOCI_ENDPOINT: http://floci:4566
depends_on:
- floci
profiles:
- test
sdk-test-go:
build:
context: ./sdk-test-go
dockerfile: Dockerfile
environment:
FLOCI_ENDPOINT: http://floci:4566
depends_on:
- floci
profiles:
- test
sdk-test-python:
build:
context: ./sdk-test-python
dockerfile: Dockerfile
environment:
FLOCI_ENDPOINT: http://floci:4566
depends_on:
- floci
profiles:
- test
floci:
build:
context: .
dockerfile: Dockerfile
# image: hectorvent/floci
# container_name: aws-local-native
ports:
- "4566:4566"
- "6379-6399:6379-6399"
- "7001-7099:7001-7099"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
# - ./data:/app/data
environment:
FLOCI_SERVICES_DOCKER_NETWORK: aws-local_default
FLOCI_SERVICES_RDS_PROXY_BASE_PORT: "7001"
# FLOCI_STORAGE_PERSISTENT_PATH: /app/data
# profiles:env
# - native
networks:
default:
aliases:
- localhost.localstack.cloud
+21
View File
@@ -0,0 +1,21 @@
services:
floci:
build:
context: .
dockerfile: Dockerfile.native
ports:
- "4566:4566"
- "6379-6399:6379-6399"
- "7001-7099:7001-7099"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
environment:
FLOCI_SERVICES_DOCKER_NETWORK: floci_default
FLOCI_SERVICES_RDS_PROXY_BASE_PORT: "7001"
FLOCI_STORAGE_PERSISTENT_PATH: /app/data
networks:
default:
aliases:
- localhost.floci.cloud
+3
View File
@@ -0,0 +1,3 @@
.md-header__button.md-logo img {
height: 2.5rem;
}
+71
View File
@@ -0,0 +1,71 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 150" width="500" height="150">
<defs>
<!-- Main cloud gradient - warm popcorn white/cream -->
<linearGradient id="cloudGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#fffdf7;stop-opacity:1" />
<stop offset="50%" style="stop-color:#fef9ee;stop-opacity:1" />
<stop offset="100%" style="stop-color:#fde68a;stop-opacity:1" />
</linearGradient>
<!-- Accent puff gradient - warm amber -->
<linearGradient id="accentGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#fbbf24;stop-opacity:1" />
<stop offset="100%" style="stop-color:#f59e0b;stop-opacity:1" />
</linearGradient>
<!-- Light puff -->
<linearGradient id="lightPuff" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:#fef3c7;stop-opacity:1" />
<stop offset="100%" style="stop-color:#fde68a;stop-opacity:1" />
</linearGradient>
<filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="2" result="blur"/>
<feComposite in="SourceGraphic" in2="blur" operator="over"/>
</filter>
<!-- Cloud outline stroke -->
<linearGradient id="strokeGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#f59e0b;stop-opacity:1" />
<stop offset="100%" style="stop-color:#d97706;stop-opacity:1" />
</linearGradient>
<filter id="softShadow" x="-10%" y="-10%" width="130%" height="140%">
<feDropShadow dx="0" dy="3" stdDeviation="4" flood-color="#92400e" flood-opacity="0.15"/>
</filter>
</defs>
<!-- Main cloud shape -->
<g filter="url(#softShadow)">
<!-- Cloud body - smooth overlapping circles -->
<circle cx="95" cy="88" r="36" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="60" cy="92" r="28" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="130" cy="92" r="28" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="75" cy="68" r="26" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="115" cy="66" r="27" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="95" cy="56" r="22" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<!-- Smooth fill -->
<rect x="38" y="88" width="120" height="24" rx="12" fill="url(#cloudGrad)"/>
</g>
<!-- Floating floccus puffs (scattered small clouds) -->
<circle cx="152" cy="52" r="8" fill="url(#lightPuff)" opacity="0.7"/>
<circle cx="145" cy="40" r="6" fill="url(#lightPuff)" opacity="0.5"/>
<circle cx="160" cy="42" r="5" fill="url(#lightPuff)" opacity="0.4"/>
<circle cx="30" cy="60" r="6" fill="url(#lightPuff)" opacity="0.5"/>
<circle cx="22" cy="70" r="5" fill="url(#lightPuff)" opacity="0.35"/>
<circle cx="155" cy="78" r="4" fill="url(#lightPuff)" opacity="0.3"/>
<!-- Accent sparkle dots (popcorn pop!) -->
<circle cx="80" cy="48" r="3.5" fill="url(#accentGrad)"/>
<circle cx="110" cy="44" r="3" fill="url(#accentGrad)" opacity="0.9"/>
<circle cx="62" cy="62" r="2.5" fill="url(#accentGrad)" opacity="0.7"/>
<circle cx="128" cy="58" r="2" fill="url(#accentGrad)" opacity="0.6"/>
<circle cx="95" cy="40" r="2" fill="url(#accentGrad)" opacity="0.8"/>
<!-- Cloud shine highlights -->
<ellipse cx="80" cy="62" rx="14" ry="8" fill="white" opacity="0.15"/>
<ellipse cx="105" cy="58" rx="10" ry="6" fill="white" opacity="0.12"/>
<circle cx="70" cy="72" r="4" fill="white" opacity="0.2"/>
<!-- Text: Floci -->
<text x="185" y="82" font-size="58" font-weight="800" font-family="'Inter', 'Nunito', 'Segoe UI', system-ui, sans-serif" fill="#78350f" letter-spacing="-2">Floci</text>
<!-- Tagline -->
<text x="188" y="108" font-size="14" font-family="'Inter', 'Nunito', 'Segoe UI', system-ui, sans-serif" fill="#b45309" letter-spacing="0.5">Light, fluffy, and always free</text>
</svg>

After

Width:  |  Height:  |  Size: 3.9 KiB

+142
View File
@@ -0,0 +1,142 @@
# application.yml Reference
All settings can be provided as YAML (mounted as a config file or in `src/main/resources/application.yml`) or overridden via environment variables (`FLOCI_` prefix, dots/dashes replaced with underscores).
## Full Reference
```yaml
floci:
base-url: "http://localhost:4566" # Used to build callback URLs (e.g. SNS subscription endpoints)
default-region: us-east-1
default-account-id: "000000000000"
auth:
validate-signatures: false # Set to true to enforce AWS request signing
presign-secret: local-emulator-secret # HMAC secret for S3 pre-signed URL verification
storage:
mode: memory # memory | persistent | hybrid | wal
persistent-path: ./data
wal:
compaction-interval-ms: 30000
services:
ssm:
mode: memory
flush-interval-ms: 5000
sqs:
mode: memory
s3:
mode: memory
dynamodb:
mode: memory
flush-interval-ms: 5000
sns:
mode: memory
flush-interval-ms: 5000
lambda:
mode: memory
flush-interval-ms: 5000
cloudwatchlogs:
mode: memory
flush-interval-ms: 5000
cloudwatchmetrics:
mode: memory
flush-interval-ms: 5000
secretsmanager:
mode: memory
flush-interval-ms: 5000
services:
ssm:
enabled: true
max-parameter-history: 5 # Max versions kept per parameter
sqs:
enabled: true
default-visibility-timeout: 30 # Seconds
max-message-size: 262144 # Bytes (256 KB)
s3:
enabled: true
default-presign-expiry-seconds: 3600
dynamodb:
enabled: true
sns:
enabled: true
lambda:
enabled: true
ephemeral: false # true = remove container after each invocation
default-memory-mb: 128
default-timeout-seconds: 3
docker-host: unix:///var/run/docker.sock
runtime-api-base-port: 9200 # Port range for Lambda Runtime API
runtime-api-max-port: 9299
code-path: ./data/lambda-code # Where ZIP archives are stored
poll-interval-ms: 1000
container-idle-timeout-seconds: 300 # Remove idle containers after this
apigateway:
enabled: true
iam:
enabled: true
elasticache:
enabled: true
proxy-base-port: 6379
proxy-max-port: 6399
default-image: "valkey/valkey:8"
rds:
enabled: true
proxy-base-port: 7001
proxy-max-port: 7099
default-postgres-image: "postgres:16-alpine"
default-mysql-image: "mysql:8.0"
default-mariadb-image: "mariadb:11"
eventbridge:
enabled: true
cloudwatchlogs:
enabled: true
max-events-per-query: 10000
cloudwatchmetrics:
enabled: true
secretsmanager:
enabled: true
default-recovery-window-days: 30
kinesis:
enabled: true
kms:
enabled: true
cognito:
enabled: true
stepfunctions:
enabled: true
cloudformation:
enabled: true
```
## Disabling Services
Set `enabled: false` for any service you don't need. Disabled services return a `ServiceUnavailableException` rather than silently ignoring calls.
```yaml
floci:
services:
cloudformation:
enabled: false
stepfunctions:
enabled: false
```
+101
View File
@@ -0,0 +1,101 @@
# Docker Compose
## Minimal Setup
For most services (SSM, SQS, SNS, S3, DynamoDB, Lambda, API Gateway, Cognito, KMS, Kinesis, Secrets Manager, CloudFormation, Step Functions, IAM, STS, EventBridge, CloudWatch) a single port is enough:
```yaml title="docker-compose.yml"
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
volumes:
- ./data:/app/data
```
## Full Setup (with ElastiCache and RDS)
ElastiCache and RDS work by proxying TCP connections to real Docker containers (Valkey/Redis, PostgreSQL, MySQL). Those containers' ports must be reachable from your host, so additional port ranges must be exposed:
```yaml title="docker-compose.yml"
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566" # All AWS API calls
- "6379-6399:6379-6399" # ElastiCache / Redis proxy ports
- "7001-7099:7001-7099" # RDS / PostgreSQL + MySQL proxy ports
volumes:
- /var/run/docker.sock:/var/run/docker.sock # required for Lambda, ElastiCache, RDS
- ./data:/app/data
environment:
FLOCI_SERVICES_DOCKER_NETWORK: my-project_default # (1)
```
1. Set this to the Docker network name that your compose project creates (usually `<project-name>_default`). Floci uses it to attach spawned Lambda / ElastiCache / RDS containers to the same network.
!!! warning "Docker socket"
Lambda, ElastiCache, and RDS require access to the Docker socket (`/var/run/docker.sock`) to spawn and manage containers. If you don't use these services, you can omit that volume.
## Persistence
By default Floci stores all data in memory — data is lost on restart. To persist data to disk, set the storage path and enable persistent mode:
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
volumes:
- ./data:/app/data
environment:
FLOCI_STORAGE_MODE: persistent
FLOCI_STORAGE_PERSISTENT_PATH: /app/data
```
## Environment Variables Reference
All `application.yml` options can be overridden via environment variables using the `FLOCI_` prefix with underscores replacing dots and dashes:
| Environment variable | Default | Description |
|---|---|---|
| `FLOCI_DEFAULT_REGION` | `us-east-1` | AWS region reported in ARNs |
| `FLOCI_DEFAULT_ACCOUNT_ID` | `000000000000` | AWS account ID used in ARNs |
| `FLOCI_STORAGE_MODE` | `memory` | Global storage mode (`memory`, `persistent`, `hybrid`, `wal`) |
| `FLOCI_STORAGE_PERSISTENT_PATH` | `./data` | Directory for persistent storage |
| `FLOCI_SERVICES_LAMBDA_DOCKER_HOST` | `unix:///var/run/docker.sock` | Docker host for Lambda containers |
| `FLOCI_SERVICES_LAMBDA_EPHEMERAL` | `false` | Remove Lambda containers after each invocation |
| `FLOCI_SERVICES_LAMBDA_DEFAULT_MEMORY_MB` | `128` | Default Lambda memory allocation |
| `FLOCI_SERVICES_LAMBDA_DEFAULT_TIMEOUT_SECONDS` | `3` | Default Lambda timeout |
| `FLOCI_SERVICES_LAMBDA_CODE_PATH` | `./data/lambda-code` | Where Lambda ZIPs are stored |
| `FLOCI_SERVICES_ELASTICACHE_PROXY_BASE_PORT` | `6379` | First ElastiCache proxy port |
| `FLOCI_SERVICES_ELASTICACHE_PROXY_MAX_PORT` | `6399` | Last ElastiCache proxy port |
| `FLOCI_SERVICES_ELASTICACHE_DEFAULT_IMAGE` | `valkey/valkey:8` | Default Redis/Valkey Docker image |
| `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First RDS proxy port |
| `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last RDS proxy port |
| `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Default PostgreSQL image |
| `FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE` | `mysql:8.0` | Default MySQL image |
| `FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE` | `mariadb:11` | Default MariaDB image |
| `FLOCI_SERVICES_DOCKER_NETWORK` | _(none)_ | Docker network to attach spawned containers |
| `FLOCI_AUTH_VALIDATE_SIGNATURES` | `false` | Verify AWS request signatures |
## CI Pipeline Example
```yaml title=".github/workflows/test.yml"
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
steps:
- name: Run tests
env:
AWS_ENDPOINT: http://localhost:4566
AWS_DEFAULT_REGION: us-east-1
AWS_ACCESS_KEY_ID: test
AWS_SECRET_ACCESS_KEY: test
run: mvn test
```
+78
View File
@@ -0,0 +1,78 @@
# Ports Reference
## Port Overview
| Port / Range | Protocol | Purpose |
|---|---|---|
| `4566` | HTTP | All AWS API calls (every service) |
| `6379–6399` | TCP | ElastiCache Redis proxy — one port per replication group |
| `7001–7099` | TCP | RDS proxy — one port per DB instance |
## Port 4566 — AWS API
Every AWS SDK and CLI call goes to port `4566`. This includes all management-plane operations: creating queues, putting items, invoking lambdas, etc.
```bash
aws s3 ls --endpoint-url http://localhost:4566
aws sqs list-queues --endpoint-url http://localhost:4566
aws lambda list-functions --endpoint-url http://localhost:4566
```
## Ports 6379–6399 — ElastiCache
When you create an ElastiCache replication group, Floci starts a Valkey/Redis Docker container and creates a TCP proxy on the next available port in the `6379–6399` range.
Connect to a Redis cluster:
```bash
# First create the replication group
aws elasticache create-replication-group \
--replication-group-id my-redis \
--replication-group-description "dev cache" \
--endpoint-url http://localhost:4566
# Then connect directly on the proxied port
redis-cli -h localhost -p 6379
```
The port assigned to a replication group is returned in the `PrimaryEndpoint.Port` field of the `DescribeReplicationGroups` response.
!!! note
The proxy range starts at `6379` by default (matching the standard Redis port for the first cluster). Configure the range with `FLOCI_SERVICES_ELASTICACHE_PROXY_BASE_PORT` and `FLOCI_SERVICES_ELASTICACHE_PROXY_MAX_PORT`.
## Ports 7001–7099 — RDS
When you create an RDS DB instance, Floci starts a PostgreSQL or MySQL Docker container and creates a TCP proxy on the next available port in the `7001–7099` range.
```bash
# Create a PostgreSQL instance
aws rds create-db-instance \
--db-instance-identifier mydb \
--db-instance-class db.t3.micro \
--engine postgres \
--master-username admin \
--master-user-password secret \
--endpoint-url http://localhost:4566
# Connect using the proxied port (returned in DescribeDBInstances Endpoint.Port)
psql -h localhost -p 7001 -U admin
```
!!! note
Configure the range with `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` and `FLOCI_SERVICES_RDS_PROXY_MAX_PORT`.
## Exposing Ports in Docker Compose
When running Floci inside Docker, you must expose these ranges to the host so your application (or Redis/psql CLI) can connect:
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
- "6379-6399:6379-6399"
- "7001-7099:7001-7099"
```
If your application runs inside the same Docker Compose network, it can reach Floci directly on container port `4566` — the host port mapping is only needed for tools running on the host (CLI, IDE plugins, etc.).
+80
View File
@@ -0,0 +1,80 @@
# Storage Modes
Floci supports four storage backends. You can set a global default and override it per service.
## Modes
| Mode | Data survives restart | Write performance | Use case |
|---|---|---|---|
| `memory` | No | Fastest | Unit tests, CI pipelines |
| `persistent` | Yes | Synchronous disk write on every change | Development with durable state |
| `hybrid` | Yes | In-memory reads, async flush to disk | General local development |
| `wal` | Yes | Append-only write-ahead log with compaction | High-write workloads |
## Global Configuration
```yaml title="application.yml"
floci:
storage:
mode: hybrid # default for all services
persistent-path: ./data # base directory for all persistent data
wal:
compaction-interval-ms: 30000
```
## Per-Service Override
```yaml title="application.yml"
floci:
storage:
mode: memory
services:
dynamodb:
mode: persistent
flush-interval-ms: 5000
s3:
mode: hybrid
sqs:
mode: memory
```
## Environment Variable Override
```bash
FLOCI_STORAGE_MODE=persistent
FLOCI_STORAGE_PERSISTENT_PATH=/app/data
```
## Recommended Profiles
=== "Fast CI"
All in memory, fastest possible startup and test execution:
```yaml
floci:
storage:
mode: memory
```
=== "Local development"
Hybrid — survive restarts without slowing down writes:
```yaml
floci:
storage:
mode: hybrid
persistent-path: ./data
```
=== "Durable development"
Persistent — every write is immediately on disk:
```yaml
floci:
storage:
mode: persistent
persistent-path: ./data
```
+60
View File
@@ -0,0 +1,60 @@
# Contributing
Floci is MIT licensed and welcomes contributions of all kinds.
## Ways to Help
- **Bug reports** — open a [GitHub issue](https://github.com/hectorvent/floci/issues/new?template=bug_report.md) with a minimal reproduction
- **Missing API actions** — open a [feature request](https://github.com/hectorvent/floci/issues/new?template=feature_request.md)
- **Pull requests** — new service actions, bug fixes, documentation improvements
## Development Setup
```bash
# Clone
git clone https://github.com/hectorvent/floci.git
cd floci
# Run in dev mode (hot reload, port 4566)
mvn quarkus:dev
# Run all tests
mvn test
# Run a specific test
mvn test -Dtest=SsmIntegrationTest
mvn test -Dtest=SsmIntegrationTest#putParameter
```
## Commit Message Format
This project uses [Conventional Commits](https://www.conventionalcommits.org/) — required for semantic-release to generate the changelog and version bumps automatically.
| Prefix | Effect |
|---|---|
| `feat:` | New feature → minor version bump |
| `fix:` | Bug fix → patch version bump |
| `perf:` | Performance improvement → patch |
| `docs:` | Documentation only → no version bump |
| `chore:` | Build/CI → no version bump |
| `feat!:` or `BREAKING CHANGE:` | Breaking change → major bump |
## Adding a New AWS Service
See [CLAUDE.md](https://github.com/hectorvent/floci/blob/main/CLAUDE.md) for the full architecture guide. Quick summary:
1. Create `src/main/java/.../services/<service>/` with a Controller, Service, and `model/` package
2. Pick the right protocol (see the protocol table in CLAUDE.md)
3. Register the service in `ServiceRegistry`
4. Add config in `EmulatorConfig.java` and `application.yml`
5. Add `*IntegrationTest.java` tests
## Pull Request Checklist
- [ ] `mvn test` passes
- [ ] New or updated integration test added
- [ ] Commit messages follow Conventional Commits
## Reporting Security Issues
Do **not** open public issues for security vulnerabilities. Use [GitHub private vulnerability reporting](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/privately-reporting-a-security-vulnerability) instead.
+138
View File
@@ -0,0 +1,138 @@
# AWS CLI & SDK Setup
Floci accepts any non-empty credentials — no real AWS account is needed.
## Environment Variables
The simplest approach for local development:
```bash
export AWS_ENDPOINT=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
```
## AWS CLI Profile
Add a dedicated profile to `~/.aws/config` and `~/.aws/credentials`:
```ini title="~/.aws/config"
[profile floci]
region = us-east-1
output = json
```
```ini title="~/.aws/credentials"
[floci]
aws_access_key_id = test
aws_secret_access_key = test
```
Then use it with every command:
```bash
aws s3 ls --profile floci --endpoint-url http://localhost:4566
```
Or set it as the default for your shell session:
```bash
export AWS_PROFILE=floci
export AWS_ENDPOINT=http://localhost:4566
```
## SDK Configuration
### Java (AWS SDK v2)
```java
// Reusable endpoint override
URI endpoint = URI.create("http://localhost:4566");
AwsCredentialsProvider creds = StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test"));
Region region = Region.US_EAST_1;
// Build any client the same way
DynamoDbClient dynamo = DynamoDbClient.builder()
.endpointOverride(endpoint)
.region(region)
.credentialsProvider(creds)
.build();
SqsClient sqs = SqsClient.builder()
.endpointOverride(endpoint)
.region(region)
.credentialsProvider(creds)
.build();
```
### Python (boto3)
```python
import boto3
def floci_client(service):
return boto3.client(
service,
endpoint_url="http://localhost:4566",
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
s3 = floci_client("s3")
sqs = floci_client("sqs")
dynamo = floci_client("dynamodb")
```
### Node.js / TypeScript
```typescript
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { SQSClient } from "@aws-sdk/client-sqs";
const config = {
endpoint: "http://localhost:4566",
region: "us-east-1",
credentials: { accessKeyId: "test", secretAccessKey: "test" },
};
const dynamo = new DynamoDBClient(config);
const sqs = new SQSClient(config);
```
!!! tip "S3 path-style URLs"
When using S3 with the AWS SDK v3 (Node.js), add `forcePathStyle: true` to the config object. Floci serves S3 in path-style mode (`http://localhost:4566/bucket-name`).
### Go
```go
import (
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
)
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("us-east-1"),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("test", "test", "")),
config.WithEndpointResolverWithOptions(
aws.EndpointResolverWithOptionsFunc(
func(service, region string, opts ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{URL: "http://localhost:4566"}, nil
},
),
),
)
```
## Default Account ID
Floci uses account ID `000000000000` in all ARNs and queue URLs. For example:
```
arn:aws:sqs:us-east-1:000000000000:my-queue
http://localhost:4566/000000000000/my-queue
```
This can be changed via the `FLOCI_DEFAULT_ACCOUNT_ID` environment variable.
+85
View File
@@ -0,0 +1,85 @@
# Installation
Floci can be run three ways: as a Docker image, as a pre-built native binary, or built from source.
## Docker (Recommended)
No installation required beyond Docker itself.
```bash
docker pull hectorvent/floci:latest
```
| Tag | Description |
|---|---|
| `latest` | Native image — sub-second startup, low memory (**default**) |
| `x.y.z` | Native image — specific release version |
| `latest-jvm` | JVM image — most compatible |
| `x.y.z-jvm` | JVM image — specific release version |
### Requirements
- Docker 20.10+
- `docker compose` v2+ (plugin syntax, not standalone `docker-compose`)
## Native vs JVM
The `latest` tag is the native image — a self-contained executable with no JVM dependency.
```yaml title="docker-compose.yml"
services:
floci:
image: hectorvent/floci:latest # native — recommended
ports:
- "4566:4566"
```
Use the JVM image if you need broader platform compatibility or encounter native image issues:
```yaml title="docker-compose.yml"
services:
floci:
image: hectorvent/floci:latest-jvm
ports:
- "4566:4566"
```
### Startup comparison
| Image | Tag | Typical startup | Idle memory |
|---|---|---|---|
| Native | `latest` / `x.y.z` | < 100 ms | ~50 MB |
| JVM | `latest-jvm` / `x.y.z-jvm` | ~2 s | ~250 MB |
## Build from Source
### Prerequisites
- Java 25+
- Maven 3.9+
- (Optional) GraalVM Mandrel for native compilation
### Clone and run
```bash
git clone https://github.com/hectorvent/floci.git
cd floci
mvn quarkus:dev # dev mode with hot reload on port 4566
```
### Build a production JAR
```bash
mvn clean package -DskipTests
java -jar target/quarkus-app/quarkus-run.jar
```
### Build a native executable
```bash
mvn clean package -Pnative -DskipTests
./target/floci-runner
```
!!! note
Native compilation requires GraalVM or Mandrel with the `native-image` tool on your PATH. Build time is typically 2–5 minutes.
+152
View File
@@ -0,0 +1,152 @@
# Quick Start
This guide gets Floci running and verifies that AWS CLI commands work against it in under five minutes.
## Step 1 — Start Floci
=== "Native (recommended)"
`latest` is the native image — sub-second startup, minimal memory:
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
volumes:
- ./data:/app/data
```
```bash
docker compose up -d
```
=== "JVM"
Use `latest-jvm` if you need broader platform compatibility:
```yaml
services:
floci:
image: hectorvent/floci:latest-jvm
ports:
- "4566:4566"
volumes:
- ./data:/app/data
```
```bash
docker compose up -d
```
=== "Build from source"
```bash
git clone https://github.com/hectorvent/floci.git
cd floci
mvn quarkus:dev # hot reload, port 4566
```
## Step 2 — Configure AWS CLI
Floci accepts any dummy credentials — no real AWS account needed.
```bash
export AWS_ENDPOINT=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
```
Add these to your shell profile (`.bashrc` / `.zshrc`) so they persist across sessions.
## Step 3 — Verify the Setup
Run a few quick smoke tests:
```bash
# S3 — create a bucket and upload a file
aws s3 mb s3://my-bucket --endpoint-url $AWS_ENDPOINT
echo "hello floci" | aws s3 cp - s3://my-bucket/hello.txt --endpoint-url $AWS_ENDPOINT
aws s3 ls s3://my-bucket --endpoint-url $AWS_ENDPOINT
# SQS — create a queue and send a message
aws sqs create-queue --queue-name orders --endpoint-url $AWS_ENDPOINT
aws sqs send-message \
--queue-url $AWS_ENDPOINT/000000000000/orders \
--message-body '{"event":"order.placed"}' \
--endpoint-url $AWS_ENDPOINT
# DynamoDB — create a table
aws dynamodb create-table \
--table-name Users \
--attribute-definitions AttributeName=id,AttributeType=S \
--key-schema AttributeName=id,KeyType=HASH \
--billing-mode PAY_PER_REQUEST \
--endpoint-url $AWS_ENDPOINT
```
You should see successful responses for all three commands.
## Step 4 — Use in Your Application
Point your AWS SDK to Floci the same way:
=== "Java"
```java
S3Client s3 = S3Client.builder()
.endpointOverride(URI.create("http://localhost:4566"))
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test")))
.build();
```
=== "Python (boto3)"
```python
import boto3
s3 = boto3.client(
"s3",
endpoint_url="http://localhost:4566",
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
```
=== "Node.js"
```javascript
import { S3Client } from "@aws-sdk/client-s3";
const s3 = new S3Client({
endpoint: "http://localhost:4566",
region: "us-east-1",
credentials: { accessKeyId: "test", secretAccessKey: "test" },
forcePathStyle: true,
});
```
=== "Go"
```go
cfg, _ := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("us-east-1"),
config.WithEndpointResolverWithOptions(
aws.EndpointResolverWithOptionsFunc(func(service, region string, opts ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{URL: "http://localhost:4566"}, nil
}),
),
)
client := s3.NewFromConfig(cfg)
```
## Next Steps
- [Configure Docker Compose with ElastiCache and RDS ports](../configuration/docker-compose.md)
- [Review all configuration options](../configuration/application-yml.md)
- [Browse per-service documentation](../services/index.md)
+67
View File
@@ -0,0 +1,67 @@
# Floci
<p align="center">
<img src="assets/logo.svg" alt="Floci" width="500" />
</p>
<p align="center"><em>Light, fluffy, and always free</em></p>
---
Floci is a fast, free, and open-source local AWS service emulator built for developers who need reliable AWS services in development and CI without cost, complexity, or vendor lock-in.
## Supported Services
| Service | Protocol |
|---|---|
| SSM Parameter Store | JSON 1.1 |
| SQS | Query / JSON |
| SNS | Query / JSON |
| S3 | REST XML |
| DynamoDB + Streams | JSON 1.1 |
| Lambda | REST JSON |
| API Gateway v1 & v2 | REST JSON |
| Cognito | JSON 1.1 |
| KMS | JSON 1.1 |
| Kinesis | JSON 1.1 |
| Secrets Manager | JSON 1.1 |
| CloudFormation | Query |
| Step Functions | JSON 1.1 |
| IAM | Query |
| STS | Query |
| ElastiCache (Redis) | Query + RESP proxy |
| RDS (PostgreSQL / MySQL) | Query + wire proxy |
| EventBridge | JSON 1.1 |
| CloudWatch Logs & Metrics | JSON 1.1 / Query |
## Why Floci?
**No account required.** No auth tokens, no sign-ups, no telemetry. Pull the image and start building.
**No feature gates.** Every feature is available to everyone — no community-edition restrictions.
**No CI restrictions.** Run in your CI pipeline with zero limitations. No credits, no quotas, no paid tiers.
**Truly open source.** MIT licensed. Fork it, extend it, embed it. No "community edition" sunset coming.
## Quick Start
```yaml title="docker-compose.yml"
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
volumes:
- ./data:/app/data
```
```bash
docker compose up -d
aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket
```
All 19+ AWS services are immediately available at `http://localhost:4566`.
[Get started →](getting-started/quick-start.md){ .md-button .md-button--primary }
[View services →](services/index.md){ .md-button }
+2
View File
@@ -0,0 +1,2 @@
mkdocs>=1.6
mkdocs-material>=9.5
+131
View File
@@ -0,0 +1,131 @@
# API Gateway
Floci supports both API Gateway v1 (REST APIs) and API Gateway v2 (HTTP APIs).
## API Gateway v1 (REST APIs) {#v1}
**Protocol:** REST JSON
**Endpoint:** `http://localhost:4566/restapis/...`
### Supported Operations
| Category | Operations |
|---|---|
| **APIs** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi |
| **Resources** | CreateResource, GetResource, GetResources, UpdateResource, DeleteResource |
| **Methods** | PutMethod, GetMethod, DeleteMethod |
| **Method Responses** | PutMethodResponse, GetMethodResponse, DeleteMethodResponse |
| **Integrations** | PutIntegration, GetIntegration, DeleteIntegration |
| **Integration Responses** | PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse |
| **Deployments** | CreateDeployment, GetDeployment, GetDeployments |
| **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage |
| **API Keys** | CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey |
| **Usage Plans** | CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan |
| **Base Path Mappings** | CreateBasePathMapping, GetBasePathMapping, DeleteBasePathMapping |
### Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a REST API
API_ID=$(aws apigateway create-rest-api \
--name "My API" \
--query id --output text \
--endpoint-url $AWS_ENDPOINT)
# Get the root resource
ROOT_ID=$(aws apigateway get-resources \
--rest-api-id $API_ID \
--query 'items[?path==`/`].id' --output text \
--endpoint-url $AWS_ENDPOINT)
# Create a resource
RESOURCE_ID=$(aws apigateway create-resource \
--rest-api-id $API_ID \
--parent-id $ROOT_ID \
--path-part users \
--query id --output text \
--endpoint-url $AWS_ENDPOINT)
# Add a GET method
aws apigateway put-method \
--rest-api-id $API_ID \
--resource-id $RESOURCE_ID \
--http-method GET \
--authorization-type NONE \
--endpoint-url $AWS_ENDPOINT
# Add a Lambda integration
aws apigateway put-integration \
--rest-api-id $API_ID \
--resource-id $RESOURCE_ID \
--http-method GET \
--type AWS_PROXY \
--integration-http-method POST \
--uri "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:my-function/invocations" \
--endpoint-url $AWS_ENDPOINT
# Deploy to a stage
aws apigateway create-deployment \
--rest-api-id $API_ID \
--stage-name dev \
--endpoint-url $AWS_ENDPOINT
# Call the deployed API
curl http://localhost:4566/restapis/$API_ID/dev/_user_request_/users
```
---
## API Gateway v2 (HTTP APIs) {#v2}
**Protocol:** REST JSON
**Endpoint:** `http://localhost:4566/v2/apis/...`
### Supported Operations
| Category | Operations |
|---|---|
| **APIs** | CreateApi, GetApi, GetApis, DeleteApi |
| **Routes** | CreateRoute, GetRoute, GetRoutes, DeleteRoute |
| **Integrations** | CreateIntegration, GetIntegration, GetIntegrations |
| **Authorizers** | CreateAuthorizer, GetAuthorizer, GetAuthorizers, DeleteAuthorizer |
| **Stages** | CreateStage, GetStage, GetStages, DeleteStage |
| **Deployments** | CreateDeployment, GetDeployments |
### Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create an HTTP API
API_ID=$(aws apigatewayv2 create-api \
--name "My HTTP API" \
--protocol-type HTTP \
--query ApiId --output text \
--endpoint-url $AWS_ENDPOINT)
# Create a Lambda integration
INTEGRATION_ID=$(aws apigatewayv2 create-integration \
--api-id $API_ID \
--integration-type AWS_PROXY \
--integration-uri "arn:aws:lambda:us-east-1:000000000000:function:my-function" \
--payload-format-version 2.0 \
--query IntegrationId --output text \
--endpoint-url $AWS_ENDPOINT)
# Create a route
aws apigatewayv2 create-route \
--api-id $API_ID \
--route-key "GET /users" \
--target "integrations/$INTEGRATION_ID" \
--endpoint-url $AWS_ENDPOINT
# Deploy
aws apigatewayv2 create-stage \
--api-id $API_ID \
--stage-name dev \
--auto-deploy \
--endpoint-url $AWS_ENDPOINT
```
+68
View File
@@ -0,0 +1,68 @@
# CloudFormation
**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateStack` | Deploy a CloudFormation template |
| `UpdateStack` | Update an existing stack |
| `DeleteStack` | Delete a stack and its resources |
| `DescribeStacks` | Get stack status and outputs |
| `ListStacks` | List stacks by status |
| `DescribeStackEvents` | Get stack creation/update event history |
| `DescribeStackResources` | Get all resources in a stack |
| `DescribeStackResource` | Get a specific stack resource |
| `ListStackResources` | List resource summaries |
| `GetTemplate` | Retrieve the template body |
| `ValidateTemplate` | Validate a template without deploying |
| `CreateChangeSet` | Create a change set |
| `DescribeChangeSet` | Get change set details |
| `ExecuteChangeSet` | Apply a change set |
| `ListChangeSets` | List change sets for a stack |
| `SetStackPolicy` | Set a stack policy |
| `GetStackPolicy` | Retrieve the current stack policy |
| `ListStackSets` | List StackSets |
| `DescribeStackSet` | Get StackSet details |
| `CreateStackSet` | Create a new StackSet |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Validate a template
aws cloudformation validate-template \
--template-body file://template.yml \
--endpoint-url $AWS_ENDPOINT
# Deploy a stack
aws cloudformation create-stack \
--stack-name my-stack \
--template-body file://template.yml \
--parameters ParameterKey=Env,ParameterValue=dev \
--endpoint-url $AWS_ENDPOINT
# Check status
aws cloudformation describe-stacks \
--stack-name my-stack \
--endpoint-url $AWS_ENDPOINT
# Watch events
aws cloudformation describe-stack-events \
--stack-name my-stack \
--endpoint-url $AWS_ENDPOINT
# Update
aws cloudformation update-stack \
--stack-name my-stack \
--template-body file://template.yml \
--endpoint-url $AWS_ENDPOINT
# Delete
aws cloudformation delete-stack \
--stack-name my-stack \
--endpoint-url $AWS_ENDPOINT
```
+143
View File
@@ -0,0 +1,143 @@
# CloudWatch
Floci supports both CloudWatch Logs and CloudWatch Metrics.
---
## CloudWatch Logs
**Protocol:** JSON 1.1 (`X-Amz-Target: Logs.*`)
**Endpoint:** `POST http://localhost:4566/`
### Supported Actions
| Action | Description |
|---|---|
| `CreateLogGroup` | Create a log group |
| `DeleteLogGroup` | Delete a log group |
| `DescribeLogGroups` | List log groups |
| `CreateLogStream` | Create a log stream inside a log group |
| `DeleteLogStream` | Delete a log stream |
| `DescribeLogStreams` | List log streams in a group |
| `PutLogEvents` | Write log events to a stream |
| `GetLogEvents` | Read log events from a stream |
| `FilterLogEvents` | Search log events with a filter pattern |
| `PutRetentionPolicy` | Set log retention (days) |
| `DeleteRetentionPolicy` | Remove log retention policy |
| `TagLogGroup` | Tag a log group |
| `UntagLogGroup` | Remove tags |
| `ListTagsLogGroup` | List tags |
### Configuration
```yaml
floci:
services:
cloudwatchlogs:
enabled: true
max-events-per-query: 10000
```
### Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a log group and stream
aws logs create-log-group --log-group-name /app/backend --endpoint-url $AWS_ENDPOINT
aws logs create-log-stream \
--log-group-name /app/backend \
--log-stream-name 2025/01/app-1 \
--endpoint-url $AWS_ENDPOINT
# Write log events
TIMESTAMP=$(date +%s%3N) # milliseconds
aws logs put-log-events \
--log-group-name /app/backend \
--log-stream-name 2025/01/app-1 \
--log-events "[{\"timestamp\":$TIMESTAMP,\"message\":\"Service started\"}]" \
--endpoint-url $AWS_ENDPOINT
# Read log events
aws logs get-log-events \
--log-group-name /app/backend \
--log-stream-name 2025/01/app-1 \
--endpoint-url $AWS_ENDPOINT
# Search logs
aws logs filter-log-events \
--log-group-name /app/backend \
--filter-pattern "ERROR" \
--endpoint-url $AWS_ENDPOINT
# Set retention
aws logs put-retention-policy \
--log-group-name /app/backend \
--retention-in-days 30 \
--endpoint-url $AWS_ENDPOINT
```
---
## CloudWatch Metrics {#metrics}
**Protocol:** Query (XML) and JSON 1.1 (both supported)
**Endpoint:** `POST http://localhost:4566/`
### Supported Actions
| Action | Description |
|---|---|
| `PutMetricData` | Publish custom metrics |
| `ListMetrics` | List available metrics |
| `GetMetricStatistics` | Get metric statistics (Average, Sum, etc.) |
| `GetMetricData` | Query metrics with math expressions |
| `PutMetricAlarm` | Create a metric alarm |
| `DescribeAlarms` | List alarms |
| `DeleteAlarms` | Delete alarms |
| `SetAlarmState` | Manually set alarm state |
### Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Publish a custom metric
aws cloudwatch put-metric-data \
--namespace MyApp \
--metric-data '[{
"MetricName": "RequestCount",
"Value": 42,
"Unit": "Count",
"Dimensions": [{"Name":"Service","Value":"api"}]
}]' \
--endpoint-url $AWS_ENDPOINT
# List metrics
aws cloudwatch list-metrics \
--namespace MyApp \
--endpoint-url $AWS_ENDPOINT
# Get statistics
aws cloudwatch get-metric-statistics \
--namespace MyApp \
--metric-name RequestCount \
--dimensions Name=Service,Value=api \
--start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
--period 300 \
--statistics Sum \
--endpoint-url $AWS_ENDPOINT
# Create an alarm
aws cloudwatch put-metric-alarm \
--alarm-name high-error-rate \
--metric-name ErrorCount \
--namespace MyApp \
--statistic Sum \
--period 60 \
--threshold 10 \
--comparison-operator GreaterThanThreshold \
--evaluation-periods 1 \
--endpoint-url $AWS_ENDPOINT
```
+82
View File
@@ -0,0 +1,82 @@
# Cognito
**Protocol:** JSON 1.1 (`X-Amz-Target: AWSCognitoIdentityProviderService.*`)
**Endpoint:** `POST http://localhost:4566/`
Floci also serves OIDC well-known endpoints, making it compatible with JWT validation libraries.
## Supported Actions
| Category | Actions |
|---|---|
| **User Pools** | CreateUserPool, DescribeUserPool, ListUserPools, DeleteUserPool |
| **User Pool Clients** | CreateUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, DeleteUserPoolClient |
| **Admin User Management** | AdminCreateUser, AdminGetUser, AdminDeleteUser, AdminSetUserPassword, AdminUpdateUserAttributes |
| **User Operations** | SignUp, ConfirmSignUp, GetUser, UpdateUserAttributes, ChangePassword, ForgotPassword, ConfirmForgotPassword |
| **Authentication** | InitiateAuth, AdminInitiateAuth, RespondToAuthChallenge |
| **User Listing** | ListUsers |
## OIDC Well-Known Endpoints
| Endpoint | Description |
|---|---|
| `GET /.well-known/openid-configuration` | OIDC discovery document |
| `GET /.well-known/jwks.json` | JSON Web Key Set for JWT validation |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a user pool
POOL_ID=$(aws cognito-idp create-user-pool \
--pool-name MyApp \
--query UserPool.Id --output text \
--endpoint-url $AWS_ENDPOINT)
# Create an app client
CLIENT_ID=$(aws cognito-idp create-user-pool-client \
--user-pool-id $POOL_ID \
--client-name my-client \
--explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH \
--query UserPoolClient.ClientId --output text \
--endpoint-url $AWS_ENDPOINT)
# Create a user
aws cognito-idp admin-create-user \
--user-pool-id $POOL_ID \
--username alice@example.com \
--temporary-password Temp1234! \
--endpoint-url $AWS_ENDPOINT
# Set a permanent password
aws cognito-idp admin-set-user-password \
--user-pool-id $POOL_ID \
--username alice@example.com \
--password Perm1234! \
--permanent \
--endpoint-url $AWS_ENDPOINT
# Authenticate
aws cognito-idp initiate-auth \
--auth-flow USER_PASSWORD_AUTH \
--client-id $CLIENT_ID \
--auth-parameters USERNAME=alice@example.com,PASSWORD=Perm1234! \
--endpoint-url $AWS_ENDPOINT
```
## JWT Validation
Tokens issued by Floci can be validated using the JWKS endpoint:
```
http://localhost:4566/.well-known/jwks.json
```
The OIDC discovery endpoint returns:
```
http://localhost:4566/.well-known/openid-configuration
```
This allows libraries like `jsonwebtoken`, `jose`, or Spring Security to validate tokens against Floci the same way they would against real Cognito.
+112
View File
@@ -0,0 +1,112 @@
# DynamoDB
**Protocol:** JSON 1.1 (`X-Amz-Target: DynamoDB_20120810.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateTable` | Create a table with indexes |
| `DeleteTable` | Delete a table |
| `DescribeTable` | Get table metadata |
| `ListTables` | List all tables |
| `UpdateTable` | Update throughput, indexes, streams |
| `PutItem` | Write an item |
| `GetItem` | Read an item by primary key |
| `DeleteItem` | Delete an item |
| `UpdateItem` | Partially update an item |
| `Query` | Query by partition key with optional filter |
| `Scan` | Full table scan with optional filter |
| `BatchWriteItem` | Write/delete up to 25 items across tables |
| `BatchGetItem` | Read up to 100 items across tables |
| `TransactWriteItems` | ACID write transaction |
| `TransactGetItems` | ACID read transaction |
| `DescribeTimeToLive` | Get TTL configuration |
| `UpdateTimeToLive` | Enable/disable TTL on a table |
| `TagResource` | Tag a table |
| `UntagResource` | Remove tags |
| `ListTagsOfResource` | List tags |
## Streams {#streams}
DynamoDB Streams are supported via a separate target (`DynamoDBStreams_20120810`):
| Action | Description |
|---|---|
| `ListStreams` | List all streams |
| `DescribeStream` | Get stream and shard info |
| `GetShardIterator` | Get a shard iterator |
| `GetRecords` | Read stream records from a shard |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a table
aws dynamodb create-table \
--table-name Users \
--attribute-definitions \
AttributeName=userId,AttributeType=S \
--key-schema \
AttributeName=userId,KeyType=HASH \
--billing-mode PAY_PER_REQUEST \
--endpoint-url $AWS_ENDPOINT
# Put an item
aws dynamodb put-item \
--table-name Users \
--item '{"userId":{"S":"u1"},"name":{"S":"Alice"},"age":{"N":"30"}}' \
--endpoint-url $AWS_ENDPOINT
# Get an item
aws dynamodb get-item \
--table-name Users \
--key '{"userId":{"S":"u1"}}' \
--endpoint-url $AWS_ENDPOINT
# Query (partition key)
aws dynamodb query \
--table-name Users \
--key-condition-expression "userId = :id" \
--expression-attribute-values '{":id":{"S":"u1"}}' \
--endpoint-url $AWS_ENDPOINT
# Scan with filter
aws dynamodb scan \
--table-name Users \
--filter-expression "age > :min" \
--expression-attribute-values '{":min":{"N":"25"}}' \
--endpoint-url $AWS_ENDPOINT
# Enable TTL
aws dynamodb update-time-to-live \
--table-name Users \
--time-to-live-specification Enabled=true,AttributeName=expiresAt \
--endpoint-url $AWS_ENDPOINT
# Enable Streams
aws dynamodb update-table \
--table-name Users \
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \
--endpoint-url $AWS_ENDPOINT
```
## Global Secondary Indexes
```bash
aws dynamodb create-table \
--table-name Orders \
--attribute-definitions \
AttributeName=orderId,AttributeType=S \
AttributeName=customerId,AttributeType=S \
--key-schema AttributeName=orderId,KeyType=HASH \
--global-secondary-indexes '[{
"IndexName": "CustomerIndex",
"KeySchema": [{"AttributeName":"customerId","KeyType":"HASH"}],
"Projection": {"ProjectionType":"ALL"}
}]' \
--billing-mode PAY_PER_REQUEST \
--endpoint-url $AWS_ENDPOINT
```
+95
View File
@@ -0,0 +1,95 @@
# ElastiCache
**Protocol:** Query (XML) for management API + Redis RESP protocol for data plane
**Management Endpoint:** `POST http://localhost:4566/`
**Data Endpoint:** `localhost:<proxy-port>` (TCP)
Floci manages real Valkey/Redis Docker containers and proxies TCP connections to them. This means any Redis client works — including IAM authentication.
## Supported Management Actions
| Action | Description |
|---|---|
| `CreateReplicationGroup` | Start a new Redis/Valkey cluster |
| `DescribeReplicationGroups` | List clusters and their connection info |
| `DeleteReplicationGroup` | Stop and remove a cluster |
| `CreateUser` | Create an ElastiCache IAM user |
| `DescribeUsers` | List ElastiCache users |
| `ModifyUser` | Update user access strings |
| `DeleteUser` | Remove an ElastiCache user |
| `ValidateIamAuthToken` | Validate an IAM auth token (data-plane auth) |
## Configuration
```yaml
floci:
services:
elasticache:
enabled: true
proxy-base-port: 6379
proxy-max-port: 6399
default-image: "valkey/valkey:8"
```
### Docker Compose
ElastiCache requires the Docker socket and port range exposure:
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
- "6379-6399:6379-6399" # ElastiCache proxy ports
volumes:
- /var/run/docker.sock:/var/run/docker.sock
environment:
FLOCI_SERVICES_DOCKER_NETWORK: my-project_default
```
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a replication group (starts a Valkey container)
aws elasticache create-replication-group \
--replication-group-id my-cache \
--replication-group-description "Dev cache" \
--endpoint-url $AWS_ENDPOINT
# Get the connection port
PORT=$(aws elasticache describe-replication-groups \
--replication-group-id my-cache \
--query 'ReplicationGroups[0].NodeGroups[0].PrimaryEndpoint.Port' \
--output text \
--endpoint-url $AWS_ENDPOINT)
# Connect with redis-cli
redis-cli -h localhost -p $PORT ping
# Use from your application
redis-cli -h localhost -p $PORT set mykey "hello"
redis-cli -h localhost -p $PORT get mykey
# Delete the cluster
aws elasticache delete-replication-group \
--replication-group-id my-cache \
--endpoint-url $AWS_ENDPOINT
```
## IAM Authentication
Floci supports ElastiCache IAM auth token validation. Create a user with access strings and validate tokens the same way real ElastiCache RBAC works.
```bash
# Create an ElastiCache user
aws elasticache create-user \
--user-id alice \
--user-name alice \
--engine redis \
--access-string "on ~* +@all" \
--no-no-password-required \
--endpoint-url $AWS_ENDPOINT
```
+76
View File
@@ -0,0 +1,76 @@
# EventBridge
**Protocol:** JSON 1.1 (`X-Amz-Target: AmazonEventBridge.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateEventBus` | Create a custom event bus |
| `DeleteEventBus` | Delete an event bus |
| `DescribeEventBus` | Get event bus details |
| `ListEventBuses` | List all event buses |
| `PutRule` | Create or update a rule with a schedule or event pattern |
| `DeleteRule` | Delete a rule |
| `DescribeRule` | Get rule details |
| `ListRules` | List rules |
| `EnableRule` | Enable a disabled rule |
| `DisableRule` | Disable a rule |
| `PutTargets` | Add targets to a rule |
| `RemoveTargets` | Remove targets from a rule |
| `ListTargetsByRule` | List targets for a rule |
| `PutEvents` | Publish custom events to an event bus |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a custom event bus
aws events create-event-bus \
--name my-bus \
--endpoint-url $AWS_ENDPOINT
# Create a rule matching a pattern
aws events put-rule \
--name order-placed-rule \
--event-bus-name my-bus \
--event-pattern '{"source":["com.myapp"],"detail-type":["OrderPlaced"]}' \
--state ENABLED \
--endpoint-url $AWS_ENDPOINT
# Add a Lambda target
aws events put-targets \
--rule order-placed-rule \
--event-bus-name my-bus \
--targets '[{
"Id": "process-order",
"Arn": "arn:aws:lambda:us-east-1:000000000000:function:process-order"
}]' \
--endpoint-url $AWS_ENDPOINT
# Publish an event
aws events put-events \
--entries '[{
"Source": "com.myapp",
"DetailType": "OrderPlaced",
"Detail": "{\"orderId\":\"123\",\"amount\":99.99}",
"EventBusName": "my-bus"
}]' \
--endpoint-url $AWS_ENDPOINT
```
## Default Event Bus
EventBridge includes a default event bus (`default`) that accepts events from AWS services. Custom buses are for your own application events.
```bash
# List rules on the default bus
aws events list-rules --endpoint-url $AWS_ENDPOINT
# Send to default bus
aws events put-events \
--entries '[{"Source":"myapp","DetailType":"test","Detail":"{}"}]' \
--endpoint-url $AWS_ENDPOINT
```
+70
View File
@@ -0,0 +1,70 @@
# IAM
**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
## Supported Actions
### Users
`CreateUser` · `GetUser` · `DeleteUser` · `ListUsers` · `UpdateUser` · `TagUser` · `UntagUser` · `ListUserTags`
### Groups
`CreateGroup` · `GetGroup` · `DeleteGroup` · `ListGroups` · `AddUserToGroup` · `RemoveUserFromGroup` · `ListGroupsForUser`
### Roles
`CreateRole` · `GetRole` · `DeleteRole` · `ListRoles` · `UpdateRole` · `UpdateAssumeRolePolicy` · `TagRole` · `UntagRole` · `ListRoleTags`
### Policies
`CreatePolicy` · `GetPolicy` · `DeletePolicy` · `ListPolicies` · `CreatePolicyVersion` · `GetPolicyVersion` · `DeletePolicyVersion` · `ListPolicyVersions` · `SetDefaultPolicyVersion` · `TagPolicy` · `UntagPolicy` · `ListPolicyTags`
### Policy Attachments
`AttachUserPolicy` · `DetachUserPolicy` · `ListAttachedUserPolicies`
`AttachGroupPolicy` · `DetachGroupPolicy` · `ListAttachedGroupPolicies`
`AttachRolePolicy` · `DetachRolePolicy` · `ListAttachedRolePolicies`
### Inline Policies
`PutUserPolicy` · `GetUserPolicy` · `DeleteUserPolicy` · `ListUserPolicies`
`PutGroupPolicy` · `GetGroupPolicy` · `DeleteGroupPolicy` · `ListGroupPolicies`
`PutRolePolicy` · `GetRolePolicy` · `DeleteRolePolicy` · `ListRolePolicies`
### Instance Profiles
`CreateInstanceProfile` · `GetInstanceProfile` · `DeleteInstanceProfile` · `ListInstanceProfiles` · `AddRoleToInstanceProfile` · `RemoveRoleFromInstanceProfile` · `ListInstanceProfilesForRole`
### Access Keys
`CreateAccessKey` · `GetAccessKeyLastUsed` · `ListAccessKeys` · `UpdateAccessKey` · `DeleteAccessKey`
### Login Profiles
`CreateLoginProfile` · `DeleteLoginProfile` · `UpdateLoginProfile`
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a role
aws iam create-role \
--role-name lambda-execution-role \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}' \
--endpoint-url $AWS_ENDPOINT
# Attach a managed policy
aws iam attach-role-policy \
--role-name lambda-execution-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole \
--endpoint-url $AWS_ENDPOINT
# Create a user
aws iam create-user --user-name alice --endpoint-url $AWS_ENDPOINT
# Create an access key
aws iam create-access-key --user-name alice --endpoint-url $AWS_ENDPOINT
# List roles
aws iam list-roles --endpoint-url $AWS_ENDPOINT
```
+41
View File
@@ -0,0 +1,41 @@
# Services Overview
Floci emulates 19+ AWS services on a single port (`4566`). All services use the real AWS wire protocol — your existing AWS CLI commands and SDK clients work without modification.
## Service Matrix
| Service | Endpoint | Protocol | Supported operations |
|---|---|---|---|
| [SSM](ssm.md) | `POST /` + `X-Amz-Target: AmazonSSM.*` | JSON 1.1 | 12 |
| [SQS](sqs.md) | `POST /` with `Action=` param | Query / JSON | 20 |
| [SNS](sns.md) | `POST /` with `Action=` param | Query / JSON | 17 |
| [S3](s3.md) | `/{bucket}/{key}` | REST XML | 50+ |
| [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 19 |
| [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 |
| [Lambda](lambda.md) | `/2015-03-31/functions/...` | REST JSON | 18 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 40+ |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 20 |
| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 24 |
| [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 18 |
| [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 21 |
| [Secrets Manager](secrets-manager.md) | `POST /` + `X-Amz-Target: secretsmanager.*` | JSON 1.1 | 14 |
| [CloudFormation](cloudformation.md) | `POST /` with `Action=` param | Query | 20 |
| [Step Functions](step-functions.md) | `POST /` + `X-Amz-Target: AmazonStatesService.*` | JSON 1.1 | 12 |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 60+ |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 |
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 8 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 13 |
| [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 14 |
| [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 14 |
| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 8 |
## Common Setup
Before calling any service, configure your AWS client to point to Floci:
```bash
export AWS_ENDPOINT=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
```
+67
View File
@@ -0,0 +1,67 @@
# Kinesis
**Protocol:** JSON 1.1 (`X-Amz-Target: Kinesis_20131202.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateStream` | Create a stream |
| `DeleteStream` | Delete a stream |
| `ListStreams` | List all streams |
| `DescribeStream` | Get stream details and shard info |
| `DescribeStreamSummary` | Lightweight stream description |
| `RegisterStreamConsumer` | Register an enhanced fan-out consumer |
| `DeregisterStreamConsumer` | Remove a consumer |
| `DescribeStreamConsumer` | Get consumer details |
| `ListStreamConsumers` | List consumers for a stream |
| `SubscribeToShard` | Subscribe to a shard for enhanced fan-out |
| `PutRecord` | Write a single record |
| `PutRecords` | Write up to 500 records |
| `GetShardIterator` | Get an iterator for reading |
| `GetRecords` | Read records from a shard |
| `SplitShard` | Split a shard into two |
| `MergeShards` | Merge two adjacent shards |
| `AddTagsToStream` | Tag a stream |
| `RemoveTagsFromStream` | Remove tags |
| `ListTagsForStream` | List tags |
| `StartStreamEncryption` | Enable KMS encryption |
| `StopStreamEncryption` | Disable encryption |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a stream
aws kinesis create-stream \
--stream-name events \
--shard-count 2 \
--endpoint-url $AWS_ENDPOINT
# Put a record
aws kinesis put-record \
--stream-name events \
--partition-key "user-123" \
--data '{"event":"page_view","page":"/home"}' \
--endpoint-url $AWS_ENDPOINT
# Get a shard iterator
SHARD_ID=$(aws kinesis describe-stream \
--stream-name events \
--query 'StreamDescription.Shards[0].ShardId' --output text \
--endpoint-url $AWS_ENDPOINT)
ITERATOR=$(aws kinesis get-shard-iterator \
--stream-name events \
--shard-id $SHARD_ID \
--shard-iterator-type TRIM_HORIZON \
--query ShardIterator --output text \
--endpoint-url $AWS_ENDPOINT)
# Read records
aws kinesis get-records \
--shard-iterator $ITERATOR \
--endpoint-url $AWS_ENDPOINT
```
+64
View File
@@ -0,0 +1,64 @@
# KMS
**Protocol:** JSON 1.1 (`X-Amz-Target: TrentService.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateKey` | Create a new KMS key |
| `DescribeKey` | Get key metadata |
| `ListKeys` | List all keys |
| `Encrypt` | Encrypt plaintext with a key |
| `Decrypt` | Decrypt ciphertext |
| `ReEncrypt` | Re-encrypt under a different key |
| `GenerateDataKey` | Generate a data key (plaintext + encrypted) |
| `GenerateDataKeyWithoutPlaintext` | Generate only the encrypted data key |
| `Sign` | Sign a message with an asymmetric key |
| `Verify` | Verify a signature |
| `CreateAlias` | Create a friendly name for a key |
| `DeleteAlias` | Remove an alias |
| `ListAliases` | List all aliases |
| `ScheduleKeyDeletion` | Mark a key for deletion |
| `CancelKeyDeletion` | Cancel pending deletion |
| `TagResource` | Tag a key |
| `UntagResource` | Remove tags |
| `ListResourceTags` | List tags |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a symmetric key
KEY_ID=$(aws kms create-key \
--description "My encryption key" \
--query KeyMetadata.KeyId --output text \
--endpoint-url $AWS_ENDPOINT)
# Create an alias
aws kms create-alias \
--alias-name alias/my-key \
--target-key-id $KEY_ID \
--endpoint-url $AWS_ENDPOINT
# Encrypt
CIPHER=$(aws kms encrypt \
--key-id alias/my-key \
--plaintext "Hello, World!" \
--query CiphertextBlob --output text \
--endpoint-url $AWS_ENDPOINT)
# Decrypt
aws kms decrypt \
--ciphertext-blob $CIPHER \
--query Plaintext --output text \
--endpoint-url $AWS_ENDPOINT | base64 --decode
# Generate a data key (envelope encryption)
aws kms generate-data-key \
--key-id alias/my-key \
--key-spec AES_256 \
--endpoint-url $AWS_ENDPOINT
```
+131
View File
@@ -0,0 +1,131 @@
# Lambda
**Protocol:** REST JSON
**Endpoint:** `http://localhost:4566/2015-03-31/functions/...`
Lambda runs your function code inside real Docker containers — the same way real AWS Lambda does.
## Supported Operations
| Operation | Description |
|---|---|
| `CreateFunction` | Deploy a Lambda function |
| `GetFunction` | Get function details and download URL |
| `GetFunctionConfiguration` | Get runtime configuration |
| `ListFunctions` | List all functions |
| `UpdateFunctionCode` | Upload new code |
| `DeleteFunction` | Remove a function |
| `Invoke` | Invoke a function synchronously or asynchronously |
| `CreateEventSourceMapping` | Connect SQS / Kinesis / DynamoDB Streams to a function |
| `GetEventSourceMapping` | Get event source mapping details |
| `ListEventSourceMappings` | List all event source mappings |
| `UpdateEventSourceMapping` | Update a mapping |
| `DeleteEventSourceMapping` | Remove a mapping |
| `PublishVersion` | Publish an immutable version |
| `CreateAlias` | Create a named alias pointing to a version |
| `GetAlias` | Get alias details |
| `ListAliases` | List all aliases for a function |
| `UpdateAlias` | Update an alias |
| `DeleteAlias` | Delete an alias |
## Configuration
```yaml
floci:
services:
lambda:
enabled: true
ephemeral: false # Remove container after each invocation
default-memory-mb: 128
default-timeout-seconds: 3
docker-host: unix:///var/run/docker.sock
runtime-api-base-port: 9200
runtime-api-max-port: 9299
code-path: ./data/lambda-code # ZIP storage location
poll-interval-ms: 1000
container-idle-timeout-seconds: 300 # Idle container cleanup
```
### Docker socket requirement
Lambda requires the Docker socket. Mount it in your compose file:
```yaml
services:
floci:
volumes:
- /var/run/docker.sock:/var/run/docker.sock
```
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Package a simple Node.js function
cat > index.mjs << 'EOF'
export const handler = async (event) => {
console.log("Event:", JSON.stringify(event));
return { statusCode: 200, body: JSON.stringify({ hello: "world" }) };
};
EOF
zip function.zip index.mjs
# Deploy the function
aws lambda create-function \
--function-name my-function \
--runtime nodejs22.x \
--role arn:aws:iam::000000000000:role/lambda-role \
--handler index.handler \
--zip-file fileb://function.zip \
--endpoint-url $AWS_ENDPOINT
# Invoke synchronously
aws lambda invoke \
--function-name my-function \
--payload '{"key":"value"}' \
--cli-binary-format raw-in-base64-out \
response.json \
--endpoint-url $AWS_ENDPOINT
cat response.json
# Invoke asynchronously
aws lambda invoke \
--function-name my-function \
--invocation-type Event \
--payload '{"key":"value"}' \
--cli-binary-format raw-in-base64-out \
/dev/null \
--endpoint-url $AWS_ENDPOINT
# Update code
zip function.zip index.mjs
aws lambda update-function-code \
--function-name my-function \
--zip-file fileb://function.zip \
--endpoint-url $AWS_ENDPOINT
```
## Event Source Mappings
Connect Lambda to SQS, Kinesis, or DynamoDB Streams:
```bash
# SQS trigger
QUEUE_ARN=$(aws sqs get-queue-attributes \
--queue-url $AWS_ENDPOINT/000000000000/orders \
--attribute-names QueueArn \
--query Attributes.QueueArn --output text \
--endpoint-url $AWS_ENDPOINT)
aws lambda create-event-source-mapping \
--function-name my-function \
--event-source-arn $QUEUE_ARN \
--batch-size 10 \
--endpoint-url $AWS_ENDPOINT
```
## Supported Runtimes
Any runtime that has an official AWS Lambda container image works with Floci (e.g. `nodejs22.x`, `python3.13`, `java21`, `go1.x`, `provided.al2023`).
+106
View File
@@ -0,0 +1,106 @@
# RDS
**Protocol:** Query (XML) for management API + PostgreSQL / MySQL wire protocol for data plane
**Management Endpoint:** `POST http://localhost:4566/`
**Data Endpoint:** `localhost:<proxy-port>` (TCP)
Floci manages real PostgreSQL, MySQL, and MariaDB Docker containers and proxies TCP connections to them, including IAM authentication support.
## Supported Management Actions
| Action | Description |
|---|---|
| `CreateDBInstance` | Start a new database instance |
| `DescribeDBInstances` | List instances and their connection info |
| `DeleteDBInstance` | Stop and remove an instance |
| `ModifyDBInstance` | Update instance settings |
| `RebootDBInstance` | Restart a database instance |
| `CreateDBCluster` | Create an Aurora-compatible cluster |
| `DescribeDBClusters` | List clusters |
| `DeleteDBCluster` | Delete a cluster |
| `ModifyDBCluster` | Update cluster settings |
| `CreateDBParameterGroup` | Create a parameter group |
| `DescribeDBParameterGroups` | List parameter groups |
| `DeleteDBParameterGroup` | Delete a parameter group |
| `ModifyDBParameterGroup` | Update parameter group settings |
| `DescribeDBParameters` | List parameters in a group |
## Configuration
```yaml
floci:
services:
rds:
enabled: true
proxy-base-port: 7001
proxy-max-port: 7099
default-postgres-image: "postgres:16-alpine"
default-mysql-image: "mysql:8.0"
default-mariadb-image: "mariadb:11"
```
### Docker Compose
RDS requires the Docker socket and port range exposure:
```yaml
services:
floci:
image: hectorvent/floci:latest
ports:
- "4566:4566"
- "7001-7099:7001-7099" # RDS proxy ports
volumes:
- /var/run/docker.sock:/var/run/docker.sock
environment:
FLOCI_SERVICES_DOCKER_NETWORK: my-project_default
FLOCI_SERVICES_RDS_PROXY_BASE_PORT: "7001"
```
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a PostgreSQL instance
aws rds create-db-instance \
--db-instance-identifier mypostgres \
--db-instance-class db.t3.micro \
--engine postgres \
--master-username admin \
--master-user-password secret123 \
--allocated-storage 20 \
--endpoint-url $AWS_ENDPOINT
# Get connection details
aws rds describe-db-instances \
--db-instance-identifier mypostgres \
--query 'DBInstances[0].Endpoint' \
--endpoint-url $AWS_ENDPOINT
# Connect with psql (use the port returned above)
psql -h localhost -p 7001 -U admin
# Create a MySQL instance
aws rds create-db-instance \
--db-instance-identifier mymysql \
--db-instance-class db.t3.micro \
--engine mysql \
--master-username root \
--master-user-password secret123 \
--allocated-storage 20 \
--endpoint-url $AWS_ENDPOINT
# Connect with mysql client
mysql -h 127.0.0.1 -P 7002 -u root -psecret123
```
## Supported Engines
| Engine | Default image |
|---|---|
| `postgres` | `postgres:16-alpine` |
| `mysql` | `mysql:8.0` |
| `mariadb` | `mariadb:11` |
Override the image per-instance with the `--engine-version` flag or globally via environment variables.
+109
View File
@@ -0,0 +1,109 @@
# S3
**Protocol:** REST XML
**Endpoint:** `http://localhost:4566/{bucket}/{key}`
## Supported Operations
| Category | Operations |
|---|---|
| **Buckets** | ListBuckets, CreateBucket, HeadBucket, DeleteBucket, GetBucketLocation |
| **Objects** | PutObject, GetObject, HeadObject, DeleteObject, DeleteObjects, CopyObject |
| **Listing** | ListObjects, ListObjectsV2, ListObjectVersions |
| **Multipart** | CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, ListMultipartUploads |
| **Versioning** | PutBucketVersioning, GetBucketVersioning |
| **Tagging** | PutBucketTagging, GetBucketTagging, PutObjectTagging, GetObjectTagging, DeleteObjectTagging |
| **Policy** | PutBucketPolicy, GetBucketPolicy, DeleteBucketPolicy |
| **CORS** | PutBucketCors, GetBucketCors, DeleteBucketCors |
| **Lifecycle** | PutBucketLifecycle, GetBucketLifecycle, DeleteBucketLifecycle |
| **ACL** | PutBucketAcl, GetBucketAcl, PutObjectAcl, GetObjectAcl |
| **Encryption** | PutBucketEncryption, GetBucketEncryption, DeleteBucketEncryption |
| **Notifications** | PutBucketNotification, GetBucketNotification |
| **Object Lock** | PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold |
| **Pre-signed URLs** | Generates and validates pre-signed GET/PUT URLs |
| **S3 Select** | SelectObjectContent |
## Configuration
```yaml
floci:
services:
s3:
enabled: true
default-presign-expiry-seconds: 3600
auth:
presign-secret: local-emulator-secret
```
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create bucket
aws s3 mb s3://my-bucket --endpoint-url $AWS_ENDPOINT
# Upload a file
aws s3 cp ./report.pdf s3://my-bucket/reports/report.pdf --endpoint-url $AWS_ENDPOINT
# Upload inline content
echo '{"hello":"world"}' | aws s3 cp - s3://my-bucket/data.json --endpoint-url $AWS_ENDPOINT
# Download
aws s3 cp s3://my-bucket/data.json ./data.json --endpoint-url $AWS_ENDPOINT
# List
aws s3 ls s3://my-bucket --endpoint-url $AWS_ENDPOINT
# Delete
aws s3 rm s3://my-bucket/data.json --endpoint-url $AWS_ENDPOINT
# Enable versioning
aws s3api put-bucket-versioning \
--bucket my-bucket \
--versioning-configuration Status=Enabled \
--endpoint-url $AWS_ENDPOINT
# Generate a pre-signed URL (valid for 1 hour)
aws s3 presign s3://my-bucket/report.pdf \
--expires-in 3600 \
--endpoint-url $AWS_ENDPOINT
```
## Path-Style URLs
Floci uses path-style URLs:
```
http://localhost:4566/my-bucket/my-key
```
When using the AWS SDK, enable path-style mode:
=== "Java"
```java
S3Client s3 = S3Client.builder()
.endpointOverride(URI.create("http://localhost:4566"))
.serviceConfiguration(S3Configuration.builder()
.pathStyleAccessEnabled(true)
.build())
.build();
```
=== "Node.js"
```javascript
const s3 = new S3Client({
endpoint: "http://localhost:4566",
forcePathStyle: true,
});
```
=== "Python"
```python
s3 = boto3.client("s3",
endpoint_url="http://localhost:4566",
config=Config(s3={"addressing_style": "path"}))
```
+77
View File
@@ -0,0 +1,77 @@
# Secrets Manager
**Protocol:** JSON 1.1 (`X-Amz-Target: secretsmanager.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateSecret` | Create a new secret |
| `GetSecretValue` | Retrieve the current secret value |
| `PutSecretValue` | Update the secret value (new version) |
| `UpdateSecret` | Update secret metadata or value |
| `DescribeSecret` | Get secret metadata and version info |
| `ListSecrets` | List all secrets |
| `DeleteSecret` | Delete a secret (with recovery window) |
| `RotateSecret` | Trigger secret rotation via a Lambda |
| `ListSecretVersionIds` | List all versions of a secret |
| `GetResourcePolicy` | Get the resource policy |
| `PutResourcePolicy` | Attach a resource policy |
| `DeleteResourcePolicy` | Remove the resource policy |
| `TagResource` | Tag a secret |
| `UntagResource` | Remove tags |
## Configuration
```yaml
floci:
services:
secretsmanager:
enabled: true
default-recovery-window-days: 30 # Days before a deleted secret is purged
```
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a string secret
aws secretsmanager create-secret \
--name /app/database-url \
--secret-string "postgresql://admin:secret@localhost/mydb" \
--endpoint-url $AWS_ENDPOINT
# Create a JSON secret
aws secretsmanager create-secret \
--name /app/api-keys \
--secret-string '{"stripe":"sk_test_xxx","sendgrid":"SG.xxx"}' \
--endpoint-url $AWS_ENDPOINT
# Retrieve a secret
aws secretsmanager get-secret-value \
--secret-id /app/database-url \
--endpoint-url $AWS_ENDPOINT
# Update a secret
aws secretsmanager put-secret-value \
--secret-id /app/database-url \
--secret-string "postgresql://admin:new-password@localhost/mydb" \
--endpoint-url $AWS_ENDPOINT
# List secrets
aws secretsmanager list-secrets --endpoint-url $AWS_ENDPOINT
# Delete (with recovery window)
aws secretsmanager delete-secret \
--secret-id /app/database-url \
--recovery-window-in-days 7 \
--endpoint-url $AWS_ENDPOINT
# Delete immediately (no recovery)
aws secretsmanager delete-secret \
--secret-id /app/database-url \
--force-delete-without-recovery \
--endpoint-url $AWS_ENDPOINT
```
+70
View File
@@ -0,0 +1,70 @@
# SNS
**Protocol:** Query (XML) and JSON 1.0 (both supported)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateTopic` | Create a topic |
| `DeleteTopic` | Delete a topic |
| `ListTopics` | List all topics |
| `GetTopicAttributes` | Get topic configuration |
| `SetTopicAttributes` | Update topic configuration |
| `Subscribe` | Subscribe an endpoint (SQS, HTTP, Lambda, email) |
| `Unsubscribe` | Remove a subscription |
| `ListSubscriptions` | List all subscriptions |
| `ListSubscriptionsByTopic` | List subscriptions for a specific topic |
| `GetSubscriptionAttributes` | Get subscription settings |
| `SetSubscriptionAttributes` | Update subscription settings |
| `ConfirmSubscription` | Confirm a pending subscription |
| `Publish` | Publish a message to a topic |
| `PublishBatch` | Publish up to 10 messages in one call |
| `TagResource` | Tag a topic |
| `UntagResource` | Remove tags from a topic |
| `ListTagsForResource` | List tags on a topic |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a topic
TOPIC_ARN=$(aws sns create-topic --name notifications \
--query TopicArn --output text \
--endpoint-url $AWS_ENDPOINT)
# Subscribe an SQS queue
QUEUE_ARN=$(aws sqs get-queue-attributes \
--queue-url $AWS_ENDPOINT/000000000000/orders \
--attribute-names QueueArn \
--query Attributes.QueueArn --output text \
--endpoint-url $AWS_ENDPOINT)
aws sns subscribe \
--topic-arn $TOPIC_ARN \
--protocol sqs \
--notification-endpoint $QUEUE_ARN \
--endpoint-url $AWS_ENDPOINT
# Publish a message
aws sns publish \
--topic-arn $TOPIC_ARN \
--message '{"event":"user.registered"}' \
--endpoint-url $AWS_ENDPOINT
# Fan-out: publish and verify the SQS queue received the message
aws sqs receive-message \
--queue-url $AWS_ENDPOINT/000000000000/orders \
--endpoint-url $AWS_ENDPOINT
```
## SNS → SQS Fan-Out
Floci supports real SNS → SQS fan-out. When you publish to a topic, all SQS-subscribed queues receive the message immediately.
Supported subscription protocols:
- `sqs` — delivers to a Floci SQS queue
- `lambda` — invokes a Floci Lambda function
- `http` / `https` — posts to an HTTP endpoint
+93
View File
@@ -0,0 +1,93 @@
# SQS
**Protocol:** Query (XML) and JSON 1.0 (both supported)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateQueue` | Create a standard or FIFO queue |
| `DeleteQueue` | Delete a queue |
| `ListQueues` | List all queues |
| `GetQueueUrl` | Look up a queue URL by name |
| `GetQueueAttributes` | Get queue configuration attributes |
| `SetQueueAttributes` | Update queue configuration |
| `SendMessage` | Send a message to a queue |
| `SendMessageBatch` | Send up to 10 messages in one call |
| `ReceiveMessage` | Poll for messages |
| `DeleteMessage` | Acknowledge and delete a message |
| `DeleteMessageBatch` | Delete multiple messages at once |
| `ChangeMessageVisibility` | Extend or reset a message's visibility timeout |
| `ChangeMessageVisibilityBatch` | Change visibility for multiple messages |
| `PurgeQueue` | Delete all messages in a queue |
| `TagQueue` | Add tags to a queue |
| `UntagQueue` | Remove tags from a queue |
| `ListQueueTags` | List tags on a queue |
| `ListDeadLetterSourceQueues` | Find queues that use this queue as DLQ |
| `StartMessageMoveTask` | Start a DLQ redrive task |
| `ListMessageMoveTasks` | List DLQ redrive tasks |
## Configuration
```yaml
floci:
services:
sqs:
enabled: true
default-visibility-timeout: 30 # Seconds
max-message-size: 262144 # 256 KB
```
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a standard queue
aws sqs create-queue --queue-name orders --endpoint-url $AWS_ENDPOINT
# Create a FIFO queue
aws sqs create-queue \
--queue-name orders.fifo \
--attributes FifoQueue=true \
--endpoint-url $AWS_ENDPOINT
# Send a message
QUEUE_URL="$AWS_ENDPOINT/000000000000/orders"
aws sqs send-message \
--queue-url $QUEUE_URL \
--message-body '{"event":"order.placed","id":"abc123"}' \
--endpoint-url $AWS_ENDPOINT
# Receive messages
aws sqs receive-message \
--queue-url $QUEUE_URL \
--max-number-of-messages 10 \
--endpoint-url $AWS_ENDPOINT
# Delete a message (replace RECEIPT_HANDLE with the value from ReceiveMessage)
aws sqs delete-message \
--queue-url $QUEUE_URL \
--receipt-handle "RECEIPT_HANDLE" \
--endpoint-url $AWS_ENDPOINT
# Set up a dead-letter queue
DLQ_ARN=$(aws sqs get-queue-attributes \
--queue-url $AWS_ENDPOINT/000000000000/orders-dlq \
--attribute-names QueueArn \
--query Attributes.QueueArn \
--output text \
--endpoint-url $AWS_ENDPOINT)
aws sqs set-queue-attributes \
--queue-url $QUEUE_URL \
--attributes "{\"RedrivePolicy\":\"{\\\"deadLetterTargetArn\\\":\\\"$DLQ_ARN\\\",\\\"maxReceiveCount\\\":3}\"}" \
--endpoint-url $AWS_ENDPOINT
```
## Queue URL Format
```
http://localhost:4566/000000000000/<queue-name>
```
+67
View File
@@ -0,0 +1,67 @@
# SSM Parameter Store
**Protocol:** JSON 1.1 (`X-Amz-Target: AmazonSSM.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `PutParameter` | Create or update a parameter |
| `GetParameter` | Get a single parameter by name |
| `GetParameters` | Get multiple parameters by name |
| `GetParametersByPath` | Get all parameters under a path prefix |
| `DeleteParameter` | Delete a parameter |
| `DeleteParameters` | Delete multiple parameters |
| `GetParameterHistory` | List all versions of a parameter |
| `DescribeParameters` | List parameters with optional filters |
| `LabelParameterVersion` | Attach a label to a specific version |
| `AddTagsToResource` | Tag a parameter |
| `ListTagsForResource` | List tags on a parameter |
| `RemoveTagsFromResource` | Remove tags from a parameter |
## Configuration
```yaml
floci:
services:
ssm:
enabled: true
max-parameter-history: 5 # Versions retained per parameter
storage:
services:
ssm:
mode: memory
flush-interval-ms: 5000
```
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Store parameters
aws ssm put-parameter --endpoint-url $AWS_ENDPOINT \
--name /app/db/host --value "localhost" --type String
aws ssm put-parameter --endpoint-url $AWS_ENDPOINT \
--name /app/db/password --value "secret" --type SecureString
# Retrieve
aws ssm get-parameter --endpoint-url $AWS_ENDPOINT \
--name /app/db/host
aws ssm get-parameters-by-path --endpoint-url $AWS_ENDPOINT \
--path /app/ --recursive
# Delete
aws ssm delete-parameter --endpoint-url $AWS_ENDPOINT \
--name /app/db/host
```
## Parameter Types
All AWS parameter types are accepted: `String`, `StringList`, `SecureString`.
!!! note
`SecureString` parameters are stored as-is without actual KMS encryption in Floci. The type is preserved and returned correctly, but the value is not encrypted at rest.
+62
View File
@@ -0,0 +1,62 @@
# Step Functions
**Protocol:** JSON 1.1 (`X-Amz-Target: AmazonStatesService.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
| Action | Description |
|---|---|
| `CreateStateMachine` | Create a state machine (Standard or Express) |
| `DescribeStateMachine` | Get state machine definition and metadata |
| `ListStateMachines` | List all state machines |
| `DeleteStateMachine` | Delete a state machine |
| `StartExecution` | Start a new execution |
| `DescribeExecution` | Get execution status and output |
| `ListExecutions` | List executions for a state machine |
| `StopExecution` | Stop a running execution |
| `GetExecutionHistory` | Get the full event history of an execution |
| `SendTaskSuccess` | Report task success (for `.waitForTaskToken` tasks) |
| `SendTaskFailure` | Report task failure |
| `SendTaskHeartbeat` | Send a heartbeat for long-running tasks |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Create a state machine
SM_ARN=$(aws stepfunctions create-state-machine \
--name my-workflow \
--definition '{
"Comment": "Simple workflow",
"StartAt": "HelloWorld",
"States": {
"HelloWorld": {
"Type": "Pass",
"Result": {"message": "Hello, World!"},
"End": true
}
}
}' \
--role-arn arn:aws:iam::000000000000:role/step-functions-role \
--query stateMachineArn --output text \
--endpoint-url $AWS_ENDPOINT)
# Start an execution
EXEC_ARN=$(aws stepfunctions start-execution \
--state-machine-arn $SM_ARN \
--input '{"key":"value"}' \
--query executionArn --output text \
--endpoint-url $AWS_ENDPOINT)
# Check status
aws stepfunctions describe-execution \
--execution-arn $EXEC_ARN \
--endpoint-url $AWS_ENDPOINT
# Get event history
aws stepfunctions get-execution-history \
--execution-arn $EXEC_ARN \
--endpoint-url $AWS_ENDPOINT
```
+35
View File
@@ -0,0 +1,35 @@
# STS
**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
## Supported Actions
| Action | Description |
|---|---|
| `GetCallerIdentity` | Returns the account ID, user ID, and ARN |
| `AssumeRole` | Assume an IAM role, returns temporary credentials |
| `AssumeRoleWithWebIdentity` | Assume a role using a web identity token (OIDC) |
| `AssumeRoleWithSAML` | Assume a role using a SAML assertion |
| `GetSessionToken` | Get temporary credentials for an IAM user |
| `GetFederationToken` | Get temporary credentials for a federated user |
| `DecodeAuthorizationMessage` | Decode an encoded authorization failure message |
## Examples
```bash
export AWS_ENDPOINT=http://localhost:4566
# Get caller identity (always works, useful for smoke testing)
aws sts get-caller-identity --endpoint-url $AWS_ENDPOINT
# Assume a role
aws sts assume-role \
--role-arn arn:aws:iam::000000000000:role/my-role \
--role-session-name dev-session \
--endpoint-url $AWS_ENDPOINT
# Get a session token
aws sts get-session-token --endpoint-url $AWS_ENDPOINT
```
`GetCallerIdentity` is commonly used in CI pipelines and integration tests as a quick connectivity check before running more complex tests.
+71
View File
@@ -0,0 +1,71 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 150" width="500" height="150">
<defs>
<!-- Main cloud gradient - warm popcorn white/cream -->
<linearGradient id="cloudGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#fffdf7;stop-opacity:1" />
<stop offset="50%" style="stop-color:#fef9ee;stop-opacity:1" />
<stop offset="100%" style="stop-color:#fde68a;stop-opacity:1" />
</linearGradient>
<!-- Accent puff gradient - warm amber -->
<linearGradient id="accentGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#fbbf24;stop-opacity:1" />
<stop offset="100%" style="stop-color:#f59e0b;stop-opacity:1" />
</linearGradient>
<!-- Light puff -->
<linearGradient id="lightPuff" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:#fef3c7;stop-opacity:1" />
<stop offset="100%" style="stop-color:#fde68a;stop-opacity:1" />
</linearGradient>
<filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="2" result="blur"/>
<feComposite in="SourceGraphic" in2="blur" operator="over"/>
</filter>
<!-- Cloud outline stroke -->
<linearGradient id="strokeGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#f59e0b;stop-opacity:1" />
<stop offset="100%" style="stop-color:#d97706;stop-opacity:1" />
</linearGradient>
<filter id="softShadow" x="-10%" y="-10%" width="130%" height="140%">
<feDropShadow dx="0" dy="3" stdDeviation="4" flood-color="#92400e" flood-opacity="0.15"/>
</filter>
</defs>
<!-- Main cloud shape -->
<g filter="url(#softShadow)">
<!-- Cloud body - smooth overlapping circles -->
<circle cx="95" cy="88" r="36" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="60" cy="92" r="28" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="130" cy="92" r="28" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="75" cy="68" r="26" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="115" cy="66" r="27" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<circle cx="95" cy="56" r="22" fill="url(#cloudGrad)" stroke="#eab308" stroke-width="0.8"/>
<!-- Smooth fill -->
<rect x="38" y="88" width="120" height="24" rx="12" fill="url(#cloudGrad)"/>
</g>
<!-- Floating floccus puffs (scattered small clouds) -->
<circle cx="152" cy="52" r="8" fill="url(#lightPuff)" opacity="0.7"/>
<circle cx="145" cy="40" r="6" fill="url(#lightPuff)" opacity="0.5"/>
<circle cx="160" cy="42" r="5" fill="url(#lightPuff)" opacity="0.4"/>
<circle cx="30" cy="60" r="6" fill="url(#lightPuff)" opacity="0.5"/>
<circle cx="22" cy="70" r="5" fill="url(#lightPuff)" opacity="0.35"/>
<circle cx="155" cy="78" r="4" fill="url(#lightPuff)" opacity="0.3"/>
<!-- Accent sparkle dots (popcorn pop!) -->
<circle cx="80" cy="48" r="3.5" fill="url(#accentGrad)"/>
<circle cx="110" cy="44" r="3" fill="url(#accentGrad)" opacity="0.9"/>
<circle cx="62" cy="62" r="2.5" fill="url(#accentGrad)" opacity="0.7"/>
<circle cx="128" cy="58" r="2" fill="url(#accentGrad)" opacity="0.6"/>
<circle cx="95" cy="40" r="2" fill="url(#accentGrad)" opacity="0.8"/>
<!-- Cloud shine highlights -->
<ellipse cx="80" cy="62" rx="14" ry="8" fill="white" opacity="0.15"/>
<ellipse cx="105" cy="58" rx="10" ry="6" fill="white" opacity="0.12"/>
<circle cx="70" cy="72" r="4" fill="white" opacity="0.2"/>
<!-- Text: Floci -->
<text x="185" y="82" font-size="58" font-weight="800" font-family="'Inter', 'Nunito', 'Segoe UI', system-ui, sans-serif" fill="#78350f" letter-spacing="-2">Floci</text>
<!-- Tagline -->
<text x="188" y="108" font-size="14" font-family="'Inter', 'Nunito', 'Segoe UI', system-ui, sans-serif" fill="#b45309" letter-spacing="0.5">Light, fluffy, and always free</text>
</svg>

After

Width:  |  Height:  |  Size: 3.9 KiB

+88
View File
@@ -0,0 +1,88 @@
site_name: Floci
site_description: Fast, free, open-source local AWS emulator
site_url: https://hectorvent.github.io/floci
repo_url: https://github.com/hectorvent/floci
repo_name: hectorvent/floci
edit_uri: edit/main/docs/
theme:
name: material
logo: assets/logo.svg
favicon: assets/logo.svg
palette:
- media: "(prefers-color-scheme: light)"
scheme: default
primary: indigo
accent: indigo
toggle:
icon: material/brightness-7
name: Switch to dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: indigo
accent: indigo
toggle:
icon: material/brightness-4
name: Switch to light mode
features:
- navigation.tabs
- navigation.sections
- navigation.top
- navigation.instant
- search.highlight
- search.suggest
- content.code.copy
- content.code.annotate
- content.tabs.link
extra_css:
- assets/extra.css
plugins:
- search
markdown_extensions:
- admonition
- pymdownx.details
- pymdownx.superfences
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.tabbed:
alternate_style: true
- pymdownx.inlinehilite
- tables
- attr_list
nav:
- Home: index.md
- Getting Started:
- Quick Start: getting-started/quick-start.md
- Installation: getting-started/installation.md
- AWS CLI & SDK Setup: getting-started/aws-setup.md
- Configuration:
- Docker Compose: configuration/docker-compose.md
- Ports Reference: configuration/ports.md
- application.yml Reference: configuration/application-yml.md
- Storage Modes: configuration/storage.md
- Services:
- Overview: services/index.md
- SSM Parameter Store: services/ssm.md
- SQS: services/sqs.md
- SNS: services/sns.md
- S3: services/s3.md
- DynamoDB: services/dynamodb.md
- Lambda: services/lambda.md
- API Gateway: services/api-gateway.md
- Cognito: services/cognito.md
- KMS: services/kms.md
- Kinesis: services/kinesis.md
- Secrets Manager: services/secrets-manager.md
- CloudFormation: services/cloudformation.md
- Step Functions: services/step-functions.md
- IAM: services/iam.md
- STS: services/sts.md
- ElastiCache: services/elasticache.md
- RDS: services/rds.md
- EventBridge: services/eventbridge.md
- CloudWatch: services/cloudwatch.md
- Contributing: contributing.md
+152
View File
@@ -0,0 +1,152 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.hectorvent</groupId>
<artifactId>floci</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>Floci</name>
<description>Fast, free, open-source local AWS emulator supporting SSM, SQS, SNS, S3, DynamoDB, Lambda, API Gateway, Cognito, KMS, Kinesis, Secrets Manager, CloudFormation, Step Functions, IAM, STS, ElastiCache, RDS, EventBridge, and CloudWatch</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<quarkus.platform.version>3.32.3</quarkus.platform.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus.platform</groupId>
<artifactId>quarkus-bom</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Quarkus REST (RESTEasy Reactive) -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-jackson</artifactId>
</dependency>
<!-- YAML config support -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-config-yaml</artifactId>
</dependency>
<!-- Jackson for JSON storage serialization -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-cbor</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<!-- Vert.x for per-container Lambda Runtime API servers -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-vertx</artifactId>
</dependency>
<!-- Docker client for Lambda container lifecycle management -->
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java-core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java-transport-httpclient5</artifactId>
<version>3.4.0</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.quarkus.platform</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.platform.version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>build</goal>
<goal>generate-code</goal>
<goal>generate-code-tests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
<configuration>
<release>${maven.compiler.release}</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<properties>
<skipITs>true</skipITs>
<quarkus.native.enabled>true</quarkus.native.enabled>
<maven.compiler.release>24</maven.compiler.release>
</properties>
</profile>
</profiles>
</project>
@@ -0,0 +1,334 @@
package io.github.hectorvent.floci.config;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithDefault;
import java.util.Optional;
@ConfigMapping(prefix = "floci")
public interface EmulatorConfig {
@WithDefault("http://localhost:4566")
String baseUrl();
@WithDefault("us-east-1")
String defaultRegion();
@WithDefault("000000000000")
String defaultAccountId();
StorageConfig storage();
AuthConfig auth();
ServicesConfig services();
interface StorageConfig {
@WithDefault("hybrid")
String mode();
@WithDefault("./data")
String persistentPath();
WalConfig wal();
ServiceStorageOverrides services();
}
interface ServiceStorageOverrides {
SsmStorageConfig ssm();
SqsStorageConfig sqs();
S3StorageConfig s3();
DynamoDbStorageConfig dynamodb();
SnsStorageConfig sns();
LambdaStorageConfig lambda();
CloudWatchLogsStorageConfig cloudwatchlogs();
CloudWatchMetricsStorageConfig cloudwatchmetrics();
SecretsManagerStorageConfig secretsmanager();
}
interface SsmStorageConfig {
@WithDefault("memory")
String mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface SqsStorageConfig {
@WithDefault("memory")
String mode();
}
interface S3StorageConfig {
@WithDefault("hybrid")
String mode();
}
interface DynamoDbStorageConfig {
@WithDefault("memory")
String mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface SnsStorageConfig {
@WithDefault("memory")
String mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface LambdaStorageConfig {
@WithDefault("memory")
String mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface CloudWatchLogsStorageConfig {
@WithDefault("memory")
String mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface CloudWatchMetricsStorageConfig {
@WithDefault("memory")
String mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface SecretsManagerStorageConfig {
@WithDefault("memory")
String mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface WalConfig {
@WithDefault("30000")
long compactionIntervalMs();
}
interface AuthConfig {
@WithDefault("false")
boolean validateSignatures();
@WithDefault("local-emulator-secret")
String presignSecret();
}
interface ServicesConfig {
/** Shared Docker network for all container-based services (Lambda, RDS, ElastiCache).
* Per-service dockerNetwork settings override this value when present. */
Optional<String> dockerNetwork();
SsmServiceConfig ssm();
SqsServiceConfig sqs();
S3ServiceConfig s3();
DynamoDbServiceConfig dynamodb();
SnsServiceConfig sns();
LambdaServiceConfig lambda();
ApiGatewayServiceConfig apigateway();
IamServiceConfig iam();
ElastiCacheServiceConfig elasticache();
RdsServiceConfig rds();
EventBridgeServiceConfig eventbridge();
CloudWatchLogsServiceConfig cloudwatchlogs();
CloudWatchMetricsServiceConfig cloudwatchmetrics();
SecretsManagerServiceConfig secretsmanager();
ApiGatewayV2ServiceConfig apigatewayv2();
KinesisServiceConfig kinesis();
KmsServiceConfig kms();
CognitoServiceConfig cognito();
StepFunctionsServiceConfig stepfunctions();
CloudFormationServiceConfig cloudformation();
}
interface SsmServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("5")
int maxParameterHistory();
}
interface SqsServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("30")
int defaultVisibilityTimeout();
@WithDefault("262144")
int maxMessageSize();
}
interface S3ServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("3600")
int defaultPresignExpirySeconds();
}
interface DynamoDbServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface SnsServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface ApiGatewayServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface IamServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface ElastiCacheServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("6379")
int proxyBasePort();
@WithDefault("6399")
int proxyMaxPort();
@WithDefault("valkey/valkey:8")
String defaultImage();
/** Docker network to attach Valkey containers to. Empty = default bridge. */
Optional<String> dockerNetwork();
}
interface RdsServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("7000")
int proxyBasePort();
@WithDefault("7099")
int proxyMaxPort();
@WithDefault("postgres:16-alpine")
String defaultPostgresImage();
@WithDefault("mysql:8.0")
String defaultMysqlImage();
@WithDefault("mariadb:11")
String defaultMariadbImage();
/** Docker network to attach DB containers to. Empty = default bridge. */
Optional<String> dockerNetwork();
}
interface EventBridgeServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface CloudWatchLogsServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("10000")
int maxEventsPerQuery();
}
interface CloudWatchMetricsServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface SecretsManagerServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("30")
int defaultRecoveryWindowDays();
}
interface ApiGatewayV2ServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface KinesisServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface KmsServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface CognitoServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface StepFunctionsServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface CloudFormationServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface LambdaServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("128")
int defaultMemoryMb();
@WithDefault("3")
int defaultTimeoutSeconds();
@WithDefault("unix:///var/run/docker.sock")
String dockerHost();
Optional<String> dockerHostOverride();
@WithDefault("9200")
int runtimeApiBasePort();
@WithDefault("9299")
int runtimeApiMaxPort();
@WithDefault("./data/lambda-code")
String codePath();
@WithDefault("1000")
long pollIntervalMs();
@WithDefault("false")
boolean ephemeral();
@WithDefault("300")
int containerIdleTimeoutSeconds();
/** Docker network to attach Lambda containers to. Empty = default bridge. */
Optional<String> dockerNetwork();
}
}
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.core.common;
public final class AwsArnUtils {
private AwsArnUtils() {}
/**
* Converts an SQS ARN to a queue URL using the given base URL.
* Example: arn:aws:sqs:us-east-1:000000000000:my-queue → http://localhost:4566/000000000000/my-queue
*/
public static String arnToQueueUrl(String arn, String baseUrl) {
String[] parts = arn.split(":");
return baseUrl + "/" + parts[4] + "/" + parts[5];
}
}
@@ -0,0 +1,29 @@
package io.github.hectorvent.floci.core.common;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.ext.Provider;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
/**
* Sets the Date response header in RFC 822 format as expected by AWS SDKs.
* Without this, Quarkus/Vert.x may send ISO 8601 format which the SDK cannot parse.
*/
@Provider
public class AwsDateHeaderFilter implements ContainerResponseFilter {
private static final ZoneId GMT = ZoneId.of("GMT");
private static final DateTimeFormatter RFC_822 = DateTimeFormatter
.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
responseContext.getHeaders().putSingle("Date",
ZonedDateTime.now(GMT).format(RFC_822));
}
}
@@ -0,0 +1,8 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public record AwsErrorResponse(@JsonProperty("__type") String type, @JsonProperty("message") String message) {
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.core.common;
/**
* Base exception for AWS emulator errors.
* Maps to AWS-style error responses with code, message, and HTTP status.
*/
public class AwsException extends RuntimeException {
private final String errorCode;
private final int httpStatus;
public AwsException(String errorCode, String message, int httpStatus) {
super(message);
this.errorCode = errorCode;
this.httpStatus = httpStatus;
}
public String getErrorCode() {
return errorCode;
}
public int getHttpStatus() {
return httpStatus;
}
}
@@ -0,0 +1,23 @@
package io.github.hectorvent.floci.core.common;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
/**
* JAX-RS exception mapper that converts AwsException to AWS-formatted JSON error responses.
*/
@Provider
public class AwsExceptionMapper implements ExceptionMapper<AwsException> {
private static final Logger LOG = Logger.getLogger(AwsExceptionMapper.class);
@Override
public Response toResponse(AwsException exception) {
LOG.debugv("Mapping exception: {0} - {1}", exception.getErrorCode(), exception.getMessage());
return Response.status(exception.getHttpStatus())
.entity(new AwsErrorResponse(exception.getErrorCode(), exception.getMessage()))
.build();
}
}
@@ -0,0 +1,152 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;
import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
/**
* Generic dispatcher for all AWS services that use the application/x-amz-json-1.1 protocol.
* Routes requests to the appropriate service handler based on the X-Amz-Target header prefix.
* <p>
* Currently supported services:
* - SSM (AmazonSSM.*)
* - EventBridge (AmazonEventBridge.*)
* - CloudWatch Logs (Logs_20140328.*)
*/
@Path("/")
public class AwsJson11Controller {
private static final Logger LOG = Logger.getLogger(AwsJson11Controller.class);
private static final String SSM_TARGET_PREFIX = "AmazonSSM.";
private static final String EVENTBRIDGE_TARGET_PREFIX = "AWSEvents.";
private static final String LOGS_TARGET_PREFIX = "Logs_20140328.";
private static final String SECRETS_MANAGER_TARGET_PREFIX = "secretsmanager.";
private static final String KINESIS_TARGET_PREFIX = "Kinesis_20131202.";
private static final String APIGW_V2_TARGET_PREFIX = "AmazonApiGatewayV2.";
private static final String KMS_TARGET_PREFIX = "TrentService.";
private static final String COGNITO_TARGET_PREFIX = "AWSCognitoIdentityProviderService.";
private final ObjectMapper objectMapper;
private final RegionResolver regionResolver;
private final SsmJsonHandler ssmJsonHandler;
private final EventBridgeHandler eventBridgeHandler;
private final CloudWatchLogsHandler cloudWatchLogsHandler;
private final SecretsManagerJsonHandler secretsManagerJsonHandler;
private final KinesisJsonHandler kinesisJsonHandler;
private final ApiGatewayV2JsonHandler apigwV2JsonHandler;
private final KmsJsonHandler kmsJsonHandler;
private final CognitoJsonHandler cognitoJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, RegionResolver regionResolver,
SsmJsonHandler ssmJsonHandler, EventBridgeHandler eventBridgeHandler,
CloudWatchLogsHandler cloudWatchLogsHandler,
SecretsManagerJsonHandler secretsManagerJsonHandler,
KinesisJsonHandler kinesisJsonHandler,
ApiGatewayV2JsonHandler apigwV2JsonHandler,
KmsJsonHandler kmsJsonHandler, CognitoJsonHandler cognitoJsonHandler) {
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
this.ssmJsonHandler = ssmJsonHandler;
this.eventBridgeHandler = eventBridgeHandler;
this.cloudWatchLogsHandler = cloudWatchLogsHandler;
this.secretsManagerJsonHandler = secretsManagerJsonHandler;
this.kinesisJsonHandler = kinesisJsonHandler;
this.apigwV2JsonHandler = apigwV2JsonHandler;
this.kmsJsonHandler = kmsJsonHandler;
this.cognitoJsonHandler = cognitoJsonHandler;
}
@POST
@Consumes("application/x-amz-json-1.1")
@Produces(MediaType.APPLICATION_JSON)
public Response handle(
@HeaderParam("X-Amz-Target") String target,
@Context HttpHeaders httpHeaders,
String body) {
if (target == null) {
return null;
}
String prefix;
String serviceName;
if (target.startsWith(SSM_TARGET_PREFIX)) {
prefix = SSM_TARGET_PREFIX;
serviceName = "SSM";
} else if (target.startsWith(EVENTBRIDGE_TARGET_PREFIX)) {
prefix = EVENTBRIDGE_TARGET_PREFIX;
serviceName = "EventBridge";
} else if (target.startsWith(LOGS_TARGET_PREFIX)) {
prefix = LOGS_TARGET_PREFIX;
serviceName = "Logs";
} else if (target.startsWith(SECRETS_MANAGER_TARGET_PREFIX)) {
prefix = SECRETS_MANAGER_TARGET_PREFIX;
serviceName = "SecretsManager";
} else if (target.startsWith(KINESIS_TARGET_PREFIX)) {
prefix = KINESIS_TARGET_PREFIX;
serviceName = "Kinesis";
} else if (target.startsWith(APIGW_V2_TARGET_PREFIX)) {
prefix = APIGW_V2_TARGET_PREFIX;
serviceName = "ApiGatewayV2";
} else if (target.startsWith(KMS_TARGET_PREFIX)) {
prefix = KMS_TARGET_PREFIX;
serviceName = "KMS";
} else if (target.startsWith(COGNITO_TARGET_PREFIX)) {
prefix = COGNITO_TARGET_PREFIX;
serviceName = "Cognito";
} else {
return Response.status(400)
.entity(new AwsErrorResponse("UnknownOperationException",
"Unknown operation: " + target))
.build();
}
String action = target.substring(prefix.length());
LOG.infov("AwsJson11Controller {0} action: {1}", serviceName, action);
try {
JsonNode request = objectMapper.readTree(body);
String region = regionResolver.resolveRegion(httpHeaders);
return switch (serviceName) {
case "SSM" -> ssmJsonHandler.handle(action, request, region);
case "EventBridge" -> eventBridgeHandler.handle(action, request, region);
case "Logs" -> cloudWatchLogsHandler.handle(action, request, region);
case "SecretsManager" -> secretsManagerJsonHandler.handle(action, request, region);
case "Kinesis" -> kinesisJsonHandler.handle(action, request, region);
case "ApiGatewayV2" -> apigwV2JsonHandler.handle(action, request, region);
case "KMS" -> kmsJsonHandler.handle(action, request, region);
case "Cognito" -> cognitoJsonHandler.handle(action, request, region);
default -> null;
};
} catch (AwsException e) {
return Response.status(e.getHttpStatus())
.type(MediaType.APPLICATION_JSON)
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
.build();
} catch (Exception e) {
LOG.errorf("Error processing %s request", serviceName, e);
return Response.status(500)
.type(MediaType.APPLICATION_JSON)
.entity(new AwsErrorResponse("InternalServerError", e.getMessage()))
.build();
}
}
}
@@ -0,0 +1,299 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import java.util.Map;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
/**
* Generic dispatcher for all AWS services that use the application/x-amz-json-1.0 protocol.
* Routes requests to the appropriate service handler based on the X-Amz-Target header prefix.
* <p>
* Currently supported services:
* - DynamoDB (DynamoDB_20120810.*)
* - SQS (AmazonSQS.*)
*/
@Path("/")
public class AwsJsonController {
private static final Logger LOG = Logger.getLogger(AwsJsonController.class);
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
private static final String DYNAMODB_TARGET_PREFIX = "DynamoDB_20120810.";
private static final String DYNAMODB_STREAMS_TARGET_PREFIX = "DynamoDBStreams_20120810.";
private static final String SQS_TARGET_PREFIX = "AmazonSQS.";
private static final String SNS_TARGET_PREFIX = "SNS_20100331.";
private static final String STEPFUNCTIONS_TARGET_PREFIX = "AWSStepFunctions.";
private static final String CLOUDWATCH_TARGET_PREFIX = "GraniteServiceVersion20100801.";
private static final String CLOUDWATCH_SERVICE_ID = "GraniteServiceVersion20100801";
private final ObjectMapper objectMapper;
private final RegionResolver regionResolver;
private final DynamoDbJsonHandler dynamoDbJsonHandler;
private final DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler;
private final SqsJsonHandler sqsJsonHandler;
private final SnsJsonHandler snsJsonHandler;
private final StepFunctionsJsonHandler sfnJsonHandler;
private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler;
@Inject
public AwsJsonController(ObjectMapper objectMapper, RegionResolver regionResolver,
DynamoDbJsonHandler dynamoDbJsonHandler,
DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler,
SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,
StepFunctionsJsonHandler sfnJsonHandler,
CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler) {
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
this.dynamoDbJsonHandler = dynamoDbJsonHandler;
this.dynamoDbStreamsJsonHandler = dynamoDbStreamsJsonHandler;
this.sqsJsonHandler = sqsJsonHandler;
this.snsJsonHandler = snsJsonHandler;
this.sfnJsonHandler = sfnJsonHandler;
this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler;
}
@POST
@Consumes("application/x-amz-json-1.0")
@Produces(MediaType.APPLICATION_JSON)
public Response handleJsonRequest(
@HeaderParam("X-Amz-Target") String target,
@Context HttpHeaders httpHeaders,
String body) {
if (target == null) {
return null;
}
String prefix;
String action;
String serviceName;
if (target.startsWith(DYNAMODB_STREAMS_TARGET_PREFIX)) {
prefix = DYNAMODB_STREAMS_TARGET_PREFIX;
action = target.substring(prefix.length());
serviceName = "DynamoDBStreams";
} else if (target.startsWith(DYNAMODB_TARGET_PREFIX)) {
prefix = DYNAMODB_TARGET_PREFIX;
action = target.substring(prefix.length());
serviceName = "DynamoDB";
} else if (target.startsWith(SQS_TARGET_PREFIX)) {
prefix = SQS_TARGET_PREFIX;
action = target.substring(prefix.length());
serviceName = "SQS";
} else if (target.startsWith(SNS_TARGET_PREFIX)) {
prefix = SNS_TARGET_PREFIX;
action = target.substring(prefix.length());
serviceName = "SNS";
} else if (target.startsWith(STEPFUNCTIONS_TARGET_PREFIX)) {
prefix = STEPFUNCTIONS_TARGET_PREFIX;
action = target.substring(prefix.length());
serviceName = "StepFunctions";
} else if (target.startsWith(CLOUDWATCH_TARGET_PREFIX)) {
prefix = CLOUDWATCH_TARGET_PREFIX;
action = target.substring(prefix.length());
serviceName = "CloudWatch";
} else {
return Response.status(400)
.entity(new AwsErrorResponse("UnknownOperationException",
"Unknown operation: " + target))
.build();
}
LOG.debugv("{0} JSON action: {1}", serviceName, action);
try {
JsonNode request = objectMapper.readTree(body);
String region = regionResolver.resolveRegion(httpHeaders);
return switch (serviceName) {
case "DynamoDB" -> dynamoDbJsonHandler.handle(action, request, region);
case "DynamoDBStreams" -> dynamoDbStreamsJsonHandler.handle(action, request, region);
case "SQS" -> sqsJsonHandler.handle(action, request, region);
case "SNS" -> snsJsonHandler.handle(action, request, region);
case "StepFunctions" -> sfnJsonHandler.handle(action, request, region);
case "CloudWatch" -> cloudWatchMetricsJsonHandler.handle(action, request, region);
default -> null;
};
} catch (AwsException e) {
return Response.status(e.getHttpStatus())
.type(MediaType.APPLICATION_JSON)
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
.build();
} catch (Exception e) {
LOG.error("Error processing " + serviceName + " JSON request", e);
return Response.status(500)
.type(MediaType.APPLICATION_JSON)
.entity(new AwsErrorResponse("InternalServerError", e.getMessage()))
.build();
}
}
/**
* Serializes a JsonNode to CBOR bytes, encoding fields named "Timestamp" with CBOR tag 1
* as required by the smithy-rpc-v2-cbor protocol specification.
*/
private static byte[] nodeToSmithyCbor(JsonNode node) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
CBORFactory factory = (CBORFactory) CBOR_MAPPER.getFactory();
try (CBORGenerator gen = factory.createGenerator(out)) {
writeNodeToCbor(gen, node, null);
}
return out.toByteArray();
}
private static void writeNodeToCbor(CBORGenerator gen, JsonNode node, String fieldName) throws Exception {
if (node.isObject()) {
gen.writeStartObject();
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
gen.writeFieldName(entry.getKey());
writeNodeToCbor(gen, entry.getValue(), entry.getKey());
}
gen.writeEndObject();
} else if (node.isArray()) {
gen.writeStartArray();
for (JsonNode item : node) {
writeNodeToCbor(gen, item, null);
}
gen.writeEndArray();
} else if ("Timestamp".equals(fieldName) && node.isNumber()) {
gen.writeTag(1);
gen.writeNumber(node.longValue());
} else if (node.isTextual()) {
gen.writeString(node.textValue());
} else if (node.isDouble() || node.isFloat()) {
gen.writeNumber(node.doubleValue());
} else if (node.isLong() || node.isInt()) {
gen.writeNumber(node.longValue());
} else if (node.isBoolean()) {
gen.writeBoolean(node.booleanValue());
} else if (node.isNull()) {
gen.writeNull();
} else {
gen.writeString(node.asText());
}
}
/**
* Handles AWS smithy-rpc-v2-cbor protocol requests.
* Go SDK CloudWatch v1.55.1+ sends to POST /service/{serviceId}/operation/{op}
* with Content-Type: application/cbor and no X-Amz-Target header.
*/
@POST
@Path("service/{serviceId}/operation/{operation}")
@Consumes("application/cbor")
@Produces("application/cbor")
public Response handleSmithyRpcV2Cbor(
@PathParam("serviceId") String serviceId,
@PathParam("operation") String operation,
@Context HttpHeaders httpHeaders,
byte[] body) {
if (!CLOUDWATCH_SERVICE_ID.equals(serviceId)) {
return Response.status(404).build();
}
LOG.debugv("CloudWatch RPC v2 CBOR action: {0}", operation);
try {
JsonNode request = (body != null && body.length > 0)
? CBOR_MAPPER.readTree(body)
: objectMapper.createObjectNode();
String region = regionResolver.resolveRegion(httpHeaders);
Response delegated = cloudWatchMetricsJsonHandler.handle(operation, request, region);
byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());
return Response.status(delegated.getStatus())
.header("Smithy-Protocol", "rpc-v2-cbor")
.type("application/cbor")
.entity(cborBytes)
.build();
} catch (AwsException e) {
try {
byte[] errBytes = CBOR_MAPPER.writeValueAsBytes(
new AwsErrorResponse(e.getErrorCode(), e.getMessage()));
return Response.status(e.getHttpStatus())
.header("Smithy-Protocol", "rpc-v2-cbor")
.type("application/cbor")
.entity(errBytes)
.build();
} catch (Exception ex) {
return Response.status(e.getHttpStatus()).build();
}
} catch (Exception e) {
LOG.error("Error processing CloudWatch CBOR request", e);
return Response.status(500).build();
}
}
/**
* Handles AWS services that migrated to the smithy-rpc-v2-cbor protocol at root path.
* Fallback handler for X-Amz-Target based routing with CBOR body.
*/
@POST
@Consumes("application/cbor")
@Produces("application/cbor")
public Response handleCborRequest(
@HeaderParam("X-Amz-Target") String target,
@Context HttpHeaders httpHeaders,
byte[] body) {
if (target == null || !target.startsWith(CLOUDWATCH_TARGET_PREFIX)) {
return null;
}
String action = target.substring(CLOUDWATCH_TARGET_PREFIX.length());
LOG.debugv("CloudWatch CBOR action: {0}", action);
try {
JsonNode request = (body != null && body.length > 0)
? CBOR_MAPPER.readTree(body)
: objectMapper.createObjectNode();
String region = regionResolver.resolveRegion(httpHeaders);
Response delegated = cloudWatchMetricsJsonHandler.handle(action, request, region);
byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());
return Response.status(delegated.getStatus())
.header("smithy-protocol", "rpc-v2-cbor")
.type("application/cbor")
.entity(cborBytes)
.build();
} catch (AwsException e) {
try {
byte[] errBytes = CBOR_MAPPER.writeValueAsBytes(
new AwsErrorResponse(e.getErrorCode(), e.getMessage()));
return Response.status(e.getHttpStatus())
.header("smithy-protocol", "rpc-v2-cbor")
.type("application/cbor")
.entity(errBytes)
.build();
} catch (Exception ex) {
return Response.status(e.getHttpStatus()).build();
}
} catch (Exception e) {
LOG.error("Error processing CloudWatch CBOR request", e);
return Response.status(500).build();
}
}
}
@@ -0,0 +1,19 @@
package io.github.hectorvent.floci.core.common;
/**
* Canonical XML namespace URIs for every AWS service that uses the Query (XML) protocol.
* Use these constants instead of inline string literals in handlers.
*/
public final class AwsNamespaces {
public static final String SQS = "https://sqs.amazonaws.com/doc/2012-11-05/";
public static final String SNS = "http://sns.amazonaws.com/doc/2010-03-31/";
public static final String IAM = "https://iam.amazonaws.com/doc/2010-05-08/";
public static final String STS = "https://sts.amazonaws.com/doc/2011-06-15/";
public static final String RDS = "http://rds.amazonaws.com/doc/2014-10-31/";
public static final String EC = "http://elasticache.amazonaws.com/doc/2015-02-02/";
public static final String CW = "http://monitoring.amazonaws.com/doc/2010-08-01/";
public static final String S3 = "http://s3.amazonaws.com/doc/2006-03-01/";
private AwsNamespaces() {}
}
@@ -0,0 +1,249 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsQueryHandler;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheQueryHandler;
import io.github.hectorvent.floci.services.iam.IamQueryHandler;
import io.github.hectorvent.floci.services.iam.StsQueryHandler;
import io.github.hectorvent.floci.services.rds.RdsQueryHandler;
import io.github.hectorvent.floci.services.sns.SnsQueryHandler;
import io.github.hectorvent.floci.services.sqs.SqsQueryHandler;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Generic dispatcher for all AWS services that use the Query Protocol (form-encoded POST, XML response).
* Routes requests to the appropriate service handler based on the service name extracted from the
* Authorization header's credential scope, falling back to action-name matching when no auth header
* is present.
*
* <p>Currently supported services:
* <ul>
* <li>SQS — form-encoded query protocol</li>
* <li>SNS — form-encoded query protocol</li>
* <li>IAM — form-encoded query protocol (global service)</li>
* <li>STS — form-encoded query protocol (global service)</li>
* </ul>
*
* @see AwsJsonController
*/
@Path("/")
public class AwsQueryController {
private static final Logger LOG = Logger.getLogger(AwsQueryController.class);
// Extracts service name: Credential=AKID/20260227/us-east-1/iam/aws4_request → "iam"
private static final Pattern SERVICE_PATTERN =
Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
private static final Set<String> STS_ACTIONS = Set.of(
"AssumeRole", "AssumeRoleWithWebIdentity", "AssumeRoleWithSAML",
"GetCallerIdentity", "GetSessionToken", "GetFederationToken",
"DecodeAuthorizationMessage"
);
private static final Set<String> SNS_ACTIONS = Set.of(
"CreateTopic", "DeleteTopic", "ListTopics", "GetTopicAttributes", "SetTopicAttributes",
"Subscribe", "Unsubscribe", "ListSubscriptions", "ListSubscriptionsByTopic",
"Publish", "PublishBatch", "TagResource", "UntagResource", "ListTagsForResource",
"CreatePlatformApplication", "DeletePlatformApplication", "GetPlatformApplicationAttributes",
"SetPlatformApplicationAttributes", "ListPlatformApplications",
"CreatePlatformEndpoint", "DeleteEndpoint", "GetEndpointAttributes",
"SetEndpointAttributes", "ListEndpointsByPlatformApplication",
"CheckIfPhoneNumberIsOptedOut", "ListPhoneNumbersOptedOut",
"OptInPhoneNumber", "SetSMSAttributes", "GetSMSAttributes",
"GetSubscriptionAttributes", "SetSubscriptionAttributes", "ConfirmSubscription",
"CreateSMSSandboxPhoneNumber", "DeleteSMSSandboxPhoneNumber",
"GetSMSSandboxAccountStatus", "ListSMSSandboxPhoneNumbers",
"VerifySMSSandboxPhoneNumber", "AddPermission", "RemovePermission"
);
private static final Set<String> IAM_ACTIONS = Set.of(
"CreateUser", "GetUser", "DeleteUser", "ListUsers", "UpdateUser",
"CreateGroup", "GetGroup", "DeleteGroup", "ListGroups",
"AddUserToGroup", "RemoveUserFromGroup", "ListGroupsForUser",
"CreateRole", "GetRole", "DeleteRole", "ListRoles", "UpdateRole",
"CreatePolicy", "GetPolicy", "DeletePolicy", "ListPolicies",
"CreatePolicyVersion", "GetPolicyVersion", "DeletePolicyVersion",
"ListPolicyVersions", "SetDefaultPolicyVersion",
"AttachUserPolicy", "DetachUserPolicy", "ListAttachedUserPolicies",
"AttachGroupPolicy", "DetachGroupPolicy", "ListAttachedGroupPolicies",
"AttachRolePolicy", "DetachRolePolicy", "ListAttachedRolePolicies",
"PutUserPolicy", "GetUserPolicy", "DeleteUserPolicy", "ListUserPolicies",
"PutRolePolicy", "GetRolePolicy", "DeleteRolePolicy", "ListRolePolicies",
"PutGroupPolicy", "GetGroupPolicy", "DeleteGroupPolicy", "ListGroupPolicies",
"CreateAccessKey", "DeleteAccessKey", "ListAccessKeys", "UpdateAccessKey",
"CreateInstanceProfile", "GetInstanceProfile", "DeleteInstanceProfile",
"ListInstanceProfiles", "AddRoleToInstanceProfile",
"RemoveRoleFromInstanceProfile", "ListInstanceProfilesForRole",
"TagUser", "UntagUser", "ListUserTags",
"TagRole", "UntagRole", "ListRoleTags",
"TagPolicy", "UntagPolicy", "ListPolicyTags",
"CreateLoginProfile", "GetLoginProfile", "DeleteLoginProfile", "UpdateLoginProfile",
"GenerateCredentialReport", "GetCredentialReport",
"GetAccountSummary", "GetAccountAuthorizationDetails"
);
private final CloudFormationQueryHandler cloudFormationQueryHandler;
private final ElastiCacheQueryHandler elastiCacheQueryHandler;
private final RdsQueryHandler rdsQueryHandler;
private final SqsQueryHandler sqsQueryHandler;
private final SnsQueryHandler snsQueryHandler;
private final IamQueryHandler iamQueryHandler;
private final StsQueryHandler stsQueryHandler;
private final CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler;
private final RegionResolver regionResolver;
@Inject
public AwsQueryController(CloudFormationQueryHandler cloudFormationQueryHandler,
ElastiCacheQueryHandler elastiCacheQueryHandler,
RdsQueryHandler rdsQueryHandler,
SqsQueryHandler sqsQueryHandler, SnsQueryHandler snsQueryHandler,
IamQueryHandler iamQueryHandler, StsQueryHandler stsQueryHandler,
CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler,
RegionResolver regionResolver) {
this.cloudFormationQueryHandler = cloudFormationQueryHandler;
this.elastiCacheQueryHandler = elastiCacheQueryHandler;
this.rdsQueryHandler = rdsQueryHandler;
this.sqsQueryHandler = sqsQueryHandler;
this.snsQueryHandler = snsQueryHandler;
this.iamQueryHandler = iamQueryHandler;
this.stsQueryHandler = stsQueryHandler;
this.cloudWatchMetricsQueryHandler = cloudWatchMetricsQueryHandler;
this.regionResolver = regionResolver;
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_XML)
public Response dispatch(
@HeaderParam("Authorization") String authorization,
@Context HttpHeaders httpHeaders,
MultivaluedMap<String, String> formParams) {
String action = formParams.getFirst("Action");
if (action == null) {
return null;
}
String service = resolveService(authorization, action);
LOG.debugv("Query protocol service={0} action={1}", service, action);
String region = regionResolver.resolveRegion(httpHeaders);
return switch (service) {
case "sqs" -> sqsQueryHandler.handle(action, formParams, region);
case "sns" -> snsQueryHandler.handle(action, formParams, region);
case "iam" -> iamQueryHandler.handle(action, formParams);
case "sts" -> stsQueryHandler.handle(action, formParams);
case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams);
case "rds" -> rdsQueryHandler.handle(action, formParams);
case "monitoring" -> cloudWatchMetricsQueryHandler.handle(action, formParams, region);
case "cloudformation" -> cloudFormationQueryHandler.handle(action, formParams, region);
default -> xmlErrorResponse("UnknownService",
"Unknown or unsupported service: " + service, 400);
};
}
/**
* Determines the target AWS service. Prefers the service name embedded in the
* Authorization header credential scope. Falls back to action-name lookup when
* the header is absent (e.g. raw HTTP testing without AWS SDK auth).
*/
private static final Set<String> ELASTICACHE_ACTIONS = Set.of(
"ValidateIamAuthToken",
"CreateReplicationGroup", "DescribeReplicationGroups", "DeleteReplicationGroup",
"CreateUser", "DescribeUsers", "ModifyUser", "DeleteUser"
);
private static final Set<String> CLOUDWATCH_ACTIONS = Set.of(
"PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData"
);
private static final Set<String> RDS_ACTIONS = Set.of(
"CreateDBInstance", "DescribeDBInstances", "DeleteDBInstance",
"ModifyDBInstance", "RebootDBInstance",
"CreateDBCluster", "DescribeDBClusters", "DeleteDBCluster", "ModifyDBCluster",
"CreateDBParameterGroup", "DescribeDBParameterGroups",
"DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters"
);
private static final Set<String> CLOUDFORMATION_ACTIONS = Set.of(
"CreateStack", "DeleteStack", "UpdateStack", "DescribeStacks",
"ListStacks", "GetTemplate", "ValidateTemplate",
"CreateChangeSet", "DeleteChangeSet", "DescribeChangeSet", "ExecuteChangeSet", "ListChangeSets",
"DescribeStackEvents", "DescribeStackResources", "ListStackResources", "DescribeStackResource",
"SetStackPolicy", "GetStackPolicy", "ListStackSets", "DescribeStackSet", "CreateStackSet"
);
private static final Set<String> QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation");
private String resolveService(String authorization, String action) {
if (authorization != null && !authorization.isEmpty()) {
Matcher m = SERVICE_PATTERN.matcher(authorization);
if (m.find()) {
String svc = m.group(1).toLowerCase();
if (QUERY_PROTOCOL_SERVICES.contains(svc)) {
return svc;
}
}
}
return inferServiceFromAction(action);
}
private String inferServiceFromAction(String action) {
if (STS_ACTIONS.contains(action)) {
return "sts";
}
if (IAM_ACTIONS.contains(action)) {
return "iam";
}
if (SNS_ACTIONS.contains(action)) {
return "sns";
}
if (ELASTICACHE_ACTIONS.contains(action)) {
return "elasticache";
}
if (RDS_ACTIONS.contains(action)) {
return "rds";
}
if (CLOUDWATCH_ACTIONS.contains(action)) {
return "monitoring";
}
if (CLOUDFORMATION_ACTIONS.contains(action)) {
return "cloudformation";
}
// SQS actions are numerous and not enumerated — fall back to sqs only for
// requests that arrived without an Authorization header (raw/test clients)
return "sqs";
}
private Response xmlErrorResponse(String code, String message, int status) {
String xml = new XmlBuilder()
.start("ErrorResponse")
.start("Error")
.elem("Type", "Sender")
.elem("Code", code)
.elem("Message", message)
.end("Error")
.elem("RequestId", UUID.randomUUID().toString())
.end("ErrorResponse")
.build();
return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build();
}
}
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.core.common;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.UUID;
/**
* Shared helpers for building AWS Query-protocol (form-encoded POST → XML) responses.
*
* <p>Every Query-protocol service handler should call these methods instead of
* hand-rolling its own {@code ResponseMetadata}, envelope, or error skeleton.
*
* <h2>Usage</h2>
* <pre>{@code
* // Simple envelope
* return Response.ok(AwsQueryResponse.envelope("CreateQueue", null, resultXml)).build();
*
* // Namespaced envelope (e.g. SNS)
* return Response.ok(AwsQueryResponse.envelope("CreateTopic", AwsNamespaces.SNS, resultXml)).build();
*
* // Error
* return AwsQueryResponse.error("InvalidParameterValue", "Queue name too long", null, 400);
* }</pre>
*/
public final class AwsQueryResponse {
private AwsQueryResponse() {}
/**
* Produces a {@code <ResponseMetadata>} block with a random request ID:
* <pre>{@code
* <ResponseMetadata><RequestId>UUID</RequestId></ResponseMetadata>
* }</pre>
*/
public static String responseMetadata() {
return new XmlBuilder()
.start("ResponseMetadata")
.elem("RequestId", UUID.randomUUID().toString())
.end("ResponseMetadata")
.build();
}
/**
* Wraps a result fragment in the standard Query-protocol outer envelope:
* <pre>{@code
* <{action}Response xmlns="{xmlns}">
* <{action}Result>{result}</{action}Result>
* <ResponseMetadata><RequestId>UUID</RequestId></ResponseMetadata>
* </{action}Response>
* }</pre>
*
* @param action the AWS action name (e.g. {@code "CreateQueue"})
* @param xmlns the XML namespace URI, or {@code null} for namespace-free responses (e.g. SQS)
* @param result the inner XML fragment placed inside the Result element
*/
public static String envelope(String action, String xmlns, String result) {
return new XmlBuilder()
.start(action + "Response", xmlns)
.start(action + "Result")
.raw(result)
.end(action + "Result")
.raw(responseMetadata())
.end(action + "Response")
.build();
}
/**
* Same as {@link #envelope} but for actions whose response element does not include
* a {@code Result} child (e.g. {@code DeleteQueue}, {@code DeleteTopic}).
*/
public static String envelopeNoResult(String action, String xmlns) {
return new XmlBuilder()
.start(action + "Response", xmlns)
.raw(responseMetadata())
.end(action + "Response")
.build();
}
/**
* Builds a Query-protocol XML error response and returns a JAX-RS {@link Response}.
*
* <pre>{@code
* <ErrorResponse xmlns="{xmlns}">
* <Error>
* <Type>Sender</Type>
* <Code>{code}</Code>
* <Message>{message}</Message>
* </Error>
* <RequestId>UUID</RequestId>
* </ErrorResponse>
* }</pre>
*
* @param xmlns the namespace URI, or {@code null} for namespace-free error responses (e.g. SQS)
*/
public static Response error(String code, String message, String xmlns, int status) {
String xml = new XmlBuilder()
.start("ErrorResponse", xmlns)
.start("Error")
.elem("Type", "Sender")
.elem("Code", code)
.elem("Message", message)
.end("Error")
.raw(responseMetadata())
.end("ErrorResponse")
.build();
return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build();
}
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.HttpHeaders;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApplicationScoped
public class RegionResolver {
// Matches: Credential=AKID/20260215/us-west-2/s3/aws4_request
private static final Pattern CREDENTIAL_REGION_PATTERN =
Pattern.compile("Credential=\\S+/\\d{8}/([^/]+)/");
private final String defaultRegion;
private final String defaultAccountId;
@Inject
public RegionResolver(EmulatorConfig config) {
this(config.defaultRegion(), config.defaultAccountId());
}
public RegionResolver(String defaultRegion, String defaultAccountId) {
this.defaultRegion = defaultRegion;
this.defaultAccountId = defaultAccountId;
}
public String resolveRegion(HttpHeaders headers) {
if (headers == null) {
return defaultRegion;
}
String auth = headers.getHeaderString("Authorization");
if (auth == null || auth.isEmpty()) {
return defaultRegion;
}
Matcher matcher = CREDENTIAL_REGION_PATTERN.matcher(auth);
if (matcher.find()) {
return matcher.group(1);
}
return defaultRegion;
}
public String getDefaultRegion() {
return defaultRegion;
}
public String getAccountId() {
return defaultAccountId;
}
public String buildArn(String service, String region, String resource) {
return "arn:aws:" + service + ":" + region + ":" + defaultAccountId + ":" + resource;
}
}
@@ -0,0 +1,102 @@
package io.github.hectorvent.floci.core.common;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Provider
public class ServiceEnabledFilter implements ContainerRequestFilter {
private static final Pattern AUTH_SERVICE_PATTERN =
Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
private final ServiceRegistry serviceRegistry;
@Inject
public ServiceEnabledFilter(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
@Override
public void filter(ContainerRequestContext ctx) {
String serviceKey = resolveServiceKey(ctx);
if (serviceKey == null) {
return;
}
if (!serviceRegistry.isServiceEnabled(serviceKey)) {
ctx.abortWith(disabledResponse(ctx, serviceKey));
}
}
private String resolveServiceKey(ContainerRequestContext ctx) {
String target = ctx.getHeaderString("X-Amz-Target");
if (target != null) {
return serviceKeyFromTarget(target);
}
String auth = ctx.getHeaderString("Authorization");
if (auth != null) {
Matcher m = AUTH_SERVICE_PATTERN.matcher(auth);
if (m.find()) {
return mapCredentialScope(m.group(1).toLowerCase());
}
}
return null;
}
private String serviceKeyFromTarget(String target) {
if (target.startsWith("AmazonSSM.")) return "ssm";
if (target.startsWith("AWSEvents.")) return "events";
if (target.startsWith("Logs_20140328.")) return "logs";
if (target.startsWith("secretsmanager.")) return "secretsmanager";
if (target.startsWith("Kinesis_20131202.")) return "kinesis";
if (target.startsWith("AmazonApiGatewayV2.")) return "apigatewayv2";
if (target.startsWith("TrentService.")) return "kms";
if (target.startsWith("AWSCognitoIdentityProviderService.")) return "cognito-idp";
if (target.startsWith("DynamoDB_20120810.") || target.startsWith("DynamoDBStreams_20120810.")) return "dynamodb";
if (target.startsWith("AmazonSQS.")) return "sqs";
if (target.startsWith("SNS_20100331.")) return "sns";
if (target.startsWith("AWSStepFunctions.")) return "states";
if (target.startsWith("GraniteServiceVersion20100801.")) return "monitoring";
return null;
}
private String mapCredentialScope(String scope) {
return switch (scope) {
case "execute-api" -> "apigateway";
default -> scope;
};
}
private Response disabledResponse(ContainerRequestContext ctx, String serviceKey) {
String message = "Service " + serviceKey + " is not enabled.";
String target = ctx.getHeaderString("X-Amz-Target");
String contentType = ctx.getMediaType() != null ? ctx.getMediaType().toString() : "";
if (target != null || contentType.contains("json")) {
return Response.status(400)
.type(MediaType.APPLICATION_JSON)
.entity(new AwsErrorResponse("ServiceNotAvailableException", message))
.build();
}
String xml = new XmlBuilder()
.start("ErrorResponse")
.start("Error")
.elem("Type", "Sender")
.elem("Code", "ServiceNotAvailableException")
.elem("Message", message)
.end("Error")
.elem("RequestId", java.util.UUID.randomUUID().toString())
.end("ErrorResponse")
.build();
return Response.status(400).entity(xml).type(MediaType.APPLICATION_XML).build();
}
}
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* Registry of enabled AWS services based on configuration.
*/
@ApplicationScoped
public class ServiceRegistry {
private static final Logger LOG = Logger.getLogger(ServiceRegistry.class);
private final EmulatorConfig config;
@Inject
public ServiceRegistry(EmulatorConfig config) {
this.config = config;
}
public boolean isServiceEnabled(String serviceName) {
return switch (serviceName) {
case "ssm" -> config.services().ssm().enabled();
case "sqs" -> config.services().sqs().enabled();
case "s3" -> config.services().s3().enabled();
case "dynamodb" -> config.services().dynamodb().enabled();
case "sns" -> config.services().sns().enabled();
case "lambda" -> config.services().lambda().enabled();
case "apigateway" -> config.services().apigateway().enabled();
case "iam", "sts" -> config.services().iam().enabled();
case "elasticache" -> config.services().elasticache().enabled();
case "rds" -> config.services().rds().enabled();
case "events" -> config.services().eventbridge().enabled();
case "logs" -> config.services().cloudwatchlogs().enabled();
case "monitoring" -> config.services().cloudwatchmetrics().enabled();
case "secretsmanager" -> config.services().secretsmanager().enabled();
case "apigatewayv2" -> config.services().apigatewayv2().enabled();
case "kinesis" -> config.services().kinesis().enabled();
case "kms" -> config.services().kms().enabled();
case "cognito-idp" -> config.services().cognito().enabled();
case "states" -> config.services().stepfunctions().enabled();
case "cloudformation" -> config.services().cloudformation().enabled();
default -> true;
};
}
public List<String> getEnabledServices() {
List<String> enabled = new ArrayList<>();
if (config.services().ssm().enabled()) enabled.add("ssm");
if (config.services().sqs().enabled()) enabled.add("sqs");
if (config.services().s3().enabled()) enabled.add("s3");
if (config.services().dynamodb().enabled()) enabled.add("dynamodb");
if (config.services().sns().enabled()) enabled.add("sns");
if (config.services().lambda().enabled()) enabled.add("lambda");
if (config.services().apigateway().enabled()) enabled.add("apigateway");
if (config.services().iam().enabled()) enabled.add("iam");
if (config.services().elasticache().enabled()) enabled.add("elasticache");
if (config.services().rds().enabled()) enabled.add("rds");
if (config.services().eventbridge().enabled()) enabled.add("events");
if (config.services().cloudwatchlogs().enabled()) enabled.add("logs");
if (config.services().cloudwatchmetrics().enabled()) enabled.add("monitoring");
if (config.services().secretsmanager().enabled()) enabled.add("secretsmanager");
if (config.services().apigatewayv2().enabled()) enabled.add("apigatewayv2");
if (config.services().kinesis().enabled()) enabled.add("kinesis");
if (config.services().kms().enabled()) enabled.add("kms");
if (config.services().cognito().enabled()) enabled.add("cognito-idp");
if (config.services().stepfunctions().enabled()) enabled.add("states");
if (config.services().cloudformation().enabled()) enabled.add("cloudformation");
return enabled;
}
public void logEnabledServices() {
LOG.infov("Enabled services: {0}", getEnabledServices());
}
}
@@ -0,0 +1,117 @@
package io.github.hectorvent.floci.core.common;
/**
* Fluent, allocation-efficient XML builder backed by a plain {@link StringBuilder}.
*
* <p>All content written via {@link #elem} and {@link #start} is automatically escaped.
* Pre-built XML fragments can be injected without re-escaping via {@link #raw}.
*
* <pre>{@code
* String xml = new XmlBuilder()
* .start("CreateQueueResponse")
* .start("CreateQueueResult")
* .elem("QueueUrl", queue.getQueueUrl())
* .end("CreateQueueResult")
* .raw(AwsQueryResponse.responseMetadata())
* .end("CreateQueueResponse")
* .build();
* }</pre>
*/
public final class XmlBuilder {
private final StringBuilder sb = new StringBuilder();
/** Opens {@code <element xmlns="xmlns">}. Omits the xmlns attribute when {@code xmlns} is null. */
public XmlBuilder start(String element, String xmlns) {
sb.append('<').append(element);
if (xmlns != null) {
sb.append(" xmlns=\"").append(xmlns).append('"');
}
sb.append('>');
return this;
}
/** Opens {@code <element>} without a namespace. */
public XmlBuilder start(String element) {
return start(element, null);
}
/** Appends {@code </element>}. */
public XmlBuilder end(String element) {
sb.append("</").append(element).append('>');
return this;
}
/**
* Appends {@code <name>escapedValue</name>}.
* Skips the element entirely when {@code value} is {@code null}.
*/
public XmlBuilder elem(String name, String value) {
if (value == null) {
return this;
}
sb.append('<').append(name).append('>')
.append(escape(value))
.append("</").append(name).append('>');
return this;
}
/** Convenience overload — converts {@code long} to string. */
public XmlBuilder elem(String name, long value) {
return elem(name, String.valueOf(value));
}
/** Convenience overload — converts {@code boolean} to string. */
public XmlBuilder elem(String name, boolean value) {
return elem(name, String.valueOf(value));
}
/**
* Appends a pre-built XML fragment verbatim, without escaping.
* The caller is responsible for correctness of the fragment.
*/
public XmlBuilder raw(String fragment) {
if (fragment != null) {
sb.append(fragment);
}
return this;
}
/** Returns the accumulated XML string. */
public String build() {
return sb.toString();
}
/**
* Escapes the five XML special characters: {@code & < > " '}.
* Returns an empty string for null or empty input.
*/
public static String escape(String s) {
if (s == null || s.isEmpty()) {
return "";
}
StringBuilder out = null;
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
String replacement = switch (c) {
case '&' -> "&amp;";
case '<' -> "&lt;";
case '>' -> "&gt;";
case '"' -> "&quot;";
case '\'' -> "&apos;";
default -> null;
};
if (replacement != null) {
if (out == null) {
out = new StringBuilder(len + 8);
out.append(s, 0, i);
}
out.append(replacement);
} else if (out != null) {
out.append(c);
}
}
return out != null ? out.toString() : s;
}
}
@@ -0,0 +1,223 @@
package io.github.hectorvent.floci.core.common;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Lightweight StAX-based helpers for parsing XML request bodies.
*
* <p>Uses {@code javax.xml.stream} (part of the JDK — no extra dependency).
* Namespace prefixes are ignored so that both plain {@code <Key>} and
* namespace-qualified {@code <s3:Key>} elements match by local name.
* Handles whitespace variations and CDATA sections correctly.
*
* <p>All methods silently return empty collections on malformed input so that
* callers receive the same result they would have from a non-matching regex.
*/
public final class XmlParser {
private static final XMLInputFactory FACTORY;
static {
FACTORY = XMLInputFactory.newInstance();
FACTORY.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
FACTORY.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
FACTORY.setProperty(XMLInputFactory.SUPPORT_DTD, false);
}
private XmlParser() {}
/**
* Extracts the text content of every element whose local name matches {@code elementName}.
*
* <pre>{@code
* List<String> keys = XmlParser.extractAll(body, "Key");
* }</pre>
*/
public static List<String> extractAll(String xml, String elementName) {
List<String> result = new ArrayList<>();
if (xml == null || xml.isEmpty()) {
return result;
}
try {
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT
&& elementName.equals(r.getLocalName())) {
result.add(r.getElementText());
}
}
r.close();
} catch (XMLStreamException ignored) {}
return result;
}
/**
* Extracts the text content of the first element matching {@code elementName},
* or {@code defaultValue} if no such element exists.
*
* <pre>{@code
* String mode = XmlParser.extractFirst(body, "Mode", null);
* }</pre>
*/
public static String extractFirst(String xml, String elementName, String defaultValue) {
List<String> all = extractAll(xml, elementName);
return all.isEmpty() ? defaultValue : all.get(0);
}
/**
* Returns {@code true} if the document contains at least one element with the given
* local name whose text is equal to {@code value} (case-sensitive).
*
* <pre>{@code
* boolean quiet = XmlParser.containsValue(body, "Quiet", "true");
* }</pre>
*/
public static boolean containsValue(String xml, String elementName, String value) {
return extractAll(xml, elementName).stream().anyMatch(value::equals);
}
/**
* Extracts sibling key/value pairs from every {@code parentElement} block.
*
* <p>Example — parses {@code <Tag><Key>env</Key><Value>prod</Value></Tag>}:
* <pre>{@code
* Map<String,String> tags = XmlParser.extractPairs(body, "Tag", "Key", "Value");
* }</pre>
*
* Insertion order is preserved (backed by {@link LinkedHashMap}).
*/
public static Map<String, String> extractPairs(String xml, String parentElement,
String keyElement, String valueElement) {
Map<String, String> result = new LinkedHashMap<>();
if (xml == null || xml.isEmpty()) {
return result;
}
try {
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
String pendingKey = null;
boolean inParent = false;
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT) {
String local = r.getLocalName();
if (parentElement.equals(local)) {
inParent = true;
pendingKey = null;
} else if (inParent && keyElement.equals(local)) {
pendingKey = r.getElementText();
} else if (inParent && valueElement.equals(local) && pendingKey != null) {
result.put(pendingKey, r.getElementText());
pendingKey = null;
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (parentElement.equals(r.getLocalName())) {
inParent = false;
}
}
}
r.close();
} catch (XMLStreamException ignored) {}
return result;
}
/**
* Extracts every group of elements nested inside a repeating {@code parentElement},
* returning each group as a {@code Map<localName, List<text>>}.
*
* <p>Allows for repeated child elements with the same name (e.g. multiple {@code <Event>}
* tags inside a single {@code <QueueConfiguration>}).
*/
public static List<Map<String, List<String>>> extractGroupsMulti(String xml, String parentElement) {
List<Map<String, List<String>>> result = new ArrayList<>();
if (xml == null || xml.isEmpty()) {
return result;
}
try {
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
Map<String, List<String>> current = null;
int depth = 0;
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT) {
String local = r.getLocalName();
if (parentElement.equals(local)) {
current = new LinkedHashMap<>();
depth = 1;
} else if (current != null && depth == 1) {
String text = r.getElementText();
current.computeIfAbsent(local, k -> new ArrayList<>()).add(text);
} else if (current != null) {
depth++;
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (current != null && parentElement.equals(r.getLocalName())) {
result.add(current);
current = null;
depth = 0;
} else if (current != null) {
depth--;
}
}
}
r.close();
} catch (XMLStreamException ignored) {}
return result;
}
/**
* Extracts every group of elements nested inside a repeating {@code parentElement},
* returning each group as a {@code Map<localName, text>}.
*
* <p>Useful for notification-configuration blocks that contain multiple fields:
* <pre>{@code
* List<Map<String,String>> configs =
* XmlParser.extractGroups(body, "QueueConfiguration");
* // configs.get(0).get("QueueArn") → "arn:aws:sqs:..."
* }</pre>
*/
public static List<Map<String, String>> extractGroups(String xml, String parentElement) {
List<Map<String, String>> result = new ArrayList<>();
if (xml == null || xml.isEmpty()) {
return result;
}
try {
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
Map<String, String> current = null;
int depth = 0;
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT) {
String local = r.getLocalName();
if (parentElement.equals(local)) {
current = new LinkedHashMap<>();
depth = 1;
} else if (current != null && depth == 1) {
String text = r.getElementText();
current.put(local, text);
} else if (current != null) {
depth++;
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
if (current != null && parentElement.equals(r.getLocalName())) {
result.add(current);
current = null;
depth = 0;
} else if (current != null) {
depth--;
}
}
}
r.close();
} catch (XMLStreamException ignored) {}
return result;
}
}
@@ -0,0 +1,49 @@
package io.github.hectorvent.floci.core.common.docker;
import io.github.hectorvent.floci.config.EmulatorConfig;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Duration;
/**
* CDI producer for the DockerClient singleton bean.
*/
@ApplicationScoped
public class DockerClientProducer {
private static final Logger LOG = Logger.getLogger(DockerClientProducer.class);
private final EmulatorConfig config;
@Inject
public DockerClientProducer(EmulatorConfig config) {
this.config = config;
}
@Produces
@ApplicationScoped
public DockerClient dockerClient() {
String dockerHost = config.services().lambda().dockerHost();
LOG.infov("Creating DockerClient for host: {0}", dockerHost);
DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost(dockerHost)
.build();
ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
.dockerHost(clientConfig.getDockerHost())
.maxConnections(100)
.connectionTimeout(Duration.ofSeconds(30))
.responseTimeout(Duration.ofMinutes(5))
.build();
return DockerClientImpl.getInstance(clientConfig, httpClient);
}
}
@@ -0,0 +1,683 @@
package io.github.hectorvent.floci.core.common.docker;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* Registers all docker-java classes for GraalVM native image reflection.
* Jackson needs reflective access to model classes when deserializing Docker API responses.
*/
@RegisterForReflection(classNames = {
"com.github.dockerjava.api.DockerClient",
"com.github.dockerjava.api.DockerClientDelegate",
"com.github.dockerjava.api.async.ResultCallback",
"com.github.dockerjava.api.async.ResultCallback$Adapter",
"com.github.dockerjava.api.async.ResultCallbackTemplate",
"com.github.dockerjava.api.command.AsyncDockerCmd",
"com.github.dockerjava.api.command.AttachContainerCmd",
"com.github.dockerjava.api.command.AttachContainerCmd$Exec",
"com.github.dockerjava.api.command.AuthCmd",
"com.github.dockerjava.api.command.AuthCmd$Exec",
"com.github.dockerjava.api.command.BuildImageCmd",
"com.github.dockerjava.api.command.BuildImageCmd$Exec",
"com.github.dockerjava.api.command.BuildImageResultCallback",
"com.github.dockerjava.api.command.CommitCmd",
"com.github.dockerjava.api.command.CommitCmd$Exec",
"com.github.dockerjava.api.command.ConnectToNetworkCmd",
"com.github.dockerjava.api.command.ConnectToNetworkCmd$Exec",
"com.github.dockerjava.api.command.ContainerDiffCmd",
"com.github.dockerjava.api.command.ContainerDiffCmd$Exec",
"com.github.dockerjava.api.command.CopyArchiveFromContainerCmd",
"com.github.dockerjava.api.command.CopyArchiveFromContainerCmd$Exec",
"com.github.dockerjava.api.command.CopyArchiveToContainerCmd",
"com.github.dockerjava.api.command.CopyArchiveToContainerCmd$Exec",
"com.github.dockerjava.api.command.CopyFileFromContainerCmd",
"com.github.dockerjava.api.command.CopyFileFromContainerCmd$Exec",
"com.github.dockerjava.api.command.CreateConfigCmd",
"com.github.dockerjava.api.command.CreateConfigCmd$Exec",
"com.github.dockerjava.api.command.CreateConfigResponse",
"com.github.dockerjava.api.command.CreateContainerCmd",
"com.github.dockerjava.api.command.CreateContainerCmd$Exec",
"com.github.dockerjava.api.command.CreateContainerResponse",
"com.github.dockerjava.api.command.CreateImageCmd",
"com.github.dockerjava.api.command.CreateImageCmd$Exec",
"com.github.dockerjava.api.command.CreateImageResponse",
"com.github.dockerjava.api.command.CreateNetworkCmd",
"com.github.dockerjava.api.command.CreateNetworkCmd$Exec",
"com.github.dockerjava.api.command.CreateNetworkResponse",
"com.github.dockerjava.api.command.CreateSecretCmd",
"com.github.dockerjava.api.command.CreateSecretCmd$Exec",
"com.github.dockerjava.api.command.CreateSecretResponse",
"com.github.dockerjava.api.command.CreateServiceCmd",
"com.github.dockerjava.api.command.CreateServiceCmd$Exec",
"com.github.dockerjava.api.command.CreateServiceResponse",
"com.github.dockerjava.api.command.CreateVolumeCmd",
"com.github.dockerjava.api.command.CreateVolumeCmd$Exec",
"com.github.dockerjava.api.command.CreateVolumeResponse",
"com.github.dockerjava.api.command.DelegatingDockerCmdExecFactory",
"com.github.dockerjava.api.command.DisconnectFromNetworkCmd",
"com.github.dockerjava.api.command.DisconnectFromNetworkCmd$Exec",
"com.github.dockerjava.api.command.DockerCmd",
"com.github.dockerjava.api.command.DockerCmdAsyncExec",
"com.github.dockerjava.api.command.DockerCmdExecFactory",
"com.github.dockerjava.api.command.DockerCmdSyncExec",
"com.github.dockerjava.api.command.EventsCmd",
"com.github.dockerjava.api.command.EventsCmd$Exec",
"com.github.dockerjava.api.command.ExecCreateCmd",
"com.github.dockerjava.api.command.ExecCreateCmd$Exec",
"com.github.dockerjava.api.command.ExecCreateCmdResponse",
"com.github.dockerjava.api.command.ExecStartCmd",
"com.github.dockerjava.api.command.ExecStartCmd$Exec",
"com.github.dockerjava.api.command.GraphData",
"com.github.dockerjava.api.command.GraphDriver",
"com.github.dockerjava.api.command.HealthState",
"com.github.dockerjava.api.command.HealthStateLog",
"com.github.dockerjava.api.command.InfoCmd",
"com.github.dockerjava.api.command.InfoCmd$Exec",
"com.github.dockerjava.api.command.InitializeSwarmCmd",
"com.github.dockerjava.api.command.InitializeSwarmCmd$Exec",
"com.github.dockerjava.api.command.InspectConfigCmd",
"com.github.dockerjava.api.command.InspectConfigCmd$Exec",
"com.github.dockerjava.api.command.InspectContainerCmd",
"com.github.dockerjava.api.command.InspectContainerCmd$Exec",
"com.github.dockerjava.api.command.InspectContainerResponse",
"com.github.dockerjava.api.command.InspectContainerResponse$ContainerState",
"com.github.dockerjava.api.command.InspectContainerResponse$Mount",
"com.github.dockerjava.api.command.InspectContainerResponse$Node",
"com.github.dockerjava.api.command.InspectExecCmd",
"com.github.dockerjava.api.command.InspectExecCmd$Exec",
"com.github.dockerjava.api.command.InspectExecResponse",
"com.github.dockerjava.api.command.InspectExecResponse$Container",
"com.github.dockerjava.api.command.InspectExecResponse$ProcessConfig",
"com.github.dockerjava.api.command.InspectImageCmd",
"com.github.dockerjava.api.command.InspectImageCmd$Exec",
"com.github.dockerjava.api.command.InspectImageResponse",
"com.github.dockerjava.api.command.InspectNetworkCmd",
"com.github.dockerjava.api.command.InspectNetworkCmd$Exec",
"com.github.dockerjava.api.command.InspectServiceCmd",
"com.github.dockerjava.api.command.InspectServiceCmd$Exec",
"com.github.dockerjava.api.command.InspectSwarmCmd",
"com.github.dockerjava.api.command.InspectSwarmCmd$Exec",
"com.github.dockerjava.api.command.InspectSwarmNodeCmd",
"com.github.dockerjava.api.command.InspectSwarmNodeCmd$Exec",
"com.github.dockerjava.api.command.InspectTaskCmd",
"com.github.dockerjava.api.command.InspectTaskCmd$Exec",
"com.github.dockerjava.api.command.InspectVolumeCmd",
"com.github.dockerjava.api.command.InspectVolumeCmd$Exec",
"com.github.dockerjava.api.command.InspectVolumeResponse",
"com.github.dockerjava.api.command.JoinSwarmCmd",
"com.github.dockerjava.api.command.JoinSwarmCmd$Exec",
"com.github.dockerjava.api.command.KillContainerCmd",
"com.github.dockerjava.api.command.KillContainerCmd$Exec",
"com.github.dockerjava.api.command.LeaveSwarmCmd",
"com.github.dockerjava.api.command.LeaveSwarmCmd$Exec",
"com.github.dockerjava.api.command.ListConfigsCmd",
"com.github.dockerjava.api.command.ListConfigsCmd$Exec",
"com.github.dockerjava.api.command.ListContainersCmd",
"com.github.dockerjava.api.command.ListContainersCmd$Exec",
"com.github.dockerjava.api.command.ListImagesCmd",
"com.github.dockerjava.api.command.ListImagesCmd$Exec",
"com.github.dockerjava.api.command.ListNetworksCmd",
"com.github.dockerjava.api.command.ListNetworksCmd$Exec",
"com.github.dockerjava.api.command.ListSecretsCmd",
"com.github.dockerjava.api.command.ListSecretsCmd$Exec",
"com.github.dockerjava.api.command.ListServicesCmd",
"com.github.dockerjava.api.command.ListServicesCmd$Exec",
"com.github.dockerjava.api.command.ListSwarmNodesCmd",
"com.github.dockerjava.api.command.ListSwarmNodesCmd$Exec",
"com.github.dockerjava.api.command.ListTasksCmd",
"com.github.dockerjava.api.command.ListTasksCmd$Exec",
"com.github.dockerjava.api.command.ListVolumesCmd",
"com.github.dockerjava.api.command.ListVolumesCmd$Exec",
"com.github.dockerjava.api.command.ListVolumesResponse",
"com.github.dockerjava.api.command.LoadImageAsyncCmd",
"com.github.dockerjava.api.command.LoadImageAsyncCmd$Exec",
"com.github.dockerjava.api.command.LoadImageCallback",
"com.github.dockerjava.api.command.LoadImageCmd",
"com.github.dockerjava.api.command.LoadImageCmd$Exec",
"com.github.dockerjava.api.command.LogContainerCmd",
"com.github.dockerjava.api.command.LogContainerCmd$Exec",
"com.github.dockerjava.api.command.LogSwarmObjectCmd",
"com.github.dockerjava.api.command.LogSwarmObjectCmd$Exec",
"com.github.dockerjava.api.command.PauseContainerCmd",
"com.github.dockerjava.api.command.PauseContainerCmd$Exec",
"com.github.dockerjava.api.command.PingCmd",
"com.github.dockerjava.api.command.PingCmd$Exec",
"com.github.dockerjava.api.command.PruneCmd",
"com.github.dockerjava.api.command.PruneCmd$Exec",
"com.github.dockerjava.api.command.PullImageCmd",
"com.github.dockerjava.api.command.PullImageCmd$Exec",
"com.github.dockerjava.api.command.PullImageResultCallback",
"com.github.dockerjava.api.command.PushImageCmd",
"com.github.dockerjava.api.command.PushImageCmd$1",
"com.github.dockerjava.api.command.PushImageCmd$Exec",
"com.github.dockerjava.api.command.RemoveConfigCmd",
"com.github.dockerjava.api.command.RemoveConfigCmd$Exec",
"com.github.dockerjava.api.command.RemoveContainerCmd",
"com.github.dockerjava.api.command.RemoveContainerCmd$Exec",
"com.github.dockerjava.api.command.RemoveImageCmd",
"com.github.dockerjava.api.command.RemoveImageCmd$Exec",
"com.github.dockerjava.api.command.RemoveNetworkCmd",
"com.github.dockerjava.api.command.RemoveNetworkCmd$Exec",
"com.github.dockerjava.api.command.RemoveSecretCmd",
"com.github.dockerjava.api.command.RemoveSecretCmd$Exec",
"com.github.dockerjava.api.command.RemoveServiceCmd",
"com.github.dockerjava.api.command.RemoveServiceCmd$Exec",
"com.github.dockerjava.api.command.RemoveSwarmNodeCmd",
"com.github.dockerjava.api.command.RemoveSwarmNodeCmd$Exec",
"com.github.dockerjava.api.command.RemoveVolumeCmd",
"com.github.dockerjava.api.command.RemoveVolumeCmd$Exec",
"com.github.dockerjava.api.command.RenameContainerCmd",
"com.github.dockerjava.api.command.RenameContainerCmd$Exec",
"com.github.dockerjava.api.command.ResizeContainerCmd",
"com.github.dockerjava.api.command.ResizeContainerCmd$Exec",
"com.github.dockerjava.api.command.ResizeExecCmd",
"com.github.dockerjava.api.command.ResizeExecCmd$Exec",
"com.github.dockerjava.api.command.RestartContainerCmd",
"com.github.dockerjava.api.command.RestartContainerCmd$Exec",
"com.github.dockerjava.api.command.RootFS",
"com.github.dockerjava.api.command.SaveImageCmd",
"com.github.dockerjava.api.command.SaveImageCmd$Exec",
"com.github.dockerjava.api.command.SaveImagesCmd",
"com.github.dockerjava.api.command.SaveImagesCmd$Exec",
"com.github.dockerjava.api.command.SaveImagesCmd$TaggedImage",
"com.github.dockerjava.api.command.SearchImagesCmd",
"com.github.dockerjava.api.command.SearchImagesCmd$Exec",
"com.github.dockerjava.api.command.StartContainerCmd",
"com.github.dockerjava.api.command.StartContainerCmd$Exec",
"com.github.dockerjava.api.command.StatsCmd",
"com.github.dockerjava.api.command.StatsCmd$Exec",
"com.github.dockerjava.api.command.StopContainerCmd",
"com.github.dockerjava.api.command.StopContainerCmd$Exec",
"com.github.dockerjava.api.command.SyncDockerCmd",
"com.github.dockerjava.api.command.TagImageCmd",
"com.github.dockerjava.api.command.TagImageCmd$Exec",
"com.github.dockerjava.api.command.TopContainerCmd",
"com.github.dockerjava.api.command.TopContainerCmd$Exec",
"com.github.dockerjava.api.command.TopContainerResponse",
"com.github.dockerjava.api.command.UnpauseContainerCmd",
"com.github.dockerjava.api.command.UnpauseContainerCmd$Exec",
"com.github.dockerjava.api.command.UpdateContainerCmd",
"com.github.dockerjava.api.command.UpdateContainerCmd$Exec",
"com.github.dockerjava.api.command.UpdateServiceCmd",
"com.github.dockerjava.api.command.UpdateServiceCmd$Exec",
"com.github.dockerjava.api.command.UpdateSwarmCmd",
"com.github.dockerjava.api.command.UpdateSwarmCmd$Exec",
"com.github.dockerjava.api.command.UpdateSwarmNodeCmd",
"com.github.dockerjava.api.command.UpdateSwarmNodeCmd$Exec",
"com.github.dockerjava.api.command.VersionCmd",
"com.github.dockerjava.api.command.VersionCmd$Exec",
"com.github.dockerjava.api.command.WaitContainerCmd",
"com.github.dockerjava.api.command.WaitContainerCmd$Exec",
"com.github.dockerjava.api.command.WaitContainerResultCallback",
"com.github.dockerjava.api.exception.BadRequestException",
"com.github.dockerjava.api.exception.ConflictException",
"com.github.dockerjava.api.exception.DockerClientException",
"com.github.dockerjava.api.exception.DockerException",
"com.github.dockerjava.api.exception.InternalServerErrorException",
"com.github.dockerjava.api.exception.NotAcceptableException",
"com.github.dockerjava.api.exception.NotFoundException",
"com.github.dockerjava.api.exception.NotModifiedException",
"com.github.dockerjava.api.exception.UnauthorizedException",
"com.github.dockerjava.api.model.AccessMode",
"com.github.dockerjava.api.model.AuthConfig",
"com.github.dockerjava.api.model.AuthConfigurations",
"com.github.dockerjava.api.model.AuthResponse",
"com.github.dockerjava.api.model.Bind",
"com.github.dockerjava.api.model.BindOptions",
"com.github.dockerjava.api.model.BindPropagation",
"com.github.dockerjava.api.model.Binds",
"com.github.dockerjava.api.model.BlkioRateDevice",
"com.github.dockerjava.api.model.BlkioStatEntry",
"com.github.dockerjava.api.model.BlkioStatsConfig",
"com.github.dockerjava.api.model.BlkioWeightDevice",
"com.github.dockerjava.api.model.BuildResponseItem",
"com.github.dockerjava.api.model.Capability",
"com.github.dockerjava.api.model.ChangeLog",
"com.github.dockerjava.api.model.ClusterInfo",
"com.github.dockerjava.api.model.Config",
"com.github.dockerjava.api.model.ConfigSpec",
"com.github.dockerjava.api.model.Container",
"com.github.dockerjava.api.model.ContainerConfig",
"com.github.dockerjava.api.model.ContainerDNSConfig",
"com.github.dockerjava.api.model.ContainerHostConfig",
"com.github.dockerjava.api.model.ContainerMount",
"com.github.dockerjava.api.model.ContainerNetwork",
"com.github.dockerjava.api.model.ContainerNetwork$Ipam",
"com.github.dockerjava.api.model.ContainerNetworkSettings",
"com.github.dockerjava.api.model.ContainerPort",
"com.github.dockerjava.api.model.ContainerSpec",
"com.github.dockerjava.api.model.ContainerSpecConfig",
"com.github.dockerjava.api.model.ContainerSpecFile",
"com.github.dockerjava.api.model.ContainerSpecPrivileges",
"com.github.dockerjava.api.model.ContainerSpecPrivilegesCredential",
"com.github.dockerjava.api.model.ContainerSpecPrivilegesSELinuxContext",
"com.github.dockerjava.api.model.ContainerSpecSecret",
"com.github.dockerjava.api.model.CpuStatsConfig",
"com.github.dockerjava.api.model.CpuUsageConfig",
"com.github.dockerjava.api.model.Device",
"com.github.dockerjava.api.model.DeviceRequest",
"com.github.dockerjava.api.model.DiscreteResourceSpec",
"com.github.dockerjava.api.model.DockerObject",
"com.github.dockerjava.api.model.DockerObjectAccessor",
"com.github.dockerjava.api.model.Driver",
"com.github.dockerjava.api.model.DriverStatus",
"com.github.dockerjava.api.model.Endpoint",
"com.github.dockerjava.api.model.EndpointResolutionMode",
"com.github.dockerjava.api.model.EndpointSpec",
"com.github.dockerjava.api.model.EndpointVirtualIP",
"com.github.dockerjava.api.model.ErrorDetail",
"com.github.dockerjava.api.model.ErrorResponse",
"com.github.dockerjava.api.model.Event",
"com.github.dockerjava.api.model.EventActor",
"com.github.dockerjava.api.model.EventType",
"com.github.dockerjava.api.model.ExposedPort",
"com.github.dockerjava.api.model.ExposedPorts",
"com.github.dockerjava.api.model.ExternalCA",
"com.github.dockerjava.api.model.ExternalCAProtocol",
"com.github.dockerjava.api.model.Frame",
"com.github.dockerjava.api.model.GenericResource",
"com.github.dockerjava.api.model.HealthCheck",
"com.github.dockerjava.api.model.HostConfig",
"com.github.dockerjava.api.model.Identifier",
"com.github.dockerjava.api.model.Image",
"com.github.dockerjava.api.model.ImageOptions",
"com.github.dockerjava.api.model.Info",
"com.github.dockerjava.api.model.InfoRegistryConfig",
"com.github.dockerjava.api.model.InfoRegistryConfig$IndexConfig",
"com.github.dockerjava.api.model.InternetProtocol",
"com.github.dockerjava.api.model.Isolation",
"com.github.dockerjava.api.model.Link",
"com.github.dockerjava.api.model.Links",
"com.github.dockerjava.api.model.LoadResponseItem",
"com.github.dockerjava.api.model.LocalNodeState",
"com.github.dockerjava.api.model.LogConfig",
"com.github.dockerjava.api.model.LogConfig$LoggingType",
"com.github.dockerjava.api.model.LxcConf",
"com.github.dockerjava.api.model.MemoryStatsConfig",
"com.github.dockerjava.api.model.Mount",
"com.github.dockerjava.api.model.MountType",
"com.github.dockerjava.api.model.NamedResourceSpec",
"com.github.dockerjava.api.model.Network",
"com.github.dockerjava.api.model.Network$ContainerNetworkConfig",
"com.github.dockerjava.api.model.Network$Ipam",
"com.github.dockerjava.api.model.Network$Ipam$Config",
"com.github.dockerjava.api.model.NetworkAttachmentConfig",
"com.github.dockerjava.api.model.NetworkSettings",
"com.github.dockerjava.api.model.Node",
"com.github.dockerjava.api.model.ObjectVersion",
"com.github.dockerjava.api.model.PeerNode",
"com.github.dockerjava.api.model.PidsStatsConfig",
"com.github.dockerjava.api.model.PortBinding",
"com.github.dockerjava.api.model.PortConfig",
"com.github.dockerjava.api.model.PortConfig$PublishMode",
"com.github.dockerjava.api.model.PortConfigProtocol",
"com.github.dockerjava.api.model.Ports",
"com.github.dockerjava.api.model.Ports$Binding",
"com.github.dockerjava.api.model.PropagationMode",
"com.github.dockerjava.api.model.PruneResponse",
"com.github.dockerjava.api.model.PruneType",
"com.github.dockerjava.api.model.PullResponseItem",
"com.github.dockerjava.api.model.PushResponseItem",
"com.github.dockerjava.api.model.Reachability",
"com.github.dockerjava.api.model.Repository",
"com.github.dockerjava.api.model.ResourceRequirements",
"com.github.dockerjava.api.model.ResourceSpecs",
"com.github.dockerjava.api.model.ResourceVersion",
"com.github.dockerjava.api.model.ResponseItem",
"com.github.dockerjava.api.model.ResponseItem$AuxDetail",
"com.github.dockerjava.api.model.ResponseItem$ErrorDetail",
"com.github.dockerjava.api.model.ResponseItem$ProgressDetail",
"com.github.dockerjava.api.model.RestartPolicy",
"com.github.dockerjava.api.model.RuntimeInfo",
"com.github.dockerjava.api.model.SELContext",
"com.github.dockerjava.api.model.SearchItem",
"com.github.dockerjava.api.model.Secret",
"com.github.dockerjava.api.model.SecretSpec",
"com.github.dockerjava.api.model.Service",
"com.github.dockerjava.api.model.ServiceGlobalModeOptions",
"com.github.dockerjava.api.model.ServiceMode",
"com.github.dockerjava.api.model.ServiceModeConfig",
"com.github.dockerjava.api.model.ServicePlacement",
"com.github.dockerjava.api.model.ServiceReplicatedModeOptions",
"com.github.dockerjava.api.model.ServiceRestartCondition",
"com.github.dockerjava.api.model.ServiceRestartPolicy",
"com.github.dockerjava.api.model.ServiceSpec",
"com.github.dockerjava.api.model.ServiceUpdateState",
"com.github.dockerjava.api.model.ServiceUpdateStatus",
"com.github.dockerjava.api.model.StatisticNetworksConfig",
"com.github.dockerjava.api.model.Statistics",
"com.github.dockerjava.api.model.StatsConfig",
"com.github.dockerjava.api.model.StreamType",
"com.github.dockerjava.api.model.Swarm",
"com.github.dockerjava.api.model.SwarmCAConfig",
"com.github.dockerjava.api.model.SwarmDispatcherConfig",
"com.github.dockerjava.api.model.SwarmInfo",
"com.github.dockerjava.api.model.SwarmJoinTokens",
"com.github.dockerjava.api.model.SwarmNode",
"com.github.dockerjava.api.model.SwarmNodeAvailability",
"com.github.dockerjava.api.model.SwarmNodeDescription",
"com.github.dockerjava.api.model.SwarmNodeEngineDescription",
"com.github.dockerjava.api.model.SwarmNodeManagerStatus",
"com.github.dockerjava.api.model.SwarmNodePlatform",
"com.github.dockerjava.api.model.SwarmNodePluginDescription",
"com.github.dockerjava.api.model.SwarmNodeResources",
"com.github.dockerjava.api.model.SwarmNodeRole",
"com.github.dockerjava.api.model.SwarmNodeSpec",
"com.github.dockerjava.api.model.SwarmNodeState",
"com.github.dockerjava.api.model.SwarmNodeStatus",
"com.github.dockerjava.api.model.SwarmNodeVersion",
"com.github.dockerjava.api.model.SwarmOrchestration",
"com.github.dockerjava.api.model.SwarmRaftConfig",
"com.github.dockerjava.api.model.SwarmSpec",
"com.github.dockerjava.api.model.SwarmVersion",
"com.github.dockerjava.api.model.Task",
"com.github.dockerjava.api.model.TaskDefaults",
"com.github.dockerjava.api.model.TaskSpec",
"com.github.dockerjava.api.model.TaskState",
"com.github.dockerjava.api.model.TaskStatus",
"com.github.dockerjava.api.model.TaskStatusContainerStatus",
"com.github.dockerjava.api.model.ThrottlingDataConfig",
"com.github.dockerjava.api.model.TmpfsOptions",
"com.github.dockerjava.api.model.Ulimit",
"com.github.dockerjava.api.model.UpdateConfig",
"com.github.dockerjava.api.model.UpdateContainerResponse",
"com.github.dockerjava.api.model.UpdateFailureAction",
"com.github.dockerjava.api.model.UpdateOrder",
"com.github.dockerjava.api.model.Version",
"com.github.dockerjava.api.model.VersionComponent",
"com.github.dockerjava.api.model.VersionPlatform",
"com.github.dockerjava.api.model.Volume",
"com.github.dockerjava.api.model.VolumeBind",
"com.github.dockerjava.api.model.VolumeBinds",
"com.github.dockerjava.api.model.VolumeOptions",
"com.github.dockerjava.api.model.VolumeRW",
"com.github.dockerjava.api.model.Volumes",
"com.github.dockerjava.api.model.VolumesFrom",
"com.github.dockerjava.api.model.VolumesRW",
"com.github.dockerjava.api.model.WaitResponse",
"com.github.dockerjava.core.AbstractDockerCmdExecFactory",
"com.github.dockerjava.core.DefaultDockerClientConfig",
"com.github.dockerjava.core.DefaultDockerClientConfig$Builder",
"com.github.dockerjava.core.DefaultDockerCmdExecFactory",
"com.github.dockerjava.core.DefaultDockerCmdExecFactory$DefaultWebTarget",
"com.github.dockerjava.core.DefaultInvocationBuilder",
"com.github.dockerjava.core.DefaultInvocationBuilder$1",
"com.github.dockerjava.core.DefaultInvocationBuilder$2",
"com.github.dockerjava.core.DefaultInvocationBuilder$JsonSink",
"com.github.dockerjava.core.DefaultObjectMapperHolder",
"com.github.dockerjava.core.DefaultObjectMapperHolder$1",
"com.github.dockerjava.core.DefaultObjectMapperHolder$1$1",
"com.github.dockerjava.core.DockerClientConfig",
"com.github.dockerjava.core.DockerClientConfigAware",
"com.github.dockerjava.core.DockerClientConfigDelegate",
"com.github.dockerjava.core.DockerClientImpl",
"com.github.dockerjava.core.DockerConfigFile",
"com.github.dockerjava.core.DockerConfigFile$1",
"com.github.dockerjava.core.DockerContextMetaFile",
"com.github.dockerjava.core.DockerContextMetaFile$Endpoints",
"com.github.dockerjava.core.DockerContextMetaFile$Endpoints$Docker",
"com.github.dockerjava.core.DockerObjectDeserializer",
"com.github.dockerjava.core.FramedInputStreamConsumer",
"com.github.dockerjava.core.GoLangFileMatch",
"com.github.dockerjava.core.GoLangFileMatch$RangeParseState",
"com.github.dockerjava.core.GoLangMatchFileFilter",
"com.github.dockerjava.core.InvocationBuilder",
"com.github.dockerjava.core.InvocationBuilder$AsyncResultCallback",
"com.github.dockerjava.core.KeystoreSSLConfig",
"com.github.dockerjava.core.KeystoreSSLConfig$1",
"com.github.dockerjava.core.LocalDirectorySSLConfig",
"com.github.dockerjava.core.MediaType",
"com.github.dockerjava.core.NameParser",
"com.github.dockerjava.core.NameParser$HostnameReposName",
"com.github.dockerjava.core.NameParser$ReposTag",
"com.github.dockerjava.core.RemoteApiVersion",
"com.github.dockerjava.core.RemoteApiVersion$1",
"com.github.dockerjava.core.SSLConfig",
"com.github.dockerjava.core.WebTarget",
"com.github.dockerjava.core.async.FrameStreamProcessor",
"com.github.dockerjava.core.async.JsonStreamProcessor",
"com.github.dockerjava.core.async.JsonStreamProcessor$1",
"com.github.dockerjava.core.async.ResponseStreamProcessor",
"com.github.dockerjava.core.async.ResultCallbackTemplate",
"com.github.dockerjava.core.command.AbstrAsyncDockerCmd",
"com.github.dockerjava.core.command.AbstrDockerCmd",
"com.github.dockerjava.core.command.AttachContainerCmdImpl",
"com.github.dockerjava.core.command.AttachContainerResultCallback",
"com.github.dockerjava.core.command.AuthCmdImpl",
"com.github.dockerjava.core.command.BuildImageCmdImpl",
"com.github.dockerjava.core.command.BuildImageResultCallback",
"com.github.dockerjava.core.command.CommitCmdImpl",
"com.github.dockerjava.core.command.ConnectToNetworkCmdImpl",
"com.github.dockerjava.core.command.ContainerDiffCmdImpl",
"com.github.dockerjava.core.command.CopyArchiveFromContainerCmdImpl",
"com.github.dockerjava.core.command.CopyArchiveToContainerCmdImpl",
"com.github.dockerjava.core.command.CopyFileFromContainerCmdImpl",
"com.github.dockerjava.core.command.CreateConfigCmdImpl",
"com.github.dockerjava.core.command.CreateContainerCmdImpl",
"com.github.dockerjava.core.command.CreateContainerCmdImpl$NetworkingConfig",
"com.github.dockerjava.core.command.CreateImageCmdImpl",
"com.github.dockerjava.core.command.CreateNetworkCmdImpl",
"com.github.dockerjava.core.command.CreateSecretCmdImpl",
"com.github.dockerjava.core.command.CreateServiceCmdImpl",
"com.github.dockerjava.core.command.CreateVolumeCmdImpl",
"com.github.dockerjava.core.command.DisconnectFromNetworkCmdImpl",
"com.github.dockerjava.core.command.EventsCmdImpl",
"com.github.dockerjava.core.command.EventsResultCallback",
"com.github.dockerjava.core.command.ExecCreateCmdImpl",
"com.github.dockerjava.core.command.ExecStartCmdImpl",
"com.github.dockerjava.core.command.ExecStartResultCallback",
"com.github.dockerjava.core.command.ExecStartResultCallback$1",
"com.github.dockerjava.core.command.FrameReader",
"com.github.dockerjava.core.command.InfoCmdImpl",
"com.github.dockerjava.core.command.InitializeSwarmCmdImpl",
"com.github.dockerjava.core.command.InpectNetworkCmdImpl",
"com.github.dockerjava.core.command.InspectConfigCmdImpl",
"com.github.dockerjava.core.command.InspectContainerCmdImpl",
"com.github.dockerjava.core.command.InspectExecCmdImpl",
"com.github.dockerjava.core.command.InspectImageCmdImpl",
"com.github.dockerjava.core.command.InspectServiceCmdImpl",
"com.github.dockerjava.core.command.InspectSwarmCmdImpl",
"com.github.dockerjava.core.command.InspectSwarmNodeCmdImpl",
"com.github.dockerjava.core.command.InspectVolumeCmdImpl",
"com.github.dockerjava.core.command.JoinSwarmCmdImpl",
"com.github.dockerjava.core.command.KillContainerCmdImpl",
"com.github.dockerjava.core.command.LeaveSwarmCmdImpl",
"com.github.dockerjava.core.command.ListConfigsCmdImpl",
"com.github.dockerjava.core.command.ListContainersCmdImpl",
"com.github.dockerjava.core.command.ListImagesCmdImpl",
"com.github.dockerjava.core.command.ListNetworksCmdImpl",
"com.github.dockerjava.core.command.ListSecretsCmdImpl",
"com.github.dockerjava.core.command.ListServicesCmdImpl",
"com.github.dockerjava.core.command.ListSwarmNodesCmdImpl",
"com.github.dockerjava.core.command.ListTasksCmdImpl",
"com.github.dockerjava.core.command.ListVolumesCmdImpl",
"com.github.dockerjava.core.command.LoadImageAsyncCmdImpl",
"com.github.dockerjava.core.command.LoadImageCmdImpl",
"com.github.dockerjava.core.command.LogContainerCmdImpl",
"com.github.dockerjava.core.command.LogContainerResultCallback",
"com.github.dockerjava.core.command.LogSwarmObjectImpl",
"com.github.dockerjava.core.command.PauseContainerCmdImpl",
"com.github.dockerjava.core.command.PingCmdImpl",
"com.github.dockerjava.core.command.PruneCmdImpl",
"com.github.dockerjava.core.command.PruneCmdImpl$1",
"com.github.dockerjava.core.command.PullImageCmdImpl",
"com.github.dockerjava.core.command.PullImageResultCallback",
"com.github.dockerjava.core.command.PushImageCmdImpl",
"com.github.dockerjava.core.command.PushImageResultCallback",
"com.github.dockerjava.core.command.RemoveConfigCmdImpl",
"com.github.dockerjava.core.command.RemoveContainerCmdImpl",
"com.github.dockerjava.core.command.RemoveImageCmdImpl",
"com.github.dockerjava.core.command.RemoveNetworkCmdImpl",
"com.github.dockerjava.core.command.RemoveSecretCmdImpl",
"com.github.dockerjava.core.command.RemoveServiceCmdImpl",
"com.github.dockerjava.core.command.RemoveSwarmNodeCmdImpl",
"com.github.dockerjava.core.command.RemoveVolumeCmdImpl",
"com.github.dockerjava.core.command.RenameContainerCmdImpl",
"com.github.dockerjava.core.command.ResizeContainerCmdImpl",
"com.github.dockerjava.core.command.ResizeExecCmdImpl",
"com.github.dockerjava.core.command.RestartContainerCmdImpl",
"com.github.dockerjava.core.command.SaveImageCmdImpl",
"com.github.dockerjava.core.command.SaveImagesCmdImpl",
"com.github.dockerjava.core.command.SaveImagesCmdImpl$1",
"com.github.dockerjava.core.command.SaveImagesCmdImpl$TaggedImageImpl",
"com.github.dockerjava.core.command.SearchImagesCmdImpl",
"com.github.dockerjava.core.command.StartContainerCmdImpl",
"com.github.dockerjava.core.command.StatsCmdImpl",
"com.github.dockerjava.core.command.StopContainerCmdImpl",
"com.github.dockerjava.core.command.TagImageCmdImpl",
"com.github.dockerjava.core.command.TopContainerCmdImpl",
"com.github.dockerjava.core.command.UnpauseContainerCmdImpl",
"com.github.dockerjava.core.command.UpdateContainerCmdImpl",
"com.github.dockerjava.core.command.UpdateServiceCmdImpl",
"com.github.dockerjava.core.command.UpdateSwarmCmdImpl",
"com.github.dockerjava.core.command.UpdateSwarmNodeCmdImpl",
"com.github.dockerjava.core.command.VersionCmdImpl",
"com.github.dockerjava.core.command.WaitContainerCmdImpl",
"com.github.dockerjava.core.command.WaitContainerResultCallback",
"com.github.dockerjava.core.dockerfile.Dockerfile",
"com.github.dockerjava.core.dockerfile.Dockerfile$1",
"com.github.dockerjava.core.dockerfile.Dockerfile$LineTransformer",
"com.github.dockerjava.core.dockerfile.Dockerfile$ScannedResult",
"com.github.dockerjava.core.dockerfile.Dockerfile$ScannedResult$1",
"com.github.dockerjava.core.dockerfile.DockerfileStatement",
"com.github.dockerjava.core.dockerfile.DockerfileStatement$1",
"com.github.dockerjava.core.dockerfile.DockerfileStatement$Add",
"com.github.dockerjava.core.dockerfile.DockerfileStatement$Env",
"com.github.dockerjava.core.dockerfile.DockerfileStatement$OtherLine",
"com.github.dockerjava.core.exception.GoLangFileMatchException",
"com.github.dockerjava.core.exception.InvalidRepositoryNameException",
"com.github.dockerjava.core.exec.AbstrAsyncDockerCmdExec",
"com.github.dockerjava.core.exec.AbstrAsyncDockerCmdExec$1",
"com.github.dockerjava.core.exec.AbstrDockerCmdExec",
"com.github.dockerjava.core.exec.AbstrSyncDockerCmdExec",
"com.github.dockerjava.core.exec.AttachContainerCmdExec",
"com.github.dockerjava.core.exec.AuthCmdExec",
"com.github.dockerjava.core.exec.AuthCmdExec$1",
"com.github.dockerjava.core.exec.BuildImageCmdExec",
"com.github.dockerjava.core.exec.BuildImageCmdExec$1",
"com.github.dockerjava.core.exec.CommitCmdExec",
"com.github.dockerjava.core.exec.CommitCmdExec$1",
"com.github.dockerjava.core.exec.ConnectToNetworkCmdExec",
"com.github.dockerjava.core.exec.ContainerDiffCmdExec",
"com.github.dockerjava.core.exec.ContainerDiffCmdExec$1",
"com.github.dockerjava.core.exec.CopyArchiveFromContainerCmdExec",
"com.github.dockerjava.core.exec.CopyArchiveToContainerCmdExec",
"com.github.dockerjava.core.exec.CopyFileFromContainerCmdExec",
"com.github.dockerjava.core.exec.CreateConfigCmdExec",
"com.github.dockerjava.core.exec.CreateConfigCmdExec$1",
"com.github.dockerjava.core.exec.CreateContainerCmdExec",
"com.github.dockerjava.core.exec.CreateContainerCmdExec$1",
"com.github.dockerjava.core.exec.CreateImageCmdExec",
"com.github.dockerjava.core.exec.CreateImageCmdExec$1",
"com.github.dockerjava.core.exec.CreateNetworkCmdExec",
"com.github.dockerjava.core.exec.CreateNetworkCmdExec$1",
"com.github.dockerjava.core.exec.CreateSecretCmdExec",
"com.github.dockerjava.core.exec.CreateSecretCmdExec$1",
"com.github.dockerjava.core.exec.CreateServiceCmdExec",
"com.github.dockerjava.core.exec.CreateServiceCmdExec$1",
"com.github.dockerjava.core.exec.CreateVolumeCmdExec",
"com.github.dockerjava.core.exec.CreateVolumeCmdExec$1",
"com.github.dockerjava.core.exec.DisconnectFromNetworkCmdExec",
"com.github.dockerjava.core.exec.EventsCmdExec",
"com.github.dockerjava.core.exec.EventsCmdExec$1",
"com.github.dockerjava.core.exec.ExecCreateCmdExec",
"com.github.dockerjava.core.exec.ExecCreateCmdExec$1",
"com.github.dockerjava.core.exec.ExecStartCmdExec",
"com.github.dockerjava.core.exec.InfoCmdExec",
"com.github.dockerjava.core.exec.InfoCmdExec$1",
"com.github.dockerjava.core.exec.InitializeSwarmCmdExec",
"com.github.dockerjava.core.exec.InspectConfigCmdExec",
"com.github.dockerjava.core.exec.InspectConfigCmdExec$1",
"com.github.dockerjava.core.exec.InspectContainerCmdExec",
"com.github.dockerjava.core.exec.InspectContainerCmdExec$1",
"com.github.dockerjava.core.exec.InspectExecCmdExec",
"com.github.dockerjava.core.exec.InspectExecCmdExec$1",
"com.github.dockerjava.core.exec.InspectImageCmdExec",
"com.github.dockerjava.core.exec.InspectImageCmdExec$1",
"com.github.dockerjava.core.exec.InspectNetworkCmdExec",
"com.github.dockerjava.core.exec.InspectNetworkCmdExec$1",
"com.github.dockerjava.core.exec.InspectServiceCmdExec",
"com.github.dockerjava.core.exec.InspectServiceCmdExec$1",
"com.github.dockerjava.core.exec.InspectSwarmCmdExec",
"com.github.dockerjava.core.exec.InspectSwarmCmdExec$1",
"com.github.dockerjava.core.exec.InspectSwarmNodeCmdExec",
"com.github.dockerjava.core.exec.InspectSwarmNodeCmdExec$1",
"com.github.dockerjava.core.exec.InspectVolumeCmdExec",
"com.github.dockerjava.core.exec.InspectVolumeCmdExec$1",
"com.github.dockerjava.core.exec.JoinSwarmCmdExec",
"com.github.dockerjava.core.exec.KillContainerCmdExec",
"com.github.dockerjava.core.exec.LeaveSwarmCmdExec",
"com.github.dockerjava.core.exec.ListConfigsCmdExec",
"com.github.dockerjava.core.exec.ListConfigsCmdExec$1",
"com.github.dockerjava.core.exec.ListContainersCmdExec",
"com.github.dockerjava.core.exec.ListContainersCmdExec$1",
"com.github.dockerjava.core.exec.ListImagesCmdExec",
"com.github.dockerjava.core.exec.ListImagesCmdExec$1",
"com.github.dockerjava.core.exec.ListNetworksCmdExec",
"com.github.dockerjava.core.exec.ListNetworksCmdExec$1",
"com.github.dockerjava.core.exec.ListSecretsCmdExec",
"com.github.dockerjava.core.exec.ListSecretsCmdExec$1",
"com.github.dockerjava.core.exec.ListServicesCmdExec",
"com.github.dockerjava.core.exec.ListServicesCmdExec$1",
"com.github.dockerjava.core.exec.ListSwarmNodesCmdExec",
"com.github.dockerjava.core.exec.ListSwarmNodesCmdExec$1",
"com.github.dockerjava.core.exec.ListTasksCmdExec",
"com.github.dockerjava.core.exec.ListTasksCmdExec$1",
"com.github.dockerjava.core.exec.ListVolumesCmdExec",
"com.github.dockerjava.core.exec.ListVolumesCmdExec$1",
"com.github.dockerjava.core.exec.LoadImageAsyncCmdExec",
"com.github.dockerjava.core.exec.LoadImageAsyncCmdExec$1",
"com.github.dockerjava.core.exec.LoadImageCmdExec",
"com.github.dockerjava.core.exec.LogContainerCmdExec",
"com.github.dockerjava.core.exec.LogSwarmObjectExec",
"com.github.dockerjava.core.exec.PauseContainerCmdExec",
"com.github.dockerjava.core.exec.PingCmdExec",
"com.github.dockerjava.core.exec.PruneCmdExec",
"com.github.dockerjava.core.exec.PruneCmdExec$1",
"com.github.dockerjava.core.exec.PullImageCmdExec",
"com.github.dockerjava.core.exec.PullImageCmdExec$1",
"com.github.dockerjava.core.exec.PushImageCmdExec",
"com.github.dockerjava.core.exec.PushImageCmdExec$1",
"com.github.dockerjava.core.exec.RemoveConfigCmdExec",
"com.github.dockerjava.core.exec.RemoveContainerCmdExec",
"com.github.dockerjava.core.exec.RemoveImageCmdExec",
"com.github.dockerjava.core.exec.RemoveNetworkCmdExec",
"com.github.dockerjava.core.exec.RemoveSecretCmdExec",
"com.github.dockerjava.core.exec.RemoveServiceCmdExec",
"com.github.dockerjava.core.exec.RemoveSwarmNodeCmdExec",
"com.github.dockerjava.core.exec.RemoveVolumeCmdExec",
"com.github.dockerjava.core.exec.RenameContainerCmdExec",
"com.github.dockerjava.core.exec.ResizeContainerCmdExec",
"com.github.dockerjava.core.exec.ResizeExecCmdExec",
"com.github.dockerjava.core.exec.RestartContainerCmdExec",
"com.github.dockerjava.core.exec.SaveImageCmdExec",
"com.github.dockerjava.core.exec.SaveImagesCmdExec",
"com.github.dockerjava.core.exec.SearchImagesCmdExec",
"com.github.dockerjava.core.exec.SearchImagesCmdExec$1",
"com.github.dockerjava.core.exec.StartContainerCmdExec",
"com.github.dockerjava.core.exec.StatsCmdExec",
"com.github.dockerjava.core.exec.StatsCmdExec$1",
"com.github.dockerjava.core.exec.StopContainerCmdExec",
"com.github.dockerjava.core.exec.TagImageCmdExec",
"com.github.dockerjava.core.exec.TopContainerCmdExec",
"com.github.dockerjava.core.exec.TopContainerCmdExec$1",
"com.github.dockerjava.core.exec.UnpauseContainerCmdExec",
"com.github.dockerjava.core.exec.UpdateContainerCmdExec",
"com.github.dockerjava.core.exec.UpdateContainerCmdExec$1",
"com.github.dockerjava.core.exec.UpdateServiceCmdExec",
"com.github.dockerjava.core.exec.UpdateSwarmCmdExec",
"com.github.dockerjava.core.exec.UpdateSwarmNodeCmdExec",
"com.github.dockerjava.core.exec.VersionCmdExec",
"com.github.dockerjava.core.exec.VersionCmdExec$1",
"com.github.dockerjava.core.exec.WaitContainerCmdExec",
"com.github.dockerjava.core.exec.WaitContainerCmdExec$1",
"com.github.dockerjava.core.util.CacheFromEncoder",
"com.github.dockerjava.core.util.CertificateUtils",
"com.github.dockerjava.core.util.CompressArchiveUtil",
"com.github.dockerjava.core.util.FilePathUtil",
"com.github.dockerjava.core.util.FiltersBuilder",
"com.github.dockerjava.core.util.FiltersEncoder",
"com.github.dockerjava.core.util.SwarmNodesFiltersBuilder",
"com.github.dockerjava.core.util.TarDirWalker"
})
public class DockerJavaNativeSupport {}
@@ -0,0 +1,37 @@
package io.github.hectorvent.floci.core.common.port;
import io.github.hectorvent.floci.config.EmulatorConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Thread-safe sequential port dispenser for Lambda Runtime API servers.
*/
@ApplicationScoped
public class PortAllocator {
private final AtomicInteger counter;
private final int maxPort;
@Inject
public PortAllocator(EmulatorConfig config) {
this.counter = new AtomicInteger(config.services().lambda().runtimeApiBasePort());
this.maxPort = config.services().lambda().runtimeApiMaxPort();
}
PortAllocator(int basePort, int maxPort) {
this.counter = new AtomicInteger(basePort);
this.maxPort = maxPort;
}
public int allocate() {
int port = counter.getAndIncrement();
if (port > maxPort) {
counter.set(counter.get() - (maxPort - counter.get() + 1));
port = counter.getAndIncrement();
}
return port;
}
}
@@ -0,0 +1,144 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
/**
* Hybrid storage: in-memory reads with async flush to disk.
* Writes go to memory immediately, then flushed to disk periodically.
*/
public class HybridStorage<K, V> implements StorageBackend<K, V> {
private static final Logger LOG = Logger.getLogger(HybridStorage.class);
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
private final Path filePath;
private final ObjectMapper objectMapper;
private final TypeReference<Map<K, V>> typeReference;
private final ScheduledExecutorService scheduler;
private final AtomicBoolean dirty = new AtomicBoolean(false);
public HybridStorage(Path filePath, TypeReference<Map<K, V>> typeReference, long flushIntervalMs) {
this.filePath = filePath;
this.typeReference = typeReference;
this.objectMapper = new ObjectMapper();
this.objectMapper.registerModule(new JavaTimeModule());
this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "hybrid-storage-flush");
t.setDaemon(true);
return t;
});
this.scheduler.scheduleAtFixedRate(this::flushIfDirty, flushIntervalMs, flushIntervalMs, TimeUnit.MILLISECONDS);
}
@Override
public void put(K key, V value) {
store.put(key, value);
dirty.set(true);
}
@Override
public Optional<V> get(K key) {
return Optional.ofNullable(store.get(key));
}
@Override
public void delete(K key) {
store.remove(key);
dirty.set(true);
}
@Override
public List<V> scan(Predicate<K> keyFilter) {
return store.entrySet().stream()
.filter(e -> keyFilter.test(e.getKey()))
.map(Map.Entry::getValue)
.toList();
}
@Override
public Set<K> keys() {
return Collections.unmodifiableSet(store.keySet());
}
@Override
public void flush() {
persistToDisk();
}
@Override
public void load() {
if (!Files.exists(filePath)) {
LOG.debugv("No persistent file found at {0}, starting with empty store", filePath);
return;
}
try {
Map<K, V> data = objectMapper.readValue(filePath.toFile(), typeReference);
store.clear();
store.putAll(data);
LOG.infov("Loaded {0} entries from {1}", store.size(), filePath);
} catch (IOException e) {
LOG.errorv(e, "Failed to load data from {0}", filePath);
}
}
@Override
public void clear() {
store.clear();
dirty.set(true);
}
public void shutdown() {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
Thread.currentThread().interrupt();
}
flush();
}
private void flushIfDirty() {
if (dirty.compareAndSet(true, false)) {
persistToDisk();
}
}
private synchronized void persistToDisk() {
try {
Files.createDirectories(filePath.getParent());
Path tempFile = filePath.resolveSibling(filePath.getFileName() + ".tmp");
objectMapper.writeValue(tempFile.toFile(), store);
Files.move(tempFile, filePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
LOG.debugv("Flushed {0} entries to {1}", store.size(), filePath);
} catch (IOException e) {
LOG.errorv(e, "Failed to persist data to {0}", filePath);
dirty.set(true);
}
}
}
@@ -0,0 +1,64 @@
package io.github.hectorvent.floci.core.storage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
/**
* Thread-safe in-memory storage backed by ConcurrentHashMap.
* No persistence — data is lost on shutdown unless explicitly flushed.
*/
public class InMemoryStorage<K, V> implements StorageBackend<K, V> {
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
@Override
public void put(K key, V value) {
store.put(key, value);
}
@Override
public Optional<V> get(K key) {
return Optional.ofNullable(store.get(key));
}
@Override
public void delete(K key) {
store.remove(key);
}
@Override
public List<V> scan(Predicate<K> keyFilter) {
List<V> result = new ArrayList<>();
store.forEach((k, v) -> {
if (keyFilter.test(k)) {
result.add(v);
}
});
return result;
}
@Override
public Set<K> keys() {
return Collections.unmodifiableSet(store.keySet());
}
@Override
public void flush() {
// No-op for in-memory storage
}
@Override
public void load() {
// No-op for in-memory storage
}
@Override
public void clear() {
store.clear();
}
}
@@ -0,0 +1,112 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
/**
* JSON file-backed persistent storage.
* Loads all data into memory on startup for fast reads.
* Write-through on every put/delete.
* Uses atomic writes (temp file + rename) for safety.
*/
public class PersistentStorage<K, V> implements StorageBackend<K, V> {
private static final Logger LOG = Logger.getLogger(PersistentStorage.class);
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
private final Path filePath;
private final ObjectMapper objectMapper;
private final TypeReference<Map<K, V>> typeReference;
public PersistentStorage(Path filePath, TypeReference<Map<K, V>> typeReference) {
this.filePath = filePath;
this.typeReference = typeReference;
this.objectMapper = new ObjectMapper();
this.objectMapper.registerModule(new JavaTimeModule());
this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
}
@Override
public void put(K key, V value) {
store.put(key, value);
persistToDisk();
}
@Override
public Optional<V> get(K key) {
return Optional.ofNullable(store.get(key));
}
@Override
public void delete(K key) {
store.remove(key);
persistToDisk();
}
@Override
public List<V> scan(Predicate<K> keyFilter) {
return store.entrySet().stream()
.filter(e -> keyFilter.test(e.getKey()))
.map(Map.Entry::getValue)
.toList();
}
@Override
public Set<K> keys() {
return Collections.unmodifiableSet(store.keySet());
}
@Override
public void flush() {
persistToDisk();
}
@Override
public void load() {
if (!Files.exists(filePath)) {
LOG.debugv("No persistent file found at {0}, starting with empty store", filePath);
return;
}
try {
Map<K, V> data = objectMapper.readValue(filePath.toFile(), typeReference);
store.clear();
store.putAll(data);
LOG.infov("Loaded {0} entries from {1}", store.size(), filePath);
} catch (IOException e) {
LOG.errorv(e, "Failed to load data from {0}", filePath);
}
}
@Override
public void clear() {
store.clear();
persistToDisk();
}
private synchronized void persistToDisk() {
try {
Files.createDirectories(filePath.getParent());
Path tempFile = filePath.resolveSibling(filePath.getFileName() + ".tmp");
objectMapper.writeValue(tempFile.toFile(), store);
Files.move(tempFile, filePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
LOG.errorv(e, "Failed to persist data to {0}", filePath);
}
}
}
@@ -0,0 +1,35 @@
package io.github.hectorvent.floci.core.storage;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
/**
* Generic storage abstraction for AWS emulator services.
*
* @param <K> the key type
* @param <V> the value type
*/
public interface StorageBackend<K, V> {
void put(K key, V value);
Optional<V> get(K key);
void delete(K key);
List<V> scan(Predicate<K> keyFilter);
/** Return all keys in this store. */
Set<K> keys();
/** Persist data to disk if applicable. */
void flush();
/** Load data from disk on startup. */
void load();
/** Clear all data. */
void clear();
}
@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.core.storage;
import io.github.hectorvent.floci.config.EmulatorConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Factory that creates StorageBackend instances based on configuration.
* Tracks all created backends for lifecycle management.
*/
@ApplicationScoped
public class StorageFactory {
private static final Logger LOG = Logger.getLogger(StorageFactory.class);
private final EmulatorConfig config;
private final List<StorageBackend<?, ?>> allBackends = new ArrayList<>();
private final List<HybridStorage<?, ?>> hybridBackends = new ArrayList<>();
private final List<WalStorage<?, ?>> walBackends = new ArrayList<>();
@Inject
public StorageFactory(EmulatorConfig config) {
this.config = config;
}
/**
* Create a storage backend for the given service.
*
* @param serviceName the service name (ssm, sqs, s3)
* @param fileName the JSON file name for persistent storage
* @param typeReference Jackson type reference for deserialization
*/
public <K, V> StorageBackend<K, V> create(String serviceName, String fileName,
TypeReference<Map<K, V>> typeReference) {
String mode = resolveMode(serviceName);
long flushInterval = resolveFlushInterval(serviceName);
Path basePath = Path.of(config.storage().persistentPath());
Path filePath = basePath.resolve(fileName);
LOG.infov("Creating {0} storage for service {1} (file: {2})", mode, serviceName, filePath);
StorageBackend<K, V> backend = switch (mode) {
case "memory" -> new InMemoryStorage<>();
case "persistent" -> new PersistentStorage<>(filePath, typeReference);
case "hybrid" -> {
var hybrid = new HybridStorage<>(filePath, typeReference, flushInterval);
hybridBackends.add(hybrid);
yield hybrid;
}
case "wal" -> {
Path snapshotPath = basePath.resolve(fileName.replace(".json", "-snapshot.json"));
Path walFilePath = basePath.resolve(fileName.replace(".json", ".wal"));
long compactionInterval = config.storage().wal().compactionIntervalMs();
var wal = new WalStorage<>(snapshotPath, walFilePath, typeReference, compactionInterval);
walBackends.add(wal);
yield wal;
}
default -> throw new IllegalArgumentException("Unknown storage mode: " + mode);
};
allBackends.add(backend);
return backend;
}
/** Load all storage backends from disk. */
public void loadAll() {
for (StorageBackend<?, ?> backend : allBackends) {
backend.load();
}
}
/** Flush all storage backends to disk. */
public void flushAll() {
for (StorageBackend<?, ?> backend : allBackends) {
backend.flush();
}
}
/** Shutdown all managed backends (stop schedulers, close connections). */
public void shutdownAll() {
for (HybridStorage<?, ?> hybrid : hybridBackends) {
hybrid.shutdown();
}
for (WalStorage<?, ?> wal : walBackends) {
wal.shutdown();
}
flushAll();
}
private String resolveMode(String serviceName) {
return switch (serviceName) {
case "ssm" -> config.storage().services().ssm().mode();
case "sqs" -> config.storage().services().sqs().mode();
case "s3" -> config.storage().services().s3().mode();
case "dynamodb" -> config.storage().services().dynamodb().mode();
case "sns" -> config.storage().services().sns().mode();
case "lambda" -> config.storage().services().lambda().mode();
case "cloudwatchlogs" -> config.storage().services().cloudwatchlogs().mode();
case "cloudwatchmetrics" -> config.storage().services().cloudwatchmetrics().mode();
case "secretsmanager" -> config.storage().services().secretsmanager().mode();
default -> config.storage().mode();
};
}
private long resolveFlushInterval(String serviceName) {
return switch (serviceName) {
case "ssm" -> config.storage().services().ssm().flushIntervalMs();
case "dynamodb" -> config.storage().services().dynamodb().flushIntervalMs();
case "sns" -> config.storage().services().sns().flushIntervalMs();
case "lambda" -> config.storage().services().lambda().flushIntervalMs();
case "cloudwatchlogs" -> config.storage().services().cloudwatchlogs().flushIntervalMs();
case "cloudwatchmetrics" -> config.storage().services().cloudwatchmetrics().flushIntervalMs();
case "secretsmanager" -> config.storage().services().secretsmanager().flushIntervalMs();
default -> 5000L;
};
}
}
@@ -0,0 +1,295 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.jboss.logging.Logger;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
/**
* Write-Ahead Log storage: in-memory reads with append-only binary WAL for durability.
* Periodic compaction writes a full snapshot and truncates the WAL.
* On startup: load snapshot, then replay WAL entries after snapshot.
*
* Binary WAL entry format:
* PUT: [0x01] [4-byte key length] [key bytes] [4-byte value length] [value bytes]
* DELETE: [0x02] [4-byte key length] [key bytes]
*
* Key and value bytes are serialized via Jackson CBOR (compact binary format).
* Snapshot files use indented JSON for debuggability.
*/
public class WalStorage<K, V> implements StorageBackend<K, V> {
private static final Logger LOG = Logger.getLogger(WalStorage.class);
static final byte OP_PUT = 0x01;
static final byte OP_DELETE = 0x02;
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
private final Path snapshotPath;
private final Path walPath;
private final ObjectMapper snapshotMapper;
private final ObjectMapper walMapper;
private final TypeReference<Map<K, V>> typeReference;
private final ReentrantReadWriteLock compactionLock = new ReentrantReadWriteLock();
private final ScheduledExecutorService scheduler;
private volatile DataOutputStream walWriter;
public WalStorage(Path snapshotPath, Path walPath, TypeReference<Map<K, V>> typeReference,
long compactionIntervalMs) {
this.snapshotPath = snapshotPath;
this.walPath = walPath;
this.typeReference = typeReference;
this.snapshotMapper = new ObjectMapper();
this.snapshotMapper.registerModule(new JavaTimeModule());
this.snapshotMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
this.snapshotMapper.enable(SerializationFeature.INDENT_OUTPUT);
this.walMapper = new ObjectMapper(new CBORFactory());
this.walMapper.registerModule(new JavaTimeModule());
this.walMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "wal-storage-compaction");
t.setDaemon(true);
return t;
});
this.scheduler.scheduleAtFixedRate(this::compact, compactionIntervalMs, compactionIntervalMs,
TimeUnit.MILLISECONDS);
}
@Override
public void put(K key, V value) {
compactionLock.readLock().lock();
try {
store.put(key, value);
appendPut(key, value);
} finally {
compactionLock.readLock().unlock();
}
}
@Override
public Optional<V> get(K key) {
return Optional.ofNullable(store.get(key));
}
@Override
public void delete(K key) {
compactionLock.readLock().lock();
try {
store.remove(key);
appendDelete(key);
} finally {
compactionLock.readLock().unlock();
}
}
@Override
public List<V> scan(Predicate<K> keyFilter) {
return store.entrySet().stream()
.filter(e -> keyFilter.test(e.getKey()))
.map(Map.Entry::getValue)
.toList();
}
@Override
public Set<K> keys() {
return Collections.unmodifiableSet(store.keySet());
}
@Override
public void flush() {
compact();
}
@Override
public void load() {
if (Files.exists(snapshotPath)) {
try {
Map<K, V> data = snapshotMapper.readValue(snapshotPath.toFile(), typeReference);
store.clear();
store.putAll(data);
LOG.infov("Loaded {0} entries from snapshot {1}", store.size(), snapshotPath);
} catch (IOException e) {
LOG.errorv(e, "Failed to load snapshot from {0}", snapshotPath);
}
}
if (Files.exists(walPath)) {
int replayed = replayWal();
LOG.infov("Replayed {0} WAL entries from {1}", replayed, walPath);
}
openWalWriter();
}
@Override
public void clear() {
compactionLock.writeLock().lock();
try {
store.clear();
closeWalWriter();
try {
Files.deleteIfExists(walPath);
Files.deleteIfExists(snapshotPath);
} catch (IOException e) {
LOG.errorv(e, "Failed to delete WAL/snapshot files");
}
openWalWriter();
} finally {
compactionLock.writeLock().unlock();
}
}
public void shutdown() {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
Thread.currentThread().interrupt();
}
compact();
closeWalWriter();
}
private void compact() {
compactionLock.writeLock().lock();
try {
Files.createDirectories(snapshotPath.getParent());
Path tempFile = snapshotPath.resolveSibling(snapshotPath.getFileName() + ".tmp");
snapshotMapper.writeValue(tempFile.toFile(), store);
Files.move(tempFile, snapshotPath, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
closeWalWriter();
Files.deleteIfExists(walPath);
openWalWriter();
LOG.debugv("Compacted {0} entries to snapshot, WAL truncated", store.size());
} catch (IOException e) {
LOG.errorv(e, "Failed to compact WAL storage");
} finally {
compactionLock.writeLock().unlock();
}
}
private void appendPut(K key, V value) {
DataOutputStream out = walWriter;
if (out == null) return;
try {
byte[] keyBytes = walMapper.writeValueAsBytes(key);
byte[] valueBytes = walMapper.writeValueAsBytes(value);
synchronized (out) {
out.writeByte(OP_PUT);
out.writeInt(keyBytes.length);
out.write(keyBytes);
out.writeInt(valueBytes.length);
out.write(valueBytes);
out.flush();
}
} catch (IOException e) {
LOG.errorv(e, "Failed to append PUT WAL entry");
}
}
private void appendDelete(K key) {
DataOutputStream out = walWriter;
if (out == null) return;
try {
byte[] keyBytes = walMapper.writeValueAsBytes(key);
synchronized (out) {
out.writeByte(OP_DELETE);
out.writeInt(keyBytes.length);
out.write(keyBytes);
out.flush();
}
} catch (IOException e) {
LOG.errorv(e, "Failed to append DELETE WAL entry");
}
}
@SuppressWarnings("unchecked")
private int replayWal() {
int replayed = 0;
try (DataInputStream in = new DataInputStream(
new BufferedInputStream(Files.newInputStream(walPath)))) {
while (true) {
int op;
try {
op = in.readByte();
} catch (EOFException e) {
break;
}
int keyLen = in.readInt();
byte[] keyBytes = in.readNBytes(keyLen);
if (keyBytes.length < keyLen) break; // truncated entry
if (op == OP_PUT) {
int valueLen = in.readInt();
byte[] valueBytes = in.readNBytes(valueLen);
if (valueBytes.length < valueLen) break; // truncated entry
K key = (K) walMapper.readValue(keyBytes, Object.class);
V value = walMapper.readValue(valueBytes,
walMapper.constructType(typeReference.getType()).getContentType());
store.put(key, value);
replayed++;
} else if (op == OP_DELETE) {
K key = (K) walMapper.readValue(keyBytes, Object.class);
store.remove(key);
replayed++;
} else {
LOG.errorv("Unknown WAL op byte: {0}, stopping replay", op);
break;
}
}
} catch (IOException e) {
LOG.errorv(e, "Failed to replay WAL from {0} (replayed {1} entries before error)",
walPath, replayed);
}
return replayed;
}
private void openWalWriter() {
try {
Files.createDirectories(walPath.getParent());
walWriter = new DataOutputStream(
new BufferedOutputStream(Files.newOutputStream(walPath,
java.nio.file.StandardOpenOption.CREATE,
java.nio.file.StandardOpenOption.APPEND)));
} catch (IOException e) {
LOG.errorv(e, "Failed to open WAL writer at {0}", walPath);
}
}
private void closeWalWriter() {
if (walWriter != null) {
try {
walWriter.close();
} catch (IOException e) {
LOG.errorv(e, "Failed to close WAL writer");
}
walWriter = null;
}
}
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@ApplicationScoped
public class EmulatorLifecycle {
private static final Logger LOG = Logger.getLogger(EmulatorLifecycle.class);
private final StorageFactory storageFactory;
private final ServiceRegistry serviceRegistry;
private final EmulatorConfig config;
private final ElastiCacheProxyManager elastiCacheProxyManager;
private final RdsProxyManager rdsProxyManager;
private final RdsContainerManager rdsContainerManager;
@Inject
public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,
EmulatorConfig config, ElastiCacheProxyManager elastiCacheProxyManager,
RdsProxyManager rdsProxyManager, RdsContainerManager rdsContainerManager) {
this.storageFactory = storageFactory;
this.serviceRegistry = serviceRegistry;
this.config = config;
this.elastiCacheProxyManager = elastiCacheProxyManager;
this.rdsProxyManager = rdsProxyManager;
this.rdsContainerManager = rdsContainerManager;
}
void onStart(@Observes StartupEvent event) {
LOG.info("=== AWS Local Emulator Starting ===");
LOG.infov("Storage mode: {0}", config.storage().mode());
LOG.infov("Persistent path: {0}", config.storage().persistentPath());
serviceRegistry.logEnabledServices();
storageFactory.loadAll();
LOG.info("=== AWS Local Emulator Ready ===");
}
void onStop(@Observes ShutdownEvent event) {
LOG.info("=== AWS Local Emulator Shutting Down ===");
elastiCacheProxyManager.stopAll();
rdsProxyManager.stopAll();
storageFactory.shutdownAll();
LOG.info("=== AWS Local Emulator Stopped ===");
}
}
@@ -0,0 +1,993 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.apigateway.model.*;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Unified AWS API Gateway management endpoints (v1 REST and v2 HTTP).
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes({MediaType.APPLICATION_JSON, "application/json-patch+json"})
public class ApiGatewayController {
private static final Logger LOG = Logger.getLogger(ApiGatewayController.class);
private final ApiGatewayService service;
private final ApiGatewayV2Service v2Service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public ApiGatewayController(ApiGatewayService service, ApiGatewayV2Service v2Service,
RegionResolver regionResolver, ObjectMapper objectMapper) {
this.service = service;
this.v2Service = v2Service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
// ──────────────────────────── Specific v1 Paths (ORDER MATTERS) ────────────────────────────
@GET
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/responses/{statusCode}")
public Response getMethodResponse(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod,
@PathParam("statusCode") String statusCode) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toMethodResponseNode(service.getMethodResponse(region, apiId, resourceId, httpMethod, statusCode)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@PUT
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/responses/{statusCode}")
public Response putMethodResponse(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod,
@PathParam("statusCode") String statusCode,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
MethodResponse resp = service.putMethodResponse(region, apiId, resourceId, httpMethod, statusCode, request);
return Response.status(201).entity(toMethodResponseNode(resp).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{statusCode}")
public Response getIntegrationResponse(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod,
@PathParam("statusCode") String statusCode) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toIntegrationResponseNode(service.getIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@PUT
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{statusCode}")
public Response putIntegrationResponse(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod,
@PathParam("statusCode") String statusCode,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
IntegrationResponse ir = service.putIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode, request);
return Response.status(201).entity(toIntegrationResponseNode(ir).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis/{apiId}/authorizers/{authorizerId}")
public Response getAuthorizer(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("authorizerId") String authorizerId) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toAuthorizerNode(service.getAuthorizer(region, apiId, authorizerId)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis/{apiId}/authorizers")
public Response getAuthorizers(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
List<Authorizer> auths = service.getAuthorizers(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
auths.forEach(a -> items.add(toAuthorizerNode(a)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis/{apiId}/stages/{stageName}")
public Response getStage(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toStageNode(service.getStage(region, apiId, stageName)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis/{apiId}/stages")
public Response getStages(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
List<Stage> stages = service.getStages(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
stages.forEach(s -> items.add(toStageNode(s)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
// ──────────────────────────── General REST APIs (v1) ────────────────────────────
@POST
@Path("/restapis")
public Response createRestApi(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
RestApi api = service.createRestApi(region, request);
return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis")
public Response getRestApis(@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
List<RestApi> apis = service.getRestApis(region);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
apis.forEach(a -> items.add(toApiNode(a)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis/{apiId}")
public Response getRestApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toApiNode(service.getRestApi(region, apiId)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@PATCH
@Path("/restapis/{apiId}")
public Response updateRestApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
String region = regionResolver.resolveRegion(headers);
try {
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
@SuppressWarnings("unchecked")
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
RestApi api = service.updateRestApi(region, apiId, patchOperations);
return Response.ok(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/restapis/{apiId}")
public Response deleteRestApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
service.deleteRestApi(region, apiId);
return Response.accepted().build();
}
// ──────────────────────────── Resources (v1) ────────────────────────────
@GET
@Path("/restapis/{apiId}/resources")
public Response getResources(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
List<ApiGatewayResource> resources = service.getResources(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
resources.forEach(r -> items.add(toResourceNode(r)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis/{apiId}/resources/{resourceId}")
public Response getResource(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toResourceNode(service.getResource(region, apiId, resourceId))).build();
}
@PATCH
@Path("/restapis/{apiId}/resources/{resourceId}")
public Response updateResource(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
@SuppressWarnings("unchecked")
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
ApiGatewayResource resource = service.updateResource(region, apiId, resourceId, patchOperations);
return Response.ok(toResourceNode(resource).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@POST
@Path("/restapis/{apiId}/resources/{parentId}")
public Response createResource(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("parentId") String parentId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
ApiGatewayResource resource = service.createResource(region, apiId, parentId, request);
return Response.status(201).entity(toResourceNode(resource).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/restapis/{apiId}/resources/{resourceId}")
public Response deleteResource(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId) {
String region = regionResolver.resolveRegion(headers);
service.deleteResource(region, apiId, resourceId);
return Response.noContent().build();
}
// ──────────────────────────── Methods (v1) ────────────────────────────
@PUT
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}")
public Response putMethod(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
MethodConfig method = service.putMethod(region, apiId, resourceId, httpMethod, request);
return Response.status(201).entity(toMethodNode(method).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}")
public Response getMethod(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toMethodNode(service.getMethod(region, apiId, resourceId, httpMethod)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@PATCH
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}")
public Response updateMethod(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
@SuppressWarnings("unchecked")
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
MethodConfig method = service.updateMethod(region, apiId, resourceId, httpMethod, patchOperations);
return Response.ok(toMethodNode(method).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}")
public Response deleteMethod(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod) {
String region = regionResolver.resolveRegion(headers);
service.deleteMethod(region, apiId, resourceId, httpMethod);
return Response.accepted().build();
}
// ──────────────────────────── Integrations (v1) ────────────────────────────
@PUT
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration")
public Response putIntegration(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
io.github.hectorvent.floci.services.apigateway.model.Integration integration = service.putIntegration(region, apiId, resourceId, httpMethod, request);
return Response.status(201).entity(toIntegrationNode(integration).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration")
public Response getIntegration(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toIntegrationNode(service.getIntegration(region, apiId, resourceId, httpMethod)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@PATCH
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration")
public Response updateIntegration(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
@SuppressWarnings("unchecked")
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
io.github.hectorvent.floci.services.apigateway.model.Integration integration = service.updateIntegration(region, apiId, resourceId, httpMethod, patchOperations);
return Response.ok(toIntegrationNode(integration).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration")
public Response deleteIntegration(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("resourceId") String resourceId,
@PathParam("httpMethod") String httpMethod) {
String region = regionResolver.resolveRegion(headers);
service.deleteIntegration(region, apiId, resourceId, httpMethod);
return Response.noContent().build();
}
// ──────────────────────────── Deployments & Stages (v1) ────────────────────────────
@POST
@Path("/restapis/{apiId}/deployments")
public Response createDeployment(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
Deployment deployment = service.createDeployment(region, apiId, request);
return Response.status(201).entity(toDeploymentNode(deployment).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis/{apiId}/deployments")
public Response getDeployments(@Context HttpHeaders headers,
@PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
List<Deployment> deployments = service.getDeployments(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
deployments.forEach(d -> items.add(toDeploymentNode(d)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@POST
@Path("/restapis/{apiId}/stages")
public Response createStage(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
Stage stage = service.createStage(region, apiId, request);
return Response.status(201).entity(toStageNode(stage).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@PATCH
@Path("/restapis/{apiId}/stages/{stageName}")
public Response updateStage(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
@SuppressWarnings("unchecked")
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
Stage stage = service.updateStage(region, apiId, stageName, patchOperations);
return Response.ok(toStageNode(stage).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/restapis/{apiId}/stages/{stageName}")
public Response deleteStage(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName) {
String region = regionResolver.resolveRegion(headers);
service.deleteStage(region, apiId, stageName);
return Response.accepted().build();
}
// ──────────────────────────── Authorizers, API Keys, Usage Plans (v1) ────────────────────────────
@POST
@Path("/restapis/{apiId}/authorizers")
public Response createAuthorizer(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
Authorizer auth = service.createAuthorizer(region, apiId, request);
return Response.status(201).entity(toAuthorizerNode(auth).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@POST
@Path("/apikeys")
public Response createApiKey(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
ApiKey key = service.createApiKey(region, request);
return Response.status(201).entity(toApiKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/apikeys")
public Response getApiKeys(@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
List<ApiKey> keys = service.getApiKeys(region);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
keys.forEach(k -> items.add(toApiKeyNode(k)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@POST
@Path("/usageplans")
public Response createUsagePlan(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
UsagePlan plan = service.createUsagePlan(region, request);
return Response.status(201).entity(toUsagePlanNode(plan).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/usageplans")
public Response getUsagePlans(@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
List<UsagePlan> plans = service.getUsagePlans(region);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
plans.forEach(p -> items.add(toUsagePlanNode(p)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/usageplans/{usagePlanId}")
public Response deleteUsagePlan(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId) {
String region = regionResolver.resolveRegion(headers);
service.deleteUsagePlan(region, usagePlanId);
return Response.accepted().build();
}
@POST
@Path("/usageplans/{usagePlanId}/keys")
public Response createUsagePlanKey(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
UsagePlanKey key = service.createUsagePlanKey(region, usagePlanId, request);
return Response.status(201).entity(toUsagePlanKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/usageplans/{usagePlanId}/keys")
public Response getUsagePlanKeys(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId) {
String region = regionResolver.resolveRegion(headers);
List<UsagePlanKey> keys = service.getUsagePlanKeys(region, usagePlanId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
keys.forEach(k -> items.add(toUsagePlanKeyNode(k)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/usageplans/{usagePlanId}/keys/{keyId}")
public Response getUsagePlanKey(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId, @PathParam("keyId") String keyId) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toUsagePlanKeyNode(service.getUsagePlanKey(region, usagePlanId, keyId)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/usageplans/{usagePlanId}/keys/{keyId}")
public Response deleteUsagePlanKey(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId, @PathParam("keyId") String keyId) {
String region = regionResolver.resolveRegion(headers);
service.deleteUsagePlanKey(region, usagePlanId, keyId);
return Response.accepted().build();
}
// ──────────────────────────── Request Validators (v1) ────────────────────────────
@POST
@Path("/restapis/{apiId}/requestvalidators")
public Response createRequestValidator(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
RequestValidator validator = service.createRequestValidator(region, apiId, request);
return Response.status(201).entity(toRequestValidatorNode(validator).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis/{apiId}/requestvalidators")
public Response getRequestValidators(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
List<RequestValidator> validators = service.getRequestValidators(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
validators.forEach(v -> items.add(toRequestValidatorNode(v)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis/{apiId}/requestvalidators/{validatorId}")
public Response getRequestValidator(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("validatorId") String validatorId) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toRequestValidatorNode(service.getRequestValidator(region, apiId, validatorId)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/restapis/{apiId}/requestvalidators/{validatorId}")
public Response deleteRequestValidator(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("validatorId") String validatorId) {
String region = regionResolver.resolveRegion(headers);
service.deleteRequestValidator(region, apiId, validatorId);
return Response.accepted().build();
}
// ──────────────────────────── Custom Domains (v1) ────────────────────────────
@POST
@Path("/domainnames")
public Response createDomainName(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
CustomDomain domain = service.createDomainName(region, request);
return Response.status(201).entity(toDomainNode(domain).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/domainnames")
public Response getDomainNames(@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
List<CustomDomain> domains = service.getDomainNames(region);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
domains.forEach(d -> items.add(toDomainNode(d)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/domainnames/{domainName}")
public Response getDomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toDomainNode(service.getDomainName(region, domainName)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/domainnames/{domainName}")
public Response deleteDomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) {
String region = regionResolver.resolveRegion(headers);
service.deleteDomainName(region, domainName);
return Response.accepted().build();
}
// ──────────────────────────── Base Path Mappings (v1) ────────────────────────────
@POST
@Path("/domainnames/{domainName}/basepathmappings")
public Response createBasePathMapping(@Context HttpHeaders headers, @PathParam("domainName") String domainName, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
BasePathMapping mapping = service.createBasePathMapping(region, domainName, request);
return Response.status(201).entity(toMappingNode(mapping).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/domainnames/{domainName}/basepathmappings")
public Response getBasePathMappings(@Context HttpHeaders headers, @PathParam("domainName") String domainName) {
String region = regionResolver.resolveRegion(headers);
List<BasePathMapping> mappings = service.getBasePathMappings(region, domainName);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
mappings.forEach(m -> items.add(toMappingNode(m)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/domainnames/{domainName}/basepathmappings/{basePath}")
public Response getBasePathMapping(@Context HttpHeaders headers, @PathParam("domainName") String domainName, @PathParam("basePath") String basePath) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toMappingNode(service.getBasePathMapping(region, domainName, basePath)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/domainnames/{domainName}/basepathmappings/{basePath}")
public Response deleteBasePathMapping(@Context HttpHeaders headers, @PathParam("domainName") String domainName, @PathParam("basePath") String basePath) {
String region = regionResolver.resolveRegion(headers);
service.deleteBasePathMapping(region, domainName, basePath);
return Response.accepted().build();
}
// ──────────────────────────── HTTP APIs (v2) ────────────────────────────
@POST
@Path("/v2/apis")
public Response createApi(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
Api api = v2Service.createApi(region, request);
return Response.status(201).entity(toV2ApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/v2/apis")
public Response getApis(@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
List<Api> apis = v2Service.getApis(region);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("items");
apis.forEach(a -> items.add(toV2ApiNode(a)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/v2/apis/{apiId}")
public Response getApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toV2ApiNode(v2Service.getApi(region, apiId)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/v2/apis/{apiId}")
public Response deleteApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
v2Service.deleteApi(region, apiId);
return Response.noContent().build();
}
@POST
@Path("/v2/apis/{apiId}/routes")
public Response createRoute(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
Route route = v2Service.createRoute(region, apiId, request);
return Response.status(201).entity(toV2RouteNode(route).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/v2/apis/{apiId}/routes")
public Response getRoutes(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
List<Route> routes = v2Service.getRoutes(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("items");
routes.forEach(r -> items.add(toV2RouteNode(r)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@POST
@Path("/v2/apis/{apiId}/integrations")
public Response createIntegration(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
Integration integration = v2Service.createIntegration(region, apiId, request);
return Response.status(201).entity(toV2IntegrationNode(integration).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/v2/apis/{apiId}/integrations")
public Response getIntegrations(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
List<Integration> integrations = v2Service.getIntegrations(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("items");
integrations.forEach(i -> items.add(toV2IntegrationNode(i)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
// ──────────────────────────── Tags ────────────────────────────
@GET
@Path("/tags/{arn: .*}")
public Response getTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {
String region = regionResolver.resolveRegion(headers);
String apiId = apiIdFromArn(arn);
Map<String, String> tags = service.getTags(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ObjectNode tagsNode = root.putObject("tags");
tags.forEach(tagsNode::put);
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
// ──────────────────────────── Helpers ────────────────────────────
private ObjectNode toApiNode(RestApi api) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", api.getId());
node.put("name", api.getName());
if (api.getDescription() != null) node.put("description", api.getDescription());
node.put("createdDate", api.getCreatedDate());
return node;
}
private ObjectNode toResourceNode(ApiGatewayResource r) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", r.getId());
if (r.getParentId() != null) node.put("parentId", r.getParentId());
if (r.getPathPart() != null) node.put("pathPart", r.getPathPart());
node.put("path", r.getPath());
return node;
}
private ObjectNode toMethodNode(MethodConfig m) {
ObjectNode node = objectMapper.createObjectNode();
node.put("httpMethod", m.getHttpMethod());
node.put("authorizationType", m.getAuthorizationType());
if (m.getAuthorizerId() != null) node.put("authorizerId", m.getAuthorizerId());
if (m.getMethodIntegration() != null) {
node.set("methodIntegration", toIntegrationNode(m.getMethodIntegration()));
}
return node;
}
private ObjectNode toMethodResponseNode(MethodResponse r) {
ObjectNode node = objectMapper.createObjectNode();
node.put("statusCode", r.statusCode());
return node;
}
private ObjectNode toIntegrationNode(io.github.hectorvent.floci.services.apigateway.model.Integration i) {
ObjectNode node = objectMapper.createObjectNode();
node.put("type", i.getType());
node.put("httpMethod", i.getHttpMethod());
node.put("uri", i.getUri());
return node;
}
private ObjectNode toIntegrationResponseNode(IntegrationResponse r) {
ObjectNode node = objectMapper.createObjectNode();
node.put("statusCode", r.statusCode());
node.put("selectionPattern", r.selectionPattern());
return node;
}
private ObjectNode toDeploymentNode(Deployment d) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", d.id());
if (d.description() != null) node.put("description", d.description());
node.put("createdDate", d.createdDate());
return node;
}
private ObjectNode toStageNode(Stage s) {
ObjectNode node = objectMapper.createObjectNode();
node.put("stageName", s.getStageName());
node.put("deploymentId", s.getDeploymentId());
if (s.getDescription() != null) node.put("description", s.getDescription());
node.put("createdDate", s.getCreatedDate());
node.put("lastUpdatedDate", s.getLastUpdatedDate());
if (!s.getVariables().isEmpty()) {
ObjectNode vars = node.putObject("variables");
s.getVariables().forEach(vars::put);
}
return node;
}
private ObjectNode toAuthorizerNode(Authorizer a) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", a.getId());
node.put("name", a.getName());
node.put("type", a.getType());
if (a.getAuthorizerUri() != null) node.put("authorizerUri", a.getAuthorizerUri());
if (a.getIdentitySource() != null) node.put("identitySource", a.getIdentitySource());
node.put("authorizerResultTtlInSeconds", Integer.parseInt(a.getAuthorizerResultTtlInSeconds()));
return node;
}
private ObjectNode toApiKeyNode(ApiKey k) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", k.getId());
node.put("name", k.getName());
node.put("value", k.getValue());
node.put("enabled", k.isEnabled());
return node;
}
private ObjectNode toUsagePlanNode(UsagePlan p) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", p.getId());
node.put("name", p.getName());
return node;
}
private ObjectNode toUsagePlanKeyNode(UsagePlanKey k) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", k.getId());
node.put("name", k.getName());
node.put("type", k.getType());
node.put("value", k.getValue());
return node;
}
private ObjectNode toDomainNode(CustomDomain d) {
ObjectNode node = objectMapper.createObjectNode();
node.put("domainName", d.getDomainName());
node.put("domainNameStatus", d.getDomainNameStatus());
node.put("endpointConfigurationType", d.getEndpointConfigurationType());
if (d.getCertificateName() != null) node.put("certificateName", d.getCertificateName());
if (d.getCertificateArn() != null) node.put("certificateArn", d.getCertificateArn());
node.put("regionalDomainName", d.getRegionalDomainName());
node.put("regionalHostedZoneId", d.getRegionalHostedZoneId());
return node;
}
private ObjectNode toMappingNode(BasePathMapping m) {
ObjectNode node = objectMapper.createObjectNode();
node.put("basePath", m.getBasePath());
node.put("restApiId", m.getRestApiId());
node.put("stage", m.getStage());
return node;
}
private ObjectNode toRequestValidatorNode(RequestValidator v) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", v.getId());
node.put("name", v.getName());
node.put("validateRequestBody", v.isValidateRequestBody());
node.put("validateRequestParameters", v.isValidateRequestParameters());
return node;
}
private ObjectNode toV2ApiNode(Api api) {
ObjectNode node = objectMapper.createObjectNode();
node.put("apiId", api.getApiId());
node.put("name", api.getName());
node.put("protocolType", api.getProtocolType());
node.put("apiEndpoint", api.getApiEndpoint());
node.put("createdDate", java.time.Instant.ofEpochMilli(api.getCreatedDate()).toString());
return node;
}
private ObjectNode toV2RouteNode(Route r) {
ObjectNode node = objectMapper.createObjectNode();
node.put("routeId", r.getRouteId());
node.put("routeKey", r.getRouteKey());
node.put("authorizationType", r.getAuthorizationType());
if (r.getTarget() != null) node.put("target", r.getTarget());
return node;
}
private ObjectNode toV2IntegrationNode(Integration i) {
ObjectNode node = objectMapper.createObjectNode();
node.put("integrationId", i.getIntegrationId());
node.put("integrationType", i.getIntegrationType());
node.put("payloadFormatVersion", i.getPayloadFormatVersion());
if (i.getIntegrationUri() != null) node.put("integrationUri", i.getIntegrationUri());
return node;
}
private String apiIdFromArn(String arn) {
String[] parts = arn.split("/restapis/");
if (parts.length < 2) return arn;
return parts[1].split("/")[0];
}
}
@@ -0,0 +1,645 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
import io.github.hectorvent.floci.services.apigateway.model.Integration;
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Executes API Gateway stage requests, routing them through the configured
* integration (AWS_PROXY or MOCK).
*
* <p>Endpoint: {@code /{apiId}/{stageName}/{proxy+}}
*
* <p>This mirrors the real AWS execute-api URL format:
* {@code https://{apiId}.execute-api.{region}.amazonaws.com/{stageName}/{path}}
*/
@Path("/execute-api/{apiId}/{stageName}")
@Produces(MediaType.WILDCARD)
public class ApiGatewayExecuteController {
private static final Logger LOG = Logger.getLogger(ApiGatewayExecuteController.class);
private final ApiGatewayService apiGatewayService;
private final ApiGatewayV2Service apiGatewayV2Service;
private final LambdaService lambdaService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
LambdaService lambdaService, RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.apiGatewayService = apiGatewayService;
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaService = lambdaService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@GET
@Path("/{proxy: .*}")
public Response handleGet(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
return dispatch("GET", apiId, stageName, proxy, headers, uriInfo, null);
}
@POST
@Path("/{proxy: .*}")
public Response handlePost(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy,
byte[] body) {
return dispatch("POST", apiId, stageName, proxy, headers, uriInfo, body);
}
@PUT
@Path("/{proxy: .*}")
public Response handlePut(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy,
byte[] body) {
return dispatch("PUT", apiId, stageName, proxy, headers, uriInfo, body);
}
@DELETE
@Path("/{proxy: .*}")
public Response handleDelete(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
return dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, null);
}
@PATCH
@Path("/{proxy: .*}")
public Response handlePatch(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy,
byte[] body) {
return dispatch("PATCH", apiId, stageName, proxy, headers, uriInfo, body);
}
// ──────────────────────────── Core dispatch ────────────────────────────
private Response dispatch(String httpMethod, String apiId, String stageName,
String proxy, HttpHeaders headers, UriInfo uriInfo, byte[] body) {
String region = regionResolver.resolveRegion(headers);
// Check if this is a v2 (HTTP API) or v1 (REST API)
boolean isV2 = false;
try {
apiGatewayV2Service.getApi(region, apiId);
isV2 = true;
} catch (AwsException ignored) {
// Not a v2 API — fall through to v1 handling
}
if (isV2) {
return dispatchV2(httpMethod, apiId, stageName, proxy, headers, uriInfo, body, region);
}
// Verify API and stage exist
try {
apiGatewayService.getRestApi(region, apiId);
apiGatewayService.getStage(region, apiId, stageName);
} catch (AwsException e) {
return Response.status(e.getHttpStatus())
.entity(jsonMessage(e.getMessage()))
.type(MediaType.APPLICATION_JSON).build();
}
String path = "/" + (proxy == null ? "" : proxy);
// Find matching resource and method
List<ApiGatewayResource> resources = apiGatewayService.getResources(region, apiId);
ApiGatewayResource matched = matchResource(resources, path);
if (matched == null) {
return Response.status(404)
.entity(jsonMessage("Not Found"))
.type(MediaType.APPLICATION_JSON).build();
}
MethodConfig method = matched.getResourceMethods().get(httpMethod.toUpperCase());
if (method == null) {
return Response.status(405)
.entity(jsonMessage("Method Not Allowed"))
.type(MediaType.APPLICATION_JSON).build();
}
// 1. Authorizer
Response authResponse = invokeAuthorizer(region, apiId, method, headers, uriInfo);
if (authResponse != null) return authResponse;
Integration integration = method.getMethodIntegration();
if (integration == null) {
return Response.status(500)
.entity(jsonMessage("No integration configured"))
.type(MediaType.APPLICATION_JSON).build();
}
LOG.debugv("execute-api: {0} {1}/{2}{3} → {4}", httpMethod, apiId, stageName, path,
integration.getType());
return switch (integration.getType().toUpperCase()) {
case "AWS_PROXY" -> invokeProxy(region, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body);
case "MOCK" -> invokeMock(integration);
default -> Response.status(500)
.entity(jsonMessage("Unsupported integration type: " + integration.getType()))
.type(MediaType.APPLICATION_JSON).build();
};
}
// ──────────────────────────── AWS_PROXY ────────────────────────────
private Response invokeProxy(String region, String httpMethod, String path, String proxy,
String stageName, ApiGatewayResource resource,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body) {
String functionName = functionNameFromUri(integration.getUri());
if (functionName == null) {
return Response.status(500)
.entity(jsonMessage("Cannot resolve function from URI: " + integration.getUri()))
.type(MediaType.APPLICATION_JSON).build();
}
String requestId = UUID.randomUUID().toString();
String eventJson = buildProxyEvent(httpMethod, path, proxy, resource.getPath(),
stageName, headers, uriInfo, body, requestId);
try {
InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(),
InvocationType.RequestResponse);
return buildProxyResponse(result);
} catch (AwsException e) {
if (e.getHttpStatus() == 404) {
return Response.status(404)
.entity(jsonMessage("Function not found: " + functionName))
.type(MediaType.APPLICATION_JSON).build();
}
throw e;
}
}
private Response invokeAuthorizer(String region, String apiId, MethodConfig method,
HttpHeaders headers, UriInfo uriInfo) {
if ("CUSTOM".equals(method.getAuthorizationType())) {
String authorizerId = method.getAuthorizerId();
if (authorizerId == null) {
return null;
}
io.github.hectorvent.floci.services.apigateway.model.Authorizer auth = apiGatewayService.getAuthorizer(region, apiId, authorizerId);
String lambdaName = functionNameFromUri(auth.getAuthorizerUri());
if (lambdaName == null) {
return null;
}
String event = toAuthorizerEvent(auth, headers);
try {
InvokeResult result = lambdaService.invoke(region, lambdaName, event.getBytes(), InvocationType.RequestResponse);
if (result.getFunctionError() != null) {
return Response.status(403).build();
}
JsonNode policy = objectMapper.readTree(result.getPayload());
String effect = policy.path("policyDocument").path("Statement").get(0).path("Effect").asText("Deny");
if ("Deny".equalsIgnoreCase(effect)) {
return Response.status(403).entity(jsonMessage("User is not authorized to access this resource")).build();
}
} catch (Exception e) {
LOG.warnv("Authorizer failure: {0}", e.getMessage());
return Response.status(500).build();
}
}
return null;
}
private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth, HttpHeaders headers) {
ObjectNode node = objectMapper.createObjectNode();
node.put("type", auth.getType());
node.put("methodArn", "arn:aws:execute-api:" + regionResolver.getDefaultRegion()
+ ":" + regionResolver.getAccountId() + ":api/stage/METHOD/path");
if ("TOKEN".equals(auth.getType())) {
String headerName = auth.getIdentitySource().replace("method.request.header.", "");
node.put("authorizationToken", headers.getHeaderString(headerName));
}
return node.toString();
}
/**
* Extracts function name from integration URI like
* {@code arn:aws:apigateway:...:lambda:path/2015-03-31/functions/{fnArn}/invocations}.
*/
private String functionNameFromUri(String uri) {
if (uri == null) {
return null;
}
// URI contains "function:{name}" or "function:{arn}"
int idx = uri.indexOf("function:");
if (idx < 0) {
return null;
}
String after = uri.substring(idx + "function:".length());
// after may be "myFn/invocations" or "arn:aws:lambda:...:function:myFn/invocations"
// If it starts with "arn:" recurse on the remaining ARN
if (after.startsWith("arn:")) {
int fnIdx = after.lastIndexOf(":function:");
if (fnIdx < 0) {
return null;
}
after = after.substring(fnIdx + ":function:".length());
}
// Strip trailing "/invocations" or any path suffix
int slash = after.indexOf('/');
return slash >= 0 ? after.substring(0, slash) : after;
}
private String buildProxyEvent(String httpMethod, String path, String proxy,
String resourcePath, String stageName,
HttpHeaders headers, UriInfo uriInfo,
byte[] body, String requestId) {
ObjectNode event = objectMapper.createObjectNode();
event.put("resource", resourcePath);
event.put("path", path);
event.put("httpMethod", httpMethod);
ObjectNode headersNode = event.putObject("headers");
MultivaluedMap<String, String> reqHeaders = headers.getRequestHeaders();
for (Map.Entry<String, java.util.List<String>> e : reqHeaders.entrySet()) {
if (!e.getValue().isEmpty()) headersNode.put(e.getKey(), e.getValue().get(0));
}
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
if (!queryParams.isEmpty()) {
ObjectNode qsp = event.putObject("queryStringParameters");
for (Map.Entry<String, java.util.List<String>> e : queryParams.entrySet()) {
if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0));
}
} else {
event.putNull("queryStringParameters");
}
ObjectNode pathParams = event.putObject("pathParameters");
if (proxy != null && !proxy.isEmpty()) pathParams.put("proxy", proxy);
event.putNull("stageVariables");
ObjectNode ctx = event.putObject("requestContext");
ctx.put("resourcePath", resourcePath);
ctx.put("httpMethod", httpMethod);
ctx.put("stage", stageName);
ctx.put("requestId", requestId);
ctx.put("requestTimeEpoch", System.currentTimeMillis());
ctx.putObject("identity").put("sourceIp", "127.0.0.1");
if (body != null && body.length > 0) {
event.put("body", new String(body));
event.put("isBase64Encoded", false);
} else {
event.putNull("body");
event.put("isBase64Encoded", false);
}
try {
return objectMapper.writeValueAsString(event);
} catch (Exception e) {
throw new RuntimeException("Failed to serialize proxy event", e);
}
}
private Response buildProxyResponse(InvokeResult result) {
if (result.getPayload() == null || result.getPayload().length == 0) {
return Response.status(result.getFunctionError() != null ? 502 : result.getStatusCode()).build();
}
try {
JsonNode node = objectMapper.readTree(result.getPayload());
int statusCode = node.path("statusCode").asInt(200);
if (result.getFunctionError() != null && !node.has("statusCode")) statusCode = 502;
Response.ResponseBuilder builder = Response.status(statusCode);
JsonNode respHeaders = node.get("headers");
if (respHeaders != null && respHeaders.isObject()) {
respHeaders.fields().forEachRemaining(e -> builder.header(e.getKey(), e.getValue().asText()));
}
JsonNode multiHeaders = node.get("multiValueHeaders");
if (multiHeaders != null && multiHeaders.isObject()) {
multiHeaders.fields().forEachRemaining(e -> {
if (e.getValue().isArray()) e.getValue().forEach(v -> builder.header(e.getKey(), v.asText()));
});
}
JsonNode bodyNode = node.get("body");
if (bodyNode != null && !bodyNode.isNull()) {
String bodyStr = bodyNode.asText();
boolean isBase64 = node.path("isBase64Encoded").asBoolean(false);
byte[] bytes = isBase64 ? Base64.getDecoder().decode(bodyStr) : bodyStr.getBytes();
String ct = MediaType.APPLICATION_JSON;
JsonNode ctNode = node.path("headers").path("Content-Type");
if (!ctNode.isMissingNode() && !ctNode.isNull()) ct = ctNode.asText();
builder.entity(bytes).type(ct);
}
return builder.build();
} catch (Exception e) {
LOG.warnv("Failed to parse Lambda response: {0}", e.getMessage());
return Response.status(502).entity(result.getPayload()).type(MediaType.APPLICATION_JSON).build();
}
}
// ──────────────────────────── MOCK ────────────────────────────
private Response invokeMock(Integration integration) {
// Use the "200" integration response if present, else return empty 200
IntegrationResponse ir = integration.getIntegrationResponses().get("200");
if (ir == null) {
return Response.ok().build();
}
String template = ir.responseTemplates() != null
? ir.responseTemplates().getOrDefault("application/json", "") : "";
return Response.status(Integer.parseInt(ir.statusCode()))
.entity(template)
.type(MediaType.APPLICATION_JSON)
.build();
}
// ──────────────────────────── API Gateway v2 dispatch ────────────────────────────
private Response dispatchV2(String httpMethod, String apiId, String stageName,
String proxy, HttpHeaders headers, UriInfo uriInfo,
byte[] body, String region) {
String path = "/" + (proxy == null ? "" : proxy);
Route route = apiGatewayV2Service.findMatchingRoute(region, apiId, httpMethod, path);
if (route == null) {
return Response.status(404)
.entity(jsonMessage("Not Found"))
.type(MediaType.APPLICATION_JSON).build();
}
if ("JWT".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
Response authError = enforceJwtAuthorizer(region, apiId, route, headers);
if (authError != null) return authError;
}
if (route.getTarget() == null) {
return Response.status(500)
.entity(jsonMessage("No integration configured"))
.type(MediaType.APPLICATION_JSON).build();
}
// target is "integrations/{integrationId}"
String integrationId = route.getTarget().startsWith("integrations/")
? route.getTarget().substring("integrations/".length()) : route.getTarget();
io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration;
try {
integration = apiGatewayV2Service.getIntegration(region, apiId, integrationId);
} catch (AwsException e) {
return Response.status(500)
.entity(jsonMessage("Integration not found: " + integrationId))
.type(MediaType.APPLICATION_JSON).build();
}
String functionName = functionNameFromUri(integration.getIntegrationUri());
if (functionName == null) {
return Response.status(500)
.entity(jsonMessage("Cannot resolve function from URI: " + integration.getIntegrationUri()))
.type(MediaType.APPLICATION_JSON).build();
}
String requestId = UUID.randomUUID().toString();
String eventJson = buildV2ProxyEvent(httpMethod, path, route.getRouteKey(),
apiId, stageName, headers, uriInfo, body, requestId);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName);
try {
InvokeResult result = lambdaService.invoke(region, functionName,
eventJson.getBytes(), InvocationType.RequestResponse);
return buildProxyResponse(result);
} catch (AwsException e) {
if (e.getHttpStatus() == 404) {
return Response.status(404)
.entity(jsonMessage("Function not found: " + functionName))
.type(MediaType.APPLICATION_JSON).build();
}
throw e;
}
}
private Response enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers) {
Authorizer authorizer;
try {
authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, route.getAuthorizerId());
} catch (AwsException e) {
return Response.status(500)
.entity(jsonMessage("Authorizer not found"))
.type(MediaType.APPLICATION_JSON).build();
}
String token = extractToken(authorizer, headers);
if (token == null) {
return Response.status(401)
.entity(jsonMessage("Unauthorized"))
.type(MediaType.APPLICATION_JSON).build();
}
JwtClaims claims = parseJwtClaims(token);
if (claims == null) {
return Response.status(401)
.entity(jsonMessage("Unauthorized"))
.type(MediaType.APPLICATION_JSON).build();
}
if (claims.exp > 0 && claims.exp < System.currentTimeMillis() / 1000) {
return Response.status(401)
.entity(jsonMessage("The incoming token has expired"))
.type(MediaType.APPLICATION_JSON).build();
}
if (authorizer.getJwtConfiguration() != null) {
String issuer = authorizer.getJwtConfiguration().issuer();
if (issuer != null && !issuer.isBlank() && !issuer.equals(claims.iss)) {
return Response.status(401)
.entity(jsonMessage("Unauthorized"))
.type(MediaType.APPLICATION_JSON).build();
}
List<String> audiences = authorizer.getJwtConfiguration().audience();
if (audiences != null && !audiences.isEmpty()) {
boolean audMatch = audiences.stream().anyMatch(a -> a.equals(claims.aud));
if (!audMatch) {
return Response.status(401)
.entity(jsonMessage("Unauthorized"))
.type(MediaType.APPLICATION_JSON).build();
}
}
}
return null; // authorized
}
private String extractToken(Authorizer authorizer, HttpHeaders headers) {
List<String> sources = authorizer.getIdentitySource();
if (sources == null || sources.isEmpty()) {
// Default: Authorization header
String raw = headers.getHeaderString("Authorization");
return stripBearer(raw);
}
for (String source : sources) {
if (source.startsWith("$request.header.")) {
String headerName = source.substring("$request.header.".length());
String value = headers.getHeaderString(headerName);
if (value != null) return stripBearer(value);
}
}
return null;
}
private String stripBearer(String value) {
if (value == null) return null;
if (value.startsWith("Bearer ")) return value.substring(7);
return value;
}
private record JwtClaims(String iss, String aud, long exp) {}
private JwtClaims parseJwtClaims(String token) {
try {
String[] parts = token.split("\\.");
if (parts.length < 2) return null;
byte[] payloadBytes = Base64.getUrlDecoder().decode(padBase64(parts[1]));
String payload = new String(payloadBytes, StandardCharsets.UTF_8);
JsonNode claims = objectMapper.readTree(payload);
String iss = claims.path("iss").asText(null);
String aud = claims.path("aud").asText(null);
long exp = claims.path("exp").asLong(0);
return new JwtClaims(iss, aud, exp);
} catch (Exception e) {
LOG.debugv("JWT parse error: {0}", e.getMessage());
return null;
}
}
private static String padBase64(String base64) {
return switch (base64.length() % 4) {
case 2 -> base64 + "==";
case 3 -> base64 + "=";
default -> base64;
};
}
private String buildV2ProxyEvent(String httpMethod, String path, String routeKey,
String apiId, String stageName,
HttpHeaders headers, UriInfo uriInfo,
byte[] body, String requestId) {
ObjectNode event = objectMapper.createObjectNode();
event.put("version", "2.0");
event.put("routeKey", routeKey != null ? routeKey : "$default");
event.put("rawPath", path);
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
event.put("rawQueryString", uriInfo.getRequestUri().getRawQuery() != null
? uriInfo.getRequestUri().getRawQuery() : "");
ObjectNode headersNode = event.putObject("headers");
for (Map.Entry<String, java.util.List<String>> e : headers.getRequestHeaders().entrySet()) {
if (!e.getValue().isEmpty()) headersNode.put(e.getKey().toLowerCase(), e.getValue().get(0));
}
if (!queryParams.isEmpty()) {
ObjectNode qsp = event.putObject("queryStringParameters");
for (Map.Entry<String, java.util.List<String>> e : queryParams.entrySet()) {
if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0));
}
}
ObjectNode ctx = event.putObject("requestContext");
ctx.put("accountId", "000000000000");
ctx.put("apiId", apiId);
ctx.put("domainName", apiId + ".execute-api.us-east-1.amazonaws.com");
ctx.put("domainPrefix", apiId);
ctx.put("requestId", requestId);
ctx.put("routeKey", routeKey != null ? routeKey : "$default");
ctx.put("stage", stageName);
ctx.put("time", java.time.format.DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
.format(java.time.ZonedDateTime.now()));
ctx.put("timeEpoch", System.currentTimeMillis());
ObjectNode http = ctx.putObject("http");
http.put("method", httpMethod);
http.put("path", path);
http.put("protocol", "HTTP/1.1");
http.put("sourceIp", "127.0.0.1");
http.put("userAgent", headers.getHeaderString("User-Agent") != null
? headers.getHeaderString("User-Agent") : "");
if (body != null && body.length > 0) {
event.put("body", new String(body));
event.put("isBase64Encoded", false);
} else {
event.putNull("body");
event.put("isBase64Encoded", false);
}
try {
return objectMapper.writeValueAsString(event);
} catch (Exception e) {
throw new RuntimeException("Failed to serialize v2 proxy event", e);
}
}
private String jsonMessage(String message) {
return objectMapper.createObjectNode().put("message", message).toString();
}
// ──────────────────────────── Path matching ────────────────────────────
/**
* Finds the best-matching resource for {@code requestPath}.
* Priority: exact match > wildcard/proxy+ match.
*/
private ApiGatewayResource matchResource(List<ApiGatewayResource> resources, String requestPath) {
// 1. Exact match
for (ApiGatewayResource r : resources) {
if (requestPath.equals(r.getPath())) {
return r;
}
}
// 2. Wildcard / {proxy+} — any resource whose pathPart contains "{"
for (ApiGatewayResource r : resources) {
if (r.getPathPart() != null && r.getPathPart().contains("{")) {
return r;
}
}
return null;
}
}
@@ -0,0 +1,737 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@ApplicationScoped
public class ApiGatewayService {
private static final Logger LOG = Logger.getLogger(ApiGatewayService.class);
private final StorageBackend<String, RestApi> apiStore;
private final StorageBackend<String, ApiGatewayResource> resourceStore;
private final StorageBackend<String, Deployment> deploymentStore;
private final StorageBackend<String, Stage> stageStore;
private final StorageBackend<String, Authorizer> authorizerStore;
private final StorageBackend<String, ApiKey> apiKeyStore;
private final StorageBackend<String, UsagePlan> usagePlanStore;
private final StorageBackend<String, UsagePlanKey> usagePlanKeyStore;
private final StorageBackend<String, RequestValidator> requestValidatorStore;
private final StorageBackend<String, CustomDomain> domainStore;
private final StorageBackend<String, BasePathMapping> basePathMappingStore;
private final RegionResolver regionResolver;
@Inject
public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
this.apiStore = storageFactory.create("apigateway", "apigateway-apis.json",
new TypeReference<>() {
});
this.resourceStore = storageFactory.create("apigateway", "apigateway-resources.json",
new TypeReference<>() {
});
this.deploymentStore = storageFactory.create("apigateway", "apigateway-deployments.json",
new TypeReference<>() {
});
this.stageStore = storageFactory.create("apigateway", "apigateway-stages.json",
new TypeReference<>() {
});
this.authorizerStore = storageFactory.create("apigateway", "apigateway-authorizers.json",
new TypeReference<>() {
});
this.apiKeyStore = storageFactory.create("apigateway", "apigateway-apikeys.json",
new TypeReference<>() {
});
this.usagePlanStore = storageFactory.create("apigateway", "apigateway-usageplans.json",
new TypeReference<>() {
});
this.usagePlanKeyStore = storageFactory.create("apigateway", "apigateway-usageplankeys.json",
new TypeReference<>() {
});
this.requestValidatorStore = storageFactory.create("apigateway", "apigateway-validators.json",
new TypeReference<>() {
});
this.domainStore = storageFactory.create("apigateway", "apigateway-domains.json",
new TypeReference<>() {
});
this.basePathMappingStore = storageFactory.create("apigateway", "apigateway-mappings.json",
new TypeReference<>() {
});
this.regionResolver = regionResolver;
}
// ──────────────────────────── REST API CRUD ────────────────────────────
public RestApi createRestApi(String region, Map<String, Object> request) {
String name = (String) request.get("name");
String description = (String) request.get("description");
RestApi api = new RestApi();
api.setId(shortId(10));
api.setName(name);
api.setDescription(description);
api.setCreatedDate(System.currentTimeMillis() / 1000L);
apiStore.put(apiKey(region, api.getId()), api);
// Create root resource "/"
ApiGatewayResource root = new ApiGatewayResource();
root.setId(shortId(8));
root.setPath("/");
resourceStore.put(resourceKey(region, api.getId(), root.getId()), root);
LOG.infov("Created REST API: {0} ({1}) in {2}", name, api.getId(), region);
return api;
}
public RestApi getRestApi(String region, String apiId) {
return apiStore.get(apiKey(region, apiId))
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404));
}
public List<RestApi> getRestApis(String region) {
String prefix = region + "::";
return apiStore.scan(k -> k.startsWith(prefix));
}
public void deleteRestApi(String region, String apiId) {
getRestApi(region, apiId);
apiStore.delete(apiKey(region, apiId));
// Simple cascade: delete resources for this API
String prefix = region + "::" + apiId + "::";
resourceStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(resourceStore::delete);
deploymentStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(deploymentStore::delete);
stageStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(stageStore::delete);
LOG.infov("Deleted REST API: {0} in {1}", apiId, region);
}
// ──────────────────────────── Resource CRUD ────────────────────────────
public List<ApiGatewayResource> getResources(String region, String apiId) {
getRestApi(region, apiId);
String prefix = region + "::" + apiId + "::";
return resourceStore.scan(k -> k.startsWith(prefix));
}
public ApiGatewayResource getResource(String region, String apiId, String resourceId) {
return resourceStore.get(resourceKey(region, apiId, resourceId))
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid resource id specified", 404));
}
public ApiGatewayResource createResource(String region, String apiId, String parentId, Map<String, Object> request) {
getRestApi(region, apiId);
ApiGatewayResource parent = getResource(region, apiId, parentId);
String pathPart = (String) request.get("pathPart");
ApiGatewayResource resource = new ApiGatewayResource();
resource.setId(shortId(8));
resource.setParentId(parentId);
resource.setPathPart(pathPart);
String childPath = parent.getPath().equals("/") ? "/" + pathPart : parent.getPath() + "/" + pathPart;
resource.setPath(childPath);
resourceStore.put(resourceKey(region, apiId, resource.getId()), resource);
LOG.infov("Created resource {0} path={1} in API {2}", resource.getId(), childPath, apiId);
return resource;
}
public void deleteResource(String region, String apiId, String resourceId) {
getResource(region, apiId, resourceId);
resourceStore.delete(resourceKey(region, apiId, resourceId));
}
// ──────────────────────────── Method CRUD ────────────────────────────
public MethodConfig putMethod(String region, String apiId, String resourceId, String httpMethod, Map<String, Object> request) {
ApiGatewayResource resource = getResource(region, apiId, resourceId);
MethodConfig method = new MethodConfig();
method.setHttpMethod(httpMethod.toUpperCase());
method.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
method.setAuthorizerId((String) request.get("authorizerId"));
@SuppressWarnings("unchecked")
Map<String, Boolean> reqParams = (Map<String, Boolean>) request.get("requestParameters");
if (reqParams != null) method.setRequestParameters(reqParams);
resource.getResourceMethods().put(httpMethod.toUpperCase(), method);
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
return method;
}
public MethodConfig getMethod(String region, String apiId, String resourceId, String httpMethod) {
ApiGatewayResource resource = getResource(region, apiId, resourceId);
MethodConfig method = resource.getResourceMethods().get(httpMethod.toUpperCase());
if (method == null) {
throw new AwsException("NotFoundException", "Invalid method specified", 404);
}
return method;
}
public void deleteMethod(String region, String apiId, String resourceId, String httpMethod) {
ApiGatewayResource resource = getResource(region, apiId, resourceId);
resource.getResourceMethods().remove(httpMethod.toUpperCase());
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
}
public MethodResponse putMethodResponse(String region, String apiId, String resourceId,
String httpMethod, String statusCode,
Map<String, Object> request) {
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
MethodResponse mr = new MethodResponse(statusCode, new HashMap<>());
method.getMethodResponses().put(statusCode, mr);
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
return mr;
}
public MethodResponse getMethodResponse(String region, String apiId, String resourceId,
String httpMethod, String statusCode) {
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
MethodResponse mr = method.getMethodResponses().get(statusCode);
if (mr == null) {
throw new AwsException("NotFoundException", "Invalid response status code specified", 404);
}
return mr;
}
// ──────────────────────────── Integrations ────────────────────────────
public Integration putIntegration(String region, String apiId, String resourceId, String httpMethod, Map<String, Object> request) {
ApiGatewayResource resource = getResource(region, apiId, resourceId);
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
Integration integration = new Integration();
integration.setType((String) request.get("type"));
integration.setHttpMethod((String) request.get("httpMethod"));
integration.setUri((String) request.get("uri"));
@SuppressWarnings("unchecked")
Map<String, String> reqTemplates = (Map<String, String>) request.get("requestTemplates");
if (reqTemplates != null) integration.setRequestTemplates(reqTemplates);
method.setMethodIntegration(integration);
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
return integration;
}
public Integration getIntegration(String region, String apiId, String resourceId, String httpMethod) {
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
if (method.getMethodIntegration() == null) {
throw new AwsException("NotFoundException", "Integration not found", 404);
}
return method.getMethodIntegration();
}
public void deleteIntegration(String region, String apiId, String resourceId, String httpMethod) {
ApiGatewayResource resource = getResource(region, apiId, resourceId);
MethodConfig method = resource.getResourceMethods().get(httpMethod.toUpperCase());
if (method == null || method.getMethodIntegration() == null) {
throw new AwsException("NotFoundException", "Integration not found", 404);
}
method.setMethodIntegration(null);
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
}
// ──────────────────────────── Integration Responses ────────────────────────────
public IntegrationResponse putIntegrationResponse(String region, String apiId, String resourceId,
String httpMethod, String statusCode,
Map<String, Object> request) {
Integration integration = getIntegration(region, apiId, resourceId, httpMethod);
@SuppressWarnings("unchecked")
Map<String, String> respParams = (Map<String, String>) request.get("responseParameters");
@SuppressWarnings("unchecked")
Map<String, String> respTemplates = (Map<String, String>) request.get("responseTemplates");
String selectionPattern = (String) request.getOrDefault("selectionPattern", "");
IntegrationResponse ir = new IntegrationResponse(statusCode, selectionPattern,
respParams != null ? respParams : new HashMap<>(),
respTemplates != null ? respTemplates : new HashMap<>());
integration.getIntegrationResponses().put(statusCode, ir);
resourceStore.put(resourceKey(region, apiId, resourceId),
getResource(region, apiId, resourceId));
return ir;
}
public IntegrationResponse getIntegrationResponse(String region, String apiId, String resourceId,
String httpMethod, String statusCode) {
Integration integration = getIntegration(region, apiId, resourceId, httpMethod);
IntegrationResponse ir = integration.getIntegrationResponses().get(statusCode);
if (ir == null) {
throw new AwsException("NotFoundException", "Invalid response status code specified", 404);
}
return ir;
}
// ──────────────────────────── Deployments ────────────────────────────
public Deployment createDeployment(String region, String apiId, Map<String, Object> request) {
getRestApi(region, apiId);
String description = (String) request.getOrDefault("description", "");
Deployment deployment = new Deployment(shortId(10), description, System.currentTimeMillis() / 1000L);
deploymentStore.put(deploymentKey(region, apiId, deployment.id()), deployment);
LOG.infov("Created deployment {0} for API {1}", deployment.id(), apiId);
return deployment;
}
public List<Deployment> getDeployments(String region, String apiId) {
getRestApi(region, apiId);
String prefix = region + "::" + apiId + "::";
return deploymentStore.scan(k -> k.startsWith(prefix));
}
public Deployment getDeployment(String region, String apiId, String deploymentId) {
return deploymentStore.get(deploymentKey(region, apiId, deploymentId))
.orElseThrow(() -> new AwsException("NotFoundException", "Deployment not found", 404));
}
public void deleteDeployment(String region, String apiId, String deploymentId) {
getDeployment(region, apiId, deploymentId);
deploymentStore.delete(deploymentKey(region, apiId, deploymentId));
}
// ──────────────────────────── Stages ────────────────────────────
public Stage createStage(String region, String apiId, Map<String, Object> request) {
getRestApi(region, apiId);
String stageName = (String) request.get("stageName");
String deploymentId = (String) request.get("deploymentId");
if (stageName == null || stageName.isBlank()) {
throw new AwsException("BadRequestException", "stageName is required", 400);
}
if (deploymentId == null || deploymentId.isBlank()) {
throw new AwsException("BadRequestException", "deploymentId is required", 400);
}
Stage stage = new Stage();
stage.setStageName(stageName);
stage.setDeploymentId(deploymentId);
stage.setDescription((String) request.get("description"));
stage.setCreatedDate(System.currentTimeMillis() / 1000L);
stage.setLastUpdatedDate(stage.getCreatedDate());
@SuppressWarnings("unchecked")
Map<String, String> variables = (Map<String, String>) request.get("variables");
if (variables != null) stage.setVariables(variables);
stageStore.put(stageKey(region, apiId, stageName), stage);
LOG.infov("Created stage {0} for API {1}", stageName, apiId);
return stage;
}
public Stage getStage(String region, String apiId, String stageName) {
getRestApi(region, apiId);
return stageStore.get(stageKey(region, apiId, stageName))
.orElseThrow(() -> new AwsException("NotFoundException", "Stage not found", 404));
}
public List<Stage> getStages(String region, String apiId) {
getRestApi(region, apiId);
String prefix = region + "::" + apiId + "::";
return stageStore.scan(k -> k.startsWith(prefix));
}
public Stage updateStage(String region, String apiId, String stageName,
List<Map<String, String>> patchOperations) {
Stage stage = getStage(region, apiId, stageName);
LOG.infov("Updating stage {0} with {1} operations", stageName, patchOperations != null ? patchOperations.size() : 0);
if (patchOperations != null) {
for (Map<String, String> op : patchOperations) {
String opType = op.get("op");
String path = op.getOrDefault("path", "");
String value = op.get("value");
LOG.infov("Patch operation: op={0}, path={1}, value={2}", opType, path, value);
if (!"replace" .equals(opType) && !"add" .equals(opType)) continue;
if ("/description" .equals(path)) {
stage.setDescription(value);
} else if ("/deploymentId" .equals(path)) {
stage.setDeploymentId(value);
} else if (path.startsWith("/variables/")) {
String varKey = path.substring("/variables/" .length());
LOG.infov("Setting stage variable {0} = {1}", varKey, value);
stage.getVariables().put(varKey, value);
}
}
}
stage.setLastUpdatedDate(System.currentTimeMillis() / 1000L);
stageStore.put(stageKey(region, apiId, stageName), stage);
return stage;
}
public void deleteStage(String region, String apiId, String stageName) {
getStage(region, apiId, stageName);
stageStore.delete(stageKey(region, apiId, stageName));
}
// ──────────────────────────── Authorizers ────────────────────────────
public Authorizer createAuthorizer(String region, String apiId, Map<String, Object> request) {
getRestApi(region, apiId);
Authorizer authorizer = new Authorizer();
authorizer.setId(shortId(6));
authorizer.setName((String) request.get("name"));
authorizer.setType((String) request.get("type"));
authorizer.setAuthorizerUri((String) request.get("authorizerUri"));
authorizer.setIdentitySource((String) request.get("identitySource"));
authorizer.setAuthorizerResultTtlInSeconds(String.valueOf(request.getOrDefault("authorizerResultTtlInSeconds", "300")));
authorizerStore.put(authorizerKey(region, apiId, authorizer.getId()), authorizer);
LOG.infov("Created authorizer {0} for API {1}", authorizer.getId(), apiId);
return authorizer;
}
public Authorizer getAuthorizer(String region, String apiId, String authorizerId) {
return authorizerStore.get(authorizerKey(region, apiId, authorizerId))
.orElseThrow(() -> new AwsException("NotFoundException", "Authorizer not found", 404));
}
public List<Authorizer> getAuthorizers(String region, String apiId) {
getRestApi(region, apiId);
String prefix = region + "::" + apiId + "::";
return authorizerStore.scan(k -> k.startsWith(prefix));
}
public void deleteAuthorizer(String region, String apiId, String authorizerId) {
getAuthorizer(region, apiId, authorizerId);
authorizerStore.delete(authorizerKey(region, apiId, authorizerId));
}
// ──────────────────────────── API Keys ────────────────────────────
public ApiKey createApiKey(String region, Map<String, Object> request) {
ApiKey apiKey = new ApiKey();
apiKey.setId(shortId(10));
apiKey.setName((String) request.get("name"));
apiKey.setValue((String) request.getOrDefault("value", UUID.randomUUID().toString().replace("-", "")));
apiKey.setEnabled(!Boolean.FALSE.equals(request.get("enabled")));
apiKey.setCreatedDate(System.currentTimeMillis() / 1000L);
apiKey.setLastUpdatedDate(apiKey.getCreatedDate());
apiKeyStore.put(apiKeyGlobalKey(region, apiKey.getId()), apiKey);
LOG.infov("Created API Key {0}", apiKey.getId());
return apiKey;
}
public ApiKey getApiKey(String region, String apiKeyId) {
return apiKeyStore.get(apiKeyGlobalKey(region, apiKeyId))
.orElseThrow(() -> new AwsException("NotFoundException", "API Key not found", 404));
}
public List<ApiKey> getApiKeys(String region) {
String prefix = region + "::";
return apiKeyStore.scan(k -> k.startsWith(prefix));
}
public void deleteApiKey(String region, String apiKeyId) {
getApiKey(region, apiKeyId);
apiKeyStore.delete(apiKeyGlobalKey(region, apiKeyId));
}
// ──────────────────────────── Usage Plans ────────────────────────────
public UsagePlan createUsagePlan(String region, Map<String, Object> request) {
UsagePlan plan = new UsagePlan();
plan.setId(shortId(10));
plan.setName((String) request.get("name"));
plan.setDescription((String) request.get("description"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> apiStages = (List<Map<String, Object>>) request.get("apiStages");
if (apiStages != null) {
for (Map<String, Object> as : apiStages) {
plan.getApiStages().add(new UsagePlan.ApiStage((String) as.get("apiId"), (String) as.get("stage")));
}
}
usagePlanStore.put(usagePlanKey(region, plan.getId()), plan);
LOG.infov("Created Usage Plan {0}", plan.getId());
return plan;
}
public UsagePlan getUsagePlan(String region, String usagePlanId) {
return usagePlanStore.get(usagePlanKey(region, usagePlanId))
.orElseThrow(() -> new AwsException("NotFoundException", "Usage Plan not found", 404));
}
public List<UsagePlan> getUsagePlans(String region) {
String prefix = region + "::";
return usagePlanStore.scan(k -> k.startsWith(prefix));
}
public void deleteUsagePlan(String region, String usagePlanId) {
getUsagePlan(region, usagePlanId);
usagePlanStore.delete(usagePlanKey(region, usagePlanId));
}
// ──────────────────────────── Usage Plan Keys ────────────────────────────
public UsagePlanKey createUsagePlanKey(String region, String usagePlanId, Map<String, Object> request) {
getUsagePlan(region, usagePlanId);
String keyId = (String) request.get("keyId");
String keyType = (String) request.get("keyType");
ApiKey apiKey = getApiKey(region, keyId);
UsagePlanKey usagePlanKey = new UsagePlanKey();
usagePlanKey.setId(apiKey.getId());
usagePlanKey.setName(apiKey.getName());
usagePlanKey.setType(keyType);
usagePlanKey.setValue(apiKey.getValue());
usagePlanKeyStore.put(usagePlanKeyPathKey(region, usagePlanId, keyId), usagePlanKey);
LOG.infov("Created Usage Plan Key {0} for Usage Plan {1}", keyId, usagePlanId);
return usagePlanKey;
}
public UsagePlanKey getUsagePlanKey(String region, String usagePlanId, String keyId) {
return usagePlanKeyStore.get(usagePlanKeyPathKey(region, usagePlanId, keyId))
.orElseThrow(() -> new AwsException("NotFoundException", "Usage Plan Key not found", 404));
}
public List<UsagePlanKey> getUsagePlanKeys(String region, String usagePlanId) {
String prefix = region + "::" + usagePlanId + "::";
return usagePlanKeyStore.scan(k -> k.startsWith(prefix));
}
public void deleteUsagePlanKey(String region, String usagePlanId, String keyId) {
getUsagePlanKey(region, usagePlanId, keyId);
usagePlanKeyStore.delete(usagePlanKeyPathKey(region, usagePlanId, keyId));
}
// ──────────────────────────── Request Validators ────────────────────────────
public RequestValidator createRequestValidator(String region, String apiId, Map<String, Object> request) {
getRestApi(region, apiId);
RequestValidator validator = new RequestValidator();
validator.setId(shortId(6));
validator.setName((String) request.get("name"));
validator.setValidateRequestBody(Boolean.TRUE.equals(request.get("validateRequestBody")));
validator.setValidateRequestParameters(Boolean.TRUE.equals(request.get("validateRequestParameters")));
requestValidatorStore.put(requestValidatorKey(region, apiId, validator.getId()), validator);
LOG.infov("Created request validator {0} for API {1}", validator.getId(), apiId);
return validator;
}
public RequestValidator getRequestValidator(String region, String apiId, String validatorId) {
return requestValidatorStore.get(requestValidatorKey(region, apiId, validatorId))
.orElseThrow(() -> new AwsException("NotFoundException", "Request validator not found", 404));
}
public List<RequestValidator> getRequestValidators(String region, String apiId) {
getRestApi(region, apiId);
String prefix = region + "::" + apiId + "::";
return requestValidatorStore.scan(k -> k.startsWith(prefix));
}
public void deleteRequestValidator(String region, String apiId, String validatorId) {
getRequestValidator(region, apiId, validatorId);
requestValidatorStore.delete(requestValidatorKey(region, apiId, validatorId));
}
// ──────────────────────────── Custom Domains ────────────────────────────
public CustomDomain createDomainName(String region, Map<String, Object> request) {
String domainName = (String) request.get("domainName");
if (domainName == null) throw new AwsException("BadRequestException", "domainName is required", 400);
CustomDomain domain = new CustomDomain();
domain.setDomainName(domainName);
domain.setCertificateName((String) request.get("certificateName"));
domain.setCertificateArn((String) request.get("certificateArn"));
domain.setRegionalDomainName(domainName + ".regional.local");
domain.setRegionalHostedZoneId("Z2FDTNDATAQYL2");
domainStore.put(domainKey(region, domainName), domain);
LOG.infov("Created custom domain {0} in {1}", domainName, region);
return domain;
}
public CustomDomain getDomainName(String region, String domainName) {
return domainStore.get(domainKey(region, domainName))
.orElseThrow(() -> new AwsException("NotFoundException", "Domain name not found", 404));
}
public List<CustomDomain> getDomainNames(String region) {
String prefix = region + "::";
return domainStore.scan(k -> k.startsWith(prefix));
}
public void deleteDomainName(String region, String domainName) {
getDomainName(region, domainName);
domainStore.delete(domainKey(region, domainName));
// Delete associated mappings
String prefix = region + "::" + domainName + "::";
basePathMappingStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(basePathMappingStore::delete);
}
// ──────────────────────────── Base Path Mappings ────────────────────────────
public BasePathMapping createBasePathMapping(String region, String domainName, Map<String, Object> request) {
getDomainName(region, domainName);
String basePath = (String) request.getOrDefault("basePath", "(none)");
String apiId = (String) request.get("restApiId");
String stage = (String) request.get("stage");
BasePathMapping mapping = new BasePathMapping(basePath, apiId, stage);
basePathMappingStore.put(mappingKey(region, domainName, basePath), mapping);
LOG.infov("Created mapping for {0} path={1} -> API {2}", domainName, basePath, apiId);
return mapping;
}
public BasePathMapping getBasePathMapping(String region, String domainName, String basePath) {
String path = (basePath == null || basePath.isEmpty() || "/" .equals(basePath)) ? "(none)" : basePath;
return basePathMappingStore.get(mappingKey(region, domainName, path))
.orElseThrow(() -> new AwsException("NotFoundException", "Base path mapping not found", 404));
}
public List<BasePathMapping> getBasePathMappings(String region, String domainName) {
getDomainName(region, domainName);
String prefix = region + "::" + domainName + "::";
return basePathMappingStore.scan(k -> k.startsWith(prefix));
}
public void deleteBasePathMapping(String region, String domainName, String basePath) {
getBasePathMapping(region, domainName, basePath);
String path = (basePath == null || basePath.isEmpty() || "/" .equals(basePath)) ? "(none)" : basePath;
basePathMappingStore.delete(mappingKey(region, domainName, path));
}
// ──────────────────────────── Update Methods ────────────────────────────
public RestApi updateRestApi(String region, String apiId, List<Map<String, String>> patchOperations) {
RestApi api = getRestApi(region, apiId);
if (patchOperations != null) {
for (Map<String, String> op : patchOperations) {
if (!"replace" .equals(op.get("op"))) continue;
String path = op.getOrDefault("path", "");
String value = op.get("value");
if ("/name" .equals(path)) api.setName(value);
else if ("/description" .equals(path)) api.setDescription(value);
}
}
apiStore.put(apiKey(region, apiId), api);
return api;
}
public ApiGatewayResource updateResource(String region, String apiId, String resourceId, List<Map<String, String>> patchOperations) {
ApiGatewayResource resource = getResource(region, apiId, resourceId);
// Minimal update support
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
return resource;
}
public MethodConfig updateMethod(String region, String apiId, String resourceId, String httpMethod, List<Map<String, String>> patchOperations) {
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
if (patchOperations != null) {
for (Map<String, String> op : patchOperations) {
if (!"replace" .equals(op.get("op"))) continue;
String path = op.getOrDefault("path", "");
String value = op.get("value");
if ("/authorizationType" .equals(path)) method.setAuthorizationType(value);
else if ("/authorizerId" .equals(path)) method.setAuthorizerId(value);
}
}
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
return method;
}
public Integration updateIntegration(String region, String apiId, String resourceId, String httpMethod, List<Map<String, String>> patchOperations) {
Integration integration = getIntegration(region, apiId, resourceId, httpMethod);
if (patchOperations != null) {
for (Map<String, String> op : patchOperations) {
if (!"replace" .equals(op.get("op"))) continue;
String path = op.getOrDefault("path", "");
String value = op.get("value");
if ("/type" .equals(path)) integration.setType(value);
else if ("/httpMethod" .equals(path)) integration.setHttpMethod(value);
else if ("/uri" .equals(path)) integration.setUri(value);
}
}
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
return integration;
}
// ──────────────────────────── Tags ────────────────────────────
public Map<String, String> getTags(String region, String apiId) {
return getRestApi(region, apiId).getTags();
}
public void tagResource(String region, String apiId, Map<String, String> tags) {
RestApi api = getRestApi(region, apiId);
api.getTags().putAll(tags);
apiStore.put(apiKey(region, apiId), api);
}
public void untagResource(String region, String apiId, List<String> tagKeys) {
RestApi api = getRestApi(region, apiId);
tagKeys.forEach(api.getTags()::remove);
apiStore.put(apiKey(region, apiId), api);
}
// ──────────────────────────── Key helpers ────────────────────────────
private String apiKey(String region, String apiId) {
return region + "::" + apiId;
}
private String resourceKey(String region, String apiId, String resourceId) {
return region + "::" + apiId + "::" + resourceId;
}
private String deploymentKey(String region, String apiId, String deploymentId) {
return region + "::" + apiId + "::" + deploymentId;
}
private String stageKey(String region, String apiId, String stageName) {
return region + "::" + apiId + "::" + stageName;
}
private String authorizerKey(String region, String apiId, String authorizerId) {
return region + "::" + apiId + "::" + authorizerId;
}
private String requestValidatorKey(String region, String apiId, String validatorId) {
return region + "::" + apiId + "::" + validatorId;
}
private String apiKeyGlobalKey(String region, String apiKeyId) {
return region + "::" + apiKeyId;
}
private String usagePlanKey(String region, String usagePlanId) {
return region + "::" + usagePlanId;
}
private String usagePlanKeyPathKey(String region, String usagePlanId, String keyId) {
return region + "::" + usagePlanId + "::" + keyId;
}
private String domainKey(String region, String domainName) {
return region + "::" + domainName;
}
private String mappingKey(String region, String domainName, String basePath) {
return region + "::" + domainName + "::" + basePath;
}
private static String shortId(int length) {
return UUID.randomUUID().toString().replace("-", "").substring(0, length);
}
}
@@ -0,0 +1,90 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
/**
* AWS API Gateway tag endpoints at /tags/{resourceArn}.
*/
@Path("/tags")
@Produces(MediaType.APPLICATION_JSON)
public class ApiGatewayTagsController {
private final ApiGatewayService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public ApiGatewayTagsController(ApiGatewayService service, RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@GET
@Path("/{arn: .*}")
public Response getTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {
String region = regionResolver.resolveRegion(headers);
String apiId = apiIdFromArn(arn);
Map<String, String> tags = service.getTags(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ObjectNode tagsNode = root.putObject("tags");
tags.forEach(tagsNode::put);
return Response.ok(root).build();
}
@PUT
@Path("/{arn: .*}")
public Response tagResource(@Context HttpHeaders headers,
@PathParam("arn") String arn,
String body) {
String region = regionResolver.resolveRegion(headers);
String apiId = apiIdFromArn(arn);
try {
JsonNode node = objectMapper.readTree(body);
Map<String, String> tags = new java.util.HashMap<>();
node.path("tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
service.tagResource(region, apiId, tags);
return Response.noContent().build();
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/{arn: .*}")
public Response untagResource(@Context HttpHeaders headers,
@PathParam("arn") String arn,
@QueryParam("tagKeys") List<String> tagKeys) {
String region = regionResolver.resolveRegion(headers);
String apiId = apiIdFromArn(arn);
service.untagResource(region, apiId, tagKeys);
return Response.noContent().build();
}
/**
* Extracts apiId from ARN: arn:aws:apigateway:region::/restapis/{apiId}
*/
private String apiIdFromArn(String arn) {
String[] parts = arn.split("/restapis/");
if (parts.length < 2) {
throw new AwsException("BadRequestException", "Invalid resource ARN: " + arn, 400);
}
return parts[1].split("/")[0];
}
}
@@ -0,0 +1,37 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.HashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiGatewayResource {
private String id;
private String apiId;
private String parentId;
private String pathPart;
private String path;
private Map<String, MethodConfig> resourceMethods = new HashMap<>();
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getApiId() { return apiId; }
public void setApiId(String apiId) { this.apiId = apiId; }
public String getParentId() { return parentId; }
public void setParentId(String parentId) { this.parentId = parentId; }
public String getPathPart() { return pathPart; }
public void setPathPart(String pathPart) { this.pathPart = pathPart; }
public String getPath() { return path; }
public void setPath(String path) { this.path = path; }
public Map<String, MethodConfig> getResourceMethods() { return resourceMethods; }
public void setResourceMethods(Map<String, MethodConfig> resourceMethods) {
this.resourceMethods = resourceMethods != null ? resourceMethods : new HashMap<>();
}
}
@@ -0,0 +1,35 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiKey {
private String id;
private String name;
private String value;
private boolean enabled;
private long createdDate;
private long lastUpdatedDate;
public ApiKey() {}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public long getCreatedDate() { return createdDate; }
public void setCreatedDate(long createdDate) { this.createdDate = createdDate; }
public long getLastUpdatedDate() { return lastUpdatedDate; }
public void setLastUpdatedDate(long lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; }
}
@@ -0,0 +1,35 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class Authorizer {
private String id;
private String name;
private String type; // TOKEN, REQUEST
private String authorizerUri;
private String identitySource;
private String authorizerResultTtlInSeconds;
public Authorizer() {}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getAuthorizerUri() { return authorizerUri; }
public void setAuthorizerUri(String authorizerUri) { this.authorizerUri = authorizerUri; }
public String getIdentitySource() { return identitySource; }
public void setIdentitySource(String identitySource) { this.identitySource = identitySource; }
public String getAuthorizerResultTtlInSeconds() { return authorizerResultTtlInSeconds; }
public void setAuthorizerResultTtlInSeconds(String ttl) { this.authorizerResultTtlInSeconds = ttl; }
}
@@ -0,0 +1,31 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class BasePathMapping {
private String basePath;
private String restApiId;
private String stage;
public BasePathMapping() {
this.basePath = "(none)";
}
public BasePathMapping(String basePath, String restApiId, String stage) {
this.basePath = (basePath == null || basePath.isEmpty()) ? "(none)" : basePath;
this.restApiId = restApiId;
this.stage = stage;
}
public String getBasePath() { return basePath; }
public void setBasePath(String basePath) { this.basePath = basePath; }
public String getRestApiId() { return restApiId; }
public void setRestApiId(String restApiId) { this.restApiId = restApiId; }
public String getStage() { return stage; }
public void setStage(String stage) { this.stage = stage; }
}
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomDomain {
private String domainName;
private String certificateName;
private String certificateArn;
private String certificateUploadDate;
private String regionalDomainName;
private String regionalHostedZoneId;
private String regionalCertificateName;
private String regionalCertificateArn;
private String distributionDomainName;
private String distributionHostedZoneId;
private String endpointConfigurationType; // REGIONAL or EDGE
private String domainNameStatus; // AVAILABLE, UPDATING, PENDING
private String securityPolicy;
public CustomDomain() {
this.domainNameStatus = "AVAILABLE";
this.endpointConfigurationType = "REGIONAL";
this.securityPolicy = "TLS_1_2";
}
public String getDomainName() { return domainName; }
public void setDomainName(String domainName) { this.domainName = domainName; }
public String getCertificateName() { return certificateName; }
public void setCertificateName(String certificateName) { this.certificateName = certificateName; }
public String getCertificateArn() { return certificateArn; }
public void setCertificateArn(String certificateArn) { this.certificateArn = certificateArn; }
public String getCertificateUploadDate() { return certificateUploadDate; }
public void setCertificateUploadDate(String certificateUploadDate) { this.certificateUploadDate = certificateUploadDate; }
public String getRegionalDomainName() { return regionalDomainName; }
public void setRegionalDomainName(String regionalDomainName) { this.regionalDomainName = regionalDomainName; }
public String getRegionalHostedZoneId() { return regionalHostedZoneId; }
public void setRegionalHostedZoneId(String regionalHostedZoneId) { this.regionalHostedZoneId = regionalHostedZoneId; }
public String getRegionalCertificateName() { return regionalCertificateName; }
public void setRegionalCertificateName(String regionalCertificateName) { this.regionalCertificateName = regionalCertificateName; }
public String getRegionalCertificateArn() { return regionalCertificateArn; }
public void setRegionalCertificateArn(String regionalCertificateArn) { this.regionalCertificateArn = regionalCertificateArn; }
public String getDistributionDomainName() { return distributionDomainName; }
public void setDistributionDomainName(String distributionDomainName) { this.distributionDomainName = distributionDomainName; }
public String getDistributionHostedZoneId() { return distributionHostedZoneId; }
public void setDistributionHostedZoneId(String distributionHostedZoneId) { this.distributionHostedZoneId = distributionHostedZoneId; }
public String getEndpointConfigurationType() { return endpointConfigurationType; }
public void setEndpointConfigurationType(String endpointConfigurationType) { this.endpointConfigurationType = endpointConfigurationType; }
public String getDomainNameStatus() { return domainNameStatus; }
public void setDomainNameStatus(String domainNameStatus) { this.domainNameStatus = domainNameStatus; }
public String getSecurityPolicy() { return securityPolicy; }
public void setSecurityPolicy(String securityPolicy) { this.securityPolicy = securityPolicy; }
}
@@ -0,0 +1,11 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public record Deployment(
String id,
String description,
long createdDate
) {
}
@@ -0,0 +1,56 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.HashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Integration {
private String type; // MOCK, HTTP, AWS, HTTP_PROXY, AWS_PROXY
private String uri;
private String httpMethod;
private Map<String, String> requestTemplates = new HashMap<>();
private Map<String, IntegrationResponse> integrationResponses = new HashMap<>();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getHttpMethod() {
return httpMethod;
}
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public Map<String, String> getRequestTemplates() {
return requestTemplates;
}
public void setRequestTemplates(Map<String, String> requestTemplates) {
this.requestTemplates = requestTemplates != null ? requestTemplates : new HashMap<>();
}
public Map<String, IntegrationResponse> getIntegrationResponses() {
return integrationResponses;
}
public void setIntegrationResponses(Map<String, IntegrationResponse> integrationResponses) {
this.integrationResponses = integrationResponses != null ? integrationResponses : new HashMap<>();
}
}
@@ -0,0 +1,13 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public record IntegrationResponse(
String statusCode,
String selectionPattern,
Map<String, String> responseParameters,
Map<String, String> responseTemplates
) {}
@@ -0,0 +1,39 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.HashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class MethodConfig {
private String httpMethod;
private String authorizationType;
private String authorizerId;
private Map<String, Boolean> requestParameters = new HashMap<>();
private Map<String, MethodResponse> methodResponses = new HashMap<>();
private Integration methodIntegration;
public String getHttpMethod() { return httpMethod; }
public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; }
public String getAuthorizationType() { return authorizationType; }
public void setAuthorizationType(String authorizationType) { this.authorizationType = authorizationType; }
public String getAuthorizerId() { return authorizerId; }
public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; }
public Map<String, Boolean> getRequestParameters() { return requestParameters; }
public void setRequestParameters(Map<String, Boolean> requestParameters) {
this.requestParameters = requestParameters != null ? requestParameters : new HashMap<>();
}
public Map<String, MethodResponse> getMethodResponses() { return methodResponses; }
public void setMethodResponses(Map<String, MethodResponse> methodResponses) {
this.methodResponses = methodResponses != null ? methodResponses : new HashMap<>();
}
public Integration getMethodIntegration() { return methodIntegration; }
public void setMethodIntegration(Integration methodIntegration) { this.methodIntegration = methodIntegration; }
}
@@ -0,0 +1,12 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public record MethodResponse(
String statusCode,
Map<String, Boolean> responseParameters
) {
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class RequestValidator {
private String id;
private String name;
private boolean validateRequestBody;
private boolean validateRequestParameters;
public RequestValidator() {}
public RequestValidator(String id, String name, boolean validateRequestBody, boolean validateRequestParameters) {
this.id = id;
this.name = name;
this.validateRequestBody = validateRequestBody;
this.validateRequestParameters = validateRequestParameters;
}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public boolean isValidateRequestBody() { return validateRequestBody; }
public void setValidateRequestBody(boolean validateRequestBody) { this.validateRequestBody = validateRequestBody; }
public boolean isValidateRequestParameters() { return validateRequestParameters; }
public void setValidateRequestParameters(boolean validateRequestParameters) { this.validateRequestParameters = validateRequestParameters; }
}
@@ -0,0 +1,56 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.HashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class RestApi {
private String id;
private String name;
private String description;
private long createdDate;
private Map<String, String> tags = new HashMap<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getCreatedDate() {
return createdDate;
}
public void setCreatedDate(long createdDate) {
this.createdDate = createdDate;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags != null ? tags : new HashMap<>();
}
}
@@ -0,0 +1,65 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.HashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Stage {
private String stageName;
private String deploymentId;
private String description;
private Map<String, String> variables = new HashMap<>();
private long createdDate;
private long lastUpdatedDate;
public String getStageName() {
return stageName;
}
public void setStageName(String stageName) {
this.stageName = stageName;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Map<String, String> getVariables() {
return variables;
}
public void setVariables(Map<String, String> variables) {
this.variables = variables != null ? variables : new HashMap<>();
}
public long getCreatedDate() {
return createdDate;
}
public void setCreatedDate(long createdDate) {
this.createdDate = createdDate;
}
public long getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(long lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
}
@@ -0,0 +1,33 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class UsagePlan {
private String id;
private String name;
private String description;
private List<ApiStage> apiStages = new ArrayList<>();
public UsagePlan() {}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public List<ApiStage> getApiStages() { return apiStages; }
public void setApiStages(List<ApiStage> apiStages) { this.apiStages = apiStages; }
@RegisterForReflection
public record ApiStage(String apiId, String stage) {}
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class UsagePlanKey {
private String id;
private String name;
private String type;
private String value;
public UsagePlanKey() {}
public UsagePlanKey(String id, String name, String type, String value) {
this.id = id;
this.name = name;
this.type = type;
this.value = value;
}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}
@@ -0,0 +1,316 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.apigatewayv2.model.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class ApiGatewayV2JsonHandler {
private final ApiGatewayV2Service service;
private final ObjectMapper objectMapper;
@Inject
public ApiGatewayV2JsonHandler(ApiGatewayV2Service service, ObjectMapper objectMapper) {
this.service = service;
this.objectMapper = objectMapper;
}
public Response handle(String action, JsonNode request, String region) {
try {
return switch (action) {
case "CreateApi" -> handleCreateApi(request, region);
case "GetApis" -> handleGetApis(region);
case "GetApi" -> handleGetApi(request, region);
case "DeleteApi" -> handleDeleteApi(request, region);
case "CreateRoute" -> handleCreateRoute(request, region);
case "GetRoute" -> handleGetRoute(request, region);
case "GetRoutes" -> handleGetRoutes(request, region);
case "DeleteRoute" -> handleDeleteRoute(request, region);
case "CreateIntegration" -> handleCreateIntegration(request, region);
case "GetIntegration" -> handleGetIntegration(request, region);
case "GetIntegrations" -> handleGetIntegrations(request, region);
case "CreateAuthorizer" -> handleCreateAuthorizer(request, region);
case "GetAuthorizer" -> handleGetAuthorizer(request, region);
case "GetAuthorizers" -> handleGetAuthorizers(request, region);
case "DeleteAuthorizer" -> handleDeleteAuthorizer(request, region);
case "CreateStage" -> handleCreateStage(request, region);
case "GetStage" -> handleGetStage(request, region);
case "GetStages" -> handleGetStages(request, region);
case "DeleteStage" -> handleDeleteStage(request, region);
case "CreateDeployment" -> handleCreateDeployment(request, region);
case "GetDeployments" -> handleGetDeployments(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation",
"Operation " + action + " is not supported."))
.type(MediaType.APPLICATION_JSON).build();
};
} catch (AwsException e) {
return Response.status(e.getHttpStatus())
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
.type(MediaType.APPLICATION_JSON).build();
}
}
// ──────────────────────────── API ────────────────────────────
private Response handleCreateApi(JsonNode request, String region) {
@SuppressWarnings("unchecked")
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
Api api = service.createApi(region, map);
return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetApis(String region) {
List<Api> apis = service.getApis(region);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("Items");
apis.forEach(a -> items.add(toApiNode(a)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetApi(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
return Response.ok(toApiNode(service.getApi(region, apiId)).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleDeleteApi(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
service.deleteApi(region, apiId);
return Response.noContent().build();
}
// ──────────────────────────── Authorizer ────────────────────────────
private Response handleCreateAuthorizer(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
@SuppressWarnings("unchecked")
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
Authorizer auth = service.createAuthorizer(region, apiId, map);
return Response.status(201).entity(toAuthorizerNode(auth).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetAuthorizer(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
String authorizerId = request.path("AuthorizerId").asText();
return Response.ok(toAuthorizerNode(service.getAuthorizer(region, apiId, authorizerId)).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetAuthorizers(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
List<Authorizer> authorizers = service.getAuthorizers(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("Items");
authorizers.forEach(a -> items.add(toAuthorizerNode(a)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
private Response handleDeleteAuthorizer(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
String authorizerId = request.path("AuthorizerId").asText();
service.deleteAuthorizer(region, apiId, authorizerId);
return Response.noContent().build();
}
// ──────────────────────────── Route ────────────────────────────
private Response handleCreateRoute(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
@SuppressWarnings("unchecked")
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
Route route = service.createRoute(region, apiId, map);
return Response.status(201).entity(toRouteNode(route).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetRoute(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
String routeId = request.path("RouteId").asText();
return Response.ok(toRouteNode(service.getRoute(region, apiId, routeId)).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetRoutes(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
List<Route> routes = service.getRoutes(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("Items");
routes.forEach(r -> items.add(toRouteNode(r)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
private Response handleDeleteRoute(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
String routeId = request.path("RouteId").asText();
service.deleteRoute(region, apiId, routeId);
return Response.noContent().build();
}
// ──────────────────────────── Integration ────────────────────────────
private Response handleCreateIntegration(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
@SuppressWarnings("unchecked")
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
Integration integration = service.createIntegration(region, apiId, map);
return Response.status(201).entity(toIntegrationNode(integration).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetIntegration(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
String integrationId = request.path("IntegrationId").asText();
return Response.ok(toIntegrationNode(service.getIntegration(region, apiId, integrationId)).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetIntegrations(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
List<Integration> integrations = service.getIntegrations(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("Items");
integrations.forEach(i -> items.add(toIntegrationNode(i)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
// ──────────────────────────── Stage ────────────────────────────
private Response handleCreateStage(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
@SuppressWarnings("unchecked")
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
Stage stage = service.createStage(region, apiId, map);
return Response.status(201).entity(toStageNode(stage).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetStage(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
String stageName = request.path("StageName").asText();
return Response.ok(toStageNode(service.getStage(region, apiId, stageName)).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetStages(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
List<Stage> stages = service.getStages(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("Items");
stages.forEach(s -> items.add(toStageNode(s)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
private Response handleDeleteStage(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
String stageName = request.path("StageName").asText();
service.deleteStage(region, apiId, stageName);
return Response.noContent().build();
}
// ──────────────────────────── Deployment ────────────────────────────
private Response handleCreateDeployment(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
@SuppressWarnings("unchecked")
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
Deployment deployment = service.createDeployment(region, apiId, map);
return Response.status(201).entity(toDeploymentNode(deployment).toString())
.type(MediaType.APPLICATION_JSON).build();
}
private Response handleGetDeployments(JsonNode request, String region) {
String apiId = request.path("ApiId").asText();
List<Deployment> deployments = service.getDeployments(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("Items");
deployments.forEach(d -> items.add(toDeploymentNode(d)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
// ──────────────────────────── Serializers ────────────────────────────
private ObjectNode toApiNode(Api api) {
ObjectNode node = objectMapper.createObjectNode();
node.put("ApiId", api.getApiId());
node.put("Name", api.getName());
node.put("ProtocolType", api.getProtocolType());
node.put("ApiEndpoint", api.getApiEndpoint());
node.put("CreatedDate", api.getCreatedDate() / 1000.0);
return node;
}
private ObjectNode toAuthorizerNode(Authorizer auth) {
ObjectNode node = objectMapper.createObjectNode();
node.put("AuthorizerId", auth.getAuthorizerId());
node.put("Name", auth.getName());
node.put("AuthorizerType", auth.getAuthorizerType());
if (auth.getIdentitySource() != null) {
ArrayNode sources = node.putArray("IdentitySource");
auth.getIdentitySource().forEach(sources::add);
}
if (auth.getJwtConfiguration() != null) {
ObjectNode jwt = node.putObject("JwtConfiguration");
if (auth.getJwtConfiguration().issuer() != null) {
jwt.put("Issuer", auth.getJwtConfiguration().issuer());
}
if (auth.getJwtConfiguration().audience() != null) {
ArrayNode aud = jwt.putArray("Audience");
auth.getJwtConfiguration().audience().forEach(aud::add);
}
}
return node;
}
private ObjectNode toRouteNode(Route r) {
ObjectNode node = objectMapper.createObjectNode();
node.put("RouteId", r.getRouteId());
node.put("RouteKey", r.getRouteKey());
node.put("AuthorizationType", r.getAuthorizationType());
if (r.getAuthorizerId() != null) node.put("AuthorizerId", r.getAuthorizerId());
if (r.getTarget() != null) node.put("Target", r.getTarget());
return node;
}
private ObjectNode toIntegrationNode(Integration i) {
ObjectNode node = objectMapper.createObjectNode();
node.put("IntegrationId", i.getIntegrationId());
node.put("IntegrationType", i.getIntegrationType());
node.put("PayloadFormatVersion", i.getPayloadFormatVersion());
if (i.getIntegrationUri() != null) node.put("IntegrationUri", i.getIntegrationUri());
return node;
}
private ObjectNode toStageNode(Stage s) {
ObjectNode node = objectMapper.createObjectNode();
node.put("StageName", s.getStageName());
node.put("AutoDeploy", s.isAutoDeploy());
node.put("CreatedDate", s.getCreatedDate() / 1000.0);
node.put("LastUpdatedDate", s.getLastUpdatedDate() / 1000.0);
if (s.getDeploymentId() != null) node.put("DeploymentId", s.getDeploymentId());
return node;
}
private ObjectNode toDeploymentNode(Deployment d) {
ObjectNode node = objectMapper.createObjectNode();
node.put("DeploymentId", d.getDeploymentId());
node.put("DeploymentStatus", d.getDeploymentStatus());
node.put("CreatedDate", d.getCreatedDate() / 1000.0);
if (d.getDescription() != null) node.put("Description", d.getDescription());
return node;
}
}
@@ -0,0 +1,298 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.services.apigatewayv2.model.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
@ApplicationScoped
public class ApiGatewayV2Service {
private static final Logger LOG = Logger.getLogger(ApiGatewayV2Service.class);
private final StorageBackend<String, Api> apiStore;
private final StorageBackend<String, Route> routeStore;
private final StorageBackend<String, Integration> integrationStore;
private final StorageBackend<String, Authorizer> authorizerStore;
private final StorageBackend<String, Deployment> deploymentStore;
private final StorageBackend<String, Stage> stageStore;
private final RegionResolver regionResolver;
@Inject
public ApiGatewayV2Service(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
this.apiStore = storageFactory.create("apigatewayv2", "apigatewayv2-apis.json",
new TypeReference<>() {});
this.routeStore = storageFactory.create("apigatewayv2", "apigatewayv2-routes.json",
new TypeReference<>() {});
this.integrationStore = storageFactory.create("apigatewayv2", "apigatewayv2-integrations.json",
new TypeReference<>() {});
this.authorizerStore = storageFactory.create("apigatewayv2", "apigatewayv2-authorizers.json",
new TypeReference<>() {});
this.deploymentStore = storageFactory.create("apigatewayv2", "apigatewayv2-deployments.json",
new TypeReference<>() {});
this.stageStore = storageFactory.create("apigatewayv2", "apigatewayv2-stages.json",
new TypeReference<>() {});
this.regionResolver = regionResolver;
}
// ──────────────────────────── API CRUD ────────────────────────────
public Api createApi(String region, Map<String, Object> request) {
String name = (String) request.get("name");
String protocolType = (String) request.getOrDefault("protocolType", "HTTP");
Api api = new Api();
api.setApiId(shortId(10));
api.setName(name);
api.setProtocolType(protocolType);
api.setCreatedDate(System.currentTimeMillis());
api.setApiEndpoint(String.format("https://%s.execute-api.%s.amazonaws.com", api.getApiId(), region));
apiStore.put(apiKey(region, api.getApiId()), api);
LOG.infov("Created HTTP API: {0} ({1}) in {2}", api.getName(), api.getApiId(), region);
return api;
}
public Api getApi(String region, String apiId) {
return apiStore.get(apiKey(region, apiId))
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404));
}
public List<Api> getApis(String region) {
String prefix = region + "::";
return apiStore.scan(k -> k.startsWith(prefix));
}
public void deleteApi(String region, String apiId) {
getApi(region, apiId);
apiStore.delete(apiKey(region, apiId));
}
// ──────────────────────────── Authorizer CRUD ────────────────────────────
public Authorizer createAuthorizer(String region, String apiId, Map<String, Object> request) {
getApi(region, apiId);
Authorizer auth = new Authorizer();
auth.setAuthorizerId(shortId(8));
auth.setName((String) request.get("name"));
auth.setAuthorizerType((String) request.get("authorizerType"));
@SuppressWarnings("unchecked")
List<String> identitySource = (List<String>) request.get("identitySource");
auth.setIdentitySource(identitySource);
@SuppressWarnings("unchecked")
Map<String, Object> jwtConfig = (Map<String, Object>) request.get("jwtConfiguration");
if (jwtConfig != null) {
@SuppressWarnings("unchecked")
List<String> audience = (List<String>) jwtConfig.get("audience");
String issuer = (String) jwtConfig.get("issuer");
auth.setJwtConfiguration(new Authorizer.JwtConfiguration(audience, issuer));
}
authorizerStore.put(authorizerKey(region, apiId, auth.getAuthorizerId()), auth);
LOG.infov("Created JWT authorizer: {0} ({1}) for API {2}", auth.getName(), auth.getAuthorizerId(), apiId);
return auth;
}
public Authorizer getAuthorizer(String region, String apiId, String authorizerId) {
return authorizerStore.get(authorizerKey(region, apiId, authorizerId))
.orElseThrow(() -> new AwsException("NotFoundException", "Authorizer not found", 404));
}
public List<Authorizer> getAuthorizers(String region, String apiId) {
String prefix = region + "::" + apiId + "::";
return authorizerStore.scan(k -> k.startsWith(prefix));
}
public void deleteAuthorizer(String region, String apiId, String authorizerId) {
getAuthorizer(region, apiId, authorizerId);
authorizerStore.delete(authorizerKey(region, apiId, authorizerId));
}
// ──────────────────────────── Route CRUD ────────────────────────────
public Route createRoute(String region, String apiId, Map<String, Object> request) {
getApi(region, apiId);
Route route = new Route();
route.setRouteId(shortId(8));
route.setRouteKey((String) request.get("routeKey"));
route.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
route.setAuthorizerId((String) request.get("authorizerId"));
route.setTarget((String) request.get("target"));
routeStore.put(routeKey(region, apiId, route.getRouteId()), route);
return route;
}
public Route getRoute(String region, String apiId, String routeId) {
return routeStore.get(routeKey(region, apiId, routeId))
.orElseThrow(() -> new AwsException("NotFoundException", "Route not found", 404));
}
public List<Route> getRoutes(String region, String apiId) {
String prefix = region + "::" + apiId + "::";
return routeStore.scan(k -> k.startsWith(prefix));
}
public void deleteRoute(String region, String apiId, String routeId) {
getRoute(region, apiId, routeId);
routeStore.delete(routeKey(region, apiId, routeId));
}
/**
* Finds the best matching route for the given HTTP method and path.
* Priority: exact match > path-template match > $default.
*/
public Route findMatchingRoute(String region, String apiId, String httpMethod, String path) {
List<Route> routes = getRoutes(region, apiId);
String candidate = httpMethod.toUpperCase() + " " + path;
// 1. Exact match
for (Route r : routes) {
if (candidate.equals(r.getRouteKey())) return r;
}
// 2. Path-template match (e.g. "GET /users/{id}")
for (Route r : routes) {
if (r.getRouteKey() == null || r.getRouteKey().equals("$default")) continue;
if (routeKeyMatchesPath(r.getRouteKey(), httpMethod, path)) return r;
}
// 3. $default catch-all
for (Route r : routes) {
if ("$default".equals(r.getRouteKey())) return r;
}
return null;
}
private boolean routeKeyMatchesPath(String routeKey, String httpMethod, String path) {
int space = routeKey.indexOf(' ');
if (space < 0) return false;
String method = routeKey.substring(0, space);
String pattern = routeKey.substring(space + 1);
if (!method.equalsIgnoreCase(httpMethod)) return false;
// Convert path template to regex: {param} → [^/]+, {proxy+} → .+
String regex = "^" + Pattern.quote(pattern)
.replace("\\{proxy+\\}", "\\E.+\\Q")
.replace("\\{", "\\E[^/]+\\Q")
.replaceAll("\\\\Q\\\\E", "") + "$";
return path.matches(regex);
}
// ──────────────────────────── Integration CRUD ────────────────────────────
public Integration createIntegration(String region, String apiId, Map<String, Object> request) {
getApi(region, apiId);
Integration integration = new Integration();
integration.setIntegrationId(shortId(8));
integration.setIntegrationType((String) request.get("integrationType"));
integration.setIntegrationUri((String) request.get("integrationUri"));
integration.setPayloadFormatVersion((String) request.getOrDefault("payloadFormatVersion", "2.0"));
integrationStore.put(integrationKey(region, apiId, integration.getIntegrationId()), integration);
return integration;
}
public Integration getIntegration(String region, String apiId, String integrationId) {
return integrationStore.get(integrationKey(region, apiId, integrationId))
.orElseThrow(() -> new AwsException("NotFoundException", "Integration not found", 404));
}
public List<Integration> getIntegrations(String region, String apiId) {
String prefix = region + "::" + apiId + "::";
return integrationStore.scan(k -> k.startsWith(prefix));
}
// ──────────────────────────── Stage CRUD ────────────────────────────
public Stage createStage(String region, String apiId, Map<String, Object> request) {
getApi(region, apiId);
Stage stage = new Stage();
stage.setStageName((String) request.getOrDefault("stageName", "$default"));
stage.setAutoDeploy(Boolean.parseBoolean(String.valueOf(request.getOrDefault("autoDeploy", "false"))));
stage.setCreatedDate(System.currentTimeMillis());
stage.setLastUpdatedDate(System.currentTimeMillis());
stageStore.put(stageKey(region, apiId, stage.getStageName()), stage);
LOG.infov("Created stage: {0} for API {1}", stage.getStageName(), apiId);
return stage;
}
public Stage getStage(String region, String apiId, String stageName) {
return stageStore.get(stageKey(region, apiId, stageName))
.orElseThrow(() -> new AwsException("NotFoundException", "Stage not found", 404));
}
public List<Stage> getStages(String region, String apiId) {
String prefix = region + "::" + apiId + "::";
return stageStore.scan(k -> k.startsWith(prefix));
}
public void deleteStage(String region, String apiId, String stageName) {
getStage(region, apiId, stageName);
stageStore.delete(stageKey(region, apiId, stageName));
}
// ──────────────────────────── Deployment CRUD ────────────────────────────
public Deployment createDeployment(String region, String apiId, Map<String, Object> request) {
getApi(region, apiId);
Deployment deployment = new Deployment();
deployment.setDeploymentId(shortId(8));
deployment.setDeploymentStatus("DEPLOYED");
deployment.setDescription((String) request.get("description"));
deployment.setCreatedDate(System.currentTimeMillis());
deploymentStore.put(deploymentKey(region, apiId, deployment.getDeploymentId()), deployment);
return deployment;
}
public List<Deployment> getDeployments(String region, String apiId) {
String prefix = region + "::" + apiId + "::";
return deploymentStore.scan(k -> k.startsWith(prefix));
}
// ──────────────────────────── Key helpers ────────────────────────────
private String apiKey(String region, String apiId) {
return region + "::" + apiId;
}
private String routeKey(String region, String apiId, String routeId) {
return region + "::" + apiId + "::" + routeId;
}
private String integrationKey(String region, String apiId, String integrationId) {
return region + "::" + apiId + "::" + integrationId;
}
private String authorizerKey(String region, String apiId, String authorizerId) {
return region + "::" + apiId + "::" + authorizerId;
}
private String stageKey(String region, String apiId, String stageName) {
return region + "::" + apiId + "::" + stageName;
}
private String deploymentKey(String region, String apiId, String deploymentId) {
return region + "::" + apiId + "::" + deploymentId;
}
private static String shortId(int length) {
return UUID.randomUUID().toString().replace("-", "").substring(0, length);
}
}
@@ -0,0 +1,38 @@
package io.github.hectorvent.floci.services.apigatewayv2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.HashMap;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class Api {
private String apiId;
private String name;
private String protocolType; // HTTP, WEBSOCKET
private String apiEndpoint;
private long createdDate;
private Map<String, String> tags = new HashMap<>();
public Api() {}
public String getApiId() { return apiId; }
public void setApiId(String apiId) { this.apiId = apiId; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getProtocolType() { return protocolType; }
public void setProtocolType(String protocolType) { this.protocolType = protocolType; }
public String getApiEndpoint() { return apiEndpoint; }
public void setApiEndpoint(String apiEndpoint) { this.apiEndpoint = apiEndpoint; }
public long getCreatedDate() { return createdDate; }
public void setCreatedDate(long createdDate) { this.createdDate = createdDate; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}
Loaded 100 of 313 files, more files were not shown because too many files have changed in this diff. Show more