Commit Graph
787 Commits
Author SHA1 Message Date
Jason van Zyl c233eb4891 feat(ec2): add instance metadata catalog and architecture parity (#1596)
* fix(ec2): expose instance processor architectures

* feat(ec2): add instance type metadata catalog

* fix(ec2): enforce instance architecture parity

* fix(ec2): tighten instance metadata parity
2026-07-05 09:26:38 -05:00
Hector Ventura 8893d2c51e fix(sqs): render Query-protocol errors as XML instead of leaking JSON (#1732)
* fix(sqs): render Query-protocol errors as XML instead of leaking JSON

SqsQueryHandler was the only Query handler without top-level error wrapping,
so AwsExceptions escaped to the global JAX-RS mapper and rendered a JSON body
(application/json, __type) on the XML Query path. Wrap the dispatch like every
other Query handler and emit the standard ErrorResponse envelope with the
legacy Query error codes (QueueAlreadyExists, AWS.SimpleQueueService.
NonExistentQueue). The existing conflicting-attributes test pinned the leaked
JSON __type code and now asserts the XML shape; the JSON protocol path is
unchanged.

* test(cloudformation): assert legacy Query error code in assertQueueAbsent

The StackSets helper probes queue absence over the SQS Query protocol but
asserted QueueDoesNotExist, the JSON-protocol __type that only appeared there
because Query errors leaked through the JSON mapper. With Query errors now
rendered as XML, assert the legacy code AWS.SimpleQueueService.NonExistentQueue
and the 400 status.
2026-07-05 09:14:23 -05:00
Anders Wasen 272e4136e5 feat(rds-data): adding data-api for postgresql (#1720)
* feat(rds-data): adding data-api for postgresql

* Moving wrongly place test file under src/test
2026-07-05 09:05:04 -05:00
Hector Ventura 068b76a195 fix(elasticbeanstalk): persist applications, versions, and environments across restart (#1729)
Elastic Beanstalk was the only stateful service wholesale bypassing the
storage layer: applications, versions, and environments lived in raw
ConcurrentHashMaps, silently lost on restart in persistent/hybrid/wal modes
and invisible to the reset endpoint. Wrap all three maps through
StorageFactory (storage key 'elasticbeanstalk'), re-put after every in-place
mutation so changes reach persistent backends, implement Resettable, register
the persisted models for native-image reflection, and wire the storage mode
and flush interval through EmulatorConfig, the service catalog, and both YAMLs.
2026-07-05 08:50:25 -05:00
Beytullah GunduzandBeytullah Gunduz 89fadbad81 feat(cloudwatch): add Logs Insights query support (#1448)
* feat(cloudwatch): add Logs Insights query support

Implement StartQuery/GetQueryResults/StopQuery for CloudWatch Logs so
clients using Logs Insights (e.g. boto3 start_query + get_query_results)
work against Floci instead of receiving UnsupportedOperation.

LogsInsightsQuery is a minimal engine covering the common subset: fields,
filter (= / !=), sort, dedup, limit; it resolves @timestamp/@message and
dotted JSON paths (e.g. params.job_id, level). StartQuery times are epoch
seconds while event timestamps are millis, scaled accordingly.

Queries follow a time-driven lifecycle: results are computed eagerly, but
a query reports Running until a configurable completion delay elapses
(FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS, default 0 =
instant for local dev), then Complete; StopQuery cancels a running query
and otherwise returns AWS-faithful errors (InvalidParameterException when
already ended, ResourceNotFoundException for an unknown id). Status is
computed on read from an injectable clock, with no background threads.
GetQueryResults returns ResourceNotFoundException for unknown ids,
reports recordsMatched independent of the Running/Cancelled row masking,
hands out a defensive copy of result rows, and drops rows once cancelled.
Results are cached by queryId with LRU eviction.

Covered by unit tests and an AWS SDK v2 compatibility test exercising the
full StartQuery/GetQueryResults/StopQuery lifecycle (stable against both
instant and delayed completion).

* test(cloudwatch): cover Logs Insights search across multiple log groups

Verify a single StartQuery spanning several log groups finds the same
params.id wherever it was logged (results merged and globally sorted by
@timestamp), and that a matching event in an un-queried group is excluded.

* test(cloudwatch): cover Logs Insights query-language edge cases

Add unit tests for limit (applied after sort), ascending sort on a nested
JSON field, the default @timestamp/@message projection, missing-field
handling (empty projection plus null-safe inequality filtering), graceful
ignoring of unsupported commands (parse/stats), and the recordsScanned vs
recordsMatched statistics.

* fix(cloudwatch): deterministic Logs Insights ordering for same-ms events and dedup

Tie-break the @timestamp/@ingestionTime sort comparators by ingestion sequence
then eventId (matching the event store's EVENT_ORDER), and apply the AWS-documented
default @timestamp desc sort when a dedup stage has no preceding sort — so the
surviving duplicate is the newest, deterministically, rather than depending on
storage-scan order.

* fix(cloudwatch): validate log groups and harden Logs Insights query parsing

StartQuery now de-duplicates the requested log groups (the same group can
arrive via multiple selectors) so it is scanned and counted once, and it
returns ResourceNotFoundException for a log group that does not exist
instead of a successful empty query — matching real AWS. The stage parser
splits on pipes only outside quotes, so a filter value containing '|'
(e.g. filter x = 'a|b') is no longer broken into fragments.

StartQuery still accepts multiple selectors and de-duplicates group names
service-side; strict AWS mutual-exclusivity rejection (InvalidParameterException
for more than one of logGroupName/logGroupNames/logGroupIdentifiers) is deferred
to a handler-side follow-up, since the handler collapses all three selectors
into one service argument.

* fix(cloudwatch): reject empty StartQuery selectors and parse quoted filter operators

StartQuery now rejects a request with no usable log-group selector
(InvalidParameterException) instead of returning a successful empty query.
parseFilter finds the equality/inequality operator outside quoted values,
so a value that itself contains '=' / '==' / '!=' (e.g. filter x = 'a==b')
is no longer misparsed.

* fix(cloudwatch): reject StartQuery requests with more than one log-group selector

AWS requires exactly one of logGroupName, logGroupNames, or logGroupIdentifiers.
The handler now rejects a request that provides more than one selector type with
InvalidParameterException, instead of silently querying the union. The
zero-selector case is already rejected by the service.

* fix(cloudwatch): count serialized StartQuery selector fields, not just non-empty ones

The mutual-exclusivity guard counted a selector only when its value was non-blank,
but the merge path added any present field — so a blank logGroupName alongside a
real logGroupNames slipped past the guard. Count serialized fields uniformly (has),
so a blank or empty selector field can't bypass the check; a lone empty selector
still yields no groups and is rejected by the service.

---------

Co-authored-by: Beytullah Gunduz <beytullah-gunduz@users.noreply.github.com>
2026-07-05 08:48:43 -05:00
David Lopes f490bbefad feat(rds): add mock mode to create clusters and instances without Docker (#1655)
* feat(rds): add mock mode to create clusters/instances without Docker

Floci backs RDS clusters and instances with real Docker containers and an
auth proxy. In CI or environments without access to the Docker socket,
CreateDBCluster/CreateDBInstance fail, so the resources never reach an
available state.

Add FLOCI_SERVICES_RDS_MOCK (default false), mirroring the existing
mock mode of EC2/EKS/ECS/OpenSearch/MSK. When enabled, cluster and
instance creation skip the container and proxy and are registered as
AVAILABLE immediately with a localhost endpoint; delete and runtime
restoration likewise skip all Docker calls. Non-mock behavior is
unchanged.

* fix(rds): make rebootDbInstance mock-aware

In mock mode, reboot skipped the container restart (guarded by a null
containerId) but still started a real TCP auth proxy, breaking the
no-container/no-proxy invariant. Gate the container restart and proxy
start on !mock so a mock reboot only flips status back to AVAILABLE.

* fix(rds): give mock resources unique ports and gate delete proxy stop

Address PR review: mock mode hardcoded proxyBasePort for every cluster and
instance, collapsing all endpoints onto localhost:7001 and leaving usedPorts
unreserved. Allocate a unique proxy port even in mock mode (still skipping the
container and auth proxy), and preserve/reserve the persisted port on restore
instead of resetting it. Also gate proxyManager.stopProxy on !mock in the
delete paths, matching the reboot path. Add tests for standalone-instance
deletion in mock mode and for distinct mock endpoint ports.

* fix(rds): skip Docker volume name for mock cluster members and document mode switching

Review feedback from #1655:
- Cluster member instances created in mock mode no longer persist a
  volume name fabricated from the cluster's null volume id, which a
  later non-mock restore could try to reference.
- Document RDS mock mode on the service page, including that switching
  FLOCI_SERVICES_RDS_MOCK over persisted state is best-effort in both
  directions, matching the other mock-capable services.
2026-07-05 08:43:41 -05:00
Jason van Zyl 4a198fd29b feat(cloudcontrol): list resources from local services (#1602)
* feat(cloudcontrol): list resources from local services

* fix(cloudcontrol): align list resources response
2026-07-05 08:30:26 -05:00
Dixit R Jain a25aa0e59f feat(cloudformation): apply S3 Bucket CorsConfiguration (#1617)
* feat(cloudformation): apply S3 Bucket CorsConfiguration Translate the AWS::S3::Bucket CorsConfiguration property into the S3 CORS document during CloudFormation provisioning. The provisioner previously created the bucket and ignored the property, so stacks defining bucket CORS came up without rules. Reconciles to the template on create and update: changed rules replace the prior document and dropping the property clears CORS. Closes #1616

* fix(cloudformation): skip blank CORS rule list values Guard appendCorsRuleElements against blank-resolved list entries so an empty string literal in a CorsRule list no longer emits an invalid empty element (e.g. <AllowedOrigin></AllowedOrigin>).
2026-07-04 08:46:22 -05:00
Hector Ventura 38bf55d323 feat(core): claim wire protocols reactively per Smithy selection guide (#1712)
* feat(core): claim wire protocols reactively per Smithy selection guide

AWS services will adopt additional wire protocols without advance notice
starting April 2026, so the protocol must be identified per request rather
than assumed per service. Adds a ProtocolClaimer that claims each request
from its non-payload signals (Smithy-Protocol header, content type,
X-Amz-Target, method, path) in Smithy precision order, exposed to
downstream filters by a pre-matching claim filter and consumed by the
service-enablement filter in place of its duplicated sniffing.

Also fixes smithy-rpc-v2 path routing: the service segment AWS SDKs send
is the target prefix (Kinesis_20131202, DynamoDB_20120810, ...), not the
SDK serviceId, so rpcv2 service names are now derived from the catalog's
target prefixes and the path-based CBOR dispatcher gains the missing
Kinesis case.

Opt-in strict mode (FLOCI_PROTOCOLS_STRICT_CLAIMING) rejects RPC-signaled
requests that no supported protocol claims, including the recognized but
unimplemented rpc-v2-json. Default wire behavior is unchanged.

Refs #156

* fix(core): scope Smithy-Protocol content-type normalization to rpcv2 paths

The normalization filter runs before the path-rewriting filters, so
rewriting Content-Type on arbitrary paths erased the signal filters like
S3VirtualHostFilter use to bypass non-S3 management traffic. Only
normalize POST requests whose path matches the rpcv2 shape — the only
requests the rpcv2Cbor claim can succeed for.
2026-07-04 00:45:31 -05:00
Hector Ventura 6d1d892a19 fix(ecr): advertise published host port when adopting registry container (#1715)
* fix(ecr): advertise published host port when adopting registry container

When Floci runs inside Docker and adopts an already-running ECR registry
container, adopt()'s endpoint resolves to the container IP and internal port
5000. That port was advertised in getRepositoryUri/getProxyEndpoint, but those
URIs are consumed by the host-side Docker daemon, so docker login against the
advertised endpoint failed. Read the published host binding when adopting and
fall back to the configured port with a warning when no binding exists.

* refactor(ecr): read published binding from adopt's existing inspect

Applies the review suggestion: adopt() already inspects the container, so
carry the published host bindings in ContainerInfo instead of re-inspecting
via a separate publishedHostPort lookup. Removes the extra Docker round-trip
on every adoption.
2026-07-03 01:23:20 -05:00
Alex Banna 44298a2755 perf(lambda): drop the base64 encode->decode round-trip on the S3 code path (#1666)
extractZipCodeFromS3 (and the S3 code-update path) base64-encoded the fetched
object bytes only for extractZipCode to immediately base64-decode them back,
burning CPU + allocating a String ~1.33x the (often tens-of-MB) zip on every
create/update. Split out extractZipCodeBytes(fn, byte[]) as the core and make
extractZipCode(fn, base64) a decode-and-delegate shim; the S3 paths now hand the
bytes straight through. Behavior-identical (decode(encode(x)) == x); covered by
the existing Lambda code tests.
2026-07-03 01:04:18 -05:00
Alex Banna 952f30293f fix(iam): resolve attached AWS-managed policies for any account (#1663)
* fix(iam): resolve attached AWS-managed policies for any account

AWS-managed policies (arn:aws:iam::aws:policy/...) are global and live in the
in-memory catalog, not the account-partitioned policy store; getPolicy already
serves them from the catalog. Several IAM read paths, however, resolved attached
policy ARNs straight from the account-scoped store (policies.get(arn) / the
flatMap variants), so a managed policy attached to a principal owned by a
non-default account was silently dropped.

Add a catalog-aware resolvePolicy(arn) helper modeled on getPolicy and route the
affected reads through it: listAttachedUser/Group/RolePolicies, the user/role
permissions-boundary document resolvers, and collectUser/RolePolicies (the
SimulatePrincipalPolicy / caller-context paths). Customer-policy-only logic and
attachment-count bookkeeping on detach are left untouched.

* test(iam): cover attached managed-policy resolution for a group in a non-default account

Adds the group analog of the existing user/role tests, exercising listAttachedGroupPolicies
(the resolvePolicy catalog fix) for a group owned by a non-default account, with a customer
policy attached to the same group as an account-scoping control.
2026-07-03 00:46:15 -05:00
Ahmed khaled 188854f2df feat(amazonmq): add Amazon MQ broker control plane backed by RabbitMQ (#1642)
* feat(amazonmq): add Amazon MQ broker control plane for RabbitMQ

* feat(amazonmq): provision RabbitMQ container with rollback

Back a broker with a real rabbitmq:3-management container, following the
MSK/ElastiCache container-manager pattern.

- RabbitMqManager starts the container, publishes AMQP (5672) and
  management (15672) ports, and resolves the broker endpoints
- Service branches on the mock flag; real brokers stay
  CREATION_IN_PROGRESS until a readiness poller observes the management
  API answering, then flip to RUNNING
- Rollback on failed provisioning: the manager removes the half-built
  container and the broker is persisted as CREATION_FAILED
- @PreDestroy stops containers on shutdown; DeleteBroker stops and
  removes the container and its storage

Readiness probes the management UI root (no auth) to avoid RabbitMQ's
loopback-only guest user over Docker port mapping.

* feat(amazonmq): seed broker admin user and reject ActiveMQ-only User API

Amazon MQ's standalone User API (CreateUser/DescribeUser/ListUsers/
DeleteUser) applies only to ActiveMQ brokers; AWS rejects it for RabbitMQ
and directs callers to the RabbitMQ web console. CreateBroker now requires
exactly one broker user (validated against AWS password rules) which is
seeded into the container via RABBITMQ_DEFAULT_USER/PASS, sidestepping
RabbitMQ's loopback-only guest restriction.

* test(amazonmq): SDK compatibility test against live RabbitMQ broker

Adds AmazonMqTest exercising the real container path via the AWS SDK MqClient:
CreateBroker provisions a rabbitmq:3-management container, the broker
transitions to RUNNING once its management API answers, endpoints are
published, the ActiveMQ-only User API is rejected, and DeleteBroker tears the
container down. Uses JUnit Assumptions to skip cleanly when Docker is absent.

* fix(amazonmq): harden error handling, persistence, and shutdown teardown

- Redact the provisioning failure 500: log the cause, return a generic AWS
  error envelope instead of leaking e.getMessage() (which can be null).
- Add @JsonIgnoreProperties(ignoreUnknown = true) to Broker, MqUser, and
  BrokerInstance so old persisted snapshots survive field changes.
- Wire RabbitMQ container teardown into EmulatorLifecycle.onStop() via
  RabbitMqManager.stopAll(), alongside the other container managers; the
  service @PreDestroy now only stops the readiness poller.

* docs(amazonmq): add Amazon MQ service page and bump service count to 66

Adds docs/services/amazonmq.md, lists Amazon MQ in the services overview and
README service tables, and updates the "65 -> 66 AWS services" count across
docs/index.md, docs/services/index.md, and README.md.

* fix(amazonmq): reject RebootBroker unless the broker is RUNNING

RebootBroker unconditionally set the broker to RUNNING, so a non-RUNNING
broker (e.g. CREATION_FAILED, which has no backing container) was silently
promoted to RUNNING and never reconciled by the readiness poller. AWS allows
RebootBroker only on a broker in the RUNNING state; guard it and return a 400
otherwise, matching the Amazon MQ API ("You can reboot only a broker with the
RUNNING status").

* fix(amazonmq): close readiness-probe connection and log tolerated failures

isReady() opened an HttpURLConnection but never disconnected it; since the
probe runs every 2s per pending broker this leaked sockets. Disconnect in a
finally block, and log the tolerated failure at debug with broker/URL context
(AGENTS.md: no empty catch; avoid noise in hot paths) instead of swallowing it.

* fix(amazonmq): tear down broker container by deterministic name after restart

containerId is in-memory bookkeeping (intentionally not persisted, since the
Broker model is serialized straight to DescribeBroker and must not leak it).
After an emulator restart it is null, so stopContainer() previously returned
early and left the container running. It now falls back to the deterministic
container name (floci-amazonmq-{brokerId}) so an explicit DeleteBroker still
removes a container left over from a previous run. Documented the field and
added RabbitMqManagerTest covering both the id and name-fallback paths.

* fix(amazonmq): keep admin password in-memory only and fail loudly if absent

The admin password is a secret used solely to seed the RabbitMQ container at
create time. Persisting it (to make it survive a restart) would write the
credential in cleartext to amazonmq-brokers.json, which the project's security
rule prohibits. It stays in-memory only via @JsonIgnore; startContainer (the
only consumer, called from CreateBroker) now throws if the password is absent
rather than seeding a null credential. Added MqUserTest asserting the password
is never serialized and round-trips to null.

* fix(amazonmq): persist broker volumeId/accountId/containerId without leaking them

These internal fields were @JsonIgnore'd, so they were absent from
amazonmq-brokers.json. After a restart in persistent mode volumeId was null
(removeBrokerStorage could not locate the named volume, leaking it) and
accountId was null (the readiness poller wrote brokers via the non-account-aware
path). Unlike the admin password, these are not secrets, so they should persist.

Remove @JsonIgnore so they round-trip through storage, and build the
DescribeBroker response explicitly in the controller so they are still never
exposed to clients (matches MskCluster, which persists volumeId/containerId).
Adds BrokerTest (round-trip) and asserts the describe response omits them.
2026-07-03 00:01:54 -05:00
Hector Ventura b3c54c1854 feat(firehose): return ExtendedS3DestinationDescription and support UpdateDestination (#1710)
* feat(firehose): return ExtendedS3DestinationDescription and support UpdateDestination

The Terraform/Pulumi provider creates delivery streams with
ExtendedS3DestinationConfiguration and reads ExtendedS3DestinationDescription
back after create; Floci parsed the config lossily and only ever emitted
S3DestinationDescription, breaking the provider read. Store the full config
(RoleARN, ErrorOutputPrefix, CompressionFormat, EncryptionConfiguration),
emit it under both wire keys like real AWS, add the required output members
(VersionId, DeliveryStreamType, HasMoreDestinations, DestinationId), and
implement UpdateDestination with version checking.

Refs #1043

* fix(firehose): reject empty destination updates and guard version parse

* fix(firehose): reject partial BufferingHints instead of absorbing defaults

AWS requires SizeInMBs and IntervalInSeconds to be specified together
(firehose service-2.json: "if you specify a value for it, you must also
specify a value for IntervalInSeconds, and vice versa"). The primitive
fields with initializers made a partial payload indistinguishable from a
full one, silently persisting a default over an existing value. Members
are now null-honest boxed Integers, create and update reject one-sided
hints with the declared InvalidArgumentException before any mutation,
and defaults apply only when the whole object is absent.
2026-07-02 23:59:11 -05:00
Mikel Amuchastegui d8c09754d5 fix(kms): normalize alias targetKeyId to plain key ID on createAlias (#1648)
Closes #1647
2026-07-02 23:58:00 -05:00
TiM 2a36522094 fix(s3,sns): preserve root service-host routing (#1625)
* fix(s3): preserve ListBuckets on S3 service hosts

- Treat bare s3.* service endpoint hosts as bucketless S3 requests

- Keep virtual-hosted bucket parsing for bucket.s3.* and bucket.localhost forms

- Add parser and integration coverage for LocalStack and Floci S3 service host domains

* fix(sns): route SubscribeURL confirmations to SNS

- Route SNS ConfirmSubscription GET requests on / through the SNS query handler before normal S3 root handling
- Preserve S3 ListBuckets behavior for non-SNS root GET requests
- Add SNS HTTP delivery regressions for inline 200 confirmation and SubscribeURL GET confirmation

* test(sns): fix race in inline-confirm HTTP delivery test

The confirming-webhook handler recorded the received request before running
confirmSubscription(), so awaitRequests() unblocked and the test published
before the subscription was actually confirmed, delivering 0 notifications
under load (flaky on CI). Record the request only after confirmSubscription()
completes, making awaitRequests() a real barrier. Log the confirmation failure
instead of swallowing it so a genuine failure is diagnosable.

* fix(sns): route UnsubscribeURL confirmations to SNS

UnsubscribeURL is emitted as a plain GET link against the service root,
the same endpoint collision with S3 ListBuckets that SubscribeURL had.
Extend the root-GET delegation to forward Action=Unsubscribe to the SNS
query handler alongside ConfirmSubscription, closing the whole class of
gap rather than a single action.

These links are unsigned, so the region cannot come from the request auth
header. Derive it from the region-bearing ARN the link carries
(SubscriptionArn for Unsubscribe, TopicArn for ConfirmSubscription), so a
subscription in a non-default region resolves instead of returning NotFound.

- Delegate Unsubscribe GETs on / to SnsQueryHandler in S3Controller
- Recover the SNS region from the link ARN via AwsArnUtils.regionOrDefault
- Add a regression in us-west-2: the UnsubscribeURL GET reaches SNS
  (UnsubscribeResponse, not ListBuckets) and the subscription is removed
2026-07-02 23:44:14 -05:00
Hector Ventura 345e83c34d fix(tagging): persist resource tag mappings across restart (#1711)
* fix(tagging): persist resource tag mappings across restart

ResourceGroupsTagging was the last stateful service keeping durable state in
a raw in-memory map. Wrap the store in a StorageBackedMap via StorageFactory
(storage key 'tagging'), restructure tag/untag to get-mutate-put so mutations
flush in persistent and hybrid modes, and wire the storage mode and flush
interval through EmulatorConfig, both application.yml files, and the service
catalog descriptor.

* fix(tagging): synchronize mutators to keep tag updates atomic
2026-07-02 23:39:22 -05:00
Robert Stupp 4f4e7be90e fix(iam): enforce STS session policies (#1636)
* test(iam): expose STS session policy S3 deny gap

* fix(iam): enforce STS session policies

## Summary

STS session policies were recorded on temporary credentials but IAM enforcement evaluated only the caller's identity policies. As a result, an assumed role with broad role permissions could still perform an action even when the inline `AssumeRole` session policy should have denied or narrowed it.

This changes enforcement to evaluate the full caller context, including identity policies, session policies, and permission boundaries. It also keeps temporary-credential lookup account-independent so assumed-role sessions can be resolved after account routing moves the request into the role account, and it uses the resolved request account when building resource ARNs for policy evaluation.

## Type of change

- [x] Bug fix (`fix:`)

## AWS Compatibility

Incorrect behavior: STS `AssumeRole` accepted the standard inline `Policy` parameter, but later requests signed with those temporary credentials did not have that session policy applied by IAM enforcement.

The fix matches AWS policy evaluation semantics: explicit denies in session policies participate in the deny pass, and a present session policy must also explicitly allow the request for the role's permissions to be effective. This preserves the existing Floci bypass behavior for unknown local credentials and the `test` root credential.

## What changed

- `IamEnforcementFilter` resolves a `CallerContext` and evaluates the complete IAM context instead of identity-policy documents only.
- `IamService` resolves STS sessions across account namespaces for caller context, caller ARN, account routing, and temporary secret lookup.
- Enforcement resource ARN construction uses the request account already resolved by `AccountContextFilter`, so assumed-role credentials evaluate account-scoped resources against the role account.
- IAM and multi-account docs now describe session-policy intersection and temporary-credential resolution accurately.
- Java SDK compatibility coverage now checks that an assumed-role session policy deny overrides a role allow.

## Checklist

- [x] `./mvnw test` passes locally - attempted; only failures were unrelated LambdaReactiveSyncIntegrationTest container startup Broken pipe errors
- [x] Selected Java SDK compatibility tests pass locally - in `compatibility-tests/sdk-test-java`: `mvn -q -Dtest=IamEnforcementTest,IamTest,StsTest,S3Test test`
- [x] New or updated integration test added
- [x] Commit messages follow Conventional Commits

* fix(iam): tighten cross-account session lookup
2026-07-02 23:29:23 -05:00
Kenshin Okinaka 3304184bd3 feat(ses): implement ContactList CRUD for SES v2 (#1638)
Add the SES v2 contact list management APIs (CreateContactList, GetContactList,
ListContactLists, UpdateContactList, DeleteContactList) under
/v2/email/contact-lists. A contact list holds subscription topics with
OPT_IN/OPT_OUT defaults. Matching real AWS, an account may hold at most one
contact list per region; a second create is rejected with BadRequestException
("A maximum of 1 Lists allowed per account."), a duplicate name with
AlreadyExistsException, and unknown lists with NotFoundException.

Covered by a RestAssured integration test and an AWS Java SDK v2 compatibility
test.
2026-07-02 23:23:38 -05:00
武田隆志 8366ac256a fix(cloudformation): register !Cidr and !GetAZs shorthand YAML tags (#1635)
The Fn::Cidr and Fn::GetAZs intrinsics were added in #1365, but their YAML shorthand tags (!Cidr, !GetAZs) were never registered in CloudFormationYamlParser. Templates using the shorthand fail to parse with "could not determine a constructor for the tag !Cidr", while the long form (Fn::Cidr / Fn::GetAZs) works. Register the two missing tags alongside the other intrinsic shorthands so both forms behave identically.
2026-07-02 23:16:04 -05:00
Hector Ventura 8b39ead1a4 fix(ec2): return groupSet from DescribeInstanceAttribute (#1709)
* fix(ec2): return groupSet from DescribeInstanceAttribute

Ansible's amazon.aws ec2_instance module reads value['Groups'] from
DescribeInstanceAttribute(Attribute=groupSet) in diff_instance_and_params;
Floci returned only instanceId for that attribute, producing the reported
KeyError. DescribeInstances group shapes were already correct.

Refs #1644

* test(ec2): give describeInstanceAttributeGroupSet a unique order slot
2026-07-02 19:13:20 -05:00
Maciej 6dfdd892aa fix(dynamodb): return a null Message for non-failed item cancellation reason (#1623)
* fix(dynamodb): return a null Message for non-failed item cancellation reason

* fix(ec2): fix flaky launchInstanceUserDataStreamToCloudWatch test

* fix: address PR review feedback for TransactWriteItems and revert unrelated imports
2026-07-02 18:23:02 -05:00
shrimptails-f 0ac1a01884 fix(ses): align CreateEmailIdentity DKIM behavior with AWS (#1620)
* fix(ses): align CreateEmailIdentity DKIM behavior with AWS

* test(ses): verify tracking domains via route53 in sdk compatibility tests

* fix(ses): cache pending DKIM Route53 lookups

* test(ses): log cleanup failures in tracking options test
2026-07-02 18:09:36 -05:00
Hector Ventura 04fd34fd22 fix: register persisted enums for native-image reflection (#1695)
Registers persisted enums (and Cognito's VerificationCode) for reflection so
the native image can deserialize persisted state on restart. Covers cognito,
eks, elasticache, eventbridge, memorydb, pipes, and rds.
2026-07-02 00:52:21 -05:00
Ahmed khaled 8ba1e92713 fix(elasticache): roll back proxy port and container on failed provisioning (#1618)
* fix(elasticache): roll back proxy port and container on failed provisioning

* fix(elasticache): stop container even if proxy rollback fails

* fix(elasticache): guard proxy stop and isolate rollback steps

* test(elasticache): cover rollback when container start fails

* fix: remove accidentally committed browse audit file

Signed-off-by: Ahmed khaled <125749397+ahmedk20@users.noreply.github.com>

* fix: remove accidentally committed browse audit file

Signed-off-by: Ahmed khaled <125749397+ahmedk20@users.noreply.github.com>

---------

Signed-off-by: Ahmed khaled <125749397+ahmedk20@users.noreply.github.com>
2026-07-02 00:15:09 -05:00
Maciej 6c5f533f34 fix(cognito): do not return optional blocks in CreateUserPoolClient when they are not set (#1615)
* fix(cognito): do not return optional blocks in CreateUserPoolClient when they are not set

* fix(cognito): fix test order in file

* fix(cognito): improve bats assertions
2026-07-02 00:11:41 -05:00
Hector Venturaandskwolvie 32ea710b68 feat(ec2): add VPC Flow Logs (#1611)
* feat(ec2): add VPC Flow Logs

Add VPC Flow Logs (CreateFlowLogs/DescribeFlowLogs/DeleteFlowLogs) with a
background generator that synthesizes realistic flow records and delivers them
to S3 in the AWS default (v5) record format and key layout
(AWSLogs/{account}/vpcflowlogs/{region}/.../*.log.gz, gzipped), correlated to
existing EC2 instances. Also seed the SecurityAudit IAM managed policy.

Carved down from #1224 and rebased on main: the original PR also re-added
Interface VPC Endpoints, which main already implements (#1252, #1476), so
those were dropped. PrivateLink-endpoint enrichment of flow records is omitted
accordingly; Ec2Service.endpointNetworkInterfaces() is an empty seam for a
future per-endpoint-ENI implementation.

Refs #1224

* fix(ec2): persist flow logs via StorageFactory and scope deletes by region

Address review comments on the VPC Flow Logs PR:

- store flow logs through StorageFactory so they survive restarts in
  persistent/hybrid/wal modes and generation resumes automatically
- scope DeleteFlowLogs to the request region, matching DescribeFlowLogs
- synthesize deterministic PrivateLink ENIs for interface VPC endpoints
  in endpointNetworkInterfaces, making the pkt-*-aws-service enrichment
  path live instead of dead code
- resolve the endpoint's real service short name from the ENI
  description instead of hardcoding S3

---------

Co-authored-by: skwolvie <skwolvie@users.noreply.github.com>
2026-07-01 23:55:21 -05:00
Jason van Zyl 2cca03bf25 feat(cloudtrail): support empty lookup events (#1603)
* feat(cloudtrail): support empty lookup events

* fix(cloudtrail): keep lookup events handler signature consistent
2026-07-01 23:54:41 -05:00
Alex Banna 6277f16fee feat(stepfunctions): add ecs:runTask service integration (#1564)
* feat(stepfunctions): add ecs:runTask service integration

Wire the Step Functions task executor to the existing docker-backed ECS
service so state machines can launch ECS tasks via the optimized
integrations:

  arn:aws:states:::ecs:runTask         (request-response)
  arn:aws:states:::ecs:runTask.sync    (wait until the task STOPs)

Previously AslExecutor had no ecs:runTask branch, so a state machine using
these resources failed with "Unsupported resource" even though Floci can
run ECS tasks. This unblocks orchestration patterns that launch a task and
wait for it to finish (e.g. a provisioning runner).

Step Functions optimized integrations use PascalCase member names for both
parameters and results, while Floci's ECS handlers use the lowerCamelCase
of the ECS data-plane API. A small recursive key-recasing bridge maps
parameters in (PascalCase -> camelCase) and results out (camelCase ->
PascalCase), reusing EcsJsonHandler.taskNode / parseContainerOverrides so
the output matches the ECS task shape exactly.

For .sync, the executor polls DescribeTasks until the task reaches STOPPED
and fails the state (States.TaskFailed) when an essential container exits
non-zero or the task never ran a container, matching real Step Functions.

Tests: recaseKeys unit coverage (nested objects/arrays, inverse, scalar
round-trip); integration tests for the PascalCase Tasks/Failures envelope,
TaskDefinition validation, and .sync error propagation (ECS mock profile,
so the wiring is asserted independently of a container runtime).

* fix(stepfunctions): poll all ecs:runTask.sync tasks and validate mode

Greptile review on #1564:
- .sync now polls every launched task (not just the first), so with Count > 1 a
  failure in any task fails the state instead of leaving later tasks unmonitored.
  Single task returns its description; multiple return the array.
- Reject unknown ecs:runTask mode suffixes (e.g. a '.Sync' typo) with
  States.TaskFailed instead of silently treating them as .sync.

* fix(stepfunctions): treat a STOPPED ecs task with no exit code as failed

Greptile follow-up on #1564: ecsTaskFailureCause reported success whenever no
container had a non-zero exit, but a container with a null exit code never
completed cleanly (OOM-killed, failed to start, force-stopped). Treat any null
exit code on a STOPPED task as a failure, matching AWS Step Functions.

* fix(stepfunctions): only essential containers fail an ecs:runTask.sync state

Greptile follow-up on #1564: ecsTaskFailureCause checked exit codes on all
containers, so a non-essential sidecar (log shipper, metrics agent) exiting
non-zero would fail the state. Resolve the task definition and skip containers
explicitly marked essential:false; anything not resolvable stays essential.

* fix(stepfunctions): log when an ecs:runTask task definition can't be resolved

nonEssentialContainerNames swallowed the RuntimeException from describeTaskDefinition
and silently returned an empty set (all containers treated as essential), violating
the AGENTS.md rule against silent catch blocks. Log the tolerated failure with the
task definition ARN so the lost essential/non-essential distinction is diagnosable.
No behavior change (still conservatively treats all containers as essential).

* fix(stepfunctions): request-response ecs:runTask must not fail on placement failure

Request-response returns the {Tasks,Failures} envelope even when no task is placed
(AWS: 200 with a non-empty Failures list); only .sync and .waitForTaskToken fail the
state, using the AWS error name AmazonECS.Unknown. Previously the launched.isEmpty()
check threw States.TaskFailed before the mode branch, so it fired for request-response
too. .waitForTaskToken is distinguished by its non-null task token.

Also thread NetworkConfiguration (awsvpc) through runTask -> EcsTask across all three
runTask callers (real RunTask API, service reconciler, ecs:runTask integration) so it is
no longer dropped at the boundary; awsvpc ENI attachments remain unemulated in the local
mock profile.
2026-07-01 23:37:25 -05:00
Alex Banna e0a1d027b9 feat(stepfunctions): ResultSelector, Pass Parameters, ArrayContains, wildcard projection; fix IsPresent for absent paths (#1558)
* feat(stepfunctions): apply ResultSelector, add States.ArrayContains and wildcard path projection

Three JSONPath/intrinsic features that AslExecutor was missing:
- ResultSelector is now applied to a Task's result (before ResultPath), the
  same template resolution used for Parameters. Previously it was accepted but
  silently ignored, so the raw result flowed through unchanged.
- $.X.*.Y wildcard projection in path resolution: a * segment projects the
  remainder of the path over each array element and collects the results
  (e.g. $.Regions.*.RegionName).
- States.ArrayContains(array, value) intrinsic.

These are used together by orchestration that lists results and validates an
input against them. Unit-tested for projection, ArrayContains, and
ResultSelector evaluation; existing Step Functions suites unchanged.

* fix(stepfunctions): apply Parameters in Pass states

A Pass state's Parameters (with intrinsics) were accepted but never applied —
the effective input flowed through unchanged. Apply Parameters to produce the
Pass result (a static Result still overrides), so transforms like
States.ArrayContains in a Pass state take effect. Integration-tested.

* fix(stepfunctions): IsPresent reports an absent path as not present

resolvePath collapses an absent path to a null node, so the Choice IsPresent
comparator (which only checked isMissingNode) reported absent fields as
present. Treat null and missing alike. Integration-tested for absent vs
present fields.

* feat(stepfunctions): bracket [*] wildcard, ResultSelector on Map/Parallel, present-null

Address review feedback on #1558:

- Support the AWS bracket wildcard form ($.Regions[*].RegionName) and
  root-level brackets ($[*][*]) by normalizing bracket notation into path
  segments; multi-level wildcards now flatten, so $[*][*] flattens an array
  of arrays. The dot form ($.Regions.*.RegionName) keeps working.
- Apply ResultSelector to Map and Parallel states (not just Task), before
  ResultPath merges the result in.
- IsPresent now treats an explicit null value as present: resolvePathNode
  preserves the missing-vs-null distinction that resolvePath collapses.

* fix(stepfunctions): keep nulls in projections, validate ArrayContains arg

Address greptile review on #1558:

- Wildcard projection now keeps explicit null values and omits only missing
  matches, so $[*].field over [{"field":null},{"field":"x"}] yields
  [null,"x"] (consistent with treating null as a present value).
- States.ArrayContains throws States.Runtime when its first argument is not an
  array, matching AWS and States.ArrayLength, instead of silently returning false.
- Documented the dotted-field-key limitation of path segment splitting.

* test(stepfunctions): update AslExecutor ctor for new main params

Current main added CloudFormationQueryHandler, Ec2Service and S3Service to the
AslExecutor constructor; pass mocks for them in AslExecutorPathIntrinsicsTest so
it compiles against main.

* fix(stepfunctions): resolve the $.[0] dot-bracket root array-index form

splitPathSegments turned "$.[0]" into "..0" (the [0]->.0 rewrite stacked on
the existing leading dot), leaving a spurious empty segment after the split, so
the path resolved to null. "$[0]" already worked. Collapse consecutive dots so
both the dot-bracket ($.[0]) and no-dot ($[0]) root array-index forms resolve.
EventBridge Pipes batch unwrapping (InputPath "$.[0]") relies on this. Covered
by AslExecutorPathIntrinsicsTest root-array-index cases.
2026-07-01 23:34:21 -05:00
Alex Banna 058e02630a feat(cloudformation): add StackSets with account-aware provisioning (#1551)
* feat(cloudformation): add StackSets with account-aware provisioning

Implement CloudFormation StackSets so a template can be deployed across
target accounts and regions, and make CloudFormation provisioning land
resources in the correct account.

Provisioning previously ran on a background executor thread with no request
scope, so the downstream service calls fell back to the default account — a
stack created by account B materialised its resources under 000000000000.
executeChangeSet/deleteStack now run the provisioning under a synthetic
request scope bound to the deploying account (the caller's account for a
single stack, the target account for a StackSet instance), mirroring the
pattern other background workers already use. Single-stack resources now
land in the caller's account.

StackSet actions are wired through CloudFormationQueryHandler and
AwsQueryController: CreateStackSet, DescribeStackSet, ListStackSets,
UpdateStackSet, DeleteStackSet, CreateStackInstances, ListStackInstances,
DeleteStackInstances, ListStackSetOperations. CreateStackInstances drives
the existing single-stack engine once per target (account, region),
provisioning each instance into that account's namespace; the stack set,
its instances and its operation history live in the administration account.

Tests: an integration test deploying a StackSet from an admin account into
accounts B and C asserts the resources materialise in B and C and are
invisible to the admin/default account, exercises describe/list/operations
and instance deletion, and covers the not-found / already-exists /
not-empty error paths. A single-stack test asserts resources now land in
the caller's account.

Design aligned with maintainers in floci-io/floci#1550.

* fix(cloudformation): await StackSet instance deletion; test UpdateStackSet

Make the account-scoped deleteStack overload return its Future so
DeleteStackInstances completes synchronously before the operation returns,
rather than racing the async resource removal. Add integration coverage for
UpdateStackSet re-applying the template to existing instances.

* test(cloudformation): add SDK compatibility test for StackSets

Adds an sdk-test-java compatibility test exercising StackSets through the real
AWS SDK CloudFormationClient (CreateStackSet, CreateStackInstances,
DescribeStackSet, ListStackInstances, ListStackSetOperations,
DeleteStackInstances, DeleteStackSet). It asserts the management responses
unmarshal cleanly and that instances provision into each target account's
namespace (verified via per-account SQS clients), per the project's policy of
validating management APIs with AWS SDK clients. Runs in the compatibility CI
on pull requests.

* feat(cloudformation): add DescribeStackInstance and DescribeStackSetOperation

Complete the StackSets API surface with the singular describe operations:
DescribeStackInstance (used by orchestration that polls a single instance's
status) and DescribeStackSetOperation (companion to ListStackSetOperations).
Covered by the integration test and the SDK compatibility test, which confirm
the StackInstance / StackSetOperation response shapes unmarshal through the
real AWS SDK.

* feat(cloudformation): resolve TemplateURL and report StackInstanceStatus.DetailedStatus for StackSets

StackSet create/update now resolve a TemplateURL (fetched from S3) in addition
to an inline TemplateBody, matching how orchestration tools reference templates
staged in S3. DescribeStackInstance and ListStackInstances now also report the
nested StackInstanceStatus.DetailedStatus that AWS returns and that pollers read
to determine when an instance operation has completed.

* feat(cloudformation): derive StackSet operation status and honor RetainStacks

Address review feedback on #1551:

- Operation status is now derived from instance outcomes: CreateStackInstances
  and UpdateStackSet report FAILED if any instance fails to deploy, instead of
  always SUCCEEDED. deployInstance also recognizes a rolled-back create
  (ROLLBACK_COMPLETE, not *_FAILED) as a failed/INOPERABLE instance, which was
  previously mis-reported as SUCCEEDED.
- DeleteStackInstances honors RetainStacks: when true, the instance is detached
  from the stack set but its underlying stack and resources are left in place.
- UpdateStackSet now persists the refreshed instance records.

Tests: RetainStacks retention and the FAILED-operation path; docs updated.

* fix(cloudformation): restore account on active scope; log StackSets test teardown

Greptile review on #1551:
- runUnderAccount now saves and restores the previous account ID when it runs
  inside an already-active request scope, so it can't leave the overridden
  account behind on a reused thread. (Background workers normally have no active
  scope, so this only hardens the synchronous-caller path.)
- CloudFormationStackSetsTest teardown no longer swallows exceptions silently;
  it logs them, per the AGENTS.md no-empty-catch rule.

* fix(cloudformation): report a failed StackSet instance delete as FAILED

deleteStackInstances awaited the underlying deleteStack via a helper that
swallows the failure, then removed the instance record unconditionally and
hardcoded the operation status to SUCCEEDED. A failed non-retained delete was
therefore reported as a success with the instance silently dropped.

await() now returns whether the future completed cleanly. On a non-retained
delete failure the instance record is retained (marked INOPERABLE/FAILED) and
the operation status is derived via deriveOperationStatus, so it reports FAILED
— matching AWS, which does not detach an instance whose stack delete failed.

Adds StackSetServiceDeleteFailureTest covering the failure, success, and
RetainStacks paths.

* fix(cloudformation): reject templateless CreateStackSet and restore interrupt in await

CreateStackSet now rejects a request with neither TemplateBody nor TemplateURL (ValidationError,
matching AWS) instead of storing a null template — which would otherwise make a later
CreateStackInstances deploy empty stacks into every target account. Also handle
InterruptedException separately in await(Future) and restore the thread's interrupt flag, so a
shutdown signal to the backing ExecutorService propagates instead of being swallowed. Adds a
CreateStackSet-without-template integration test.
2026-07-01 23:11:16 -05:00
Hector Ventura a27971c7d5 feat(ec2): publish security-group TCP ingress ports on the host (#1680)
* feat(ec2): publish security-group TCP ingress ports on the host

For each TCP port opened to a CIDR source by an instance's security
groups, start an alpine/socat sidecar that binds an allocated host port
(default 30000-30999) and forwards to the instance container's IP, so
the app is reachable from localhost. Forwards reconcile at launch, on
authorize/revoke-security-group-ingress, and on ModifyInstanceAttribute
group reassignment (previously ignored). Mappings persist and are
restored across restarts. SSH is never re-forwarded; wide rules and
per-instance totals are capped; disable with
publish-security-group-ports=false.

* fix(ec2): drop stale port mapping when sidecar recreation fails

On restore, a failed socat recreation released the host port but left
the appPort->hostPort entry in publishedPorts, so later reconciles saw
the port as already published and never re-published it, and a later
unpublish could double-release the host port. Remove the entry and
persist on failure. Also null-guard portForwardManager.restore() for
consistency with the setPersister guard. Adds a regression test.

* fix(ec2): skip port-forward reconcile on non-running instances

A reconcile queued by authorize-security-group-ingress could run after
a concurrent stop/terminate had already cleared publishedPorts and
removed the container; it then republished via the stale bridge IP,
leaking an orphaned socat sidecar and a host port that nothing would
release. Stop/terminate flip the instance state before their async
unpublishAll, so guarding reconcileNow on the running state under the
instance lock closes every window. Adds regression tests.
2026-07-01 23:00:27 -05:00
Alex Banna 3fe7a60a58 feat(stepfunctions): add state machine version APIs (Publish/List/DeleteStateMachineVersion) (#1562)
* feat(stepfunctions): add state machine version APIs

Add PublishStateMachineVersion, ListStateMachineVersions, and
DeleteStateMachineVersion, plus publish-on-create support (publish=true). The
Terraform AWS provider calls ListStateMachineVersions after creating an
aws_sfn_state_machine; Floci previously returned UnsupportedOperation, failing
both apply and destroy. Versions are tracked per state machine
(<arn>:<n>). Integration-tested; verified end-to-end with terraform apply +
destroy of an aws_sfn_state_machine against Floci.

* fix(stepfunctions): return a defensive copy from listStateMachineVersions

Greptile review on #1562: listStateMachineVersions returned the StateMachine's
internal list directly, exposing it to external mutation and concurrent-modification
hazards. Return List.copyOf(...) instead.

* fix(stepfunctions): ListStateMachineVersions newest-first and InvalidArn for missing SM

AWS lists state machine versions newest first (descending by creationDate, tie-broken on
the version number since creationDate is only second-resolution); returning insertion order
made the Terraform provider latch onto the wrong version ARN once more than one version
existed. Listing versions for a non-existent state machine now returns InvalidArn rather
than StateMachineDoesNotExist, which is not a declared error for this operation. Adds a
two-version ordering test and a missing-state-machine InvalidArn test.
2026-07-01 22:35:10 -05:00
Jason van Zyl a895802b8b fix(autoscaling): fail SSM commands for stale ASG instances (#1600)
* fix(autoscaling): fail SSM commands for stale ASG instances

* fix(ssm): clear stale instance message indexes
2026-07-01 22:28:04 -05:00
Jason van Zyl fef03c6b0f fix(ec2): align AMI guest and launch template parity (#1597)
* fix(ec2): preserve launch template instance profiles

* fix(ec2): skip networkd wait-online in AMI guests

* feat(docker): add image registry override

* fix(ec2): align launch template AMI parity

* fix(docker): simplify registry base config handling

* fix(docker): normalize registry base once
2026-07-01 22:05:06 -05:00
Alex Banna 6223fc4a02 feat(tls): serve HTTPS on 443 and trust Floci's cert in Lambda containers (#1595)
* feat(lambda): trust Floci's TLS cert and serve HTTPS on 443 for CDK callbacks

CDK/CloudFormation custom resources (LogRetention, the provider framework,
AwsCustomResource, ...) PUT their result to the cfn-response ResponseURL using
aws-cdk-lib's bundled cfn-response code. That code parses only the URL's hostname
and path and then calls require("https").request(...) — it ignores the scheme and
port. So even though Floci hands the resource an http://...:4566 ResponseURL, the
callback always goes to https://<host>:443. Against Floci that fails — so every
custom resource rolls back, even though its own AWS SDK calls (on 4566) succeed.

This makes Floci reachable, and trusted, where the callback actually connects,
without touching the CDK-owned handler:

- TlsProxyServer binds the same protocol-detecting handler on a configurable
  floci.tls.aws-https-port (default 443, 0 to disable, deduped against the public
  port) in addition to the public Floci port. The first byte still selects the
  HTTP (4510) or HTTPS (4511) backend, so 443 serves both like the main port.

- CertificateGenerator gains generateSelfSignedCertificate(): a genuinely
  self-signed cert (issuer == subject, CA:true, keyCertSign) that can be a trust
  anchor. The existing generateCertificate() is unchanged — it still stamps the
  cosmetic Amazon issuer DN for ACM realism, which is NOT verifiable as an anchor.
  TlsConfigSource now uses the self-signed variant for Floci's HTTPS cert and
  regenerates legacy non-self-signed certs on upgrade.

- ContainerLauncher, when TLS is enabled, copies Floci's CA certificate into each
  Lambda container at /etc/floci-ca.crt and sets NODE_EXTRA_CA_CERTS, AWS_CA_BUNDLE,
  SSL_CERT_FILE and REQUESTS_CA_BUNDLE so the container trusts Floci's HTTPS
  endpoint. NODE_EXTRA_CA_CERTS adds to Node's built-in CAs, so public TLS still
  works.

All behaviors are gated on floci.tls.enabled (default false); non-TLS setups are
unchanged.

* fix(tls): guard TlsConfig access in launcher tests and soften 443 bind log

CI surfaced 18 NPEs in the existing ContainerLauncherTest and LambdaImageConfigTest:
ContainerLauncher.launch() now reads config.tls().enabled(), but those tests mock
EmulatorConfig without stubbing tls() (returns null). Fixes:
- launch() short-circuits so cert-path/storage config is only read when TLS is enabled.
- Both tests stub config.tls() with a TlsConfig whose enabled() is false.
- TlsProxyServer logs a failed bind of the extra AWS-HTTPS port (443, privileged) at
  WARN instead of ERROR — it is expected and non-fatal in unprivileged envs (CI/test);
  the public port still errors loudly.

* fix(tls): don't replace the Lambda's CA bundle; warn on a non-CA cert

flociCaEnv set SSL_CERT_FILE and REQUESTS_CA_BUNDLE to Floci's cert, which
REPLACE the OpenSSL / Python-requests trust store with only that cert — so a
Lambda's external HTTPS calls (curl, openssl, requests/botocore) to anything but
Floci failed certificate verification. Inject only the appending/AWS-scoped vars:
NODE_EXTRA_CA_CERTS (adds to Node's CAs) and AWS_CA_BUNDLE (AWS-SDK traffic is
redirected to Floci via AWS_ENDPOINT_URL anyway).

resolveFlociCaCertPath injects the resolved cert into containers as a trust
anchor (CA). A user-supplied floci.tls.cert-path pointing at a leaf/server cert
only pins that exact certificate; document that and log a warning when the
configured cert is not a self-signed CA (issuer != subject or no BasicConstraints
CA:true), via the new isSelfSignedCaCertificate helper.

Updates ContainerLauncherCaTrustTest for the trimmed env set and adds coverage
for self-signed-CA vs leaf-cert detection.
2026-07-01 21:29:05 -05:00
Kenshin Okinaka dec3b6366e fix(ses): treat missing SendingEnabled as false in v2 PutConfigurationSetSendingOptions (#1594)
The v2 PutConfigurationSetSendingOptions required SendingEnabled and returned
400 when it was absent, which is stricter than AWS. Reuse the AWS-aligned
SendingEnabled deserialization shared with CreateConfigurationSet (parsed via
the shared readOptionBody helper): an empty body / {} disables sending (200),
a string coerces to true, and an explicit null/number raises
SerializationException — all verified against real AWS.
2026-07-01 20:50:05 -05:00
Christine Nguyen b99d9fc383 fix(cloudformation): treat missing SecretsManager secret as already-deleted on stack delete (#1672)
Fixes #1668
2026-07-01 17:18:08 -05:00
Stuart Lang 7f76009cdb fix(cloudwatch-logs): preserve ingestion order for same-timestamp events (#1592)
* fix(cloudwatch-logs): preserve ingestion order for same-timestamp events

GetLogEvents and FilterLogEvents sorted events by timestamp only, so
events sharing the same millisecond came back in arbitrary store order.
Add a monotonic ingestion sequence to LogEvent and use it as a sort
tie-breaker, matching CloudWatch Logs which returns same-timestamp
events in ingestion order. The counter is seeded from the highest
stored sequence so ordering survives persistence reloads.

Closes #1584

* fix(cloudwatch-logs): add eventId as final ordering tie-breaker

Legacy events created before the sequence field default to sequence 0,
so timestamp+sequence alone left their relative order to arbitrary scan
order. Fall back to eventId to keep ordering deterministic.

* test(cloudwatch-logs): import ArrayList instead of inline FQN

Add an import for java.util.ArrayList and use the short name across the
test, replacing inline new java.util.ArrayList<>() usages.
2026-07-01 00:55:35 -05:00
Matt Van HornandMatt Van Horn 189d893803 fix: wrap ELBv2 void query responses in their Result envelope (#1189)
Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-06-30 23:06:30 -05:00
Alex Banna f558472a4d feat(stepfunctions): run executions under the execution's account (#1566)
* feat(stepfunctions): run executions under the execution's account

AslExecutor runs each execution on a worker-thread pool with no active CDI
request scope, so service integrations (Lambda, DynamoDB, SQS, …) and the
execution-store writes fell back to the configured default account. An
execution started under account B therefore had its integrations run
against account A's resources — e.g. a dynamodb:putItem targeting a table
that exists only in account B would fail with ResourceNotFound.

Wrap doExecute in a synthetic request scope whose account is the one
encoded in the state machine ARN (mirroring CurEmissionScheduler's
runUnderAccount), so integrations and store writes resolve to the
execution's own account. Falls back to running directly when Arc is not
running (plain unit tests that construct AslExecutor without a container).

Test: an execution started under a non-default account writes to a table
that exists only in that account; the execution succeeds, the item is
readable in that account, and a different account has no such table.

* fix(stepfunctions): restore previous account after runUnderExecutionAccount

Greptile review on #1566: when execution ran inside an already-active request
scope, runUnderExecutionAccount overwrote the account ID without restoring it.
Save and restore the previous account in finally so a reused thread isn't left
with the execution's account. (Executions run on background workers with no
active scope, so this hardens the already-active path.)

* fix(stepfunctions): run Parallel branches under the execution's account

executeParallelState submitted each branch to the executor pool without
re-establishing the execution's CDI request scope. RequestContext is
@RequestScoped (thread-bound), so a branch running on a worker thread had no
active scope: its Task integrations resolved via RegionResolver.getAccountId(),
which falls back to the default account on ContextNotActiveException. Branch
Task states therefore ran against the default account's resources instead of
the execution's.

Extract the scope-activation logic into a Callable-returning
callUnderExecutionAccount (runUnderExecutionAccount now delegates to it) and wrap
each branch submission with it, so every branch worker thread activates its own
request scope for the execution's account — mirroring how executeAsync/executeSync
wrap doExecute. Map states already run executeBranch synchronously on the parent
thread, so they were unaffected.

Adds a Parallel-branch case to StepFunctionsAccountContextIntegrationTest whose
branches dynamodb:putItem into a table that exists only in the execution's
account; it FAILs without per-branch propagation and SUCCEEDs with it.
2026-06-30 22:17:52 -05:00
Alex Banna d54a307ca9 feat(iam): enforce AssumeRole trust policies when enforcement is enabled (#1552)
* feat(iam): enforce AssumeRole trust policies when enforcement is enabled

When floci.iam.enforcement-enabled is true, STS AssumeRole now evaluates the
target role's trust policy (AssumeRolePolicyDocument) against the caller and
returns AccessDenied if it is not permitted. Enforcement is off by default,
so existing behavior is unchanged.

Trust policies are principal-centric and carry no Resource element, so the
identity/resource-oriented IamPolicyEvaluator cannot evaluate them. A focused
AssumeRolePolicyEvaluator matches each statement's Action (sts:AssumeRole) and
AWS Principal (account id, account-root ARN, exact principal ARN, or "*")
against the caller, with explicit Deny taking precedence. The role is resolved
in its own account (from the role ARN) via a new IamService.findRole overload,
since roles are account-namespaced. Roles unknown to Floci stay permissive to
preserve backward compatibility.

Tests: unit coverage for the evaluator across principal/action/deny/malformed
cases, plus an enforcement-enabled integration test asserting a permitted
caller succeeds, an unauthorized caller is denied, and an unknown role stays
permissive.

* docs(sts): restore Configuration section and note NotAction limitation

Greptile review on #1552:
- Restore the FLOCI_SERVICES_STS_ENABLED Configuration section that was dropped
  when the Trust Policy Enforcement section was added.
- Document that NotAction is not evaluated (a Deny with NotAction won't block).

* fix(iam): honor NotAction in AssumeRole trust statements

evaluateStatement only inspected the Action key, so a trust statement using
NotAction returned NO_MATCH and was skipped entirely. A Deny that should block
sts:AssumeRole (NotAction excluding some other action) was therefore ignored,
over-permitting AssumeRole when IAM enforcement is enabled. Add actionApplies()
mirroring IamPolicyEvaluator's Action/NotAction semantics: Action applies when
any pattern matches, NotAction applies when none match. Covered by three new
AssumeRolePolicyEvaluatorTest cases.

* fix(iam): match an assumed-role caller against a role-ARN trust principal

When a caller uses assumed-role temporary credentials, resolveCallerArn (rightly,
for GetCallerIdentity) yields the STS assumed-role ARN
(arn:aws:sts::ACCT:assumed-role/Role/session). enforceTrustPolicy passes that to
the trust-policy evaluator, but role trust policies name the role's IAM principal
ARN (arn:aws:iam::ACCT:role/Role) — the canonical form AWS resolves the session
back to. So a legitimate role-to-role AssumeRole was denied.

matchesAwsPrincipal now also normalizes an assumed-role caller ARN to its
underlying IAM role ARN and matches the principal against that, while still
matching an exact session-ARN principal. resolveCallerArn is unchanged, so
GetCallerIdentity keeps returning the assumed-role ARN.

Adds AssumeRolePolicyEvaluatorTest cases for role-ARN match, differing-role
denial, and exact session-ARN match.
2026-06-30 21:44:04 -05:00
Hector Ventura 04e0f2dddb fix(cloudformation): idempotent ECS resource deletion on stack delete (#1645)
Deleting a stack that tracked an AWS::ECS::TaskDefinition (or Cluster) failed
with DELETE_FAILED after a persistent restore when ECS no longer had the record.
Treat an already-missing task definition, cluster, or service as delete-complete,
matching how AWS tolerates absent resources during stack deletion.

Also hardens ECS persistence so records survive a native-image restore: register
the NetworkMode and LaunchType enums for reflection, and quarantine an unreadable
persisted file instead of silently starting empty.

Closes #1634
2026-06-29 23:39:17 -05:00
Kenshin Okinaka 01c7e1e62d fix(ses): make FromEmailAddress optional for v2 SendEmail (#1561)
The v2 SendEmail handler required FromEmailAddress for every content type,
diverging from AWS where it is marked Required: No. Match the AWS behavior,
verified against real AWS via probes (including the raw HTTP error bodies):

- Raw content takes its sender from the MIME From header; FromEmailAddress may
  be omitted. When neither is present the send fails. The check lives in the
  shared SesService.sendRawEmail and throws the v1-native InvalidParameterValue
  "Missing required header 'From'." — the v2 controller's remapV1Exception turns
  it into BadRequestException, so v1 Query keeps InvalidParameterValue and v2
  REST returns BadRequestException, both matching real AWS. This also fixes the
  v1 SendRawEmail path, which previously accepted a From-less raw message.
- Simple content with no FromEmailAddress returns BadRequestException with a
  null message body ({"message":null}), exactly as AWS does.
- Templated content with no FromEmailAddress returns BadRequestException
  "Source cannot be empty".

Tests: v2 cases folded into SesV2IntegrationTest (Raw-with-MIME-From success,
Simple null-message, Templated "Source cannot be empty") and a v1 case in
SesIntegrationTest pinning the Query wire shape.
2026-06-29 22:40:44 -05:00
David Lopes 2142ff6e3c feat(iam): add AmazonRDSEnhancedMonitoringRole managed policy (#1559)
* feat(iam): add AmazonRDSEnhancedMonitoringRole managed policy

Seeds the AmazonRDSEnhancedMonitoringRole service-role policy at
startup so callers can attach it to IAM roles without a NotFound error.

* test(iam): cover AmazonRDSEnhancedMonitoringRole seeding and attachment

Adds an assertion in seedAwsManagedPolicies(), a unit test that attaches
the policy to a role, and an integration test that retrieves it via
GetPolicy.
2026-06-29 20:19:07 -05:00
Alex Banna 677dfd6a16 feat(stepfunctions): add aws-sdk CloudFormation/EC2 and S3 PutObject integrations (#1556)
Step Functions could only invoke a few optimized/aws-sdk integrations
(Lambda, DynamoDB, SQS, nested state machines); any other resource failed
with 'Unsupported resource'. Provisioning state machines that drive
CloudFormation (StackSets), look up regions, or stage templates in S3 could
not run.

Add:
- a generic query-protocol bridge for arn:aws:states:::aws-sdk:cloudformation:*
  that flattens the task input to Query parameters, dispatches to the
  CloudFormation handler, and converts the XML response to the JSON shape the
  aws-sdk integration returns (member lists unwrapped to arrays);
- arn:aws:states:::aws-sdk:ec2:describeRegions;
- arn:aws:states:::s3:putObject (optimized and aws-sdk forms).

Tests: a unit test for the XML->JSON converter (scalars, nested objects,
member lists) and an integration test exercising ec2:describeRegions,
cloudformation:validateTemplate, and s3:putObject through Step Functions.
2026-06-29 20:03:10 -05:00
Prakhar Kapoor f4c7a84de6 feat(floci-core): implement state reset and nuke endpoints (#1482)
* feat(floci-core): implement state reset and nuke endpoints

* feat(floci-core): implement core interface to handle service wide state clearing when the emulator's state is reset

* feat(floci-core): genericize state reset via Resettable interface
2026-06-29 19:37:36 -05:00
Alex Banna f52b9209cf feat(iam): route assumed-role credentials to the target account (#1549)
* feat(iam): route assumed-role credentials to the target account

Assumed-role temporary credentials (ASIA… keys) collapsed to the default
account: account resolution only recognised 12-digit access key IDs and had
no link to the STS session store. Cross-account "assume a role in account B,
then provision" flows therefore landed resources in account 000000000000
instead of B.

Add a SessionAccountLookup port in core.common, implemented by IamService,
mapping a temporary access key to its account — the account in the session's
role (or federated-user) ARN, or the caller account captured at mint time for
role-less GetSessionToken credentials. AccountContextFilter now resolves with
the precedence 12-digit AKID → session lookup → default, for both the
Authorization header and the presigned X-Amz-Credential parameter.

STS handlers record the caller account on every minted session, and
SessionCredential gains an originAccountId field. The session lookup is
account-independent, since sessions are keyed by a globally unique access key.

IamService is now @Startup so AWS-managed policies seed under the default
account at boot. Seeding is account-namespaced and AccountContextFilter now
instantiates IamService to resolve the request account, so lazy seeding would
otherwise bind managed policies to whichever account made the first request.

Tests: unit coverage for resolver/filter precedence and session lookup, plus
an integration test proving a table created with role-B credentials
materialises in account B and is invisible to account A.

* perf(iam): skip session-store scan for non-ASIA access keys

Account resolution runs on every request. Gating the session lookup on the
ASIA temporary-credential prefix keeps the common case (e.g. the 'test'
default credential) off the session-store scan, which would otherwise grow
with every issued session.

* chore: re-trigger CI

Unrelated flaky CodeBuildTest.batchGetBuilds_eventuallySucceeds; root-cause
fix in floci-io/floci#1577.
2026-06-28 21:30:34 -05:00
Jason van Zyl 94468ba56f fix(elbv2): publish resolvable local ALB DNS names (#1492) 2026-06-28 21:02:44 -05:00
AgustinBertagna 113c7d7e7d feat(appsync): Phase 4 — VTL Engine (#1288)
* feat(appsync): add VTL engine core infrastructure

Add ReturnSignal exception for #return directive, AppSyncVtlResult record
for evaluation results, and ReturnDirective custom Velocity directive.

* feat(appsync): wire AppSyncUtil to VTL context

Add errorList and authTypeValue fields with setters. Change authType()
to return configured value. Change appendError() overloads to accumulate
errors in internal list. Add toJson() exclusion for selectionSetList and
selectionSetGraphQL. Add base64Encode(String) overload.

* feat(appsync): add VTL engine context and evaluator

AppSyncVtlContext builds the  map with all aliases (, ,
, , , , ). AppSyncVtlEngine evaluates VTL
templates using Apache Velocity with AppSync-specific context variables,
custom #return directive, and VtlErrorSignal/ReturnSignal handling.

* chore(appsync): add GraalVM reflection config for VTL engine classes

Register AppSyncVtlEngine, AppSyncVtlContext, ReturnDirective, and
all Phase 3 util classes for native image reflection.

* test(appsync): add VTL engine unit tests

89 tests across categories A-J covering context variables, util methods,
error handling, appendError accumulation, #return directive, authType,
velocity directives, pipeline simulation, and edge cases. Validates
AWS AppSync behavior: null references render as literal text, #return
clears buffer, .error() clears output, var silent references.

* fix(appsync): set $context.prev to null for unit resolvers

AWS AppSync does not initialize $context.prev in unit (non-pipeline)
resolvers. It is null, not an empty map. Accessing $ctx.prev in a unit
resolver renders the literal text (e.g. "$ctx.prev") in non-strict
Velocity mode, matching AWS behavior.

* fix(appsync): accept Object in $util.qr() and $util.quiet()

AWS AppSync defines qr/quiet as accepting any Object, not just String.
The previous String signature caused method resolution failures in
Velocity when non-String values (Integer, Boolean, List, Map, or method
return values like Map.put) were passed. Changed to Object to match AWS.

* fix(appsync): remove dead exception handling in VTL engine

Velocity wraps exceptions thrown by method calls inside a generic
Exception, but exceptions thrown by custom directives (ReturnSignal)
propagate directly. The catch(VtlErrorSignal) and ReturnSignal unwrap
branches were dead code. Simplified to only unwrap VtlErrorSignal from
wrapped method exceptions.

* test(appsync): update and add tests for AWS parity and full coverage

Updates:
- j11: $context.prev default is now null (not empty map)
- j11b/j11c: undefined prev renders as literal text
- qr/quiet: expanded with Integer, Boolean, List, Map arguments

New tests for 100% coverage:
- c21: $util.transform accessible from VTL
- e6: appendError with errorInfo (4-arg overload)
- getTransform_returnsInstance: getter coverage
- escapeJavaScript_controlCharDefault: control char <0x20 branch
- toJson_mapWithFieldNameOnlyDoesNotFilter: fieldName-only branch
- toJson_serializationFailureReturnsNull: JsonProcessingException catch
- appendError_withErrorInfo: errorInfo non-null branch
2026-06-28 17:25:49 -05:00