Commit Graph
366 Commits
Author SHA1 Message Date
Kenshin Okinaka 646b4199df feat(ses): extend tag endpoints to v2 EmailTemplate ARNs (#759)
Adds support for arn:aws:ses:<region>:<account>:template/<name> ARNs
across TagResource / UntagResource / ListTagsForResource. Behaviour
was verified against real AWS via aws sesv2 commands and aligned where
it diverged.

- EmailTemplate gains a tags field. CreateEmailTemplate accepts an
  optional Tags array; tag validation reuses validateTag().
- UpdateEmailTemplate intentionally preserves the existing tags so
  that AWS-style "tags only mutated via Tag/UntagResource" semantics
  hold.
- GetEmailTemplate response surfaces stored tags.
- Missing templates return NotFoundException with the AWS-canonical
  "No Template present with name: <name>" message — AWS uses the bare
  "Template" (not "EmailTemplate") for tag-endpoint lookups even
  though the SDK type is EmailTemplate.

Resource-type-specific routing in the tag endpoints:

- TagResource on a template ARN strictly validates ARN/signing region
  match (BadRequestException "Failed to tag resource" on mismatch),
  matching the existing ConfigurationSet behaviour.
- UntagResource on a template ARN strictly validates ARN/signing
  region match (BadRequestException "Failed to untag resource"),
  whereas ConfigurationSet's lenient ARN-region lookup is preserved.
  AWS treats the two resource types asymmetrically here.
- ListTagsForResource on a template ARN ignores the ARN region and
  resolves the template against the signing region. ConfigurationSet
  continues to route by ARN region.

Three small refactors that fall out naturally from adding a second
taggable resource:

- Tag is promoted from ConfigurationSet.Tag to a top-level
  services/ses/model/Tag so EmailTemplate and the shared helpers no
  longer reference a Configuration-scoped name. JSON serialization is
  unchanged.
- A private mergeTags(existing, incoming) helper centralizes the
  LinkedHashMap merge previously duplicated between
  tagConfigurationSet and tagEmailTemplate.
- A private parseTagsArray(JsonNode) helper centralizes the JSON Tags
  array parse previously duplicated across createConfigurationSet,
  createEmailTemplate, and tagResource. The helper returns null for
  missing/null nodes; the required caller (tagResource) treats null
  as BadRequestException.

Tests:

- SesTagsV2IntegrationTest gains a template lifecycle case, a
  template-not-found assertion, and the two template-specific
  region-mismatch / signing-region-lookup cases.
- SesTemplateV2IntegrationTest covers create-with-tags, list-via-tags
  endpoint, and update-preserves-tags round-trips.
- SesTagResourceTest (Java SDK compat) exercises CreateEmailTemplate
  with Tags and the Tag/Untag lifecycle on the template ARN.
2026-05-09 20:57:29 -05:00
Asha Somayajula ce2012de45 fix(s3): parse copy-source versionId for CopyObject and part copy iss… (#751)
* fix(s3): parse copy-source versionId for CopyObject and part copy issue-748
* fix(s3): support versionId in CopyObject and UploadPartCopy sources - issue-748
* fix(s3): added new line at the end of class S3Controller - issue-748
2026-05-09 08:25:50 -05:00
Hector Ventura 2bed9ec3ad feat(multitenancy): add per-account storage isolation across all services (#753)
Introduces multi-account isolation so that requests authenticated with
different AWS account IDs operate on completely separate resources,
with no cross-account data leakage.

- Add `RequestContext` (@RequestScoped CDI bean) to hold the current
  account ID for the duration of each HTTP request
- Add `AccountResolver` to extract a 12-digit numeric account ID from
  an AWS access key (AKID[4..15]), falling back to `defaultAccountId`
  for non-numeric or legacy keys
- Add `AccountContextFilter` (JAX-RS ContainerRequestFilter) to populate
  `RequestContext` on every incoming request
- Add `AccountAwareStorageBackend<V>` that transparently prefixes every
  storage key with the current account ID; provides explicit-account
  overloads (`getForAccount`, `putForAccount`, `scanAllAccounts`,
 `scanAllAccountsAsMap`, `keysForAccount`) for use by background
  workers that run outside request scope
- Update `StorageFactory` to always wrap created backends in
  `AccountAwareStorageBackend`, making isolation the default for all
  services with no per-service wiring required
- Update `RegionResolver.getAccountId()` to read from `RequestContext`,
  falling back to `defaultAccountId` outside request scope

Store `accountId` on model objects at creation time and use explicit-
account overloads in background pollers and schedulers to prevent
account overloads in background pollers and schedulers to prevent
cross-account data access:

- **SQS** — queue keys scoped per account; DLQ routing and ESM polling
  account-aware
- **SNS** — topic and subscription keys scoped per account
- **Lambda** — function store and ESM store account-aware; SQS, Kinesis,
  and DynamoDB Streams pollers use stored `accountId` for background reads
- **EventBridge** — rules, archives, and replays scoped per account;
  `RuleScheduler` uses rule's stored `accountId` for background dispatch
- **Kinesis** — stream keys and shard iterators scoped per account
- **Firehose** — delivery stream keys scoped per account
- **Pipes** — pipe keys scoped per account; poller uses stored `accountId`
- **Scheduler** — schedule and group keys scoped per account; dispatcher
  uses stored `accountId` for background execution
- **EKS** — cluster keys scoped per account; `accountId` stored on
 `Cluster` model (`@JsonIgnore`) for background use
- **MSK** — cluster keys scoped per account; readiness poller uses stored
  `accountId`; `accountId` stored on `MskCluster` model (`@JsonIgnore`)
- **ECR** — repository keys scoped per account via `effectiveAccount()`
  backed by `regionResolver`
- **OpenSearch** — domain keys scoped per account; readiness poller uses
  stored `accountId`; `accountId` stored on `Domain` model (`@JsonIgnore`)

Replace all occurrences of the hardcoded literal `"000000000000"` and
`config.defaultAccountId()` calls in ARN construction with
`regionResolver.getAccountId()` so that ARNs reflect the actual requesting
account:

- KMS — key ARNs and default key policy principal
- ELBv2 — load balancer, target group, listener, and rule ARNs
- AutoScaling — group, launch configuration, and policy ARNs
- API Gateway — VTL execution context `accountId`
- ElastiCache — user ARNs in DescribeUsers response
- CodeDeploy — application, deployment group, instance, and target ARNs
- CodeBuild — CloudWatch log group ARN
- Transfer — server and user ARNs
- S3 — ACL owner ID in GetBucketAcl / GetObjectAcl responses
- CloudFormation — stack ARN, changeset ARN, and `AWS::AccountId`
  pseudo-parameter; captures account at request time before handing
  off to executor thread
- DynamoDB TTL sweeper — use `scanAllAccountsAsMap()` so the background
  TTL sweep covers all accounts, not just the default

- Add `AccountIsolationIntegrationTest` verifying that SQS queues,
  DynamoDB tables, S3 buckets, Kinesis streams, EventBridge rules,
  Lambda functions, and Secrets Manager secrets created under one
  account are invisible when queried under a different account
- Update unit tests for EKS, MSK, ECR, Pipes, Scheduler, and Glue
  to pass `RegionResolver` through constructors (removes mock of
  `config.defaultAccountId()`)
2026-05-09 08:02:24 -05:00
Kenshin Okinaka 7a036fdf59 fix(sqs): drop uppercase "Tags" read from CreateQueue JSON handler (#752)
* fix(sqs): drop uppercase "Tags" read from CreateQueue JSON handler

AWS SQS JSON 1.0 schema uses lowercase "tags" for CreateQueue (uppercase
"Tags" is reserved for TagQueue). Real AWS treats unknown JSON fields as
ignored, so a hand-crafted client sending uppercase "Tags" would lose its
tags on AWS — but floci silently persisted them, diverging from AWS
behavior and masking client bugs at migration time.

Drop the defensive uppercase merge and add JSON-protocol integration
tests for both the canonical lowercase path (tags persist) and the
uppercase-as-unknown-field path (tags ignored).

* test(sqs): wrap CreateQueue-with-tags tests in try/finally for cleanup

Wrap CreateQueue + ListQueueTags + DeleteQueue test bodies so the
cleanup DeleteQueue runs in a finally block. A failed assertion
previously left an orphan queue, which could mask flake under re-runs
since CreateQueue is idempotent and won't re-apply tags to an existing
queue.
2026-05-09 00:32:49 -05:00
Hector Ventura 15c9f58aae fix(apigateway): treat ANY method as wildcard for concrete HTTP methods (#710) (#750) 2026-05-08 23:38:36 -05:00
Kenshin Okinaka 9b68bd0377 feat(ses): add v2 TagResource / UntagResource / ListTagsForResource (#749)
* feat(ses): add v2 TagResource / UntagResource / ListTagsForResource

Implements the v2 SES tag endpoints at /v2/email/tags. Initial scope
covers ConfigurationSet ARNs only
(arn:aws:ses:<region>:<account>:configuration-set/<name>); other
resource types return NotFoundException so follow-up PRs can extend
coverage to Identity, EmailTemplate, etc.

Behavior aligned with observed AWS responses:

- TagResource enforces ARN/signing region match strictly and rejects
  mismatches with BadRequestException ("Failed to tag resource").
- UntagResource and ListTagsForResource route lookups to the ARN's
  region instead, so a region mismatch surfaces as NotFoundException
  with the resource-specific message (e.g. "No ConfigurationSet
  present with name: <name>").
- TagResource merges by key (existing keys are replaced, others
  retained); UntagResource silently skips keys not present.
- Empty Tags / TagKeys lists are rejected with BadRequestException to
  match AWS validation.
- ARN parsing uses the shared AwsArnUtils helper; missing region or
  account in the ARN is rejected as BadRequest, matching AWS.

Tests:

- New SesTagsV2IntegrationTest for endpoint-focused coverage (lifecycle,
  region-mismatch asymmetry, validation errors).
- Cross-feature round-trip in SesConfigurationSetV2IntegrationTest
  verifying that tags supplied to CreateConfigurationSet are reachable
  via ListTagsForResource.
- New SesTagResourceTest in the Java SDK compatibility suite.

* refactor(ses): drop unused region parameter from list/untag tag service methods

listResourceTags and untagResource route lookups by the ARN's region, so
the request signing region they accepted was never read. Remove it and
stop resolving it in the controller. tagResource still takes region
because it strictly validates it against the ARN.
2026-05-08 19:42:54 -05:00
Dixit R Jain 1ffe905271 fix: SQS tags set at CreateQueue not returned by ListQueueTags (#747)
Tags passed to CreateQueue were silently dropped in both the Query
and JSON protocol handlers — neither extracted the Tags parameter
before calling sqsService.createQueue().

Changes:
- SqsQueryHandler: extract Tag.N.Key/Value params and pass to service
- SqsJsonHandler: read both 'Tags' and 'tags' fields (botocore sends
  lowercase 'tags' for CreateQueue but uppercase 'Tags' for TagQueue)
- SqsService: add createQueue overload accepting tags; existing 2-arg
  and 3-arg overloads delegate with null tags (no callers broken)

Closes #699
2026-05-08 17:17:36 -05:00
Dixit R Jain 3ae5c7b467 feat(apigatewayv2): Add WebSocket data-plane support (#712)
* feat: implement API Gateway v2 WebSocket data-plane support Implement full WebSocket data-plane for API Gateway v2, including: - Real WebSocket connection handling via Vert.x (ws://localhost:4566/ws/{apiId}/{stage}) - $connect/$disconnect/$default route lifecycle with Lambda integration - Custom route selection via routeSelectionExpression ($request.body.{field}) - @connections management API (POST/GET/DELETE) for server-to-client messaging - Lambda REQUEST authorizer support on $connect with identity source validation - Stage variable substitution in integration URIs - Multiple integration types: AWS_PROXY, AWS (VTL), HTTP_PROXY, HTTP (VTL), MOCK - Route response selection expression for bidirectional messaging - Binary frame support (isBase64Encoded: true) - 128 KB payload size limit enforcement (frames and @connections POST) - 10-minute idle timeout and 2-hour max connection duration - GoneException (410) for disconnected connections - $connect response headers propagation - Server-initiated close via @connections DELETE (skips $disconnect Lambda) Also includes: - Refactored LambdaArnUtils.extractFunctionNameFromUri as shared utility - Extended Authorizer/Integration/Stage models with new fields - Comprehensive Java integration tests (WebSocket lifecycle, routing, auth, etc.) - Node.js SDK compatibility tests using ws client and @aws-sdk/client-apigatewaymanagementapi - Updated documentation with full feature matrix

* test(apigatewayv2): support custom WebSocket endpoint via env var

- Update wsUrl helper to read FLOCI_ENDPOINT environment variable
- Convert http/https schemes to ws/wss for WebSocket compatibility
- Strip trailing slashes from endpoint URL for consistent formatting
- Enable testing against non-localhost endpoints for CI/CD flexibility

* fix: use AwsErrorResponse for @connections API error responses

Replace raw JSON string literals in handlePostToConnection,
handleGetConnectionInfo, and handleDeleteConnection with the
project-standard AwsErrorResponse record, which serialises to
the correct {"__type": ..., "message": ...} wire shape.

* fix: simplify extractFunctionNameFromUri using AwsArnUtils.parse

Adopt AwsArnUtils.parse() as the core of the implementation per
reviewer suggestion. One addition beyond the suggested snippet:
the API Gateway v1 integration URI format embeds a Lambda ARN
inside an apigateway ARN (resource starts with 'path/.../functions/'),
so we detect that pattern and recurse on the embedded ARN before
applying the standard function-name extraction. All 43
LambdaArnUtilsTest cases pass, including the API Gateway v1 style URI.
2026-05-08 17:15:35 -05:00
Hector Ventura 01dbc76fc8 feat(docker): named-volume storage for child containers (#743)
Replace the FLOCI_STORAGE_HOST_PERSISTENT_PATH footgun with automatic
named Docker volume management for RDS, OpenSearch, MSK, and ECR.

- Each resource gets a collision-free 6-char hex volumeId generated once
  at creation and stored in the model. Container and volume names both use
  it: floci-{service}-{volumeId}
- Volumes are labelled floci=true for easy pruning
- Memory mode always removes volumes on resource delete. Persistent modes
  retain by default; set prune-volumes-on-delete: true to remove on delete
- Mode detection: FLOCI_STORAGE_HOST_PERSISTENT_PATH set to an absolute
  path → host bind-mount mode (legacy); unset or non-absolute → named-
  volume mode. Volume names in host-persistent-path are not supported
- Removed the container-storage config key — no longer needed
- Updated docker-compose.yml, and all docs
2026-05-08 17:12:36 -05:00
Hector Ventura ccac5f63fd fix(eventbridge): persist and forward SqsParameters.MessageGroupId for FIFO SQS targets (#722) (#742)
EventBridgeHandler manually extracted only Id, Arn, Input, InputPath,
and InputTransformer from the request JSON node — SqsParameters was
never read. This meant the field was never stored, ListTargetsByRule
never returned it, and EventBridgeInvoker called sendMessage without
MessageGroupId, causing FIFO queue delivery to fail with:
"The request must contain the parameter MessageGroupId."

Fix:
- Add SqsParameters model (messageGroupId field)
- Add sqsParameters field to Target model
- EventBridgeHandler.handlePutTargets: read SqsParameters node and
  set it on the target before storing
- EventBridgeHandler.handleListTargetsByRule: write SqsParameters back
  into the response node when present
- EventBridgeInvoker: pass messageGroupId to sendMessage() for SQS
  targets, enabling FIFO queue delivery

Fixes #722
2026-05-07 23:23:29 -05:00
Roméo d7ec2b284f feat(textract): add Textract service support and integration tests (#719)
* feat(textract): add Textract service support and integration tests
* chore(textract): Implement PR suggestions
* fix(textract): remove completed async jobs to prevent memory growth
2026-05-07 21:08:39 -05:00
Kenshin Okinaka d971288d02 feat(ses): add UpdateAccountSendingEnabled (v1) (#737)
Implements the v1 Query action mirroring the existing v2
PUT /v2/email/account/sending endpoint. The Enabled parameter is
optional per AWS docs; missing or empty is treated as false.

Adds integration tests and a Java SDK compatibility test that
exercises both v1 UpdateAccountSendingEnabled and verifies state
is shared with the v2 GetAccount / PutAccountSendingAttributes path.
2026-05-07 21:03:05 -05:00
Chris Wright 271f27da62 fix(cfn): reconcile lambda functions on update (#736) 2026-05-07 20:49:45 -05:00
Hector Ventura 8e617c6add feat(transfer): add AWS Transfer Family management-plane API (#732)
Implements Phase 1 of the Transfer Family JSON 1.1 handler covering
17 operations across server lifecycle, user management, SSH key
management, and tagging.
2026-05-07 01:30:43 -05:00
Leonid Bogdanov 2cc3a1a3ba fix(s3): use queue ARN region when delivering notifications to SQS (#735) 2026-05-07 01:30:32 -05:00
Hector Ventura c2cc053853 feat(backup): AWS Backup management-plane API (#734) 2026-05-07 00:56:34 -05:00
Hector Ventura d51a0f9ce8 fix(ec2): prevent SSH port collision on concurrent RunInstances (#721) (#733)
immediately closing a ServerSocket. Between that check and Docker
binding the port, a second concurrent RunInstances call saw the same
port as free — both instances raced to bind 2200 and the second one
failed with "port is already allocated".

Fix: PortAllocator now maintains an in-memory ConcurrentSkipListSet of
reserved ports. allocate() is synchronized and adds the chosen port to
the set before returning, so concurrent callers skip it even before
Docker has bound it. release() removes the entry when the container is
terminated, making the port available for future instances.

Ec2ContainerManager.terminate() now calls portAllocator.release() after
the Docker container is removed.

Add PortAllocatorTest with 5 cases including a concurrency test that
races 20 threads simultaneously to confirm uniqueness.

Fixes #721
2026-05-07 00:37:31 -05:00
Hector Ventura 3b54255d7f feat(route53): add Route53 management-plane emulation (#715)
* feat(route53): add Route53 management-plane emulation

Implements Route53 Phase 1 with 17 operations: hosted zones (Create,
Get, Delete, List, ListByName, Count), resource record sets
(ChangeResourceRecordSets, List), change tracking (GetChange), health
checks (Create, Get, Delete, List, Update), tagging
(ListTagsForResource, ChangeTagsForResource), and GetAccountLimit.

Auto-creates SOA and NS apex records on zone creation. Rejects deletion
of non-empty zones. All changes return INSYNC immediately. IDs are
returned with path prefixes (/hostedzone/Z…, /change/C…) to satisfy
the SDK Route53IdInterceptor. Nameservers are configurable via
floci.services.route53.default-nameserver[1-4].

Adds OpenTofu and Terraform compatibility tests covering zone creation,
A record, auto-created SOA/NS records, health check, and tag persistence.

* feat(feat): adding missing endpoints

* feat(route53): fix timeout when creating route dns from terraform
2026-05-07 00:22:22 -05:00
Hector Ventura 86eac926f9 feat(elbv2): ALB Lambda target type (#730)
* feat(elbv2): add Lambda target type support for ALB forwarding
2026-05-06 23:51:38 -05:00
Hector Ventura e402c6ec18 feat(codedeploy): Server platform — on-premises instance management, Server AppSpec YAML, lifecycle events, SSM hook execution (#731)
- Add 7 on-premises instance operations: RegisterOnPremisesInstance,
  DeregisterOnPremisesInstance, GetOnPremisesInstance,
  BatchGetOnPremisesInstances, ListOnPremisesInstances,
  AddTagsToOnPremisesInstances, RemoveTagsFromOnPremisesInstances

- Add Server AppSpec YAML parsing (jackson-dataformat-yaml) extracting
  os and hooks map (hookName → [{location, timeout, runas}])

- Resolve deployment targets from EC2 tag filters (via Ec2Service) and
  on-premises instance tag filters; fall back to all registered
  on-premises instances when no filters are configured

- Run lifecycle events in order (ApplicationStop → DownloadBundle →
  ValidateService) on a virtual thread per deployment; DownloadBundle
  and Install auto-succeed as infrastructure steps

- Execute AppSpec hook scripts via SSM Run Command when the instance is
  registered in SSM; graceful degradation (treat as succeeded) when SSM
  is not available for an instance

- Refactor deploymentTargets from two-level to three-level
  (region→deploymentId→targetId→wrapper) to support multi-instance
  Server deployments alongside existing Lambda/ECS single-target shape

- Add SsmCommandService helpers: isInstanceRegistered,
  sendCommandToInstance, getCommandInvocationStatus

- Add OnPremisesInstance model with instanceName, instanceArn,
  iamSessionArn, iamUserArn, registerTime, deregisterTime, tags,
  registrationStatus
2026-05-06 23:36:50 -05:00
Hector Ventura f31a07f287 feat(ssm): add Run Command and ec2messages agent protocol (#728) 2026-05-06 22:21:59 -05:00
Kenshin Okinaka 59faf568fc fix(ses): align V2 identity error responses with AWS (#723)
PutEmailIdentityDkimAttributes, CreateEmailIdentity, and DeleteEmailIdentity
now return the same error codes and messages as real AWS SES v2:

- PutEmailIdentityDkimAttributes on unknown identity -> 400 BadRequestException
  ("Domain X is not verified for DKIM signing.")
- PutEmailIdentityDkimAttributes on email-format identity whose parent
  domain is registered -> 200 OK no-op (DKIM is a domain-level concept)
- CreateEmailIdentity on duplicate identity -> 400 AlreadyExistsException
- DeleteEmailIdentity on unknown identity -> 404 NotFoundException

V1 idempotent semantics (VerifyEmailIdentity / VerifyDomainIdentity /
DeleteIdentity) are preserved -- strict checks are added at the V2
controller level only.

Integration tests assert the exact AWS error messages (with trailing
period) and, for the email-with-registered-parent no-op case, verify
that the parent domain's DkimAttributes are unchanged before and after.
2026-05-06 18:51:48 -05:00
Christine Nguyen 692d665734 fix(s3): persist x-amz-meta-* metadata from presigned POST uploads (#727) 2026-05-06 18:36:15 -05:00
Christine Nguyen 9c3f263aa0 fix(sqs): add SenderId and ApproximateFirstReceiveTimestamp to Lambda event records (#726) 2026-05-06 18:34:19 -05:00
Christine Nguyen 860e35f6af fix(eventbridge): support account, region, and nested detail pattern matching (#725) 2026-05-06 18:31:33 -05:00
Kenshin Okinaka 00082d280f refactor(pipes): remove unused 2-arg invokeSqs overload (#718)
Following #714, the 2-arg PipesTargetInvoker.invokeSqs(arn, payload)
overload became dead code; only the region-aware 3-arg version is
called from invoke().
2026-05-06 17:55:49 -05:00
Arthur Tristram 254990c089 Fix[Eventbridge pipe - SQS] Eventbridge pipe always delivers sqs message to default region (#714)
* Issue #647 Fix- Added missing region functionality.
* Issue #647 Fix- Added missing region functionality.
2026-05-06 00:05:37 -05:00
Kenshin Okinaka bd3a33326c feat(ses): add MAIL FROM domain and identity attribute operations (#716)
* feat(ses): add MAIL FROM domain and identity attribute operations

v1 (Query):
- SetIdentityMailFromDomain / GetIdentityMailFromDomainAttributes
- SetIdentityFeedbackForwardingEnabled
- SetIdentityHeadersInNotificationsEnabled
- GetIdentityNotificationAttributes now reflects the stored
  feedbackForwardingEnabled and per-NotificationType
  headersInNotificationsEnabled flags instead of hard-coded defaults

v2 (REST JSON):
- PUT /v2/email/identities/{id}/mail-from -> PutEmailIdentityMailFromAttributes
- GetEmailIdentity response surfaces real MailFromAttributes
  (MailFromDomain / MailFromDomainStatus / BehaviorOnMxFailure) instead
  of the previously hard-coded "" / NOT_STARTED / USE_DEFAULT_VALUE
- v1 PascalCase <-> v2 SCREAMING_SNAKE BehaviorOnMxFailure values are
  translated at the controller boundary, with both ends rejecting
  unknown enum values

Identity gains mailFromDomain, behaviorOnMxFailure (v1 form),
mailFromDomainStatus, and headersInNotificationsEnabled fields. The
service layer normalizes BehaviorOnMxFailure to the canonical SESv1
enum values (UseDefaultValue / RejectMessage), so storage is
consistent regardless of which protocol wrote it.

Validation (verified against live aws-cli output):
- ForwardingEnabled / Enabled / MailFromDomain are required on the
  matching v1 setters; missing values produce InvalidParameterValue
  rather than silently being treated as false / null
- An empty-string MailFromDomain remains the documented "clear" path,
  distinct from a missing parameter; whitespace-only values are
  rejected (only "" or null clear the setting)
- BehaviorOnMxFailure / NotificationType enum violations return the
  AWS-canonical "1 validation error detected: Value at '<param>' failed
  to satisfy constraint: Member must satisfy enum value set: [...]"
  message: ValidationError on v1, BadRequestException on v2
- Unknown identity on v1 setters returns InvalidParameterValue with
  the AWS-canonical "Identity <X> does not exist." form (HTTP 400)
- v2 PutEmailIdentityMailFromAttributes follows the same wire mapping:
  unknown identity surfaces as BadRequestException (HTTP 400) via
  remapV1Exception, with the same "Identity <X> does not exist."
  message text. Schema / enum validation runs before the service call
  so an unknown enum on a missing identity still surfaces as an enum
  error rather than as the identity error
- v2 controller validates that MailFromDomain and BehaviorOnMxFailure
  are JSON strings; non-textual values produce BadRequestException
- AwsQueryController.SES_ACTIONS picks up the new v1 actions for the
  auth-less fallback dispatch

Tests: 21 v1 integration cases, 9 v2 integration cases, 4 SDK compat
cases (AWS Java SDK 2.42.24).

* fix(ses): align identity-setter missing-identity errors with live AWS

Previously setFeedbackForwardingEnabled threw NotFoundException/404 and
setHeadersInNotificationsEnabled threw a Floci-specific
"Identity <X> does not exist." message. Real AWS verified via
aws-cli returns InvalidParameterValue (HTTP 400) for both, but with
*different* operation-specific message texts:

- SetIdentityFeedbackForwardingEnabled (also v2 PUT /feedback after
  remapV1Exception):
    Identity X is invalid. Must be a verified email address or domain.
- SetIdentityHeadersInNotificationsEnabled:
    Identity X is invalid. It must be a verified email address or domain.
- SetIdentityMailFromDomain (unchanged in this commit):
    Identity <X> does not exist.

Update the service-level throws so each setter emits its operation's
exact wire shape. setFeedbackForwardingEnabled now also benefits the
pre-existing v2 PUT /feedback endpoint, which previously surfaced
NotFoundException/404 instead of BadRequestException/400.

Tests:
- v1 unknown-identity coverage for SetIdentityFeedbackForwardingEnabled
  (new) and updated message-text assertion for HeadersInNotificationsEnabled
- v2 unknown-identity coverage for PUT /feedback
- SDK compat additions: getIdentityNotificationAttributes round-trip
  exercising forwarding/header flags, and v2
  PutEmailIdentityMailFromAttributes unknown-identity throwing
  BadRequestException

* test(ses): update putFeedbackAttributes_notFound to expect BadRequest

The previous commit changed setFeedbackForwardingEnabled to throw
InvalidParameterValue (HTTP 400) for missing identities to match real
AWS, which propagates through remapV1Exception as BadRequestException
on the v2 PUT /feedback path. The pre-existing
SesV2IntegrationTest.putFeedbackAttributes_notFound still asserted the
old 404 / NotFoundException behavior, so it began failing in CI.

Update the test to expect 400 / BadRequestException, matching the
verified live AWS response.
2026-05-05 22:41:17 -05:00
Taewoo Ryu aee46fe2da feat(lambda): mount host AWS config for real credential discovery (#703)
When FLOCI_SERVICES_LAMBDA_AWS_CONFIG_PATH is set, bind-mount the host
path read-only into Lambda containers at /opt/aws-config and set
AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE env vars so the SDK
discovers credentials regardless of container HOME directory.

When unset, credentials are read from Floci's own environment with a
fallback to test/test/test. Blank values are treated as absent.

Closes #686
2026-05-05 18:22:12 -05:00
Hector Ventura d620c18534 fix(ec2): AssociateRouteTable associationState, RouteTable association filters, DescribeTags filters (#706)
- Include <associationState> in AssociateRouteTable response so Terraform
  v6 waiters can confirm association without timing out
- Add association.route-table-association-id, association.subnet-id,
  association.gateway-id, and association.main filter support to
  DescribeRouteTables
- Apply resource-id, resource-type, key, and value filters in DescribeTags
  (previously all filters were ignored, returning every tag)
- Add RouteTableAssociation.gatewayId field for gateway-id filter support
- Add integration tests covering new filters and associationState assertion
- Add VPC networking resources to compat-terraform and compat-opentofu
  suites (IGW, subnet, route table + association, security group)
2026-05-05 00:11:51 -05:00
Hector Ventura 7900cdbcb2 fix(docker): respect DOCKER_HOST env var and handle missing URI scheme (#705)
When DOCKER_HOST is set without a scheme (e.g. "10.37.124.101:2375" in
Bitbucket Pipelines), docker-java's createDefaultConfigBuilder() calls
URI.create() on the raw value and throws IllegalArgumentException before
Floci's own withDockerHost() override can take effect. PR #665 normalized
the value from floci.docker.docker-host but left this crash path open.

- Add createDockerConfigBuilder() to catch the IAE and fall back to a
  fresh Builder() so the normalized host can still be applied
- Add resolveEffectiveDockerHost() to use DOCKER_HOST env var (normalized)
  as a fallback when floci.docker.docker-host is at its default unix socket,
  so CI environments like Bitbucket Pipelines work without requiring a
  separate FLOCI_DOCKER_DOCKER_HOST setting
- Add unit tests covering the Bitbucket scenario and edge cases

Fixes #663
2026-05-04 23:04:13 -05:00
Kenshin Okinaka 7fa2a28c62 fix(appconfig): use capital "Tags" body key matching AWS SDK wire format (#704)
AppConfigTagHandler inherited the default tagsBodyKey() = "tags"
(lowercase), so SharedTagsController parsed and serialised the tag
payload with the lowercase key. The AWS spec for AppConfig
TagResource and ListTagsForResource is capital "Tags" with a map
body, which is what AWS SDK clients send and expect — so SDK calls
to appConfig.tagResource(...) silently dropped tags and listing
came back empty.

Override tagsBodyKey() on AppConfigTagHandler to return "Tags".
The other axes (POST method, map body, lowercase tagKeys query)
already match the defaults so no further override is needed.

AppConfigIntegrationTest is updated to send capital "Tags" bodies
and assert capital "Tags" response keys, matching the AWS SDK
wire format. AppConfigTest (SDK compatibility) now exercises a
tagResource → listTagsForResource → untagResource round-trip via
AppConfigClient to lock in the wire format end-to-end.
2026-05-04 20:18:53 -05:00
Hector Ventura 4fe93aa379 feat(eventbridge): add Archive and Replay support (#702)
Implement EventBridge Archive and Replay APIs:
- Archive, ArchivedEvent, Replay, ArchiveState, ReplayState models
- ReplayDispatcher: async Vertx-based replay execution with cancel support
- EventBridgeService: createArchive, describeArchive, updateArchive,
  deleteArchive, listArchives, startReplay, describeReplay, cancelReplay,
  listReplays; event capture on putEvents via captureToArchives
- EventBridgeHandler: 9 new action cases wired to service methods
- Storage: 3 new StorageBackend fields (archives, archivedEvents, replays)
  wired through StorageFactory
2026-05-04 17:30:27 -05:00
3cc04994ea feat(sqs,dynamodb): TRACE-level payload logging (#697)
* feat(sqs,dynamodb): add TRACE-level payload logging

Add TRACE log lines that include request/response payloads for the
common SQS and DynamoDB operations -- off by default, opt-in via
per-category log level. Helps diagnose TestContainers-based test
failures where DEBUG IDs alone don't reveal what was sent.

SQS: SendMessage / SendMessageBatch / ReceiveMessage / DeleteMessage /
DeleteMessageBatch log body and attributes.

DynamoDB: PutItem / GetItem / UpdateItem / DeleteItem log the item;
Query and Scan log the returned and scanned counts (bodies would be
too noisy).

Ship quarkus.log.min-level: TRACE so a single category override is
enough -- users don't also have to lower the root floor.

Closes #613

* Apply suggestions from code review

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Hector Ventura <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-04 17:30:10 -05:00
Kenshin Okinaka 8e30c09d0a feat(scheduler): support TagResource, UntagResource, ListTagsForResource (#700)
* feat(scheduler): support TagResource, UntagResource, ListTagsForResource

Implements the three remaining EventBridge Scheduler tag APIs by
extending the shared /tags/{arn} dispatcher. Tags apply to schedule
groups only, matching AWS behavior; ARNs pointing at individual
schedules return ValidationException.

A survey of all ~75 AWS services that share the /tags/{arn} path
shows three independent shape axes — body key (`tags` lower vs
`Tags` capital), body structure (map vs list of {Key, Value}), and
untag query parameter name (`tagKeys` vs `TagKeys`) — and most
"capital Tags" services still use lowercase tagKeys query, so these
axes vary independently. TagHandler exposes them as five orthogonal
default methods rather than a coarse-grained enum:

- tagsBodyKey()           defaults to "tags"
- tagsBodyIsList()        defaults to false (map)
- tagKeysQueryName()      defaults to "tagKeys"
- tagResourceUsesPut()    defaults to false (POST)
- strictTagValidation()   defaults to false (lenient parsing)

The defaults match the most common AWS shape (~73 services use
lowercase tags map + POST + lowercase tagKeys) so handlers like
EKS, Pipes, and AppConfig need no overrides. The dispatcher
returns 405 MethodNotAllowedException for the unused HTTP method
per handler. Strict input validation (missing Tags, wrong-shaped
Tags, missing TagKeys, entries missing Key or Value) is enforced
when strictTagValidation() is true, mirroring the AWS Scheduler
error shape; lenient handlers retain the looser parsing they had
before.

SchedulerTagHandler overrides tagsBodyKey, tagsBodyIsList,
tagKeysQueryName, and strictTagValidation. ApiGatewayTagHandler
overrides tagResourceUsesPut to true. AppConfigIntegrationTest
switches its tagApplication call from PUT to POST to match the
AWS spec for AppConfig (was relying on the dispatcher's prior
leniency on HTTP method).

* fix(tags): normalize empty body and reject non-object payloads

Address Copilot review on floci-io/floci#700.

- doTagResource normalizes null/blank request bodies to "{}" before
  passing to ObjectMapper.readTree, mirroring SchedulerController's
  parseTags. Previously an empty body raised a Jackson parse error
  that strict handlers surfaced as a ValidationException with a raw
  Java/Jackson message instead of the structured AWS error shape.
- parseTags adds a strict-only check that the JSON root is an
  object. A request body like a JSON array or string used to fall
  through to "Value null at 'Tags' ..." which misleads about the
  actual problem; it now reports that the payload itself must be a
  JSON object.

SchedulerIntegrationTest covers both paths with a 400 assertion.
2026-05-04 17:22:12 -05:00
Hector Ventura 023880b7d9 feat(parity): LocalStack drop-in compatibility (#696)
- Translate LocalStack env vars (LOCALSTACK_HOST, PERSISTENCE, LAMBDA_DOCKER_NETWORK, etc.)
  to Floci equivalents automatically at startup; opt out with LOCALSTACK_PARITY=false
- Serve /_localstack/init and /_localstack/health alongside /_floci/* equivalents
- Report executed scripts with path, state, and return_code in /_floci/init response
- Add /_aws/sqs/messages GET (non-destructive peek) and DELETE (purge) inspection endpoint
- Add /_aws/execute-api/{apiId}/{stageName} LocalStack-compat path for REST API invocation
- Add four-phase init hook lifecycle (boot/start/ready/stop) with dual-path discovery
  (/etc/floci/init/ and /etc/localstack/init/ compat paths)
- Install Python 3, AWS CLI, boto3 in standard image; wrap aws binary to pre-configure
  --endpoint-url=http://localhost:4566 so init scripts need no extra flags
- Wire entrypoint.sh + gosu privilege drop into all Dockerfile variants
- Add migration guide and update README, docker-compose, docker-images, SQS, and
  initialization-hooks docs
2026-05-04 01:15:59 -05:00
Tristan BurchandHector Ventura b84d205b89 feat: Glue Schema Registry support (#621)
* feat(glue): add Glue Schema Registry support
* Move Glue SDK coverage to compatibility tests
* Align protobuf compatibility expectations
* Resolve services index merge conflict
* Remove unused Lombok compatibility dependency
* Serialize Glue schema registry timestamps as strings
* Tighten Glue schema registry name validation
* Avoid duplicate schema registry index rebuild
* Limit schema registry in-memory constructor visibility
* Clone Glue tables before resolving schema references
* Align Glue schema registry response shapes
* Extract Glue schema version resolver helper

Both validateSchemaReference and withResolvedSchemaReference duplicated
the latest-version computation and the four-argument getSchemaVersion
call. Pull that into a private resolveSchemaVersion(SchemaReference)
helper so the call sites read at one level of abstraction and a future
change to the resolution rule lands in one place.
* Fix Glue schema version list projection

---------

Signed-off-by: Tristan Burch <tburch@users.noreply.github.com>
Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
2026-05-03 22:41:19 -05:00
Kenshin Okinaka ac891db5a7 feat(ses): add TestRenderTemplate (v1) and TestRenderEmailTemplate (v2) (#692)
* feat(ses): add TestRenderTemplate (v1) and TestRenderEmailTemplate (v2)

Render a stored SES template against caller-supplied data and return the
resulting MIME message. v1 is dispatched via the Query protocol; v2 is
exposed at POST /v2/email/templates/{name}/render.

Template variable substitution is now strict: a missing attribute in the
rendering data raises MissingRenderingAttribute (mapped to BadRequestException
on v2), matching AWS / moto / LocalStack semantics. Invalid TemplateData
JSON raises InvalidRenderingParameter; non-object TemplateData is rejected
with operation-appropriate errors on the send paths (InvalidParameterValue
on v1, BadRequestException on v2).

The rendered output is a hand-rolled multipart/alternative MIME with a
Date header (UTC), Subject header, and text/plain + text/html parts.
Transfer encoding is auto-selected (7bit for ASCII bodies, 8bit for UTF-8)
matching moto's encode_7or8bit. Body line endings are normalized to CRLF.
Subject control characters and XML 1.0 invalid characters in the rendered
output are stripped to keep the response parseable by SDK clients.

Bulk per-entry rendering errors (MissingRenderingAttribute /
InvalidRenderingParameter raised at apply time) surface as INVALID_PARAMETER
in BulkEmailEntryResults rather than generic FAILED.

No new dependencies are introduced.

* test(ses): consolidate new SesServiceTemplateTest cases via @ParameterizedTest

Group 23 of the new unit tests added in this PR into 6
@ParameterizedTest methods driven by MethodSource data sets:

- pickTransferEncoding (ascii vs non-ascii) -> 1 test, 4 cases
- parseRenderingData invalid inputs -> 1 test, 5 cases
- normalizeToCrlf line-ending variants -> 1 test, 4 cases
- mapErrorCodeToBulkStatus -> 1 test, 4 cases
- sanitizeSubject control / DEL / Unicode preservation -> 1 test,
  6 cases (null-input case kept separate)
- stripXml10InvalidChars C0 / noncharacters / surrogates -> 1 test,
  11 cases

Coverage is preserved (every input that was exercised before is still
exercised; surfacing each case as an individual test makes the run
report show 58 cases instead of 49 for this file). The remaining
tests -- buildTestRenderMime structure assertions and the original
applyTemplateData edge cases -- stay as individual @Test methods
because they have distinct multi-step assertions.

* test(ses): address upstream Copilot style nits

- Remove unused containsString static import in
  SesTestRenderV2IntegrationTest after the parameterized refactor
- Replace assertEquals(true/false, ...) with assertTrue/assertFalse in
  SesServiceTemplateTest for clearer intent and better failure output
2026-05-03 09:18:10 -05:00
Chris Wright 7b0df82a86 fix(cfn): resolve floci virtual-hosted template urls (#690) 2026-05-02 20:55:42 -05:00
Chris Wright f359a94eaa fix(cfn): adopt existing dynamodb tables on update (#689) 2026-05-02 20:54:18 -05:00
Chris Wright c6763f12e7 fix(lambda): use function region in container AWS env (#687) 2026-05-02 20:53:06 -05:00
Hector Ventura 86bc33d115 fix: ecs delete resource issue (#685) 2026-05-02 16:51:05 -05:00
Hector Ventura b56c7ced82 fix(sfn): apply ItemSelector/Parameters transformation in Map state (#683)
Map state was passing each item raw to the branch executor, ignoring
ItemSelector (current AWS syntax) and Parameters (legacy syntax).

Now resolves the transform against the Map state's effective input
(after InputPath) and enriches the context with $$.Map.Item.Index
and $$.Map.Item.Value per iteration before calling executeBranch.
2026-05-02 13:32:17 -05:00
Hector Ventura b5dde6dae8 feat(autoscaling): EC2 Auto Scaling stored-state API + capacity reconciler (#681)
* feat(autoscaling): implement EC2 Auto Scaling Phase 1+2
* docs: updating documentation
2026-05-02 07:53:45 -05:00
Dixit R Jain 8fe2bf4c97 feat(apigatewayv2): add WebSocket API support, Update ops, Route/Integration Responses, Models, and Tagging (#682)
Closes #526

Add 27 new API Gateway v2 operations (21 → 48 total):

- WebSocket protocol: CreateApi with WEBSOCKET, wss:// endpoints,
  routeSelectionExpression validation, routeResponseSelectionExpression
- Update operations: UpdateApi, UpdateRoute, UpdateIntegration,
  UpdateAuthorizer, UpdateStage, UpdateDeployment
- Route Responses: full CRUD (5 ops)
- Integration Responses: full CRUD (5 ops)
- Models: full CRUD (5 ops)
- Tagging: TagResource, UntagResource, GetTags
2026-05-02 07:53:13 -05:00
Christian Franzen aaa1998508 fix(ecr): Properly check if host-persistent-path is the name of a Docker volume (#678) 2026-05-01 17:15:21 -05:00
Hector Ventura 91ed829ea0 feat(elbv2) alb proxy codedeploy ecs (#677)
* feat(elbv2,codedeploy): real ALB Vert.x proxy and ECS blue/green deployment

ELB v2 Phase 2: replace the mock ALB with a real Vert.x HTTP reverse proxy.
ElbV2DataPlane compiles listener rules into an atomic rule chain and proxies
requests to target group members. ElbV2HealthChecker runs periodic health
checks against registered targets. shiftListenerForward atomically rewrites
the default forward rule (simple or weighted) for CodeDeploy traffic shifts.

CodeDeploy Phase 3: implement full ECS blue/green deployment. CreateDeployment
drives the complete lifecycle — green task set creation, BeforeInstall /
AfterInstall / BeforeAllowTraffic hooks, ALB listener traffic shift (AllAtOnce,
Canary, or Linear), AfterAllowTraffic hook, green task set promoted to PRIMARY,
blue task set deleted. Compute platform is resolved from the Application when
the deployment group doesn't carry it, matching real AWS SDK behavior.

* fix: refactor to use arnUtils
2026-05-01 02:05:00 -05:00
Hector Ventura 57a8d58ed4 refactor: centralize ARN parsing and construction in AwsArnUtils (#676)
Replace ~60 scattered split(":")[n] accesses and "arn:aws:..." string
concatenations with a single Arn record that owns both responsibilities.

AwsArnUtils.Arn.of(service, region, accountId, resource).toString()
covers all construction. AwsArnUtils.parse() with regionOrDefault() /
accountOrDefault() covers all parsing. RegionResolver.buildArn() delegates
to Arn.of() internally.

Service-specific ARN parsers (LambdaArnUtils, DynamoDbTableNames,
AppConfigTagHandler) keep their domain validation but delegate the
six-field base parsing to AwsArnUtils.parse().
2026-05-01 01:19:17 -05:00
Chris Wright b15daf51ed feat: add Fn::ImportValue cross-stack reference resolution for CloudFormation (#669)
Implement cross-stack export/import support so CDK multi-stack deployments
resolve Fn::ImportValue tokens to actual values instead of passing them
through as literal strings.

Changes:
- Track exports from stack Outputs with Export.Name declarations
- Maintain a global per-region export registry in CloudFormationService
- Resolve Fn::ImportValue in CloudFormationTemplateEngine via the registry
- Add ListExports API action with AWS-compatible XML response
- Include ExportName in DescribeStacks output XML
- Validate duplicate export names across stacks (AWS-compatible error)
- Fail stack creation when Fn::ImportValue references a missing export
- Clean up exports on stack delete and update
- Route ListExports through AwsQueryController

Tests:
- Cross-stack Fn::ImportValue with Fn::Join
- Dynamic export names via Fn::Sub
- Export rename on stack update
- Duplicate export name rejection
- Missing import value failure
2026-04-30 21:27:53 -05:00
Avi Shefi 4bb4f24fcd fix(sqs): inject QueueUrl into form body for query protocol path-based requests (#670)
AWS SDKs using the form-encoded query protocol send queue-specific operations
(GetQueueAttributes, SendMessage, ReceiveMessage, etc.) with the queue URL as
the HTTP path and no QueueUrl in the body:

  POST /000000000000/my-queue HTTP/1.1
  Content-Type: application/x-www-form-urlencoded
  Action=GetQueueAttributes&AttributeName.1=QueueArn

#153 fixed routing for this pattern (preventing S3Controller from handling
the request), but QueueUrl was lost after the path rewrite, so SqsQueryHandler
received null and returned QueueDoesNotExist.

Fix: before rewriting the path, reconstruct the queue URL from the original
path components and append it to the entity stream as a form parameter
(&QueueUrl=...). SqsQueryHandler then reads it naturally from the form body.
Content-Length is updated when present. AwsQueryController is unchanged.

Affects Java SDK v1, Python boto3 (legacy), Go SDK v1, .NET SDK v1, and any
other client using the query protocol with path-based queue URL routing.
2026-04-30 20:33:25 -05:00