Commit Graph
78 Commits
Author SHA1 Message Date
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
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
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
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
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
jsoizo 13203954b3 feat(cognito): implement AdminRespondToAuthChallenge operation (#666)
Adds the admin variant of RespondToAuthChallenge, enabling server-side
challenge response handling with explicit UserPoolId validation.
Extracts shared challenge logic into processChallenge to avoid duplication.
2026-04-30 20:29:36 -05:00
Hector Ventura 832cdf94db feat(ec2): real Docker container execution with SSH, UserData, and IMDS (#658)
* feat(ec2): real Docker container execution with SSH, UserData, and IMDS
* fix: test for ec2
2026-04-30 18:28:17 -05:00
Christine Nguyen aeace3a778 fix(test): handle SDK retry race in OpenSearch createDomain test (#668) 2026-04-30 18:16:26 -05:00
Yorí 3f4865b949 Fix/lambda incorrect size limit (#674)
* fix(http): remove 8 KB per-attribute limit on form-encoded request bodies

Vert.x 4.x defaults HttpServerOptions.maxFormAttributeSize to a small
value (effectively 8 KB via the Netty AbstractHttpData limit). This
causes any request with Content-Type: application/x-www-form-urlencoded
that carries a single attribute larger than the limit to be rejected with
"Size exceed allowed maximum capacity".

Two places fixed:

- HttpOptionsCustomizer (new CDI bean): sets maxFormAttributeSize=-1 on
  the main Quarkus HTTP server so large form-encoded AWS Query Protocol
  requests (CloudFormation templates, EC2 UserData in base64, large IAM
  policies, etc.) are accepted. The overall body size is still bounded
  by quarkus.http.limits.max-body-size (512 MB).

- RuntimeApiServer: passes HttpServerOptions with maxFormAttributeSize=-1
  when creating the per-container Vert.x HTTP server. This fixes the case
  where the Lambda runtime posts a large synchronous response body (e.g.
  a 5 MB base64 payload) back to the Runtime API endpoint and the body
  is incorrectly decoded through the form attribute path.

* fix(lambda): enforce AWS invoke payload size limits (sync 6 MB, async 1 MB)

Rejects oversized invocation requests with HTTP 413 RequestTooLargeException
before dispatching to the container, matching the AWS Lambda API contract.
Also enforces the 6 MB sync response limit after the function returns.

* test(lambda): add tests for invoke payload size limits

Unit/integration tests (LambdaIntegrationTest) cover sync >6 MB and async >1 MB
request rejections plus boundary-at-limit acceptance. Compat test
(LambdaPayloadSizeLimitTest) uses the Java SDK to verify RequestTooLargeException
is surfaced correctly, including a Docker-gated test for the 6 MB response limit.

* test(lambda): add regression test for 5 MB response via RuntimeApiServer

Verifies that a sync invocation returning a 5 MB body (within the 6 MB AWS
limit) succeeds end-to-end. Without the maxFormAttributeSize fix on the
RuntimeApiServer, the Lambda runtime's POST of the large response body was
rejected by Netty's 8 KB form-attribute cap, crashing the request with
"Size exceed allowed maximum capacity".
2026-04-30 18:08:36 -05:00
Yorí 8eeb2244a7 Feat/lambda image config working directory (#673)
* feat(lambda): support ImageConfig.WorkingDirectory override

Propagate WorkingDirectory from the Lambda ImageConfig through the full
stack so container images that rely on a specific WORKDIR can be invoked
correctly, matching real AWS behavior.

- LambdaFunction: add imageConfigWorkingDirectory field + getter/setter
- LambdaService: parse WorkingDirectory on CreateFunction and
  UpdateFunctionConfiguration
- ContainerSpec: add workingDir record component
- ContainerBuilder: add withWorkingDir() fluent method
- ContainerLifecycleManager: pass workingDir to Docker via withWorkingDir()
- ContainerLauncher: apply workingDir when building the container spec
- LambdaController: serialize WorkingDirectory in ImageConfigResponse

* test(lambda): add tests for ImageConfig.WorkingDirectory

Unit tests (LambdaImageConfigTest):
- CreateFunction stores WorkingDirectory alongside Command/EntryPoint
- createFunction with all three fields together
- updateFunctionConfiguration updates and clears WorkingDirectory
- ContainerLauncher passes workingDir to ContainerSpec

Compat tests across all SDKs:
- awscli (lambda.bats): create/get/update WorkingDirectory round-trip
- Java SDK (LambdaFunctionConfigTest): ImageConfig.WorkingDirectory round-trip
- Python (test_lambda_function_config.py): TestImageConfigWorkingDirectory class
- Node (lambda.test.ts): create/update WorkingDirectory assertions
- Go (lambda_test.go): TestLambdaImageConfigWorkingDirectory subtests
- Rust (lambda_test.rs): full create/get/update round-trip
2026-04-30 17:25:03 -05:00
Hector Ventura 37c7969cb4 feat(cloudformation): support AWS::Lambda::EventSourceMapping resource type (#654) 2026-04-30 00:26:43 -05:00
Hector Ventura c91b74ae4e feat(dynamodb): implement ExportTableToPointInTime, DescribeExport, and ListExports (#653) 2026-04-29 23:16:50 -05:00
Hector Ventura 2832bc7714 feat(codebuild,codedeploy): Implementing real build in docker phase2 (#649)
* feat(codebuild,codedeploy): real build execution and Lambda deployment engine

CodeBuild Phase 2: runs buildspec phases inside real Docker containers.
Source injected via docker cp (copyArchiveToContainerCmd); artifacts
extracted via docker cp (copyArchiveFromContainerCmd). No bind mounts —
works transparently in Docker-in-Docker. CloudWatch log streaming, S3
artifact upload, StopBuild, RetryBuild, ListBuilds, ListBuildsForProject.

CodeDeploy Phase 2: real Lambda deployments with traffic shifting via
alias RoutingConfig, lifecycle hook invocation against live Lambda
functions, PutLifecycleEventHookExecutionStatus callback, and
auto-rollback on hook failure. CreateDeployment, GetDeployment,
deployment state polling, ListDeployments, BatchGetDeployments,
ListDeploymentTargets, BatchGetDeploymentTargets.

* docs: updating docs with new services details
2026-04-29 22:11:55 -05:00
Kenshin Okinaka 44eb8d2379 feat(ses): add SendBulkEmail (v2) and SendBulkTemplatedEmail (v1) (#645)
* feat(ses): add SendBulkEmail (v2) and SendBulkTemplatedEmail (v1)

Adds bulk templated email support for both the SES v1 Query API
(SendBulkTemplatedEmail) and the SES v2 REST JSON API
(POST /v2/email/outbound-bulk-emails). The two endpoints share a
single SesService.sendBulkTemplatedEmail method that resolves the
template upfront, merges DefaultTemplateData with each entry's
ReplacementTemplateData at the JSON-key level (replacement wins),
renders subject/text/html via the existing applyTemplateData helper,
and reuses sendEmail per destination so each successful entry appears
in the existing /_aws/ses inspection mailbox with a unique MessageId.

Per-entry results are returned in the BulkEmailEntryResult shape with
status mapped to the AWS wire format expected by each protocol
(CamelCase for v1, SCREAMING_SNAKE for v2). Per-entry AwsException
codes are mapped to the closest BulkEmailEntryResult.Status (e.g.
InvalidParameterValue -> INVALID_PARAMETER, which renders as
"InvalidParameterValue" on v1), falling back to FAILED for unexpected
exceptions.

Template lookup failures and account-sending-paused conditions are
top-level errors on both protocols, with v1 raising
AccountSendingPausedException to match AWS semantics.

* fix(ses): enforce account sending check in v1 SendEmail/SendRawEmail/SendTemplatedEmail

v1 Query SES handlers previously sent mail even when account-level
sending was disabled, while v2 REST JSON handlers and the new
SendBulkTemplatedEmail correctly return AccountSendingPausedException.
Add the same guard at the top of handleSendEmail, handleSendRawEmail,
and handleSendTemplatedEmail to align v1 with v2 and AWS semantics.
2026-04-29 17:28:09 -05:00
Yorí 1cccf43f7b feat(cognito): include all standard attributes in DescribeUserPool Schema (#642)
* feat(cognito): include all standard attributes in DescribeUserPool SchemaAttributes

AWS Cognito always returns all 20 standard OIDC attributes (sub, name,
email, phone_number, etc.) in SchemaAttributes when describing a user
pool, even if none were explicitly configured. Floci was returning only
what was passed in Schema during creation.

Adds CognitoStandardAttributes with the full default set and a merge()
helper that overlays explicit schema overrides and appends custom:
attributes after the standard ones.

* test(cognito): add compat tests for standard SchemaAttributes across all SDKs

Adds DescribeUserPool SchemaAttributes coverage to all compatibility test
suites (AWS CLI/bats, Go, Java, Node, Python, Rust), verifying that all
20 standard OIDC attributes are returned and that sub is required and
immutable.
2026-04-29 00:01:48 -05:00
Hector Ventura 87eda4bcfc fix(cloudformation): wrap ZipFile inline source in zip archive before passing to Lambda (#639)
CloudFormation's ZipFile property contains raw source code (JS, Python, etc.),
but LambdaService expects Code.ZipFile to be a base64-encoded zip archive per
the Lambda REST API contract. Passing raw source directly caused every inline
Lambda to land in CREATE_FAILED with "Illegal base64 character".

Fix: added sourceToZipBase64() that wraps the raw source in a ZipEntry (filename
derived from the Handler property and runtime extension — .js for Node, .py for
Python) and base64-encodes the archive before forwarding to LambdaService.

Closes #607
2026-04-28 22:36:30 -05:00
Kenshin Okinaka cd42caa254 feat(ses): add ConfigurationSet CRUD on v1 Query and v2 REST JSON (#631)
* feat(ses): add ConfigurationSet CRUD on v1 Query and v2 REST JSON

Adds Configuration Set name management on both protocols:

- v1 Query: CreateConfigurationSet, DescribeConfigurationSet,
  ListConfigurationSets, DeleteConfigurationSet
- v2 REST JSON: POST/GET (single)/GET (list)/DELETE under
  /v2/email/configuration-sets[/{name}]

Storage is region-scoped and shared across both protocols, with name as
the primary key. Tags are persisted on v2 create and returned on v2 get;
v1 only round-trips the name (real SES v1 has no tags on configuration
sets). Errors map ConfigurationSetAlreadyExists / ConfigurationSetDoesNotExist
(v1) onto AlreadyExistsException 400 and NotFoundException 404 (v2)
via the existing SesController remap helper.

Field validation (per AWS limits): ConfigurationSetName must match
^[A-Za-z0-9_-]{1,64}$; each Tag Key is 1-128 chars and each Tag Value is
0-256 chars; non-array Tags are rejected with BadRequestException.

Out of scope (future PRs): SendingOptions / EventDestinations /
TrackingOptions / DeliveryOptions / ReputationOptions / SuppressionOptions /
VdmOptions, and ConfigurationSetName validation in the Send* APIs.

* fix(ses): allow Tag without Value on ConfigurationSet create

AWS SDKs commonly omit Tag.Value when only the key matters
(Tag.builder().key("env").build()), serialising the request without a
Value field. Floci was rejecting these calls with "Tag Value is
required", diverging from typical SDK and LocalStack behaviour. Drop
the required-value check; the 0-256 length constraint still applies
when a value is present.
2026-04-28 20:21:07 -05:00
Hector Ventura d28b175cb0 fix(ec2): persist VPC DNS attributes and support DescribeVpcEndpointServices (#624) 2026-04-28 00:39:32 -05:00
Hector Ventura f5ec6fc887 feat(codebuild,codedeploy): add management APIs (#622) 2026-04-28 00:09:12 -05:00
Hector Ventura d39bdf1c22 feat(elbv2): Elastic Load Balancing v2 management API (Phase 1) (#617)
* feat(elbv2): add Elastic Load Balancing v2 management API (Phase 1)
* fix: adding new service to health check test
2026-04-27 22:52:52 -05:00
Hector Ventura c7152cef8a fix(kms): GetKeyRotationStatus returns false for asymmetric and HMAC keys (#618)
* fix(kms): return false for GetKeyRotationStatus on asymmetric/HMAC keys

AWS updated GetKeyRotationStatus behavior so asymmetric and HMAC keys
return { KeyRotationEnabled: false } instead of UnsupportedOperationException.
EnableKeyRotation and DisableKeyRotation still reject these key types.

* fix(kms): return false for GetKeyRotationStatus on asymmetric/HMAC keys

AWS updated GetKeyRotationStatus behavior so asymmetric and HMAC keys
return { KeyRotationEnabled: false } instead of UnsupportedOperationException.
EnableKeyRotation and DisableKeyRotation still reject these key types.
2026-04-27 22:50:49 -05:00
TiM e6341cfc09 fix(s3): emit x-amz-transition-default-minimum-object-size on lifecycle GET/PUT (#441) (#615)
* fix(s3): emit x-amz-transition-default-minimum-object-size on lifecycle GET/PUT (#441)

terraform-provider-aws v6.x added a stability wait that compares
TransitionDefaultMinimumObjectSize between PUT input and GET output.
The AWS SDK v2 reads that field only from the
x-amz-transition-default-minimum-object-size response header, never
from the XML body. Floci stored lifecycle XML verbatim and never set
the header, so the SDK parsed it as null/empty, never matched the
provider default (all_storage_classes_128K), and the wait timed out
after 3 minutes.

Persist the value on the Bucket model, read it from the PUT request
header (defaulting to all_storage_classes_128K), and emit it on both
PUT and GET responses. DELETE clears it for symmetry.

Coverage:
- REST Assured tests for default/custom/round-trip/delete-clears.
- AWS Java SDK v2 round-trip in S3LifecycleSdkIntegrationTest, the
  level the existing #492 body-only fix did not exercise.

Issue #441 was auto-closed by #492 without a real fix; reopens the
underlying defect.

* test(s3): move SDK lifecycle round-trip to compatibility-tests

- Move S3LifecycleSdkIntegrationTest to compatibility-tests/sdk-test-java as S3LifecycleTest, adapted to use TestFixtures.s3Client() and AssertJ to match the existing compat suite.
- Drop the test-scope software.amazon.awssdk:s3 dependency from the main pom.xml; the in-tree JUnit tests do not need an SDK client.
- Addresses review feedback on PR #615.
2026-04-27 18:11:14 -05:00
Hector Ventura c7987ad1de fix(s3-control): accept plain S3 ARN (arn:aws:s3:::bucket) in ListTagsForResource (#603)
Go SDK v2 and Terraform AWS provider v6 send arn:aws:s3:::<name> for
general-purpose buckets instead of the S3 Control form
arn:aws:s3:<region>:<account>:bucket/<name>. The plain ARN has no
region and no account segment, so the existing :bucket/ search found
nothing and returned a 400.

extractBucketName() now recognises both forms: the existing
:bucket/<name> form first, then the plain arn:<p>:s3:::<name> form
as a fallback.
2026-04-25 19:38:41 -05:00
Hector Ventura 404b42bdc0 feat(lambda): bind-mount hot-reload via S3Bucket=hot-reload (#601)
* feat(lambda): add bind-mount hot-reload mode via S3Bucket=hot-reload

Functions created with S3Bucket=hot-reload and S3Key=/absolute/path
have their host directory bind-mounted into /var/task rather than
packaged as a ZIP. Each invocation runs an ephemeral container so
file changes on disk are picked up immediately without calling
UpdateFunctionCode or re-uploading code.

Feature is disabled by default; opt in with:
  FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true

An optional path allowlist (FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ALLOWED_PATHS)
restricts which host directories may be bind-mounted.

* fix: missing hot reload enable env
2026-04-25 19:38:03 -05:00
Hector Ventura 7dbd0225d4 fix(lambda): wire S3VirtualHostFilter to container-aware DNS suffix (#598)
S3VirtualHostFilter was reading config via ConfigProvider at
  construction time, always deriving baseHostname from floci.base-url.
  When running inside Docker, Lambda containers resolve S3 via the
  embedded DNS suffix (e.g. bucket.floci:4566), not the external
  base-url hostname. The filter never matched those virtual-host headers,
  so S3 requests from Lambda containers were served as path-style misses.

  Switch to CDI injection (EmulatorConfig + ContainerDetector) so that
  in Docker mode baseHostname is set to EmbeddedDnsServer.DEFAULT_SUFFIX
  (or FLOCI_HOSTNAME when configured), consistent with what the embedded
  DNS actually resolves.

  Add @Startup to EmbeddedDnsServer for eager initialisation and export
  DEFAULT_SUFFIX as a shared constant. Add LambdaDnsResolutionTest to
  validate the full path: Lambda container → embedded DNS → virtual-host
  filter → S3 object.
2026-04-25 19:37:42 -05:00
Hector Ventura 1ddbec0efb feat(athena): real SQL execution via floci-duck DuckDB sidecar (#584)
* feat(athena): real SQL execution via floci-duck DuckDB sidecar

  - Lazy-start floci/floci-duck:latest on first StartQueryExecution call;
    reuse the running container for all subsequent queries
  - Inject Glue tables as CREATE OR REPLACE VIEW statements via setup_sql
    before the user SQL so DDL runs outside the COPY(...) wrapper
  - SerDe-aware format inference: inferReadFunction now checks
    SerdeInfo.SerializationLibrary in addition to InputFormat, so standard
    AWS JSON tables (TextInputFormat + JsonSerDe) map to read_json_auto
  - ImageCacheService: skip Docker Hub pull when image is already present
    locally, preventing local builds from being overwritten
  - Add AthenaIntegrationTest (5 unit integration tests)
  - Add AthenaTest and DataLakeTest SDK compatibility tests
  - Update docs: athena.md (full rewrite), glue.md, README, CHANGELOG

* fix: docker image check fix
2026-04-25 08:28:20 -05:00
Kenshin OkinakaandKenshin OKINAKA 763ea379d7 feat(ses): implement email template CRUD with stored, inline, and ARN variants (#573)
* feat(ses): implement email template CRUD with stored, inline, and ARN variants

Adds CreateTemplate / GetTemplate / UpdateTemplate /
DeleteTemplate / ListTemplates on both V2 REST JSON
(/v2/email/templates) and V1 Query.

SendEmail / SendTemplatedEmail resolve templates in three forms
with Mustache-style {{var}} substitution against TemplateData:
  - TemplateName references a stored template
  - TemplateArn extracts the name from the template/<name>
    segment of an SES template ARN (region and account segments
    are not validated, mirroring how KMS / Secrets Manager
    handle ARNs in Floci)
  - TemplateContent (V2 only) supplies inline subject / text /
    html without storing the template first

V2 Content.Template requires exactly one of TemplateName,
TemplateArn, or TemplateContent; violations return
BadRequestException (400). V1 SendTemplatedEmail accepts
TemplateArn either alone or alongside Template (name) — the
name is used for resolution when both are present, matching
AWS where boto3 and the Java SDK keep Template as a required
field and treat TemplateArn as supplementary for cross-account
addressing.

Templates persist region-scoped via StorageFactory in
ses-templates.json. Template names reject leading/trailing
whitespace (same rule as identities) and are validated through
a single validateTemplateName helper reachable from every
resolution path. listTemplates is sorted by CreatedTimestamp
with TemplateName as a tiebreaker for deterministic output.

Error codes: the service layer throws V1-style codes
(TemplateDoesNotExist / AlreadyExists / InvalidTemplate /
InvalidParameterValue); SesController remaps them to
NotFoundException (404) / AlreadyExistsException (400) /
BadRequestException (400) for V2 callers.

* test(ses): add Python and Java SDK compatibility tests for templates

Covers boto3 (ses / sesv2) and AWS Java SDK v2 (SesClient /
SesV2Client) against the SES email template CRUD, inline
TemplateContent, and TemplateArn paths. Happy path,
duplicate-create rejection, missing-template lookups,
Mustache-style variable substitution, and 3-way selector
conflicts on V2 Content.Template are exercised on both SDK
surfaces.

Adds:
- Python: ses_client / sesv2_client conftest fixtures and a
  tests/test_ses_templates.py suite covering V1 + V2
- Java: sesv2 Maven dependency, SesV2Client factory in
  TestFixtures, and a SesTemplateTest covering V1 + V2

* docs(ses): document email template CRUD and templated send

Adds the new V1 template actions (CreateTemplate / GetTemplate
/ UpdateTemplate / DeleteTemplate / ListTemplates /
SendTemplatedEmail) and the V2 /v2/email/templates endpoints
to the SES service reference, and extends the README service
matrix to mention template support on the SES / SES v2 rows.

* fix(ses): add template actions to SES_ACTIONS for unsigned request routing

Unsigned clients (curl, aws --no-sign-request) were falling through to
the SQS handler because the six template Query actions were not
registered in SES_ACTIONS.

* fix(ses): narrow exception catch to JsonProcessingException in template endpoints

Broad Exception catch was masking unexpected errors (e.g. NPE) as 400
responses. Narrowed to JsonProcessingException which is the only
checked exception from objectMapper.readTree().

* test(ses): add template variable substitution edge cases and cross-region isolation

Add SesServiceTemplateTest with 14 unit tests for applyTemplateData
covering undefined variables, spaced/hyphenated names, unclosed braces,
non-string JSON values, regex metacharacters, and case sensitivity.

Add cross-region isolation integration test verifying templates created
in one region are not visible in another.

* test(ses): add awscli compatibility tests for template CRUD and templated send

Cover create, get, update, list, delete template and send-templated-email
via the AWS CLI. Uses JSON parameter format to avoid awscli parser issues
with Mustache-style {{variable}} syntax.

---------

Co-authored-by: Kenshin OKINAKA <kenshin_okinaka@realcross.co.jp>
2026-04-24 20:59:49 -05:00
Stas Burnashev e0dc45e012 fix(dynamodb): serialise concurrent mutations and transactions (#572)
* test(dynamodb): failing concurrency tests reproducing #571

Exercises DynamoDbService directly with a starting-gate CountDownLatch and
@RepeatedTest(5) to catch read-check-mutate-put races that single-threaded
tests cannot see.

Scenarios cover: arithmetic if_not_exists counters, ADD updates, conditional
PutItem/DeleteItem with attribute_exists/attribute_not_exists, mixed put+update
on the same key, transactWriteItems (overlap and disjoint), batchWriteItem,
and stream event ordering. Each scenario has a baseline single-threaded sibling.

30 of 51 executions fail on main, matching the races described in the plan.

* fix(dynamodb): serialise single-item mutations with per-item locks

Adds a per-(storageKey, itemKey) ReentrantLock registry and wraps the full
read → check-condition → mutate → put → persist → stream-capture sequence
inside putItem, updateItem, and deleteItem. Locks are created lazily on first
access and never removed; ReentrantLock is used so the upcoming transaction
path can re-enter these methods after acquiring each participant's lock.

Unrelated items still run in parallel — only threads contending for the same
item serialise, matching real DynamoDB's per-item linearisability.

Fixes the updateItem, putItem, deleteItem, and stream-ordering scenarios in
DynamoDbConcurrencyIntegrationTest. The transactWriteItems scenario still
races and is addressed in the next commit.

Refs #571.

* fix(dynamodb): serialise transactWriteItems via total-ordered lock acquisition

Resolves every participant's (storageKey, itemKey) up front, acquires each
ReentrantLock in deterministic ascending order, then evaluates all conditions
against a snapshot nobody else can mutate. Writes apply under the same locks;
inner putItem/updateItem/deleteItem calls re-enter their lock for free.

Fixes the last remaining DynamoDbConcurrencyIntegrationTest scenarios — the
all-or-nothing transaction test now observes committed == versionA == versionB
across repeated runs, and the disjoint-commute scenario proves the sort order
prevents deadlock.

Closes #571.

* test(compat): end-to-end concurrency scenarios against running Floci

Adds the four mandatory compatibility tests that exercise the same locking
semantics through the AWS SDK over HTTP: concurrent UpdateItem arithmetic,
concurrent PutItem(attribute_not_exists), concurrent overlapping
TransactWriteItems, and mixed concurrent UpdateItem + PutItem.

N=20 per scenario to keep CI fast; each scenario uses a CountDownLatch starting
gate so client threads dispatch simultaneously and the server actually sees
overlapping work.

* docs(changelog): note the DynamoDB concurrency fix under [Unreleased]

Flags the behaviour change for callers whose previously-racing
UpdateItem/PutItem/TransactWriteItems calls will now see the
ConditionalCheckFailedException or TransactionCanceledException that real
DynamoDB would raise.

* fix(dynamodb): harden transaction ordering and drop dangling plan references

Addresses review feedback on #572:

* Replace the delimited-string ordering key for transactWriteItems with a
  Comparator over TransactParticipant tuples. User-supplied PK/SK bytes can
  contain any character, so "storageKey + \0 + itemKey" is not an injective
  ordering — tuple comparison avoids the collision risk entirely.
* Release a table's item locks alongside itemsByTable / itemStore in
  deleteTable so the registry tracks the table's lifetime instead of growing
  unboundedly across create/drop cycles.
* Remove Javadoc and inline comment references to PLAN-dynamodb-concurrency.md,
  which was a local working doc and was never committed. Issue #571 stays as
  the public reference.
2026-04-24 20:53:20 -05:00
TiM 273434893f feat(cognito): add TagResource, UntagResource, ListTagsForResource for user pools (#579)
* feat(cognito): add TagResource, UntagResource, ListTagsForResource for user pools

Dispatch the three Cognito IDP tag operations through CognitoJsonHandler and
resolve user pools by parsing the resource ARN (O(1) pool-store lookup, not a
full scan). Malformed ARNs now surface as InvalidParameterException rather
than a swallowed ResourceNotFoundException.

Reject reserved floci:* keys on standalone TagResource via
ReservedTags.rejectReservedTagsOnUpdate, matching the existing strip-on-write
behavior on CreateUserPool / UpdateUserPool. Mutations are synchronized on
the pool instance to match the ensureJwtSigningKeys pattern.

Covered by new unit tests (CognitoServiceTest, CognitoJsonHandlerTest), AWS
CLI bats (cognito.bats), and Java SDK compat tests (CognitoFeaturesTest).

* chore: retrigger CI
2026-04-24 01:56:03 -05:00
Christine Nguyen eed72e6222 feat(pipes): add filtering, input templates, batch sizes, and DLQ routing (#576) 2026-04-23 22:56:05 -05:00
Christine Nguyen 51bf4f8480 feat(pipes): add source polling and target invocation for EventBridge Pipes (#555) 2026-04-22 23:36:48 -05:00
Hector Ventura ce60457392 fix(lambda): add missing FunctionConfiguration fields and fix response shape (#546) 2026-04-21 19:44:34 -05:00
Hector Ventura ee08d3ad44 feat(opensearch): add real os with docker image (#528)
* feat(opensearch): add real os with docker image
* fix: fix opensearch network issue
2026-04-19 19:04:31 -05:00
Kenshin Okinaka bc951bf4bf fix(lambda): restore create-copy-start ordering for provided runtimes (#524)
* fix(lambda): restore create-copy-start ordering for provided runtimes

The refactor in #466 changed ContainerLauncher from create → copy →
start to createAndStart → copy, breaking provided.* runtimes whose
entrypoint execs /var/runtime/bootstrap immediately on start — before
the file has been copied in.

Split ContainerLifecycleManager into create(spec) and
startCreated(containerId, spec) so ContainerLauncher can copy code and
the bootstrap file into the container filesystem before starting it.
Other services (ECS, ECR, EKS, MSK, ElastiCache, RDS) continue using
createAndStart since they have no pre-start file copy requirement.

Fixes #494

* test(lambda): verify create-copy-start ordering for provided runtimes

Update ContainerLauncherTest to use the new create/startCreated API
and add two ordering tests:

- launchFunction_createsBeforeCopyAndStartsAfter: verifies the
  create → copy → startCreated sequence for any runtime using
  Mockito InOrder.
- launchProvidedRuntime_copiesBootstrapBeforeStart: verifies the same
  ordering specifically for provided.al2023 with a bootstrap file,
  and asserts createAndStart is never called. This is the exact
  regression from #466 that caused exit 127.

* refactor: delegate createAndStart to create + startCreated

Eliminate duplicated container-creation logic by making createAndStart
a thin delegate to create(spec) + startCreated(containerId, spec).
Future fixes to either step now apply to both call paths automatically.

* test(lambda): add SDK compatibility test for provided runtime invoke

Create and invoke a provided.al2023 function using the shell-based
bootstrap from LambdaUtils.providedRuntimeZip(). Asserts the response
contains the expected payload without timeout or FunctionError.

This test fails on 1.5.4 (Read timed out after 120s due to the
create-start ordering regression in #466) and passes on the fix.

* docs: add @param to create() and rename misleading test

- Add missing @param spec tag to ContainerLifecycleManager.create()
  for consistency with surrounding methods.
- Rename launchFunctionCopiesCode to launchFunction_createsWithoutBindMounts
  to reflect what the test actually asserts. Remove the getDockerClient
  verify that didn't prove code copying.

* test(lambda): stub Docker copy chain and add cleanup for provided runtime test

- Stub dockerClient.copyArchiveToContainerCmd → withRemotePath →
  withTarInputStream so copy operations execute against the mock
  instead of throwing silently. Ordering tests now verify actual
  Docker copy invocations between create and startCreated.
- Provided runtime test asserts both /var/task and /var/runtime
  remote paths were targeted.
- Add sdk-test-provided-fn to @AfterAll cleanup in LambdaTest so
  assertion failures don't leak the function across test runs.

* test(lambda): drain tar InputStream in copy mock to prevent thread leaks

Each copy mock now returns a fresh CopyArchiveToContainerCmd that
drains the PipedInputStream on exec(), so the background tar writer
thread can complete instead of blocking when the pipe buffer fills.
Remote paths are captured via the mock's withRemotePath answer and
asserted from the shared list.

Also adds sdk-test-provided-fn to @AfterAll cleanup in the compat
test to prevent function leaks on assertion failure.

* refactor(lambda): drop unused ContainerInfo variable from launch

The return value of startCreated() was assigned but never read.
Remove the variable and its now-unused import.

* test(lambda): include getDockerClient in InOrder verification

Add the getDockerClient() call between create() and
copyArchiveToContainerCmd() in both ordering tests so the verified
sequence matches the actual call flow in ContainerLauncher.launch().

* style: remove redundant doAnswer import

The wildcard import already covers it.
2026-04-19 09:33:54 -05:00
Hector Ventura 63ed81c59d feat(eks): implement EKS service with real k3s data plane support (#493)
* feat(eks): implement EKS service with real k3s data plane support
* fix: adjusting eks volume issues
2026-04-18 01:35:25 -05:00
rbelakapytski-aet f4ce6ef445 fix(kms): support ECC_SECG_P256K1 via BouncyCastle JCA (#502)
* fix(kms): support ECC_SECG_P256K1 via BouncyCastle JCA
use BC for EC keygen, KeyFactory, and Signature on ECC_* specs. Add test.
* fix(kms): support ECC_SECG_P256K1 via BouncyCastle JCA
2026-04-17 21:54:40 -05:00
Stas Burnashev b899f177e4 fix(dynamoDB): support arithmetic in DynamoDB SET expressions (#480)
* fix: support arithmetic in DynamoDB SET expressions

SET expressions like `SET cnt = cnt + :inc` or
`SET cnt = if_not_exists(cnt, :start) + :inc` silently ignored
the arithmetic operator - only the left operand was assigned.

Add `findArithmeticOperator()` to locate `+`/`-` outside function
parentheses, and evaluate both operands via `evaluateSetExpr` with
BigDecimal arithmetic.

Closes #479

* fix: address review - path-aware evaluateSetExpr, proper error handling

- Make evaluateSetExpr use hasValueAtPath/getValueAtPath for nested
  path support (e.g. SET a.b = a.b + :inc)
- Throw ValidationException for non-numeric operands instead of
  silent no-op
- Catch NumberFormatException on BigDecimal parsing

* fix: add integration and compatibility tests for SET arithmetic

- Add DynamoDbIntegrationTest for if_not_exists + arithmetic (repro from #479)
- Add Java SDK compatibility test covering increment, consecutive
  increments, and subtraction
2026-04-17 18:17:02 -05:00
Kenshin Okinaka d8243b8803 feat(lambda): support ScalingConfig.MaximumConcurrency on SQS event source mappings (#490)
* feat(lambda): support ScalingConfig.MaximumConcurrency on SQS event source mappings

Wire-level support for ScalingConfig on CreateEventSourceMapping,
UpdateEventSourceMapping, GetEventSourceMapping, and
ListEventSourceMappings:

- New ScalingConfig model carrying MaximumConcurrency (Integer, nullable).
- Create and Update parse ScalingConfig from the request, validate range
  (2-1000), reject non-SQS event sources with InvalidParameterValueException.
- Response includes ScalingConfig only when a cap is set; omitted when
  null, matching AWS behavior.
- Update with an empty ScalingConfig clears the cap (AWS reset semantics).

The value is persisted on the EventSourceMapping but not yet enforced at
invocation time — the SQS poller today serializes to one concurrent
invocation per ESM regardless. Real parallel dispatch capped by
MaximumConcurrency is a follow-up (Scope B).

Tests:
- EsmIntegrationTest: 6 new cases covering round-trip, below/above range
  rejection, non-SQS rejection, omission when unset, add-then-clear via
  update.
- LambdaEsmScalingConfigTest (SDK compat): 5 cases verifying SDK typed
  ScalingConfig round-trips, InvalidParameterValueException on range
  violations, and add/clear lifecycle via update.

* fix(lambda): reject non-integer MaximumConcurrency and ScalingConfig on non-SQS sources

- parseScalingConfig now detects fractional values (e.g. 2.5) and
  returns InvalidParameterValueException instead of silently truncating.
- Empty ScalingConfig ({}) on a non-SQS event source is now rejected.
  Previously the non-SQS check only fired when MaximumConcurrency was
  non-null, so an empty ScalingConfig on Kinesis / DynamoDB Streams
  slipped through.
- Two new integration tests cover both cases.

* fix(lambda): tighten ScalingConfig input validation

- Reject non-object ScalingConfig (e.g. "foo", []) with 400 instead of
  silently treating it as absent. In update paths this previously cleared
  an existing cap unintentionally.
- Reject non-numeric MaximumConcurrency (e.g. string "7"). AWS expects a
  JSON number on the wire; the previous toString + parseInt path accepted
  strings that real AWS would reject.
- Use longValue() before range-checking to avoid intValue() overflow on
  large inputs (e.g. 5000000000) that would produce a negative value and
  a misleading error message.
- Two new integration tests: string MaximumConcurrency and non-object
  ScalingConfig.

* fix(lambda): add NaN/Infinity guard and expand ScalingConfig test coverage

- parseScalingConfig now explicitly rejects NaN and Infinity rather than
  letting them fall through to longValue() with a misleading error.
- The post-range non-SQS guard was flagged as dead code by the reviewer
  but is in fact reachable (non-SQS + valid numeric MaximumConcurrency).
  Retained and confirmed by the existing @Order(43) test.
- New tests: update range validation (below/above on PUT), and list
  with mixed ScalingConfig presence across ESMs.
2026-04-17 00:16:55 -05:00
Conor Heine 4d1f8b4907 test: fix CloudFormationVirtualHostTests.java (#467) 2026-04-15 15:35:38 -05:00
Dmitriy Polomoshnov 25f360002e fix: DynamoDB expression evaluation, UpdateExpression paths, and ConsumedCapacity (#197)
* fix: replace regex-based DynamoDB expression evaluation with AST parser
* feat: add ConsumedCapacity in DynamoDB responses and GSI throughput in DescribeTable
* test: add DynamoDB expression compatibility tests and fix rebase conflicts
2026-04-15 09:55:58 -05:00
TiM c2653db2e7 fix(kinesis): accept AWS SDK v2 CBOR content type (#457)
* fix(kinesis): accept aws sdk v2 cbor content type
* test(kinesis): move sdk v2 coverage to compatibility suite
2026-04-15 07:50:37 -05:00
Hector Ventura ea597c67d6 feat: implement local Data Lake stack (Athena, Glue, and Firehose) (#429)
* feat: implement local Data Lake stack (Athena, Glue, and Firehose)
* fix: adding athena, firehose and glue documentation
* fix: updating dataLateTest
2026-04-15 01:22:10 -05:00
Kenshin Okinaka fb26731131 feat(lambda): enforce reserved and per-region concurrency (#424)
* feat(lambda): enforce reserved concurrency at invocation time

Introduce LambdaConcurrencyLimiter using AtomicInteger + CAS. Acquire a
permit before invoke and release in finally for both sync and async
paths. DryRun skips enforcement. Functions without a reserved value are
not enforced in this step (account-pool enforcement will follow).

Reset inflight counters when a function is deleted to prevent leaks.

* test(lambda): use JUnit Assertions in LambdaConcurrencyLimiterTest

AssertJ is not on the unit-test classpath; switch to the Jupiter
assertions already used by sibling tests.

* feat(lambda): enforce account-wide concurrency pool and validate Put

Extend LambdaConcurrencyLimiter with an account-shared unreserved pool
sized as accountLimit - Σreserved. Functions without a reserved value
now share this pool; exhaustion returns TooManyRequestsException.

PutFunctionConcurrency rejects values that would leave less than
unreserved-concurrency-min (AWS default: 100) available, matching AWS's
LimitExceededException behavior.

Config: floci.services.lambda.account-concurrency-limit (default 1000)
and floci.services.lambda.unreserved-concurrency-min (default 100).
Docs and controller javadoc updated accordingly.

* feat(lambda): rehydrate reserved concurrency and handle throttle in pollers

On startup, LambdaService walks functionStore.listAll() and re-registers
reserved values with the limiter so validatePut and the unreserved pool
see the correct totals before the first Put of the session.

SQS/Kinesis/DynamoDB Streams pollers now catch TooManyRequestsException
explicitly. SQS lets messages return via visibility timeout; Kinesis and
DynamoDB Streams skip advancing the shard iterator, so records are
redelivered on the next poll.

* test(lambda): add SDK compatibility tests for concurrency enforcement

Verify end-to-end wire behavior: LimitExceededException on Put that
violates unreserved-min, TooManyRequestsException on Event invoke when
reserved=0, and DryRun bypassing the concurrency gate.

* fix(lambda): close concurrency races in limiter and rehydrate

- Recompute cap inside the unreserved CAS loop so concurrent setReserved
  does not leave permits granted above the live pool.
- Replace validatePut + setReserved with a single validateAndSetReserved
  guarded by a reservedLock; concurrent Puts for different functions
  can no longer each pass validation against stale totals.
- Rehydrate only $LATEST entries so published versions do not
  double-count into totalReserved().

* fix(lambda): address PR review feedback

- Partition limiter state by region. AWS Lambda concurrency is per
  account-per-region; functions in different regions no longer share
  the same reserved totals or unreserved pool.
- PutFunctionConcurrency and DeleteFunctionConcurrency now roll back
  the limiter update if functionStore.save() fails, so limiter and
  persisted state stay consistent.
- Replace the awkward (InvokeResult) null cast in the DynamoDB Streams
  poller with a plain forward declaration.

* refactor(lambda): rename account-concurrency-limit to region-concurrency-limit

The limit applies per-region (AWS Lambda's "account-level" quota is
actually per-account-per-region). Rename the config key, field, and
accessor to match what the value controls, and clarify the doc note.

No functional change.

* fix(lambda): O(1) region total and compare-and-rollback on save failure

- Maintain per-region AtomicInteger running total of reserved values,
  updated under reservedLock on every mutation. acquireUnreserved reads
  the cap in O(1) without iterating the map, eliminating the weakly-
  consistent partial-sum window that existed when reads happened off
  the lock while writes were serialized.
- Replace unconditional rollback with rollbackReservedIfExpected: the
  limiter only restores the previous value if the current entry still
  matches what the caller wrote, so a concurrent successful Put cannot
  be clobbered by an earlier request's rollback after its save fails.

* docs(lambda): scrub remaining account-wide wording and document drain semantics

Replace lingering "account-wide" / "account pool" phrasing with
per-region terminology in the controller javadoc and unit-test comment.
Two references remain by design: EmulatorConfig and the lambda service
doc quote AWS's own "account-level" label to explain the renamed key.

Also fold two follow-up review items into this change:
- Replace fully-qualified AwsException / InvokeResult references in the
  SQS, Kinesis, and DynamoDB Streams pollers with normal imports.
- Document that reducing or clearing a reserved value does not kill
  already-inflight invocations, mirroring AWS behavior and causing a
  brief drain window where total inflight may exceed the region limit.

* fix(lambda): serialize Put/Delete per function and preserve busy inflight

- Wrap PutFunctionConcurrency and DeleteFunctionConcurrency in a
  per-function lock so concurrent requests for the same ARN can't
  interleave the limiter update and the store save in a way that
  leaves them out of sync.
- Retain the inflight counter on reset when permits are still open,
  so an ARN recreated under load sees the remaining inflight rather
  than starting fresh and briefly allowing more than reserved capacity.
  Idle counters (value 0) are still dropped to prevent leaks.
- Tests now close acquired permits via try-with-resources and cover
  both the retain-while-busy and drop-when-idle reset behaviors.

* test(lambda): close all permits via try-with-resources

Close the acquire() result in regions_areIndependent so the test leaves
no inflight state behind and accurately asserts both the exhausted and
recovered cases.

* perf(lambda): avoid regex split in regionOf on the invoke hot path

regionOf() runs on every acquire/release. Replace String.split(":"),
which uses regex and allocates an array, with a single pass that finds
the fourth ':' segment and returns a substring — same semantics, no
allocation beyond the returned region string.

* fix(lambda): keep per-function lock map and tighten compat assertion

- deleteFunction no longer removes the per-function entry from
  concurrencyOpLocks. Removing it could race with a concurrent
  Put/Delete still synchronized on the old lock object, letting the
  next request create a fresh lock and run in parallel — defeating
  the very serialization the map provides. The map grows by one
  Object per deleted function, acceptable for a local emulator.
- LambdaConcurrencyTest now asserts the wire-level error identity
  (400 status + "LimitExceededException" errorCode) for the Put
  rejection. The Lambda SDK v2 model does not declare a typed
  LimitExceededException class, so wire-level assertions catch
  protocol-fidelity regressions more precisely than the previous
  generic LambdaException check.

* fix(lambda): retain inflight counter on reset and allow over-committed reductions

- reset() no longer drops idle inflight counters. The previous
  counter.get()==0 + remove pattern races with a concurrent
  acquireReserved that has already obtained the AtomicInteger
  reference and is about to increment it: a successful remove
  between those two moments would leave the next acquire to
  allocate a fresh counter and silently undercount inflight,
  permitting reserved over-subscription.
- validateAndSetReserved now allows any value <= the function's
  current reservation unconditionally. Reductions cannot worsen
  unreserved capacity, so blocking them in an already over-committed
  state (e.g. after lowering region-concurrency-limit at runtime)
  prevented operators from recovering. Increases still go through
  the unreserved-min check.

* fix(lambda): take per-function lock in deleteFunction

A concurrent deleteFunction + Put/DeleteFunctionConcurrency for the
same ARN could interleave the limiter reset and the store delete,
leaving the limiter holding (or clearing) state for a function the
store no longer knows about. Wrap the limiter+store mutations in the
same lockForConcurrencyOp(arn) used by the concurrency endpoints.

Tighten the surrounding comment so it describes the current code
rather than the lock-removal call that earlier revisions used to have.

* test(lambda): wire a real concurrency limiter into the test constructor

The package-private LambdaService constructor used by unit tests passed
null for concurrencyLimiter, so the null-guards in
putFunctionConcurrency / deleteFunctionConcurrency / deleteFunction made
those paths silently skip validation and limiter bookkeeping under tests.
That hid divergence from production behavior.

Construct a default LambdaConcurrencyLimiter (AWS defaults: 1000 / 100)
in the test ctor so the same enforcement runs in unit tests.

* test(lambda): cover concurrent PutFunctionConcurrency for the same ARN

Verify that the per-function lock in LambdaService serializes racing
Puts so the limiter and the functionStore always agree on whichever
write landed last. 50 iterations across two threads against the same
function exercise the lock discipline and assert store/limiter
consistency on every iteration.

* docs: document reserved concurrency config keys

- docs/services/lambda.md: drop redundant "(enforced at invocation)"
  from the PutFunctionConcurrency table entry (the admonition below
  already explains enforcement); add region-concurrency-limit and
  unreserved-concurrency-min to the Configuration YAML sample.
- docs/configuration/application-yml.md: mirror the two new keys in
  the top-level reference sample so every known lambda setting is
  discoverable in one place.

* refactor(lambda): address review feedback (A)

- LambdaServiceTest.concurrentPutFunctionConcurrency now asserts against
  limiter.totalReserved(region) instead of getFunctionConcurrency(), which
  read the same field as the value under test. The new assertion actually
  proves the limiter and the persisted store stayed in agreement.
- Expose a package-private concurrencyLimiter() accessor on LambdaService
  so tests can inspect limiter state without reflection.
- Drop unused Permit.NOOP: the reserved=null path now runs through
  acquireUnreserved and always returns a real decrement closure.
- Document the intentional unbounded growth of the inflight counter map
  (race avoidance on reset) and concurrencyOpLocks (race avoidance on
  deleteFunction). Both are acceptable for a local emulator workload.

* test(lambda): add rehydrate, multi-ARN race, and qualified-invoke coverage

- LambdaServiceTest.rehydrateConcurrency_restoresReservedFromStore
  prepopulates a LambdaFunctionStore with reserved values, builds a
  fresh LambdaService over it, and verifies totalReserved(region) goes
  from 0 to the expected sum after the @PostConstruct hook runs.
- LambdaServiceTest.multiArnPutFunctionConcurrency_respectsRegionTotalUnderContention
  races two Puts on different ARNs that would together push the region
  below unreserved-min. reservedLock must let exactly one win; the
  other must fail with LimitExceededException and the limiter's total
  must reflect only the winning reservation.
- Compat LambdaConcurrencyTest.invoke_withVersionQualifier_stillHonorsReservedOnLatest
  publishes a version, sets reserved=0, and invokes with the qualifier
  set. Today Floci drops the qualifier and routes to $LATEST, so the
  reservation throttles the call. This test locks the behavior in: a
  future qualifier-routing change must either copy the reservation onto
  the snapshot or key the limiter off the base ARN to keep it green.

* refactor(lambda): idempotent permits, warn on malformed ARN, more tests

- Wrap acquire()/release() counter closures in an AtomicBoolean guard so
  a double-close of a Permit can never drive the inflight counter
  negative. Future callers that mix try-with-resources with explicit
  close, or that add retry logic around invoke, stay safe by default.
- regionOf() now warns once per unique malformed input instead of
  silently coalescing everything into "unknown". The first occurrence
  is logged so a bug that passes a bare function name into the limiter
  is debuggable without spamming the log.
- New LambdaServiceTest.putFunctionConcurrency_rollsBackLimiterIfSaveFails
  injects a failing LambdaFunctionStore and verifies the limiter total
  is restored when functionStore.save throws.
- New LambdaServiceTest.deleteFunction_preservesInflightPermitUntilItCloses
  holds a permit through a deleteFunction call and asserts the inflight
  counter stays live until the permit is closed.
- New LambdaConcurrencyLimiterTest.permit_closeIsIdempotent locks in the
  double-close guarantee.
2026-04-14 01:09:22 -05:00
TiM 38eb0125a9 refactor(test): narrow Lambda dispatch probe to transport-level exceptions (#395)
* refactor: narrow exception handling to transport-level failures only

The broad catch(Exception) in the Lambda dispatch probe and warmup
swallowed all errors, masking real service regressions as skipped tests.
Narrow to specific transport-level exceptions so only environment
unavailability (timeout, connection refused) triggers a skip:

- Java probe: SdkClientException + ConnectException (not all Exception)
- APIGW warmup: HttpTimeoutException + ConnectException
- Go invoke: net.Error via errors.As (not any error)

Unexpected service errors now propagate as test failures.

* fix: remove unreachable ConnectException catch in lambda probe

AWS SDK wraps all transport-level failures (ConnectException,
ApiCallTimeoutException, etc.) in SdkClientException, so the
separate ConnectException catch was unreachable and broke compilation.

* fix(compat): use unique_name in s3-notifications.bats to avoid parallel collisions

Parallel bats workers could share the same $(date +%s) timestamp,
producing identical bucket/queue/topic names. One worker's
put-bucket-notification-configuration would overwrite another's,
and the round-trip read would return zero filter rules. Switch to
unique_name which appends the shell PID.

* fix(compat): use unique_name in kms and ses bats to avoid parallel collisions

Same class of flake as s3-notifications.bats. Under --jobs 4, parallel
bats workers sharing a $(date +%s) timestamp produce identical alias
names (kms) and identity names (ses), causing cross-worker interference.
2026-04-13 21:49:26 -05:00
Hector Ventura 91071aaae7 feat: implement Amazon MSK service with Redpanda orchestration (#419)
* feat: implement Amazon MSK service with Redpanda orchestration
* fix: adding missing msk service on the test
2026-04-13 20:22:37 -05:00
Hector Ventura cfe48dfabe fix(iam): enforce iam when it turned on (#411)
* fix: iam enforment feature
* fix: adding iam enforment test
* fix: adding iam enforment and update documentation
2026-04-13 14:21:47 -05:00
TiM 0c8395244a test(compat): gate Lambda dispatch tests on container availability (#387)
Tests that invoke Lambda with REQUEST_RESPONSE depend on Docker-in-Docker
for container execution. When DinD is unavailable in CI, these tests time
out instead of skipping. Add a shared memoized probe
(TestFixtures.isLambdaDispatchAvailable) that creates a throwaway Lambda,
invokes it with a 30s timeout, and caches the result per JVM. Tests that
need real dispatch now skip cleanly via Assumptions.assumeTrue.

Java: ApiGatewayV2ExecuteTest, LambdaLongPathTest, S3NotificationsTest
Go: lambda_test.go Invoke subtest
2026-04-12 22:06:41 -05:00
TiM 9ffb26497d test(elasticache): SDK compat suite for replication groups and users (#370)
* test(elasticache): add SDK compat suite

New ElastiCacheTest drives Floci through the AWS SDK v2
ElastiCacheClient surface. First SDK-level compat coverage for this
service.

Covers:
- CreateReplicationGroup / DescribeReplicationGroups /
  DeleteReplicationGroup lifecycle
- CreateUser / DescribeUsers / ModifyUser / DeleteUser lifecycle
- duplicate group / user rejection (AlreadyExistsException shapes)
- missing group / user retrieval (NotFoundException shapes)
- proxy port allocation via direct TCP connection using raw Socket
  (Lettuce is already in sdk-test-java/pom.xml:118 if a real Redis
  client is needed later)

Run separately from the internal Phase 3 integration test so
SDK-contract failures don't tangle with server-logic bugs in review.

* fix(test): add user-group association step for scoped auth validation

Tests now associate user with group via ModifyReplicationGroup before
authenticating. Verifies pre-association rejection, then post-association
success.

* fix(test): document userGroupIdsToAdd deviation in ElastiCache compat suite

Floci treats userGroupIdsToAdd as raw user IDs because UserGroup
resources are not yet implemented. Documented as known deviation
so the test is explicit about exercising current behavior.

* fix(test): replace Java 21 getFirst() with get(0) for Java 17 compat

CI targets Java 17; List.getFirst() requires Java 21.

* fix(test): use proxyHost() and relax exception types for emulator deviations

* ci: re-trigger after flaky ApiGatewayV2ExecuteTest timeout
2026-04-12 21:04:35 -05:00