mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
264b909e8715296fa4af459f90df6b9da3c0fa19
868
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
264b909e87 |
fix(cloudformation): model AWS::IAM::Policy as an inline policy (Fixes #1531) (#1800)
* fix(cloudformation): model AWS::IAM::Policy as an inline policy (Fixes #1531) AWS::IAM::Policy is an inline policy embedded in the roles/users/groups it names (PutRolePolicy/PutUserPolicy/PutGroupPolicy), not a standalone managed policy. Floci provisioned it via iamService.createPolicy, giving it an account-global name. When two stacks reused the same construct sub-tree — as CDK does, emitting the same auto-generated PolicyName (IamTaskRoleDefaultPolicy<hash>) on different roles — the second stack failed with "Policy ... already exists" and rolled back, even though real AWS scopes an inline policy's name to its owning principal. Provision AWS::IAM::Policy as an inline policy attached to each named principal, and remember the targets so a resource/stack delete detaches it cleanly (an inline policy has no ARN and is removed with its principal). AWS::IAM::ManagedPolicy keeps its standalone managed-policy behaviour and now honours ManagedPolicyName. Two stacks reusing the same inline policy name on different roles both deploy. * fix(cloudformation): address review — log inline-detach failures, safe delimiter, test delete Review feedback on the AWS::IAM::Policy inline-policy handling: - detachInline no longer swallows exceptions silently (AGENTS.md forbids empty catch blocks); it logs at debug like the sibling *Safe helpers. - Inline-policy target principals are joined/split on a newline instead of a comma. IAM friendly names permit commas ([\w+=,.@-]+) but never newlines, so a role/user/group name containing a comma no longer corrupts the target list and orphans the inline policy on delete. - Added a test that deletes the stack and asserts the inline policy is detached (GetRolePolicy -> NoSuchEntity) from a role created outside the stack, so the detach path (deleteInlinePolicySafe/detachInline) is exercised rather than a cascade role delete. * fix(cloudformation): surface IAM attachment failures * fix(cloudformation): roll back IAM resources safely * fix(cloudformation): roll back partial inline policies * fix(cloudformation): detach removed IAM targets * fix(cloudformation): verify IAM policy target updates * fix(cloudformation): preserve inline policy update state * fix(cloudformation): migrate legacy IAM policies * fix(cloudformation): roll back legacy policy migration --------- Co-authored-by: Alexy Grabov <Alexy.Grabov@cyberark.com> |
||
|
|
468e943c83 |
fix(elbv2): move persisted-listener restore out of @PostConstruct (#2015)
* fix(elbv2): move persisted-listener restore out of @PostConstruct ElbV2Service called back into itself through its own CDI client proxy while it was still being constructed. rebuildIndexes(), reached from the @PostConstruct initializeStorage(), called dataPlane.startListener() for every restored listener; ElbV2DataPlane.binding() then called elbV2Service.getLoadBalancer(), and because Arc had not yet registered the instance in the ApplicationScoped context the proxy started another bean creation. That recursed until the process died. Only reproducible after a restart with persistent storage: on a fresh boot the listener map is empty, so rebuildIndexes() never reaches startListener and the callback never happens. rebuildIndexes() now only builds the in-memory indexes. Starting the data plane and the health checks moved to restorePersistedRuntime(), invoked from EmulatorLifecycle after storageFactory.loadAll() alongside the four services that already restore persisted runtime there. With the bean fully constructed before any listener starts, the callback resolves normally. The blast radius was wider than the issue title: the bean is created lazily on first use, so after a restart every ELBv2 operation failed, not just DeleteStack. DescribeLoadBalancers and DescribeTargetGroups both returned 500. Note the symptom changed with #1931: the storage dedupe removed the per-level allocation, so current main raises StackOverflowError where 1.5.32 exhausted the heap and was OOM-killed. Closes #1913 * test(elbv2): cover the enabled and disabled lifecycle restore paths elbv2 was stubbed disabled in setup, so nothing exercised the new EmulatorLifecycle call: dropping it entirely would have left the suite green. Pin both halves of the gate — restore runs after loadAll when elbv2 is enabled, and does not run when it is disabled. Verified the ordering assertion fails with 'Wanted but not invoked' when the lifecycle call is removed. Refs #1913 |
||
|
|
836c162136 |
fix(core): stop unknown-service REST requests falling through to S3 (#1967)
* fix(core): stop unknown-service REST requests falling through to S3 REST requests whose SigV4 credential scope names a service Floci does not implement matched no JAX-RS resource and fell through to S3's path-style wildcard routes, surfacing as misleading NoSuchBucket XML and triggering SDK retry storms. Reject them with UnknownOperationException instead. The guard fires only on positive identification: a parseable SigV4 scope naming a service absent from the catalog. Unsigned, presigned, Bearer/Basic and SigV4a requests are untouched. Also declares the EKS read-only sub-resource lists the emulator does not model (ListAccessEntries, ListAddons, ListIdentityProviderConfigs, ListPodIdentityAssociations) as explicit routes, so they outrank the S3 catch-all and answer with each operation's model-exact empty result key, or ResourceNotFoundException for a missing cluster. Closes #1754 * fix(iam): normalise signing-scope aliases before IAM enforcement S3 accepts requests signed under the s3express scope, but IAM action rules, resource ARNs and condition keys are all keyed by the canonical signing name. An alias therefore resolved to no action, which IamEnforcementFilter treats as ALLOW, so policy-protected S3 operations were reachable without a policy check. Resolve the scope through the catalog before enforcement runs. Only aliases are rewritten: a service whose external key is not itself one of its credential scopes (CloudWatch Logs signs as logs) is left unchanged, as is any scope the catalog does not know. Also documents why SigV4a stays outside the unknown-service guard — its credential omits the region segment, so SigV4CredentialScope does not match it — and pins that with a test, since widening the pattern would silently start rejecting SigV4a traffic. Refs #1754 * fix(iot): declare the iot-jobs-data signing scope so its routes stay reachable The IoT Jobs Data Plane (GetPendingJobExecutions, DescribeJobExecution, StartNextPendingJobExecution, UpdateJobExecution) signs under iot-jobs-data while IotController serves its /things/{thing}/jobs routes. The scope was not in the catalog, so the unknown-service guard rejected requests to routes Floci does implement. The Go, Java and Python SDK compat suites all caught it on GetPendingJobExecutions. Audited the other sibling signing names for the same failure mode: ssmmessages, eks-auth, ecr-public, cognito-identity and aoss have no Floci routes, so rejecting those stays correct. Refs #1754 * fix(iam): scope alias normalisation to an explicit table Deriving the canonical scope from the descriptor's external key was wrong: the external key is a routing key, not an IAM namespace. SES routes under email and Bedrock Runtime under bedrock-runtime while their IAM namespaces are ses: and bedrock:, so ses, sesv2 and bedrock were rewritten onto prefixes AWS never issues. Every action would then resolve to null and enforcement would be skipped for those services — the same bypass the s3express fix closed. Replace the derivation with an explicit alias table holding the one case that genuinely shares a namespace, s3express -> s3, and sweep every scope the catalog declares in the test so any future rewrite has to be deliberate. Refs #1754 * fix(core): make the unknown-service guard configurable and verify scope coverage The guard is only as good as the catalog's scope list, and the iot-jobs-data miss showed the list can be wrong. Two changes so that is recoverable and detectable rather than a hard 404 nobody can work around. Gate the rejection behind floci.protocols.reject-unknown-service-scope, matching the other two abort paths in AwsProtocolClaimFilter, which are both already gated. It defaults to true so #1754 stays fixed out of the box; turning it off restores the previous fall-through for anyone blocked by a scope Floci has not enumerated yet. Add CredentialScopeCoverageTest, which walks botocore's models and fails when Floci routes most of a service's operations without declaring the name that service signs with. Removing iot-jobs-data from the catalog makes it fail with 'iot-jobs-data=2/3 routes served'. Thresholds are conservative because small services share generic templates, so it is a tripwire rather than a proof, and it skips where the gitignored botocore checkout is absent (CI runners). Refs #1754 * fix(iam): resolve the iot-jobs-data signing scope to the iot namespace Admitting iot-jobs-data to the catalog let the IoT Jobs Data Plane reach its routes, but IAM enforcement still saw the raw scope. Its policy actions live under iot: (iot:DescribeJobExecution and peers in the Service Authorization Reference), so the scope belongs in the alias table next to s3express. No behaviour change today: IamActionRegistry carries no iot rules at all, so every IoT request resolves to no action and is allowed through regardless. This makes the mapping correct ahead of those rules existing, rather than leaving a scope that would silently escape them. Refs #1754 |
||
|
|
551df6371b |
fix(storage): dedupe backends by resolved file path (#1931)
* fix(storage): dedupe backends by resolved file path StorageFactory.create() built a new backend on every call, so two components opening the same file (DynamoDbService and DynamoDbStreamService both open dynamodb-tables.json) got independent in-memory stores. On graceful shutdown flushAll() flushed them in registration order and the stale duplicate clobbered the file. Cache backends by resolved file path so repeat create() calls reuse the same backend. Add a regression test reproducing the clobber. * fix(storage): guard lifecycle methods and harden dedup test Synchronize loadAll/flushAll/clearAll/shutdownAll on the same monitor as create(), so the /state/reset and /state/nuke endpoints can't iterate allBackends while a lazily-created service mutates it. Reset the singleton factory in the dedup test setup so it no longer depends on backend startup state or test ordering. |
||
|
|
b0e56a9a45 |
fix: return 4xx client errors instead of 500 for malformed JSON-protocol input (#1926)
* fix: return 4xx client errors instead of 500 for malformed JSON-protocol input
Parse request bodies up front in both JSON dispatchers and return 400
SerializationException for unparseable payloads. Convert input-parsing
failures that previously fell into the catch-all 500 InternalFailure into
their modeled client errors: KMS base64 blob decodes (SerializationException),
Kinesis shard iterators and record data (InvalidArgumentException/
SerializationException), DynamoDB Streams iterator positions
(ValidationException), and EventBridge PutPermission Policy/Condition JSON
(ValidationException; a malformed Policy was previously stored raw and
silently accepted).
* fix: reject trailing content after a valid JSON request body
Jackson's default readTree stops at the first complete JSON value, so a
body like '{} garbage' bypassed the new up-front SerializationException
check and was processed as if the trailing content weren't there. Parse
dispatcher bodies and EventBridge PutPermission Policy/Condition with
FAIL_ON_TRAILING_TOKENS; trailing whitespace remains accepted.
|
||
|
|
1c8b851bea |
fix(cognito): build OIDC URLs from effectiveBaseUrl so FLOCI_HOSTNAME is honored (#1929)
* fix(cognito): build OIDC URLs from effectiveBaseUrl so FLOCI_HOSTNAME is honored CognitoService was wired from the raw emulatorConfig.baseUrl(), so its issuer, JWKS URI, and token/userInfo endpoints ignored FLOCI_HOSTNAME. Every other response-facing service (SQS QueueUrl, SNS, S3 pre-signed URLs, Lambda function URLs) uses effectiveBaseUrl(), which applies the hostname override (and the TLS http->https switch). These Cognito URLs are external-facing — they land in the JWT `iss` claim and the .well-known/openid-configuration document that clients must reach — so in a multi-container / Docker Compose setup with FLOCI_HOSTNAME set they were emitted as http://localhost:4566/... and unreachable, breaking OIDC discovery and JWT validation. Switch the injection to effectiveBaseUrl(). It falls back to baseUrl() when hostname is unset, so the default localhost behavior (and all existing tests) are unchanged. * test(cognito): drive real effectiveBaseUrl so the test reproduces the bug Stub only effectiveBaseUrl()'s inputs (baseUrl, hostname, tls) and call the real default method, instead of stubbing effectiveBaseUrl() itself. The previous version asserted little more than "Cognito calls the getter it was told to" — it stubbed away the very override logic under test and would not fail against the old raw-baseUrl() wiring. Now the localhost->floci host swap actually runs, so the test fails on a revert. Also add a no-hostname case pinning the baseUrl() fallback. * test(cognito): drop dedicated effectiveBaseUrl wiring test On review of the repo's testing patterns this test isn't idiomatic and adds little. Every peer service that reads effectiveBaseUrl() (SQS, SNS, S3, Lambda, ECS, Pipes, IoT, SSM) either stubs it to a literal or is constructed with a literal baseUrl — none has a dedicated test proving the FLOCI_HOSTNAME override reaches its response URLs; the accessor choice is simply trusted. The removed test was also the only thenCallRealMethod on effectiveBaseUrl in the suite. The existing issuerUrlForPinnedPoolResolvesAsBaseUrlSlashPoolId already covers the getIssuer URL shape, and effectiveBaseUrl()'s own override logic is exercised via TlsConfigSource tests. The fix is a one-token consistency change aligning Cognito with its peers. |
||
|
|
9308687f5a |
fix(s3): preserve literal question marks in copy source keys (#1924)
CopyObject and UploadPartCopy decoded the entire x-amz-copy-source header before splitting bucket, key, and query. A key containing a literal '?' (sent as %3F or raw) was then truncated at the first '?', so the copy resolved the wrong key and returned NoSuchKey. Split bucket/key/query on the raw header and decode each component separately. A trailing '?...' is only treated as a query string when it contains versionId=; otherwise the '?' is kept as part of the key. The same parsing is used by both CopyObject and UploadPartCopy. Adds a regression test covering encoded (%3F) and raw '?' copy sources. Closes #1713 |
||
|
|
526a62317f |
fix: return 400 MalformedXML for unparseable PutObjectRetention RetainUntilDate (#1631)
PutObjectRetention crashed with an uncaught DateTimeParseException when RetainUntilDate could not be parsed, leaking as an HTTP 500 HTML page. Wrap the Instant.parse call and throw an AwsException mapped to HTTP 400 MalformedXML, matching real AWS S3 behavior. Fixes #1614 |
||
|
|
ac8a3d7c82 |
feat(sfn): support http invoke step (#1503)
* feat(1047): Http invocation support * feat(1047): add tests for http invoke * fix(1047): remove irrelevant headers * fix(1047): fix assertion * chore(sfn): merge main * chore(sfn): add statusText * chore(sfn): add correct timeout handling and improve http server tests * chore(sfn): adress pr comments arount url encoded body handling * chore(sfn): only allow https by default * chore(sfn): better error message |
||
|
|
2a9ab4598f |
fix(dynamodb): throw ValidationException when list_append operand is not a list type (#1702)
* fix(dynamodb): throw ValidationException when list_append operand is not a list type list_append silently no-oped when either operand resolved to a non-list attribute (e.g. NULL type), returning HTTP 200 with the item unchanged. AWS returns a 400 ValidationException in this case. * test(dynamodb): add integration test for list_append against missing attribute |
||
|
|
b245632a2e |
feat(stepfunctions): implement States.JsonMerge intrinsic (#1662)
* feat(stepfunctions): implement States.JsonMerge intrinsic The DPS provisioning state machine uses States.JsonMerge, which AslExecutor rejected with "Unsupported intrinsic function: States.JsonMerge". Implement the shallow merge (second object's top-level fields win on conflict); reject the deep-merge form (third argument true) and non-object arguments, as AWS does. Also resolve boolean/null literal intrinsic arguments so the third argument evaluates correctly. Covered by AslExecutorJsonMergeTest. * fix(stepfunctions): reject a non-boolean States.JsonMerge third argument The third (deep) argument was read with JsonNode.asBoolean(), which silently coerces null/number/string/object nodes to false, so States.JsonMerge($.a,$.b,$.x) with a non-boolean $.x quietly performed a shallow merge instead of failing. Validate that the resolved third argument is a boolean and raise States.Runtime otherwise. Covered by AslExecutorJsonMergeTest.nonBooleanThirdArgumentRejected. * fix(stepfunctions): validate JsonMerge argument types before the deep-merge flag AWS validates the argument types of States.JsonMerge before evaluating the deep-merge flag, so two non-objects passed with true should report "requires two JSON objects" rather than "shallow merge only". Reorder the object-type check ahead of the deep-flag rejection and add a precedence test. * test(stepfunctions): adapt JsonMerge test to main's AslExecutor constructor main's AslExecutor constructor now takes EcsService and EcsJsonHandler; pass the two new mocks. Also generalize a comment that named a specific downstream system. * docs: regenerate action tables * fix(stepfunctions): thread context into States.JsonMerge intrinsic args The intrinsic pipeline gained a context argument on main (resolveIntrinsicArg / evaluateIntrinsic now take three parameters). Thread the surrounding case's root/context through the three States.JsonMerge argument resolutions so the branch compiles against current main. * fix: align JsonMerge intrinsic failures * fix(athena): harden compatibility query polling |
||
|
|
024d74e5c4 |
feat(cloudtrail): in-process CloudTrail with S3 data event emission (#1460)
* feat(cloudtrail): in-process CloudTrail with S3 data event emission
New service supporting CreateTrail / DescribeTrails / DeleteTrail /
UpdateTrail / PutEventSelectors / GetEventSelectors / StartLogging /
StopLogging / GetTrailStatus.
S3 ops (PutObject / GetObject / HeadObject / DeleteObject / ListObjects
/ GetObjectAcl) emit CloudTrail data events through a per-trail buffer.
The CloudTrailLogWriter scheduler flushes pending records as gzipped
JSON envelopes into the destination bucket at AWS-shaped key paths
(AWSLogs/<account>/CloudTrail/<region>/yyyy/MM/dd/<file>.json.gz) on
a configurable cadence (default 60s).
IAM-enforcement denials emit matching AccessDenied records by hooking
IamEnforcementFilter. IamActionRegistry now distinguishes
s3:GetObjectAcl / PutObjectAcl / {Get|Put|Delete}ObjectTagging from
their base ops via ?acl / ?tagging query parameters so the right
event names land in the trail.
Seeded AWSCloudTrail_FullAccess / _ReadOnlyAccess managed policies.
* fix(cloudtrail): return LatestDeliveryTime in GetTrailStatus after StartLogging
The sdk-test-java compatibility test asserts latestDeliveryTime() is
non-null immediately after startLogging. Seed it with the startLoggingTime
so the field is always present once logging has been started.
* fix(cloudtrail): emit SnsTopicARN alongside SnsTopicName in CreateTrail/UpdateTrail responses
Accept both SnsTopicARN and SnsTopicName on input (SnsTopicARN takes
precedence). Emit both fields on output so clients reading the current
field name (SnsTopicARN) get a non-null value.
* fix(cloudtrail): wildcard S3 ARN matching, trail name validation, LookupEvents
- matchesS3DataResourceArn: handle bare "arn:aws:s3", "arn:aws:s3:::*", and
"arn:aws:s3:::*/*" wildcard forms so trails configured via the AWS Console
"capture everything" selector actually record events (previously fell through
silently). Unit tests added to CloudTrailSelectorMatchingTest.
- createTrail: enforce AWS trail name rules (3–128 chars, start/end with letter
or digit, only letters/numbers/./_/-). Integration tests in new
CloudTrailNameValidationTest.
- CloudTrailJsonHandler: add LookupEvents stub returning an empty Events array,
matching upstream's addition in #1603.
* fix(cloudtrail): log empty catches, key selectors/logging by trail home region
- CloudTrailLogWriter.stop(): log at WARN instead of silently swallowing the
final-flush exception (AGENTS.md: never leave a catch block empty).
- CloudTrailService.putEventSelectors / getEventSelectors / startLogging /
stopLogging / getTrailStatus: use trail.homeRegion() as the storage key
instead of the request region. Previously a cross-region call (e.g. accessing
a trail by ARN from a different-region endpoint) stored selectors and logging
state in the wrong region's map, so trailsMatching() found an empty selector
list and logging never fired.
- S3Controller.emitCloudTrailEvent / IamEnforcementFilter.emitS3DenialIfApplicable:
replace empty inner catch blocks with LOG.tracev() so unexpected failures
during request-context extraction surface at trace level.
* fix(iam): distinguish bucket-level vs object-level ?acl / ?tagging IAM actions
resolveS3SubResourceAction was always mapping ?acl and ?tagging to object-level
actions (s3:PutObjectAcl, s3:GetObjectAcl, etc.) regardless of path depth.
A PUT /{bucket}?acl request requires s3:PutBucketAcl, not s3:PutObjectAcl —
callers with the correct bucket-level permission were incorrectly denied.
Fix: inspect the URL path after stripping the leading slash. When there is no
slash (or the path ends with one), the target is a bucket; otherwise it is an
object. Applies to all six variants: GetBucketAcl, PutBucketAcl,
GetBucketTagging, PutBucketTagging, DeleteBucketTagging (and their object
counterparts).
* fix(cloudtrail): re-queue records on flush failure instead of dropping them
drainPendingRecords atomically dequeues all records before the S3 write.
If serializeAndGzip or s3Service.putObject threw, those records were gone —
permanently lost before the re-throw reached flushAll.
Fix: wrap the serialize+write block in a try-catch that calls requeueRecords
before rethrowing. Records are added back to the tail of the queue and will be
retried on the next flush cycle. The new CloudTrailService.requeueRecords helper
also makes the re-queue path unit-testable independently of flushTrail.
* fix(s3): emit GetObjectAcl error record under correct event name
getObjectAcl was called inside the outer GET-object try block. On any
AwsException (NoSuchKey, AccessDenied, etc.) the catch at the bottom fired
and emitted a GetObject error record. CloudTrail consumers auditing ACL
errors would see the wrong event name.
Wrap the acl branch in its own try-catch that emits GetObjectAcl on both
success and failure paths, mirroring the pattern used by the other hooked ops.
* ci: retrigger
* fix(test): pass CloudTrailService and CurrentVertxRequest to IamEnforcementFilter constructor
* fix(cloudtrail): persist trail state via StorageFactory instead of volatile in-memory maps
* fix(cloudtrail): address review feedback on region, name lookup, and ACL detection
- S3Controller: use request region (from credential scope) instead of
getDefaultRegion() for CloudTrail event emission, matching the IAM
denial hook behaviour so allowed and denied calls land in the same trail.
- CloudTrailService.findTrail: name lookup now uses regionKey(region, name)
directly; ARNs still do a cross-region scan. Prevents two same-name
single-region trails from resolving ambiguously by map iteration order.
- TrailKey: add eventRegion field so multi-region trail events are written
to the correct S3 delivery path (CloudTrail/<eventRegion>/) rather than
always the trail home region. drainPendingRecords/requeueRecords now take
a TrailKey to carry all three dimensions.
- IamActionRegistry: fix isBucketLevel — trailing slash is a valid S3 key
character, so /bucket/folder/?acl is an object ACL request. Replaced the
endsWith("/") check with an index-based test. Add IamActionRegistryTest
cases for the folder/ regression.
* docs(cloudtrail): sync action table order with make docs-sync
|
||
|
|
e0b7b3f8ee | fix(eks): register FargateProfileStatus for reflection (#1876) | ||
|
|
095e167bae |
Nodegroups eks fargate eks (#1523)
* feat(eks): add nodegroups and fargate profiles * docs: sync generated action tables |
||
|
|
43a80381ee |
fix(s3): honor ACL headers and explicit grants (#1768)
* fix(s3): honor ACL headers and explicit grants Closes #1766 #1767 PutObjectAcl/PutBucketAcl ignored x-amz-acl and x-amz-grant-* headers, storing the raw (often empty) request body as the ACL verbatim. AWS SDKs send canned ACLs to these endpoints as a header with an empty body, so a canned-ACL update corrupted the stored ACL and the next GetObjectAcl failed client-side XML parsing with "Premature end of file". PutObject/CopyObject also silently dropped x-amz-grant-* (explicit ACL grant) headers - no error, just a missing grant. Add resolveObjectAclXml() to parse canned ACLs and explicit grant headers (uri=/id=/emailAddress= tokens, comma-separated per grantee header) into proper Grant XML, and wire it into all four call sites: PutObject, CopyObject, PutObjectAcl, PutBucketAcl. emailAddress grantees return 501 (no account directory to resolve them against). Add regression coverage in S3AclIntegrationTest for both the header-with-empty-body case and explicit multi-grantee headers. * fix(s3): Fixing review comments --------- Co-authored-by: Krishnan Mahadevan <kmahadevan-bidgely@users.noreply.github.com> |
||
|
|
4a109b2f6c |
fix(cloudformation): carry PackageType through SAM Function expansion (#1772)
* fix(cloudformation): carry PackageType through SAM Function expansion
expandServerlessFunction/createLambdaFunction copied FunctionName, Handler,
and Runtime from AWS::Serverless::Function onto the expanded
AWS::Lambda::Function, but never PackageType. CloudFormationResourceProvisioner's
buildLambdaDesiredState defaults a missing PackageType to "Zip"
(resolveOrDefault(props, "PackageType", engine, "Zip")), which then also
forces Runtime/Handler defaults (nodejs18.x / index.handler) onto a
function that declared neither. Net effect: a SAM function declared with
PackageType: Image and an ImageUri silently deployed as a broken Zip
function running the wrong runtime instead of the real container image —
Code.ImageUri was preserved by buildLambdaCode, but nothing on the
resource said to actually use it as an image.
Found by deploying a real container-image SAM template end-to-end against
a build with #1758+#1759 applied: the function created successfully and
the stack reported CREATE_COMPLETE, but invoking it pulled
public.ecr.aws/lambda/nodejs:18 and failed with
Runtime.ImportModuleError ("Cannot find module 'index'") instead of
running the pushed image.
Adds a one-line copyIfPresent(properties, "PackageType", lambdaProps) fix,
a SamTransformProcessorTest unit test asserting the transform output
carries PackageType/ImageUri through with no synthesized Handler/Runtime,
and a CloudFormationIntegrationTest asserting the full create-stack ->
GetFunction round trip reports PackageType: Image.
* fix(cloudformation): carry ImageConfig through SAM Function expansion
Same class of omission as PackageType: CloudFormationResourceProvisioner
already reads ImageConfig off AWS::Lambda::Function (provisionLambda's
putResolvedMapIfPresent(configRequest, props, "ImageConfig", ...)), but
SamTransformProcessor.createLambdaFunction never copied it from the SAM
resource's Properties. A PackageType: Image SAM function combined with an
ImageConfig block (EntryPoint/Command/WorkingDirectory container overrides)
silently lost that configuration on the deployed function.
ImageConfig's SAM shape is identical to raw CFN's, so a plain
copyIfPresent is sufficient (no case conversion needed, unlike some other
SAM->CFN property mappings in this file).
Adds a unit test asserting the expanded resource carries ImageConfig
through, and an integration test asserting the full CreateStack ->
GetFunction round trip reports it under Configuration.ImageConfigResponse.
Addresses review feedback on #1772.
|
||
|
|
fe49bee41e |
fix(s3): fail fast on unwritable data root instead of opaque 500s (#1868)
When the persistent path is not writable (read-only or root-owned bind mounts), S3Service's constructor failed lazily and every S3 request surfaced as an opaque plain-text 500 that REST-XML SDK parsers cannot read. - validate the persistent path at boot and refuse to start with an actionable error when any enabled service uses non-memory storage - add class-scoped exception mappers so unhandled failures on S3 and S3-Control routes render the S3 InternalError XML contract instead of Quarkus's plain-text error page - warn loudly from the container entrypoint when the state dir is not writable by the runtime user Fixes #1664 |
||
|
|
1ba15f0ce7 |
fix(rds): return DBSubnetGroupNotFoundFault for missing DescribeDBSubnetGroups name (#1870)
DescribeDBSubnetGroups with a missing DBSubnetGroupName returned HTTP 200 and an empty list; reuse resolveDbSubnetGroupView so AWS clients get a 404 fault instead. |
||
|
|
a7d33ba885 |
feat(cloudformation): Parse secrets in ContainerDefinitions (#1874)
* feat(cloudformation): Parse secrets in ContainerDefinitions * test(cloudformation): cover TaskDefinition creation with secrets |
||
|
|
eae039fbd0 |
fix(lifecycle): tear down process-bound containers on shutdown (#1869)
Containers whose lifetime is bound to the emulator process (Lambda warm pool, ECS tasks, EC2 instances, in-flight Batch and CodeBuild jobs) were cleaned up ad hoc via @PreDestroy, which runs after the ShutdownEvent observers when the storage flush schedulers are already stopped — so containers could leak and state changes made during stop were lost. Introduce a ContainerTeardown contract implemented by each runner and invoke every implementation from EmulatorLifecycle.onStop before StorageFactory.shutdownAll(), making teardown deterministic and keeping its state changes in the final flush. Implementations stay idempotent, with @PreDestroy retained as a fallback. |
||
|
|
aa77d4ce46 | fix(elbv2): expose target health reason parity (#1743) | ||
|
|
e49bc432bd |
fix(scheduler): forward MessageAttributes in universal sns:publish target (#1706)
* fix(events): SNS universal target message attributes * fix(scheduler): handle Binary MessageAttributes in universal sns:publish target |
||
|
|
05302bc63b |
fix(iam): pass S3 list condition context to IAM enforcement (#1748)
IAM policy evaluation already supported condition keys, but request-time enforcement did not provide S3 list request parameters to the evaluator. As a result, assumed-role session policies that allowed s3:ListBucket only for a matching s3:prefix were denied because the condition context was empty. Add an application-scoped IamConditionContextResolver and have IamEnforcementFilter pass resolved condition context into IamPolicyEvaluator. The resolver currently maps S3 ListBucket query parameters to s3:prefix, s3:delimiter, and s3:max-keys, keeping action-specific condition extraction out of the filter. Add regression coverage for prefix-restricted STS session policies through direct integration tests and the Java SDK compatibility suite. The SDK test also uses a trust policy matching the root/test principal that performs AssumeRole when IAM enforcement is enabled. Tests: - ./mvnw test -Dtest=IamConditionContextResolverTest,IamEnforcementFilterTest,IamEnforcementIntegrationTest,StsSessionPolicyS3EnforcementIntegrationTest - compatibility-tests/sdk-test-java: mvn -q -DskipTests test-compile |
||
|
|
f9360cbf86 |
fix(ec2): reject duplicate key pair names in ImportKeyPair (#1848)
ImportKeyPair accepted any KeyName even when a key pair with the same name already existed in the region, so DescribeKeyPairs could list multiple entries with the same name (e.g. after repeated terraform apply runs). Real AWS rejects this with InvalidKeyPair.Duplicate. Apply the same duplicate-name check that CreateKeyPair already performs, scoped to the region. Fixes #1845 |
||
|
|
28252763f5 |
feat: emit jti/origin_jti and support RevokeToken (#1705)
* feat: emit jti/origin_jti and support RevokeToken * fix(cognito): authenticate RevokeToken caller before revocation-config check Address PR review feedback on the jti/origin_jti + RevokeToken change: - RevokeToken now validates the client secret before the EnableTokenRevocation check, so a confidential client with revocation disabled returns NotAuthorizedException (not UnsupportedOperationException) for a wrong/missing secret, matching AWS's identity-first ordering and avoiding leaking revocation state to unauthenticated callers. - OriginJtiIntegrationTest guards the shared ordered-test state via requireSetup()/requireInitialAuthState() so a setup or initial-auth failure reports a clear cause instead of misleading downstream assertions, and adds a regression test for the auth-ordering fix. * fix(cognito): revoke access tokens by origin_jti and use UnauthorizedException Address review feedback on PR #1705: - Check origin_jti (not just jti) when validating access tokens against the revocation store, so RevokeToken actually kills issued access tokens for GetUser, ChangePassword, UpdateUserAttributes and DeleteUserAttributes. - Change RevokeToken error from NotAuthorizedException to UnauthorizedException to match the declared API model. - Remove unused three-arg buildRefreshToken overload. - Add Order(12) test proving GetUser fails after RevokeToken. |
||
|
|
001e530aca |
feat: Implement Cognito GlobalSignOut (#1701)
* feat: Implement Cognito GlobalSignOut * fix(cognito): validate user existence and jti in GlobalSignOut Address PR #1701 review: - Add adminGetUser existence check before revoking tokens so a crafted token referencing a nonexistent pool/user returns UserNotFoundException/ ResourceNotFoundException instead of silently writing revocation records and returning 200, matching AdminUserGlobalSignOut and getUser. - Include jti in the invalid-token guard so legacy tokens without a jti claim cannot be used as a sign-out credential, consistent with getUser. - Cover the nonexistent-user path with an integration test. * fix(cognito): error reporting * fix: map ResourceNotFoundException -> NotAuthorizedException |
||
|
|
742bb8cf03 |
fix(s3): return default SSE-S3 from GetBucketEncryption instead of 404 (#1838)
* fix(s3): return default SSE-S3 from GetBucketEncryption instead of 404 Real S3 no longer 404s GetBucketEncryption for a bucket with no explicit config: since 2023-01-05 every bucket has SSE-S3 (AES256) default encryption, so GetBucketEncryption returns that config rather than ServerSideEncryptionConfigurationNotFoundError. https://docs.aws.amazon.com/AmazonS3/latest/userguide/default-bucket-encryption.html "Amazon S3 now applies server-side encryption with Amazon S3 managed keys (SSE-S3) as the base level of encryption for every bucket in Amazon S3. Starting January 5, 2023, all new object uploads to Amazon S3 are automatically encrypted." Floci still emulated the pre-2023 404-when-unset behavior. Some software relies on the new behavior, such as AWS's AWS Controllers for K8s s3-controller: its Bucket read-back catches the NotFound code but does not return, then dereferences ServerSideEncryptionConfiguration.Rules on a nil response (nil-pointer panic that loops the controller). ACK code for reference: https://github.com/aws-controllers-k8s/s3-controller/blob/v1.6.0/pkg/resource/bucket/hook.go Return the AWS default SSE-S3 config when none is set; an explicit PutBucketEncryption config is still echoed back, and a missing bucket still 404s NoSuchBucket. Mirrors GetBucketRequestPayment's existing default. Closes #1836 * test(s3): cover GetBucketEncryption default after DeleteBucketEncryption Greptile flagged the delete-then-get path was uncovered: after DeleteBucketEncryption nulls the stored config, GetBucketEncryption must fall back to the default SSE-S3 (AES256) rather than the prior KMS config or a 404. Adds an ordered case exercising the ?encryption DELETE handler plus the null-after-delete branch. |
||
|
|
2d250ccf3c |
fix(s3): handle DeleteBucketReplication instead of deleting the whole bucket (#1837)
DELETE /{bucket}?replication fell through the sub-resource switch (which handled
tagging/website/policy/cors/lifecycle/encryption/publicAccessBlock/ownershipControls
but not replication) to the unqualified DeleteBucket, silently destroying the
entire bucket and returning 204.
Real S3 DeleteBucketReplication removes only the replication configuration and
returns 204; a sub-resource-qualified DELETE never deletes the bucket:
https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketReplication.html
Floci does not model replication, so DeleteBucketReplication is a no-op 204 --
handled explicitly so it cannot reach the bucket-delete fall-through.
Closes #1835
|
||
|
|
3ec4dc65f2 |
feat(stepfunctions): support JSONata workflow variables (Assign) (#1824)
* feat(stepfunctions): support JSONata workflow variables (Assign) Add support for execution-scoped workflow variables in JSONata state machines. States may declare an `Assign` field whose values are evaluated as JSONata and stored as variables that later states reference as top-level `$name` bindings. An execution-scoped `variables` object is threaded through every state executor and mutated in place, so assignments persist across states. Parallel branches and Map iterations each receive an isolated copy, so assignments inside them do not leak back to the parent scope, matching AWS. Within a state, `Assign` is evaluated before `Output`, so a state's own `Output` (and all later states) observe the newly assigned variables, matching AWS evaluation order. Assign is currently supported for JSONata states only; JSONPath-mode Assign is left as a follow-up. Closes #1507 Co-authored-by: Juri Duval <27741935+Mulgish@users.noreply.github.com> * fix(stepfunctions): resolve JSONata Assign against the state-entry scope Variable references in a state, including the state's own Output, must resolve against the values the variables held on state entry. Assign and Output are now both evaluated against the pre-assignment scope, and the new values are committed afterwards, so they first become visible to the next state. Verified against a recorded AWS execution (localstack's AWS-validated BASE_EVALUATION_ORDER_PASS_STATE snapshot): a state that assigns answer="<omitted>" while reading $answer in its own output still emits the state-entry value 42. Workflow variables are also bound alongside $states rather than inside it, since AWS reserves $states for input/result/errorOutput/context. Tests: - assignedVariablesAreNotVisibleUntilTheNextState replaces assignedVariableVisibleToSameStateOutput, which asserted the inverse. It follows the evaluation-order example from the AWS docs: from $x=3, $a=6, the block {"x": "{% $a %}", "nextX": "{% $x %}"} ends with $x=6 and $nextX=3 while the assigning state's Output still emits 3. - variablesAssignedInsideMapDoNotLeakToParentScope now uses a distinct inner variable name, mirroring AWS's own BASE_SCOPE_MAP fixture; AWS rejects an inner scope reusing an outer-scope variable name. * feat(stepfunctions): apply JSONata Assign in Choice rules, Wait states and Catch blocks Assign was only committed via applyJsonataOutput, which Choice and Wait never call, so an Assign on either state was silently dropped and Catch blocks could not assign at all. AWS supports Assign on Pass, Task, Map, Parallel, Choice and Wait, plus inside Choice rules and Catch fields. - Choice: a matched rule applies its own Assign and Output; the state-level ones apply only on the Default path. - Wait: applies Assign and Output. - Catch: applies Assign and Output with $states.errorOutput bound, into the scope the catching state lives in. - Bind $states after the workflow variables so a variable named "states" cannot clobber the reserved binding. Assign, Choice-rule and Catch blocks all keep the AWS evaluation rule already in place for states: every expression is evaluated against the values held on state entry, and the new values are committed only afterwards. --------- Co-authored-by: Juri Duval <27741935+Mulgish@users.noreply.github.com> |
||
|
|
6856c7f1e6 |
refactor(cloudformation): extract a per-service provisioner registry, migrate SQS (#1825)
First slice of decomposing CloudFormationResourceProvisioner (the repo's largest
class: ~30 injected services and 75 resource types in two switches).
Introduce the scaffolding for per-service provisioners:
- CfnResourceProvisioner: a provision/delete interface for one service's types.
- ProvisionContext: the {engine, region, accountId, stackName} handlers draw from,
with resolveOptional/generatePhysicalName lifted verbatim from the monolith.
- CloudFormationResourceRegistry: a CDI-collected resource-type -> provisioner map,
with a public factory constructor for tests; duplicate registration throws.
CloudFormationResourceProvisioner now consults the registry before its switch and
falls through for unmigrated types, so the two coexist during the migration. SQS is
the first extraction: SqsCfnProvisioner (injects only SqsService) owns Queue and
QueuePolicy; its switch cases and provisionXxx methods are removed. The registry is
added to the constructor once so later slices do not reshuffle positional args.
SqsCfnProvisionerTest exercises the provisioner with a single mocked service, the
payoff versus the ~30 mocks the monolith requires. Behavior is unchanged: the full
CloudFormation integration suite (174 tests) stays green.
|
||
|
|
eb2fa9c25f |
fix(iam): default UserName to the calling access key's owner (#1801)
GetUser, ListAccessKeys and DeleteAccessKey treat UserName as optional: the IAM model documents it as defaulting to the user making the request. Floci ignored the caller and passed the missing name straight through, so GetUser fell back to a "root" user that is never seeded and the access-key actions passed null. Every one of them ended in NoSuchEntity. Resolve UserName from the access key that signed the request, falling back to NoSuchEntity (the model's code for these operations, 404, senderFault) when the key maps to no stored user. Those errors were also rendered wrong. Query handlers that catch AwsException build their own error XML, but the ones that don't reach AwsExceptionMapper, which emits JSON — a JSON error body on the XML wire, which SDK parsers fail on before they can surface anything useful. AwsQueryController now renders AwsException as the Query error contract, preserving the declared code and status, and maps any other handler exception to InternalFailure rather than letting Quarkus' JSON error page escape. CloudWatch Metrics is the handler that renders no error XML of its own, so it is the regression test for the pass-through: SetAlarmState on a missing alarm must stay 404 ResourceNotFound and not collapse into a 500. Closes #1753 |
||
|
|
ad47b39800 |
fix(lambda): register EventSourceMapping nested types for native-image reflection (#1826)
EventSourceMapping.DestinationConfig and its nested OnFailure are reachable from Lambda's persisted event-source-mapping storage but carried no @RegisterForReflection (the annotation on the enclosing class does not cover nested static classes). In native-image mode this breaks deserialization of a mapping's failure destination on restart. Annotate both nested classes with @RegisterForReflection, matching the existing convention (IotPolicy.PolicyVersion, LambdaUrlConfig.Cors). Also add @JsonIgnoreProperties(ignoreUnknown = true) — as the enclosing class already has — so the nested wire shapes tolerate future AWS field additions rather than failing deserialization. PersistedModelReflectionTest, the classpath-scan guard that flagged this, now passes. Refs #1629, #1781 |
||
|
|
9b63b31530 |
fix(tls): add host.docker.internal to self-signed cert SANs (#1821)
Lambda containers reach Floci via host.docker.internal when Floci runs on the host instead of in a container, but the cert never included it as a SAN, failing TLS verification. |
||
|
|
fe2008848f |
fix(rds): preserve network placement metadata (#1735)
* fix(rds): honor request region for subnet placement * fix(rds): persist DB instance VPC security groups * docs: sync service action tables * fix(rds): tidy region-aware query dispatch |
||
|
|
10f799a2b7 |
feat(ses): implement Contact CRUD for SES v2 (#1723)
* feat(ses): implement Contact CRUD for SES v2
Add the SES v2 Contact APIs under /v2/email/contact-lists/{name}/contacts:
CreateContact, GetContact, ListContacts (POST .../contacts/list),
UpdateContact, DeleteContact. Contacts carry per-topic subscription
preferences, an unsubscribe-all flag, and free-form attributes;
TopicDefaultPreferences is derived at read time from the list's topics.
Behaviour is verified against real AWS: validation order (Smithy enum ->
EmailAddress format -> list existence -> topic existence), AlreadyExists /
NotFound / invalid-topic / invalid-email error shapes, and the UpdateContact
semantics (TopicPreferences merge by topic name; AttributesData and
UnsubscribeAll replaced). Covered by a RestAssured integration test and an
AWS Java SDK v2 compatibility test.
* refactor(ses): resolve contact list once for reads and delete under lock
Address review consistency findings on the Contact CRUD read/delete paths:
- getContact/listContacts returned only the contact(s), so the controller
fetched the ContactList a second time to render TopicDefaultPreferences.
Between the two calls a concurrent delete could turn a successful read into a
misleading "List not found". The service now returns the resolved list
alongside the contact(s) (ContactWithList / ContactsWithList), so the read is
a single, consistent lookup.
- deleteContact re-checked list existence before acquiring contactMutationLock,
unlike createContact/updateContact which re-check inside it. Move the
getContactList check inside the lock so a concurrent deleteContactList
surfaces "list not found" rather than "contact not found".
|
||
|
|
48f310b63f |
fix(s3): omit checksum headers from GetObject/HeadObject unless x-amz-checksum-mode: ENABLED (#1633)
* fix(s3): omit checksum headers from GetObject/HeadObject unless x-amz-checksum-mode: ENABLED Real AWS only returns x-amz-checksum-* headers on GetObject and HeadObject responses when the client sends x-amz-checksum-mode: ENABLED. Without that header, returning the checksum causes the PHP AWS SDK to attempt checksum validation on a non-seekable streaming response body, throwing "Stream is not seekable" and making fopen fail. Closes #1632 * refactor(s3): drop dead appendObjectHeaders overloads, dedupe test @Order Addresses Greptile review on PR #1633: - Remove the now-unreachable 2-arg and 3-arg appendObjectHeaders overloads. All real callers pass includeChecksum explicitly to the 4-arg version, so the 3-arg overload's hard-coded `true` was a footgun that could silently re-emit checksum headers. Also drops the now-orphaned ResponseHeaderOverrides.NONE. - Move getObjectWithChecksumModeReturnsChecksum / headObjectWithChecksumMode... to the end of the 5-22 test block with unique @Order(23)/@Order(24), so they no longer share @Order(5)/@Order(7) with getObject/headObject. All 117 S3IntegrationTest cases pass. * fix(s3): include checksum in empty-object suffix-range response when requested The empty-object suffix-range path returns a full 200 via fullObjectResponse instead of a 206, so it must honor x-amz-checksum-mode: ENABLED like any other full-object response. It previously hardcoded includeChecksum=false, omitting the checksum even when the client asked for it. Also extends the existing suffix-range test to assert the checksum is omitted without the header, and adds a new test covering the x-amz-checksum-mode: ENABLED case. * fix(s3): resolve rebase-onto-main test conflicts for checksum-mode gate Sends x-amz-checksum-mode: ENABLED on the GetObject verification calls that require checksum headers in the response (copyObject, copyObjectWithoutChecksumOverride, copyObjectPreservesNonDefaultChecksum), consistent with the behavioral fix in this branch. Adds getObjectWithChecksumModeReturnsChecksum and headObjectWithChecksumModeReturnsChecksum as self-contained tests with unique, non-colliding @Order values. --------- Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com> |
||
|
|
cd7370c730 |
feat(kms): support KeyId filter on ListAliases (#1651)
* feat(kms): support KeyId filter on ListAliases * feat(kms): avoid null key ids in handler |
||
|
|
af0ec51f98 |
fix(lambda): return event source mapping failure config (#1629)
Signed-off-by: Vinod Kumar <codingkiddo@gmail.com> |
||
|
|
a3e8bf5a8b | fix: Support S3 auth enforcement (#1689) | ||
|
|
8590ffec34 |
fix(scheduler): honor target EventBridgeParameters DetailType/Source (#1489)
* fix(scheduler): honor target EventBridgeParameters DetailType/Source * chore: update after review * chore: update after greptile feedbacks * chore(scheduler): add missing validation for eventbridge target * chore: add missing test annotation * chore: sync docs |
||
|
|
f915622e36 |
feat(appsync): Phase 5 — Management API Coverage + AWS Behavior Alignment + Async Schema Creation (#1590)
* test(appsync): strengthen existing integration error tests with __type and message assertions
All 30 existing error assertions (400/404) previously checked only the HTTP
status code. Each now also verifies the AWS error body shape:
{"__type":"<ExceptionClass>","message":"<...>"}
This locks in the __type field that the AWS SDK v2 uses to instantiate the
typed exception (NotFoundException, BadRequestException, etc.) and guards
against accidental changes to error codes and messages.
* test(appsync): add 409 conflict and 429 limit tests
Add 7 new integration tests covering previously untested error paths:
ConflictException (409):
- createDataSourceDuplicateReturns409
- createResolverDuplicateReturns409
- createTypeDuplicateReturns409
- createDomainNameDuplicateReturns409
- createChannelNamespaceDuplicateReturns409
- associateApiDuplicateReturns409 (domain already associated)
LimitExceededException (429):
- createApiKeyExceedsLimitReturns429 (3rd key exceeds max 2 per API)
All tests are self-contained: create resources, assert the error, then
clean up. Each asserts statusCode + __type + message substring.
* test(appsync): add 404 tests for update/delete and cross-resource create
Add 11 new integration tests covering previously untested 404 paths:
Update/delete of non-existent resources (8):
- updateResolverNonExistentReturns404
- deleteResolverNonExistentReturns404
- updateFunctionNonExistentReturns404
- deleteFunctionNonExistentReturns404
- updateApiKeyNonExistentReturns404
- deleteApiKeyNonExistentReturns404
- updateDomainNameNonExistentReturns404
- updateChannelNamespaceNonExistentReturns404
Cross-resource 404 on create (3) — missing referenced resource:
- createResolverMissingDataSourceReturns404
- createFunctionMissingDataSourceReturns404
- associateApiMissingDomainReturns404
Each asserts statusCode + __type=NotFoundException + message substring.
* test(appsync): add pagination, edge case, and updateChannelNamespace tests
Add 7 new integration tests:
Pagination for previously untested list operations (3):
- listDomainNamesWithMaxResults
- listChannelNamespacesWithMaxResults
- listSourceApiAssociationsWithMaxResults
Each creates >=2 items, verifies page size + nextToken, follows token,
and cleans up.
Pagination edge cases (3):
- listWithMaxResultsZero (empty page + nextToken present)
- listWithNegativeMaxResultsReturns400
- listWithInvalidNextTokenNonApiReturns400 (data sources path)
Update channel namespace (1):
- updateChannelNamespace (verify description field change)
* test(appsync): upgrade SDK error tests to typed exceptions
Upgrade 4 existing SDK error tests from the generic AppSyncException to
the typed exception classes that the AWS SDK v2 maps from the __type
response field:
- getNonExistentApiThrowsException -> NotFoundException
- getNonExistentDataSourceThrowsException -> NotFoundException
- getNonExistentTypeThrowsException -> NotFoundException
- startSchemaCreation_invalidSchema -> BadRequestException
Each now also asserts hasMessageContaining with the expected message
substring. This aligns AppSyncTest with the repo convention used by
ApiGatewayV2ManagementTest, SchedulerTest, and ElbV2Test.
Also strengthen two existing update tests with field assertions:
- updateChannelNamespace: now sets codeHandlers and verifies the response
- updateDomainName: now asserts description field equals updated value
* fix: correct environment variables API path case for SDK compatibility
The AppSync controller used lowercase /v1/apis/{apiId}/environmentvariables
but the AWS SDK v2 sends to /v1/apis/{apiId}/environmentVariables (capital V).
This broke both getGraphqlApiEnvironmentVariables and
putGraphqlApiEnvironmentVariables for all SDK clients.
Fix the @Path annotations in the controller and update integration test
paths to match the SDK-expected casing.
* fix(appsync): align error codes and messages with AWS AppSync behavior
- DataSource duplicate: ConflictException 409 → BadRequestException 400
- Resolver duplicate: ConflictException 409 → BadRequestException 400
- Type duplicate: ConflictException 409 → BadRequestException 400
- DomainName duplicate: ConflictException 409 → BadRequestException 400
- Domain association duplicate: ConflictException 409 → BadRequestException 400
- API key limit: LimitExceededException 429 → ApiKeyLimitExceededException 400
- Add duplicate validation for Source API associations
- Add checkDuplicateSourceApiAssociation helper method
- Update all integration and SDK test assertions to match AWS exact messages
* feat(core): add extended data support to AwsException for AWS error parity
Add optional extended data to AwsException so the exception mapper can
emit structured error payloads matching the AWS error contract (e.g.
AppSync BadRequestException with reason=CODE_ERROR and detail.codeErrors).
The mapper auto-detects extended data and serializes it as additional
JSON fields alongside __type and message. When extended data is null
the previous simple AwsErrorResponse is returned, preserving behavior
for every existing error site.
* fix(appsync): return ConcurrentModificationException for duplicate source API association
AWS AppSync's AssociateSourceGraphqlApi returns ConcurrentModificationException
(HTTP 409) when an association already exists for the same source and merged
API pair. Floci was returning BadRequestException (400) with an association
ID in the message that did not match AWS.
Also filter out associations in DELETION_SCHEDULED status so a new
association can be created after the previous one has been removed, matching
AWS behavior where the previous association is no longer 'live'.
Message format now mirrors AWS: 'Source API association already exists
for Source API ID: <id> and Merged API ID: <id>.'
* refactor(appsync): remove non-AWS endpoints getApiKey and listAllResolvers
AWS AppSync does not expose:
- GetApiKey: there is no GetApiKey operation in the AppSync API
Reference. API keys can be listed, created, updated, and deleted
but not retrieved by id.
- ListAllResolvers: ListResolvers requires typeName. There is no
endpoint that lists resolvers across all types for an API.
Both endpoints were Floci-only and violated the 'no custom endpoint
shapes' rule. The associated service method (listResolvers) is also
removed. The corresponding integration tests are dropped in a
follow-up commit.
The getApiKey service helper stays because it is still used
internally by updateApiKey and deleteApiKey flows.
* feat(appsync): emit AWS-compatible BadRequestException extended format for SDL errors
AWS AppSync's StartSchemaCreation returns 400 BadRequestException with a
reason=CODE_ERROR field and a detail.codeErrors array. Each code error
carries errorType, value, and location{line, column, span}.
This commit:
- Catches SchemaProblem and InvalidSyntaxException from the parser and
throws BadRequestException with extended data built from
graphql-java's GraphQLError locations.
- Catches SchemaProblem from makeExecutableSchema for validation errors
(unknown types, missing fields) with errorType=VALIDATION_ERROR.
- Catches generic RuntimeException without extended data so flow
exceptions (NPE, OOM) do not produce a misleading codeErrors array.
- Validates unknown AppSync directives with errorType=VALIDATION_ERROR
and line/column/span from the SDL.
The errorType values follow the AWS Javadoc (PARSER_ERROR, VALIDATION_ERROR)
and span defaults to -1 when unknown, matching CodeErrorLocation.span()
in the AWS SDK.
* test(appsync): cover AWS-aligned error format, dead-code cleanup
- Add Order 157: createSourceApiAssociationDuplicateReturns409 asserts
ConcurrentModificationException 409 with the AWS message format.
- Add Order 158: createSourceApiAssociationReplacesDeletionScheduled
covers the new DELETION_SCHEDULED filter (a new association can
replace a previously deleted one).
- Add Orders 700, 701, 702: extended BadRequestException format for
PARSER_ERROR (syntax), VALIDATION_ERROR (semantic), and unknown
directive cases. Each asserts reason=CODE_ERROR, detail.codeErrors,
and the location{line, column, span=-1} shape.
- Update Order 124 (deleteApiKeyStandalone): the verification step
used the removed getApiKey endpoint, replace it with listApiKeys
asserting the deleted key is no longer present.
- Update Orders 600 and 607 to assert the new extended format for
generic SDL validation and unknown directive cases.
- Drop Order 32 (getApiKey) and Order 62 (listAllResolvers): the
underlying endpoints no longer exist.
- Drop encodeArn helper and the URLEncoder / StandardCharsets
imports that were no longer used by any test.
* test(sdk-java): cover AssociateSourceGraphqlApi 409 and extended schema error body
- Add Order 137 (createSourceApiAssociationDuplicateThrowsConcurrentModificationException):
use the typed AWS SDK exception ConcurrentModificationException instead
of the generic AppSyncException, validating the message format that
AWS returns.
- Add Order 200 (startSchemaCreation_syntaxError_throwsBadRequestWithExtendedBody):
send a raw HTTP POST with an invalid schema, then inspect the JSON body
to assert the AWS-compatible shape (__type, reason, detail.codeErrors[],
errorType=PARSER_ERROR, location{line, column, span=-1}). Uses a
jackson mapper rather than the SDK to read the response body directly.
- Import java.util.List to support the new deserialization in Order 200.
* feat(appsync): async schema creation with 409 in-progress gates
StartSchemaCreation is asynchronous in AWS: the request returns 200 +
PROCESSING, and the schema compiles in a background thread, transitioning
to ACTIVE (success) or FAILED (error) with the extended error format in
the polled GetSchemaCreationStatus response.
This commit:
- Adds SchemaCreationWorker, a singleton executor with configurable
thread count and graceful shutdown, that transitions the schema
status asynchronously and serializes the AwsException extended data
into the FAILED details string.
- Adds SchemaStatusStoreProducer so AppSyncService and the worker see
the same in-memory state for the schema status store (otherwise
two StorageFactory.create() calls would create independent maps).
- Refactors startSchemaCreation to set PROCESSING synchronously and
hand off compilation to the worker.
- Removes the synchronous ACTIVE override from the controller.
- Gates 27 per-API mutations and 2 account-wide operations
(CreateGraphqlApi, CreateApi) plus self-blocking on second
StartSchemaCreation with ConcurrentModificationException 409,
matching the AWS behavior documented in the AppSync API Reference
and service-2.json.
- Adds recoverOrphans() to EmulatorLifecycle.onStart so schemas left
in PROCESSING by a previous emulator run are marked FAILED instead
of permanently blocking the API.
- Adds schemaWorkerThreads and schemaWorkerShutdownTimeoutSeconds
to EmulatorConfig (FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_THREADS,
FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_SHUTDOWN_TIMEOUT_SECONDS).
* test(appsync): cover async schema polling, FAILED state, and 409 gates
- Adapts the 7 existing schema creation tests to the async pattern:
the post returns PROCESSING, tests poll for the terminal status with
Awaitility, and the extended format body is now read from the
polled FAILED details.
- Adds 9 new tests (Orders 703-711) covering the 409 in-progress gates
for createDataSource, createResolver, createFunction, createType,
putEnvironmentVariables, startSchemaCreation, createGraphqlApi,
updateGraphqlApi, and deleteGraphqlApi. The gates are exercised by
setting the status to PROCESSING directly via the shared store
backend, which is deterministic and avoids the race window of
waiting for the worker.
- Updates the EmulatorLifecycleTest constructor for the new
SchemaCreationWorker dependency.
* test(sdk-java): cover async schema with typed SDK polling
- Adds awaitility 4.2.2 to pom.xml (test scope) so the SDK test for
the polled status can use the same Awaitility DSL the integration
tests use.
- Updates the existing getSchemaCreationStatus test (Order 11) to
poll via the typed SDK call until the terminal status is reached
(ACTIVE in this case) instead of a single request. Without this,
the gate added in the previous commit would 409 every subsequent
SDK test that runs while the schema is still PROCESSING.
* fix(build): remove duplicate awaitility declaration in pom.xml
The pre-existing version-less awaitility declaration (BOM-managed by
Quarkus) was shadowed by the pinned 4.2.2 declaration added in this PR.
Maven resolves the first declaration it encounters, silently ignoring
the BOM version. Removed the version-less dup so the pinned 4.2.2
takes effect.
Addresses P1 from Greptile review.
* fix(appsync): add missing 409 gates and synchronize startSchemaCreation
Validating all 43 ConcurrentModificationException operations from
service-2.json against the code surfaced 5 operations missing the
PROCESSING gate (Greptile caught 1, 4 more were found during review):
- getChannelNamespace: added assertSchemaNotBusy (protects both get
and deleteChannelNamespace, matching getResolver/getFunction/getType)
- deleteDomainName: resolves the associated apiId from the domain
association store and gates on it (no-op if no association exists)
- disassociateApi: same pattern as deleteDomainName
- deleteMergedApiAssociation: gate on sourceApiIdentifier
- updateDomainName: resolves the associated apiId and gates on it
Also wraps the startSchemaCreation check-and-set in synchronized(this)
to close the TOCTOU race window between assertSchemaNotBusy and the
PROCESSING put. The async submitSchemaCreation call stays outside the
lock to avoid blocking the worker thread.
Addresses P1 and P2 from Greptile review.
* chore(appsync): document schema worker config in application.yml
Adds the appsync section under storage.services in both main and test
application.yml, documenting the three AppSyncStorageConfig keys:
- flush-interval-ms (5000 main / 60000 test, matching other services)
- schema-worker-threads (4)
- schema-worker-shutdown-timeout-seconds (30)
These already had @WithDefault fallbacks so the code worked without
the YAML entries, but the repository convention (AGENTS.md) requires
storage config to be documented in application.yml as the source of
truth for operators.
Addresses P2 from Greptile review.
* test(appsync): cover additional 409 gates for domain and merged operations
Adds 5 new integration tests (Orders 712-716) covering the PROCESSING
409 gates added in the previous commit:
- 712: deleteChannelNamespace_busy_returns409
- 713: deleteDomainName_busy_returns409
- 714: disassociateApi_busy_returns409
- 715: disassociateMergedGraphqlApi_busy_returns409
- 716: updateDomainName_busy_returns409
Each test creates the necessary resources (temp API, channel namespace,
domain name + association, or merged API association) before setting
the schema status to PROCESSING directly via the shared store, then
asserts the gated operation returns 409 ConcurrentModificationException
with the AWS-style message.
Integration test count: 154 -> 159.
* fix(appsync): remove incorrect CME gate from getChannelNamespace, add to deleteChannelNamespace
GetChannelNamespace does not declare ConcurrentModificationException in
service-2.json or the AWS Java SDK v2. Only BadRequestException,
NotFoundException, UnauthorizedException, InternalFailureException, and
AccessDeniedException are declared. The gate was incorrectly returning
409 during PROCESSING for an undeclared error code.
DeleteChannelNamespace does declare CME, so the gate is now applied
directly in deleteChannelNamespace instead of being inherited from
getChannelNamespace.
* fix(appsync): account-aware schema creation and worker store isolation
Scope schema creation status to the requesting account so concurrent
accounts cannot interfere with each other's in-flight schema operations.
- Add accountId field to SchemaCreationStatus
- Worker uses AccountAwareStorageBackend (putForAccount/getForAccount)
- SchemaStatusStoreProducer now produces AccountAwareStorageBackend
- SchemaStoreProducer CDI bean shares schemaStore between service and worker
- schemaStore.put moved to worker success path only
- assertSchemaNotBusy scoped to current account via getForAccount
- assertNoSchemaBusyAnywhere scoped to keysForAccount
- currentAccountId() helper reads RequestContext
- Worker config moved from AppSyncStorageConfig to AppSyncServiceConfig
* fix(appsync): ACTIVE→SUCCESS terminal schema status
Match AWS behavior: a successfully compiled schema is SUCCESS, not
ACTIVE. ACTIVE is not a valid terminal status in real AppSync.
- Worker marks SUCCESS on successful compilation
- Integration tests assert SUCCESS
- SDK compatibility test asserts SUCCESS
* refactor(appsync): remove circular dependency between SchemaRegistry and SchemaCreationWorker
SchemaRegistry depended on SchemaCreationWorker solely to delegate
submitSchemaCreation calls, creating a circular dependency. AppSyncService
now calls the worker directly, making the delegation unnecessary.
- Remove SchemaCreationWorker dependency from SchemaRegistry
- Remove submitSchemaCreation method
* fix(appsync): add assertSchemaNotBusy to deleteResolver, deleteFunction, deleteType
These three delete operations mutate the schema and should be blocked
while a schema creation is in PROCESSING state, matching the 409 gates
on the other schema-mutating operations.
* fix(appsync): return PROCESSING status synchronously from StartSchemaCreation
The controller was re-reading the status from the store after submitting
to the worker pool. In fast environments the worker could complete
(fail) before the read, causing the POST response to return FAILED
instead of PROCESSING — breaking the SDK compatibility test.
startSchemaCreation now returns the PROCESSING status it just set, and
the controller uses it directly instead of re-reading.
|
||
|
|
27f0124e36 |
fix(neptune): roll back proxy port and container on failed provisioning (#1742)
* fix(neptune): roll back proxy port and container on failed provisioning createDbCluster reserved a proxy port and started the container/proxy with no rollback: any throw after allocateProxyPort() leaked the port (only freed on delete) and orphaned the container. Repeated failures could exhaust the proxy-port range and surface as a spurious InsufficientNeptuneCapacity error. Wrap startup in try/catch, add rollbackDbCluster() that stops the proxy and container in isolated try blocks (guarded by handle != null) and always releases the port in finally, then rethrow. Mirrors the merged ElastiCache fix (#1618). Adds unit tests for both rollback branches (proxy-start throws after container is up; container-start throws before any handle). * fix(neptune): clean up container by id on readiness-timeout rollback Address Copilot review: NeptuneContainerManager.start() registers the container in activeContainers before the readiness probe, which throws on timeout without returning a handle. The previous handle-based rollback saw a null handle and skipped the container stop, orphaning a running container. Add an idempotent stopByClusterId() (with a deterministic-name fallback) and call it from rollbackDbCluster instead of stop(handle); the proxy stop stays guarded by handle != null. Update the service tests to the by-id cleanup and add a container-manager test for the name fallback. * fix(neptune): guarantee proxy-port release against non-RuntimeException Address greptile review: the finally that runs releaseProxyPort was attached only to the container-stop try, so an Error (e.g. NoClassDefFoundError) escaping the proxy-stop step would bypass it and leak the port — the exact failure this rollback prevents. Wrap both cleanup steps in an outer try whose finally always releases the port; each step keeps its own RuntimeException handling. * fix(neptune): roll back on JVM Errors during provisioning, not just RuntimeException Address greptile P1: the outer catch (RuntimeException) in createDbCluster would not intercept a JVM Error (OutOfMemoryError, NoClassDefFoundError, etc.) thrown by a Docker operation, so rollback never ran and the port + container leaked. (Note: catch (Exception) would not fix this — Error extends Throwable, not Exception.) Move the rollback into a finally guarded by a success flag so it fires on any non-success exit, including an Error, while the catch still logs the common RuntimeException case with detail. Adds a StackOverflowError rollback test. * fix(neptune): reserve proxy port inside the try to prevent leak on config-read failure allocateProxyPort() ran before the try opened, so a throw from the db-type/image config reads between them would leak the reserved port — the exact failure this rollback path prevents. Move the try to open immediately after the allocation. |
||
|
|
bf53ff71d8 |
fix(secrets-manager): return partial result for missing secrets in batch (#1591)
* fix(secrets-manager): return partial result for missing secrets in batch * fix(secrets-manager): remove hardcoded errorCode mapping * fix(secrets-manager): report deleted and missing current version secrets in BatchGetSecretValue errors |
||
|
|
97b64a1d3b |
feat: add AWS Lightsail emulation (#1583)
* feat(lightsail): add AWS Lightsail emulation * fix(lightsail): align error responses with AWS * fix(lightsail): address review edge cases * fix(lightsail): reject attached disk reattach * fix(lightsail): reject static ip reattach * fix: register lightsail docs handler |
||
|
|
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. |
||
|
|
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. |
||
|
|
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 |
||
|
|
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. |
||
|
|
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. |
||
|
|
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> |