Commit Graph
874 Commits
Author SHA1 Message Date
TiM 13772fb5f8 feat(ecs): resolve containerDefinitions[].secrets at task launch (#1687)
RegisterTaskDefinition now parses and stores containerDefinitions[].secrets
(name + valueFrom) and round-trips them on register/describe as references,
matching AWS (the resolved values are never returned).

At RunTask launch, EcsContainerManager resolves each secret to an environment
variable through the in-process SsmService / SecretsManagerService (the same
local resolution CodeBuildRunner already uses, no extra HTTP hops):

- SSM parameter by name or full ARN -> Parameter.value
- Secrets Manager full ARN -> SecretString
- a full ARN's own region is used, so cross-region references resolve correctly
- env precedence: task-def environment < resolved secrets < RunTask container
  override environment (override still wins on a name collision)

When a referenced secret/parameter cannot be resolved the launch fails the way
AWS does: no container is started and the task goes STOPPED with a
ResourceInitializationError stoppedReason, rather than silently starting the
container without the variable.

Deferred (noted in floci-io/floci#1624): the Secrets Manager valueFrom selector
suffix (:json-key:version-stage:version-id) is not yet parsed; such a valueFrom
is resolved as the plain secret.

Adds handler round-trip tests, container-manager resolution / override /
cross-region unit tests, a stopped-task failure test, and Java SDK
compatibility coverage.
2026-07-10 20:41:43 -05:00
Kenshin Okinaka efc9453fd7 fix(ses): populate VerificationStatus in v2 ListEmailIdentities (#1722)
* fix(ses): populate VerificationStatus in v2 ListEmailIdentities

ListEmailIdentities built each item with only IdentityType / IdentityName /
SendingEnabled, so VerificationStatus always serialized as null and clients had
to call GetEmailIdentity per identity. Populate it from the identity's stored
status (mapped to the v2 enum via toV2Status), and refresh each identity's
state the same way GetEmailIdentity does so the list stays consistent (e.g. a
domain that transitioned to SUCCESS via its DKIM records).

* fix(ses): derive SendingEnabled from verification status in v2 ListEmailIdentities

SendingEnabled was hard-coded to true, so a not-yet-verified identity was
reported as sendable, which is inconsistent now that VerificationStatus is
populated. AWS returns SendingEnabled=true only when the identity is verified
(VerificationStatus SUCCESS) and false otherwise (PENDING/FAILED), matching the
VerifiedForSendingStatus logic already used by GetEmailIdentity. Derive it the
same way here.
2026-07-09 23:54:43 -05:00
Hector Ventura 3771c1e9a2 fix(ecs): assign awsvpc tasks dynamic host ports to avoid collisions (#1785)
In awsvpc mode every AWS task receives its own ENI, so a portMapping's
hostPort carries no host-binding semantics. Floci was publishing it
literally on the single local Docker host, so two tasks of the same
service — or two services sharing a port — collided on start.

awsvpc mappings now get a dynamic host port in native mode, or
expose-only in Docker mode where consumers reach containers via the
docker network IP. bridge and host mode keep publishing hostPort
literally, matching AWS.

Also fix the leak this surfaced: a failed start in
ContainerLifecycleManager.createAndStart left the created container
behind, so retrying callers accumulated Created containers and
fixed-name callers hit name conflicts on the next attempt.

Refs #1778
2026-07-09 23:45:54 -05:00
Jongsic Choi 768019836f fix(lambda): return a downloadable GetFunction Code.Location (#1718)
* fix(lambda): return a downloadable GetFunction Code.Location

GetFunction returned a fabricated real-AWS S3 URL for Code.Location that
404s, so clients (and browser UIs) cannot download the deployment package.
Persist the uploaded zip in Floci's own S3 (awslambda-<region>-tasks) on
every successful code deploy and return a path-style URL on the local
endpoint (built from the request via UriInfo), matching AWS/LocalStack.
Bytes are exact, so the download hashes to the stored CodeSha256.

Centralized in extractZipCode so it covers ZipFile, S3-source, and the
reactive S3-update listener; hot-reload is excluded by design. The stored
object is overwritten on redeploy and removed on DeleteFunction.

* fix(lambda): log deleteFunction S3 cleanup failure instead of swallowing it

The best-effort deleteObject cleanup caught and ignored exceptions with an
empty catch block, violating the AGENTS.md rule that a tolerated exception
must be logged with enough context to diagnose it. Log it via LOG.warnv,
matching storeDeploymentPackage.
2026-07-09 23:43:44 -05:00
Hector Ventura 342bb52df4 fix(ec2): serialize concurrent mutations of shared resources per resource (#1786)
* fix(ec2): serialize concurrent mutations of shared resources per resource

The storage backend's get() returns the live stored object, so mutating
its collections in place raced under parallel clients. Terraform runs
10-wide by default, and concurrent AssociateRouteTable calls dropped
associations; describes could also observe a half-updated list.

Mutators of route tables, network ACLs, security groups, and tags now
take a per-resource lock and swap collections copy-on-write, so a
concurrent describe only ever sees a complete list. The lock is striped
by storage key, so unrelated resources never contend — replacing the
coarse `synchronized` methods on the NACL paths.

Refs #1464

* fix(ec2): make ReplaceNetworkAclAssociation atomic and bound the lock stripes

The unlocked membership scan let concurrent callers with the same
associationId each claim the association: the loser's remove() silently
no-opped, so every caller minted a distinct moved association and added it
to the target ACL, leaving one subnet associated several times.

Claim the association under lock, and hold the source and target locks for
the whole move so a describe never observes the subnet associated with
neither ACL. Losers now fall through to InvalidAssociationID.NotFound.

Replace the per-key lock map, which never evicted, with a fixed stripe
array. Two-lock callers order acquisition by stripe index rather than
storage key, since distinct keys may share a stripe and key order would
not be a total order over the monitors.

Drop the redundant pre-lock getRequiredRouteTable in createRoute; the
call inside the lock throws identically, matching deleteRoute.
2026-07-09 22:57:32 -05:00
Hector Venturaandseyi idowu 5cce73da45 fix(ec2): round-trip create-time tags and route/SG-rule attributes (#1763)
Create-time values were dropped, causing perpetual terraform plan diffs:

- Inline TagSpecification tags now round-trip on create for subnets,
  route tables, internet gateways, elastic IPs, security groups, and
  security group rules (each rule gets its own tag copy).
- CreateRoute stores and returns natGatewayId (was only gatewayId),
  in both the query handler and the CloudFormation provisioner.
- DescribeSecurityGroupRules supports the security-group-rule-id
  filter and multiple group-id values; the SecurityGroupRuleId
  parameter and the filter are intersected (conjunctive), matching
  AWS semantics.

Closes #1463
Supersedes #1491

Co-authored-by: seyi idowu <160403633+awsvigilante@users.noreply.github.com>
2026-07-09 20:52:23 -05:00
Jason van Zyl acedc30017 fix(autoscaling): propagate ASG tags at launch (#1734)
* fix(autoscaling): propagate ASG tags at launch

* docs: sync service action tables
2026-07-09 00:21:36 -05:00
Alex Banna 291752c36e feat(ecs): inject the AWS SDK baseline env into launched task containers (#1697)
* test(stepfunctions): pass ecs:runTask ctor args in AslExecutorPathIntrinsicsTest

Same one-line fix as #1696: AslExecutor gained EcsService/EcsJsonHandler ctor
params in #1564 but this test (from #1558) was not updated, breaking test
compilation on main. Included here so this PR's CI is green independently of
#1696; resolves cleanly once #1696 merges (identical change).

* feat(ecs): inject the AWS SDK baseline env into launched task containers

Launched ECS task containers previously received only their task-definition and
override environment. An AWS SDK running inside such a container therefore had
no AWS_ENDPOINT_URL (so it targeted real AWS instead of the emulator), no
region, and an empty credential-provider chain. Lambda containers already avoid
this because ContainerLauncher injects those variables.

Extract that baseline into a shared LaunchedContainerAwsEnv helper and apply it
to ECS tasks too:

- LaunchedContainerAwsEnv (core/common/docker): builds the KEY=value baseline —
  AWS_DEFAULT_REGION/AWS_REGION, credentials (a mounted ~/.aws dir when
  configured, otherwise placeholder credentials from Floci's own env falling
  back to test/test/test), and FLOCI_HOSTNAME/FLOCI_ENDPOINT/AWS_ENDPOINT_URL
  from ContainerReachableEndpoint.
- ContainerLauncher (Lambda): replace the inline region/credentials/endpoint
  block with the shared helper. The resulting environment is byte-for-byte
  identical to before; only the source of the entries moved.
- EcsContainerManager (ECS): prepend the baseline to each task container's
  environment as overridable defaults (task-def and RunTask containerOverride
  values still win on key conflict), and enable withHostDockerInternalOnLinux()
  + withEmbeddedDns() so the endpoint hostname resolves to Floci from inside the
  task container, the same way Lambda containers do.

Credentials are injected as env placeholders (as ContainerLauncher already does
for Lambda), not via the real ECS task-role container-credentials metadata
endpoint; emulating that endpoint would be a reasonable follow-up.

Adds LaunchedContainerAwsEnvTest and EcsContainerManagerAwsBaselineTest, and
updates the existing launcher/manager constructor call-sites.

* refactor(ecs): address review feedback on LaunchedContainerAwsEnv

- Drop the unused single-argument constructor that stored a null
  ContainerReachableEndpoint and would NPE on any sdkBaselineEnv call
  (Greptile P1), along with the vestigial EmulatorConfig field/param it
  carried — the helper only needs ContainerReachableEndpoint.
- Remove the now-dead null guard in EcsContainerManager.buildEnvVars
  (the real sdkBaselineEnv never returns null) and instead stub the mocked
  helper with List.of() in the ECS unit tests, making the contract explicit
  (Greptile P2).

* docs: regenerate action tables
2026-07-09 00:19:39 -05:00
Alex Banna 54b378ed6c feat(stepfunctions): resolve payload-template .$ inside arrays and $$ context in intrinsic args (#1691)
* feat(stepfunctions): resolve payload-template .$ inside arrays and $$ context in intrinsic args

Two AWS States Language parity fixes in the payload-template / intrinsic path:

- resolveParameters now recurses into arrays, not just objects. A Parameters / ItemSelector /
  ResultSelector template resolves .$ references at any nesting depth, including inside arrays
  (e.g. an ECS Overrides.ContainerOverrides[].Environment[].Value.$). Previously array elements
  passed through verbatim, so those references were never substituted.
- Intrinsic-function arguments can now reference the Context Object ($$). resolvePath /
  evaluateIntrinsic / resolveIntrinsicArg thread the Context Object through, so an argument like
  States.Format('{}', $$.Map.Item.Value.x) or a bare $$.Execution.Id resolves against the
  context. Ordinary $. / input-only resolution is unchanged (context is null there).

Adds AslExecutorArrayParamsTest and AslExecutorIntrinsicContextTest.

* docs: regenerate action tables
2026-07-09 00:17:24 -05:00
Alex Banna 4a16266f48 feat(cloudformation): support UpdateTerminationProtection (#1692)
* feat(cloudformation): support UpdateTerminationProtection

CDK bootstrap calls UpdateTerminationProtection on the CDKToolkit stack; Floci returned
UnknownAction. Add it: a boolean enableTerminationProtection on Stack, a
CloudFormationService.updateTerminationProtection(stackName, enabled, region) that sets and
persists it, a handler returning the UpdateTerminationProtectionResult/StackId envelope, and
the flag echoed as <EnableTerminationProtection> in DescribeStacks. Register the action in
AwsQueryController's CloudFormation action set so the Query-protocol POST routes to
CloudFormation instead of falling through. Adds an integration test toggling the flag and
asserting it round-trips through DescribeStacks.

* docs: regenerate action tables
2026-07-09 00:16:38 -05:00
Jason van Zyl dd566857ef fix(elbv2): dispatch same-port listeners by host (#1700)
* fix(elbv2): dispatch same-port listeners by host

* fix(elbv2): fall back to sole port listener

* fix(elbv2): avoid restricted Host header dependency

* fix(elbv2): keep same binding restarts in place

* docs: sync service action tables
2026-07-09 00:15:46 -05:00
Alex Banna 0e85ac92c7 feat(pipes): apply EventBridge Pipe enrichment before target delivery (#1658)
* feat(pipes): apply EventBridge Pipe enrichment before target delivery

PipesPoller delivered the raw source record straight to the target; pipe.getEnrichment() was
stored but never invoked. Implement the AWS Pipes source->filter->ENRICHMENT->target flow: when an
enrichment Lambda is configured, invoke it once with the filtered events (bare JSON array) and
forward its response to the target (null/empty response skips the target, per AWS). Also resolve
qualified Lambda ARNs (:$LATEST) in PipesTargetInvoker. Covered by PipesTargetInvokerTest.

* fix(pipes): deliver enrichment result to the target as an event array

EventBridge Pipes delivers events to a target as a batch (JSON array). The
enrichment path forwarded a single-object enrichment response verbatim, so a
target expecting an array (e.g. a Step Functions state machine with
InputPath "$.[0]") received an object and resolved null. Wrap a non-array
enrichment response in a one-element array before target delivery. Covered by
PipesPollerTest.asEventArray*.

(cherry picked from commit f160f66857c2362e3f1bad3bbfdb025396b281a0)

* fix(pipes): treat a target/enrichment Lambda FunctionError as failed delivery

invokeLambda (the Lambda target path) discarded the InvokeResult, so a target
Lambda that returned a FunctionError (unhandled exception, throttle) was treated
as a successful delivery and the source record was consumed. Surface it (throw)
so the caller routes the record to the DLQ. Also switch applyEnrichment's
FunctionError failure from a bare RuntimeException to AwsException, per the
service-layer convention. Covered by PipesTargetInvokerTest.invoke_lambdaTargetFunctionErrorThrows.

* fix(pipes): only array-wrap the enrichment response for Lambda targets

deliverEnrichedBatch wrapped the enrichment response in a JSON batch array before invoking
the target unconditionally. That is correct for a Lambda target (which expects an
SQSRecord[]-style batch) but corrupts every other target — a Step Functions execution, SQS
message, SNS publish or EventBridge event must receive the raw enrichment response. Gate the
wrapping on isLambdaTarget, matching the non-enrichment delivery path. Adds pollSqs tests for
both a non-Lambda (raw) and a Lambda (wrapped) target.

* fix(pipes): align enrichment empty/unsupported handling with AWS + document SQS-only wiring

Review feedback:
- applyEnrichment now also skips the target when the Lambda enrichment returns an
  empty object {} or empty array [] (whitespace variants included), matching AWS;
  a non-empty array such as [{}] still invokes the target.
- A non-Lambda enrichment type (API destination, API Gateway, SFN Express) now
  fails the batch to the DLQ instead of silently delivering the unenriched payload.
- Documented that enrichment is currently applied only on the SQS source path
  (Kinesis/DynamoDB Streams/Kafka bypass it) in code and docs/services/pipes.md.
- Generalized a comment that named a specific downstream consumer.
- Tests: empty {}/[] skip, [{}] invokes, unsupported type throws.

* docs: regenerate action tables
2026-07-09 00:14:53 -05:00
Alex Banna 45ed00ebc7 feat(ecs): apply EFS access point POSIX ownership to shared local volumes (#1686)
* feat(ecs): apply EFS access point POSIX ownership to shared local volumes

#1569 materialises an ECS task's efsVolumeConfiguration volume as a shared
local Docker named volume (floci-efs-<fileSystemId>). Docker creates a named
volume root:root 0755, so a task whose image runs as a non-root USER — as
containers mounting an EFS access point typically do — cannot create files on
it and fails with EACCES.

Real EFS initialises an access point's root directory per
RootDirectory.CreationInfo {OwnerUid, OwnerGid, Permissions} and applies the
access point's PosixUser to all I/O regardless of the process uid. This change
emulates that mechanism for the shared local volume, driven by generic config:

- New floci.storage.efs.* block (owner-uid, owner-gid, root-permissions,
  setgid, init-image, mount-user, mount-group-add). Every value is empty/false
  by default, so a shared volume behaves exactly as before (a plain named
  volume, no ownership change) unless explicitly configured.
- ContainerLifecycleManager.ensureSharedVolume(...) ensures the volume then, if
  ownership is configured, chowns/chmods the mount root once (run-once guard;
  optional setgid so subdirectories inherit the owner gid) inside a short-lived
  helper container.
- ContainerSpec/ContainerBuilder gain withUser/withGroupAdd; wired into
  createContainerCmd.withUser and HostConfig.withGroupAdd.
- EcsContainerManager initialises the EFS volume root via ensureSharedVolume
  before mounting it.

Unit tests cover the no-op default (no helper container, no image pull), the
one-off chown/chmod/setgid helper with the run-once guard, the builder
round-trip, and the EcsContainerManager wiring.

* fix(ecs): apply configured EFS PosixUser to containers mounting a shared volume

Wire the previously-inert floci.storage.efs.mount-user / mount-group-add config into the
ECS container spec: a container mounting an EFS-backed shared volume now runs under the
configured uid[:gid] and adds the supplementary group, emulating the access point's
PosixUser squashing. Without this a non-root image USER could not write a volume owned by
owner-uid/owner-gid. Also add the floci.storage.efs.* section to application.yml (the
source of truth for effective defaults) and correct the root-permissions Javadoc, which
implied leaving it empty always skips volume init even when owner/setgid are set.

* docs: regenerate action tables
2026-07-08 23:24:48 -05:00
Kenshin Okinaka 312fe377fc feat(ses): implement PutEmailIdentityConfigurationSetAttributes for SES v2 (#1698)
* feat(ses): implement PutEmailIdentityConfigurationSetAttributes for SES v2

Add the v2 PutEmailIdentityConfigurationSetAttributes API and wire an email
identity's default configuration set into the send path so its event
destinations fire. This includes Raw sends with no explicit FromEmailAddress:
the configuration set is re-resolved from the MIME "From" header once parsed,
so an omitted-sender Raw send still routes through the identity default.
Unknown identities surface the AWS-matched error message.

* test(ses): log instead of swallowing cleanup failures in the identity config-set compat test

* docs(ses): clarify default config-set precedence and clear-on-null semantics

* fix(ses): fail send when an identity's default configuration set was deleted

Per the SES Developer Guide, sending through an identity whose default
configuration set has been deleted fails with a bad-request error. The default
resolution was silently dropping the stale association; make it throw
BadRequestException ("Configuration set <name> does not exist.") to match AWS.
2026-07-08 23:23:28 -05:00
Hector Ventura de13017cd3 fix: register persisted model types for native-image reflection (#1781)
An audit found 69 types reachable from StorageFactory persistence
still unregistered after #1695: iot (all 10 persisted roots),
cloudfront (20), apigateway (13), route53 (7), transfer (4), appsync
enums (6), plus nested inner types file-level sweeps miss (memorydb
Endpoint, Secret$RotationRules/$Tag, KinesisShard ranges,
IotPolicy$PolicyVersion). Native-image builds failed to deserialize
their persisted state on restart.

Adds PersistedModelReflectionTest, a classpath-scan guard that
discovers every persistence-root TypeReference<Map<String,V>>, walks
V's reachable field graph, and fails listing any type missing
@RegisterForReflection (direct or via targets=).

Refs #1695
2026-07-08 22:19:00 -05:00
Hector Ventura 959eb16700 chore: adopt shared ARN and XML utilities across services (#1780)
Replace hand-built "arn:aws:..." string concatenation with
AwsArnUtils.Arn.of/RegionResolver.buildArn (13 files) and migrate 16
manual ARN-parsing sites (split/substring/regex helpers) to
AwsArnUtils regionOrDefault/accountOrDefault/parse. Adds
XmlParser.childElementNames and moves S3SelectService off
indexOf/substring parsing and string-concat XML onto
XmlParser/XmlBuilder.

Also fixes the websocket $connect methodArn hardcoding account
000000000000 instead of resolving the caller account. Resource-tail
slicers (:stream/, :repository/, ...) are intentionally kept: parse()
would not remove the suffix logic.
2026-07-08 22:18:38 -05:00
shrimptails-f 36ef98047e feat(stepfunctions): support Map ItemReader for S3-backed JSON datasets (#1588)
* feat(stepfunctions): support Map ItemReader for S3-backed JSON datasets

* feat(stepfunctions): support Map ItemReader for S3-backed JSON datasets

* fix(stepfunctions): surface non-array ItemReader JSON as ItemReaderFailed

* fix(stepfunctions): align ItemReader runtime failures with emulator support

* refactor(stepfunctions): remove unused state machine parameter from resolveMapItems

* fix(stepfunctions): require DISTRIBUTED mode for ItemReader maps

* fix(stepfunctions): surface unimplemented ItemReader input types as ItemReaderFailed

* fix(stepfunctions): update AslExecutorCatchTest for constructor changes

* fix(stepfunctions): align ItemReader JSON object handling with AWS

* fix(stepfunctions): support ItemReader ItemsPointer for JSON datasets

* fix(stepfunctions): align ItemReader mode and JSONata arguments with AWS

* fix(stepfunctions): preserve array item context for Key/Value-shaped data
2026-07-06 22:51:39 -05:00
Abhishek Dubey a40dc52f4d feat: implement read-only describe/list APIs for resource collection (#1581)
* feat: implement read-only describe/list APIs for resource collection

Several read-only AWS actions returned UnsupportedOperation (HTTP 400) — or,
where no route existed, a 404 the AWS SDKs deserialize to a retryable
UnknownError. Both break clients that enumerate an account read-only: the 400
aborts the collection of the whole resource type, and the 404 sends the SDK
through its full retry/backoff schedule (~9 attempts, minutes) on every call.

Implement minimal, wire-accurate responses that mirror each service's documented
contract so SDK clients complete the read:

- IAM
  - GetLoginProfile -> NoSuchEntity (404), the documented result when a user has
    no console password; clients branch on it, so a 200 or 400 misleads them.
  - GetAccessKeyLastUsed -> the "never used" shape (ServiceName/Region = N/A, no
    LastUsedDate).
  - ListSAMLProviders / ListOpenIDConnectProviders / ListServerCertificates ->
    empty lists (non-paginated; ListServerCertificates carries IsTruncated=false).
- RDS: DescribeDBSnapshots / DescribeDBProxies / DescribeDBClusterSnapshots ->
  empty results (empty wrapper, no Marker).
- DocDB: DescribeDBClusterSnapshots -> empty result (RDS namespace).
- ElastiCache: DescribeCacheSubnetGroups / DescribeCacheParameterGroups -> empty.
- Glue: GetJobs / GetCrawlers / ListDataQualityRulesets /
  GetSecurityConfigurations / GetTags -> empty result under each result key.
- SSM: ListDocuments / ListAssociations / DescribeMaintenanceWindows -> empty
  (NextToken omitted).
- AWS Backup: GetBackupVaultNotifications / GetBackupVaultAccessPolicy ->
  ResourceNotFoundException (400), the documented "not configured" signal.
- S3 Control: ListAccessPoints -> empty AccessPointList (200), replacing the
  missing-route 404 that triggered the SDK retry storm.

Responses are grounded in the AWS API reference for each action (error codes,
HTTP statuses, and "empty"/"never used" shapes). Adds focused unit and
integration tests for each handler.

* docs: ground ListAccessPoints comment in the S3 Control contract

Drop the consumer-specific retry magnitude ("~9 attempts") from the
ListAccessPoints comment and justify the empty-200 response purely on the AWS
contract: ListAccessPoints documents a single success path — HTTP 200 with an
AccessPointList (empty when the account has none) and an optional NextToken.
404 is not a documented outcome for the operation, so a missing route leaves
SDK clients unable to map the response to the expected result or a known error.

* fix(glue): keep GetTags delegating to the schema registry

The earlier commit replaced Glue GetTags with a hardcoded empty {"Tags":{}},
which regressed the schema-registry tagging path: GetTags must return the tags
stored for a registry/schema ARN and InvalidInputException for an unknown ARN.
Restore the original handleGetTags delegation and drop the empty-stub test for
it. GetTags was already implemented — only GetJobs/GetCrawlers/
ListDataQualityRulesets/GetSecurityConfigurations were genuine gaps, and those
remain empty stubs.

Fixes GlueSchemaRegistryMetadataAndTagsIntegrationTest (getTagsReturnsAddedTags,
untagResourceRemovesKey, getTagsOnUnknownArnReturnsInvalidInput) and the
sdk-test-java GlueSchemaRegistryTest compat failure.

* fix(iam): omit empty UserName from GetAccessKeyLastUsed

UserName is optional in the IAM model and its type is non-empty
(length 1-128). The emulator has no AccessKeyId->UserName lookup, so
emitting an empty <UserName></UserName> could be rejected by a strict
client. Omit the element entirely instead; callers that need the owner
already have it from the preceding ListAccessKeys response.

* fix(backup): drop unused headers param from vault notification/access-policy stubs

* test(iam): cover GetLoginProfile, ListSAMLProviders, ListOpenIDConnectProviders, ListServerCertificates
2026-07-06 22:49:55 -05:00
Hector Ventura 94a2ff3993 feat(eventbridge): deliver events to Firehose delivery stream targets (#1739)
* feat(eventbridge): deliver events to Firehose delivery stream targets

EventBridgeInvoker dispatched Lambda, SQS, SNS, and Batch targets but silently
dropped Firehose-targeted events with an unsupported-ARN warning. Add the
:firehose: branch: the (input-transformed) event JSON becomes the record Data
verbatim, matching AWS, which appends no newline; the stream's NDJSON flush
handles separation. Covered by invoker unit tests and an end-to-end
PutEvents to rule to Firehose to S3 integration test.

Refs #1043

* refactor(eventbridge): use the Record constructor in the Firehose branch
2026-07-06 22:34:06 -05:00
Alex Banna 070b43d0f7 fix(stepfunctions): resolve qualified Lambda function ARNs in lambda:invoke (#1660)
The lambda:invoke integration took the last ':'-segment of FunctionName, yielding the version/alias qualifier (e.g. $LATEST) instead of the function name for ARNs like arn:aws:lambda:region:acct:function:NAME:$LATEST -> "Lambda function not found: $LATEST". Add extractLambdaFunctionName() to strip the :function: prefix and an optional trailing qualifier, used at both lambda:invoke call sites. Covered by AslExecutorLambdaArnTest.
2026-07-06 21:45:30 -05:00
Prakhar Kapoor caacbc8afa Fix(s3)/1560 fix copy object (#1670)
* fix(s3): add support for S3 CopyObject operation and multipart uploads

* fix(s3): correct checksum type when copying multipart objects in S3

* fix(s3): validate checksum algorithms and support standard header fallbacks

* fix(s3): handle integration tests

* fix(s3): return InvalidRequest for valid but unsupported checksum algorithms
2026-07-06 21:44:36 -05:00
Yahia 2288da7f23 feat(apigateway): persist API key tags and add GetApiKey route (#1677)
* feat(apigateway): persist API key tags and add GetApiKey route

CreateApiKey now stores the request tags and returns them from CreateApiKey, GetApiKey and GetApiKeys. Adds the missing GET /apikeys/{apiKeyId} route, which omits the value unless includeValue=true and returns 404 when the key is unknown.

* fix(apigateway): always emit tags object and harden API key tag parsing

Address review feedback: toApiKeyNode always emits "tags" (AWS returns "tags": {} even when empty); createApiKey coerces tag keys/values to String instead of an unchecked cast; the integration test initialises the shared apiKeyId to a sentinel and asserts the JSON error body on the 404 path.

* fix(apigateway): align 404 message and strip api key values from list by default

Address maintainer review: getApiKey now returns the AWS-accurate "Invalid API Key identifier specified" message; GetApiKeys honors the includeValues query param and omits each key's value unless requested (was leaking values by default); toApiKeyNode emits tags only when non-empty. Tests updated accordingly.
2026-07-06 21:43:34 -05:00
Federico Mariani 0626cd94d6 fix: honor queue-level DelaySeconds for standard SQS queues (#1567) 2026-07-06 21:42:36 -05:00
Jason van Zyl c3980ebab0 feat(scheduler): dispatch ECS targets to RunTask (#1733)
* feat(scheduler): dispatch ECS targets to RunTask

* fix(scheduler): preserve ECS target parameters
2026-07-06 21:40:24 -05:00
Jason van Zyl 3a31439a84 fix(ec2): honor launch template default version updates (#1704) 2026-07-06 21:39:37 -05:00
Jason van Zyl b8bb2ec6b3 fix(rds): improve postgres proxy startup parity (#1599)
* fix(rds): close postgres proxy bridge on relay exit

* fix(rds): decline postgres ssl negotiation

* fix(rds): support postgres ssl startup
2026-07-06 21:38:47 -05:00
Hector Ventura 7586a01cf9 fix(eks): let pods pull images pushed to the Floci ECR registry (#1762)
k3s containerd could not reach the emulated ECR registry: repository
URIs embed localhost plus the host-published port, which resolves to the
k3s container itself, and containerd requires a registries.yaml entry
before it will speak plain HTTP to a registry.

New clusters now get a generated /etc/rancher/k3s/registries.yaml,
injected through the Docker API before the container starts, that
mirrors every repository hostname the emulator can mint (the default
account across the region catalog, plus the path-style form) to the
registry container's in-network endpoint. Public registries are never
matched, and any failure skips the mirror without aborting cluster
creation. Opt out with FLOCI_SERVICES_EKS_ECR_REGISTRY_MIRROR=false.

Closes #1761
2026-07-06 21:36:14 -05:00
Matt Van HornandMatt Van Horn 2c746b25a1 fix(cloudwatch): return ResourceNotFound for SetAlarmState on missing alarm (#1621)
* fix: return ResourceNotFound 400 for SetAlarmState on missing alarm

* fix: use CloudWatch ResourceNotFound error code for missing alarm

* fix: use HTTP 404 for CloudWatch ResourceNotFound

Per @hectorvent's review: the CloudWatch service model (botocore
cloudwatch/2010-08-01 service-2.json) declares the ResourceNotFound shape with
httpStatusCode 404, so correct the AwsException status from 400 to 404 for the
missing-alarm SetAlarmState path and update the test assertion to match.

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-07-06 21:35:55 -05:00
Jason van Zyl 073e653d35 fix(docker): isolate managed resource containers (#1703)
* fix(docker): namespace managed resource containers

* fix(rds): avoid containerized host path creation

* fix(docker): isolate child container names

* fix(opensearch): preserve legacy domain container names
2026-07-06 21:01:26 -05:00
Jason van Zyl ab32758cfe fix(autoscaling): align active instance refresh behavior (#1598)
* fix(autoscaling): reject active refresh config updates

* fix(autoscaling): align active refresh SDK error shape

* fix(autoscaling): reject version-only launch template updates

* fix(autoscaling): match refresh config validation message
2026-07-06 21:00:50 -05:00
David Lopes 98464b4433 fix(rds): resolve tags by ARN resource type, not only DB instances (#1649)
* fix(rds): resolve tags by ARN resource type, not only DB instances

ListTagsForResource, AddTagsToResource and RemoveTagsFromResource
unconditionally resolved every ResourceName to a DB instance, so any
non-instance ARN (e.g. a DB subnet group) returned 404 DBInstanceNotFound.
This broke tools such as the Crossplane Upbound AWS provider, which calls
ListTagsForResource on every observe of a DB subnet group and never sees
it become ready.

Parse the ARN's resource-type segment and dispatch to the matching store
(db, cluster, subgrp): return the resource's tags, the resource-specific
NotFound fault when it is missing, and InvalidParameterValue for
unsupported resource types. Add tag storage to DbCluster and DbSubnetGroup
mirroring DbInstance. A bare (non-ARN) resource name still resolves to a
DB instance for backwards compatibility.

* fix(rds): return InvalidParameterValue for malformed or non-RDS tag ARNs

Address PR review: only fall back to a DB-instance lookup for bare,
non-ARN resource names. Strings that start with arn: are now parsed
strictly and must be RDS ARNs; malformed ARNs and ARNs for other
services return 400 InvalidParameterValue instead of a misleading
DBInstanceNotFound/DBClusterNotFoundFault.

* fix(rds): preserve subnet group tags across modifyDbSubnetGroup

Address PR review: buildSubnetGroup constructs a fresh DbSubnetGroup with
an empty tag map, so modifying a subnet group's subnets dropped any tags
added via AddTagsToResource. Carry the existing group's tags onto the
rebuilt object before persisting, matching AWS ModifyDBSubnetGroup.

* fix(rds): reject type-less RDS ARNs in tag ops and clarify unsupported-type message

Review feedback from #1649:
- An RDS ARN whose resource part is not <type>:<id> now returns 400
  InvalidParameterValue (matching real AWS) instead of falling back to a
  DB-instance lookup; bare non-ARN names keep resolving as DB instances.
- The unsupported-resource-type message now states the Floci scope
  limitation instead of implying those types are untaggable on AWS.
2026-07-06 21:00:22 -05:00
Hector VenturaandShivam Srivastav c99dd75b87 feat(secretsmanager): support Filters and pagination in BatchGetSecretValue (#1737)
* feat(secretsmanager): Support Filters and Pagination in BatchGetSecretValue

* fix(secretsmanager): Use InvalidParameterException for MaxResults out of bounds and document owning-service gap

* fix(secretsmanager): reject negative NextToken and tidy batch filter path

Review follow-up: a negative NextToken parsed successfully and fell into the
range guard, returning 200 with empty SecretValues instead of the
InvalidNextTokenException the ListSecrets path returns. Validate MaxResults
and NextToken before the service scans the store, extract the duplicated
Filters parsing into a shared parseFilters helper, and drop the dead
deleted-date guard (listSecrets already excludes deleted secrets).

* fix(secretsmanager): sort batch results before pagination

The batch filter path offset-paginated raw store-scan order, which can skip
or duplicate entries across pages when scan order shifts. Sort by created
date then name before returning, the same stable-pagination contract the
ListSecrets handler documents. Also document why the primary-region filter
compares the request region: with no cross-region replication model, every
secret's primary region is the region it lives in.

---------

Co-authored-by: Shivam Srivastav <shivamsriv961@gmail.com>
2026-07-05 10:21:10 -05:00
Alex Banna 47abda8e9f perf(lambda): mount function code from a read-only volume instead of copying per cold start (#1673)
* perf(lambda): mount function code from a read-only volume instead of copying it into every container

Every container launch tar-copied the function's whole /var/task tree into the
container's overlay filesystem. For a function with a large node_modules
(~34k files / 310MB) that small-file copy alone is ~95s on Docker Desktop; run
several at once (an app firing parallel requests at a cold pool) it saturates the
daemon so even `docker create` balloons to ~80s and a burst can take minutes.

Populate the code into a named Docker volume once per code version, then mount that
volume read-only into every container. Mounting is ~0.2s and the volume is shared by
all containers of the function - matching AWS, where /var/task is read-only.

Measured (310MB / 34k-file function): one-time populate ~120s (first launch only);
subsequent cold start ~95s copy -> 0.24s mount; 6 concurrent cold starts ~10 min -> ~1.3s.

Also: gate the whole create->copy->start with a semaphore (not just the copy) so a
cold-pool burst can't pile up half-built "Created" containers; treat a failed docker
inspect in isContainerRunning() as not-running so the warm pool discards dead
containers; enlarge the tar pipe buffer for the remaining small per-container copies.

* fix(lambda): only use code volume for large functions; gate populate not launch; fix stale-volume race and lock leak

Small functions keep the fast direct per-container copy of /var/task and only
large code (>= CODE_VOLUME_MIN_BYTES, default 32 MiB) is served from a shared
read-only volume. This fixes the apigatewayv2-websocket dataplane/tls cold-start
timeout regression: those routes invoke tiny Lambda handlers, and the volume
populate-helper round-trip plus launch serialization pushed the first invoke past
the 5s WS timeout. shouldUseCodeVolume walks the tree short-circuiting once the
running total crosses the threshold, and returns false on IO errors (falls back to
direct copy). The threshold is package-private and non-final so tests can override it.

The launch semaphore now guards ONLY the heavy volume populate (helper create +
tar copy) rather than every launch, so ordinary cold starts (volume mounts and
small-code direct copies) are never serialized (renamed to POPULATE_SEMAPHORE /
acquirePopulatePermit).

P1 (stale-volume race): removed the racy inline deletion of a function's previous
code-version volume. A concurrent in-flight launch could have already resolved the
old volume name and be about to mount it, so deleting it gave that container an
empty /var/task. Stale volumes are labeled floci=true and reclaimed by
`docker volume prune --filter label=floci`. Dropped the codeVolumeByFunction map.

P2 (lock leak): after a successful populate, codeVolumeLocks.remove(volName) is
called so the lock map only ever holds in-flight populates instead of growing
monotonically across redeploys.

* fix(lambda): release the runtime-api port when a launch fails before container create

runtimeApiServerFactory.create() allocates a runtime-api port up front, but the
launch's cleanup try/catch only opened at the container create() call. A failure
between them — most importantly the code-volume populate (ensureCodeVolume), but
also image/host resolve and the spec build — propagated past the catch and leaked
the port. That is exactly the cold-start-burst path this PR targets: when the
Docker daemon rejects the populate helper under load, each failed attempt leaked
one runtime-api port until the pool exhausted and every subsequent launch failed
even after the daemon recovered.

Widen the try to open right after the runtime-api server is allocated and run
through the container-handle build + log-stream attach, so any failure below
releases the port (and reaps any half-built container; containerId stays null when
we fail before create). Add a regression test that a populate failure still
releases the runtime-api server and creates/starts nothing.

Addresses the Greptile P1 (runtimeApiServer port leak) on #1673.

* chore: re-trigger CI (unrelated AutoScalingIntegrationTest.describeAutoScalingGroupsEmpty flake)

* fix(lambda): correct isContainerRunning Javadoc and widen the single-file tar buffer

Correct the isContainerRunning Javadoc, which still described the old return-true-on-error
behaviour and contradicted the implementation (an inspect error now returns false so a
hung/dead container is not reused). Widen copyFileToContainer's pipe buffer to the same
TAR_PIPE_BUFFER_BYTES used by copyDirToContainer (subsumes the separate tar-buffer change).
Resolve a merge with the TLS CA-cert copy from main: containerId is assigned along the
code-volume path and so is no longer effectively final, so its lambda capture becomes an
if-block.
2026-07-05 10:19:43 -05:00
Hector Ventura 87749e4600 fix(emr): return AWS client-error codes instead of 500 InternalServerError (#1731)
* fix(emr): return AWS client-error codes instead of 500 InternalServerError

Three EMR paths returned 500 InternalServerError for pure client errors,
which SDK clients treat as retryable server faults. Verified against the
botocore model and moto: RunJobFlow with a missing Name now returns 400
ValidationException in the AWS validation-message format, AddJobFlowSteps
with an unknown cluster returns 400 InvalidRequestException with the
'Cluster id ... is not valid.' message already used by DescribeCluster,
and TerminateJobFlows now matches AWS semantics by terminating the
unprotected clusters in the request before failing with 400
ValidationException when any cluster is termination protected.

* fix(emr): reject only a missing Name and pin the validation message

Review follow-up: the blank-name branch produced a message claiming the value
was null, and rejecting an explicit empty string was itself stricter than AWS.
The Name member is REQUIRED with a len=[0..256] constraint, so real EMR accepts
an empty string and framework validation only rejects null. Restrict the check
to null, pin the validation message in the missing-Name test, and add a test
that an empty Name creates a cluster.
2026-07-05 09:48:34 -05:00
Jason van Zyl 71ee94d8b0 fix(storage): make computeIfAbsent atomic (#1699) 2026-07-05 09:32:43 -05:00
Hector Ventura f8e8984c16 fix(lambda): persist version counters and event-invoke configs across restart (#1730)
* fix(lambda): persist version counters and event-invoke configs across restart

versionCounters and eventInvokeConfigs were memory-only while the rest of
Lambda state persists, so a restart in persistent mode let PublishVersion
re-issue already-used version numbers and dropped PutFunctionEventInvokeConfig
data. Wrap both maps through the existing 'lambda' storage key, restructure
the counter merge into a synchronized get-increment-put, re-put updated
event-invoke configs so mutations reach the backend, and add the LastModified
deserialization counterpart so the timestamp survives reload.

* fix(lambda): scope version-counter lock per key and align test storage with account prefixing

PublishVersion no longer serializes on the service instance monitor:
the counter increment locks per counter key, mirroring the existing
concurrencyOpLocks pattern, so unrelated functions publish in parallel
while same-function publishes still cannot issue duplicate numbers.

The persistence test factory now wraps its InMemoryStorage in
AccountAwareStorageBackend like the production StorageFactory, so the
restart tests exercise the account-prefixed key space.
2026-07-05 09:31:33 -05:00
Jason van Zyl 2a6cf1c147 feat(ec2): support registered images and snapshots (#1601)
* feat(ec2): support registered images and snapshots

* fix(ec2): scope self-owned image matches
2026-07-05 09:31:08 -05:00
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