mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
07d6cabd8a41ffd7be81b0d31c10ba9bb2f0b328
1693
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
f2b4c08481 |
fix(cloudformation): expand AWS::Serverless::StateMachine, and reject every unresolvable DefinitionUri on both StateMachine and HttpApi (#2885)
* test(cloudformation): pin AWS::Serverless::StateMachine expansion against the deployed template
The expected values come from a deployed stack's processed template, read with
get-template --template-stage Processed, and from change-set probes against real
AWS. Every assertion states its expected value as a literal.
* fix(cloudformation): expand AWS::Serverless::StateMachine into the native resource
The SAM transform switched on four resource types. A state machine fell through
the default arm, kept its AWS::Serverless:: type, and was stubbed by the
provisioner with a physical id of <logicalId>-<8 hex> and an attribute Arn of
arn:aws:stub:::<logicalId>. The stack reported CREATE_COMPLETE, ListStateMachines
was empty, and Fn::GetAtt on the resource handed downstream resources an ARN that
named no state machine.
Measured against a deployed stack, both template stages: 67 AWS::Serverless::StateMachine
in the original template, 67 AWS::StepFunctions::StateMachine in the processed one,
0 AWS::Serverless:: survivors. Eight properties are mapped on 67 of 67: Name to
StateMachineName, Type to StateMachineType, Role to RoleArn, DefinitionUri to
DefinitionS3Location, Logging to LoggingConfiguration, Tracing to
TracingConfiguration, DefinitionSubstitutions unchanged, and the Tags map to a list
of {Key, Value} with stateMachine:createdBy first. Every mapped value stays an
unevaluated intrinsic and tag values keep their JSON type. Metadata is carried
through, not synthesized: it is already present in the original template on 67 of 67.
Three further behaviours come from change-set probes against real AWS. A local
DefinitionUri does not raise an HTTP error: the change set is created with
Status FAILED, ExecutionStatus UNAVAILABLE, zero changes, and the transform's own
sentence in StatusReason. ExecuteChangeSet on that change set is refused with
InvalidChangeSetStatus. A DefinitionUri carrying ?versionId= is accepted and split
into a third field, Version.
* test(cloudformation): pin rejection of an intrinsic DefinitionUri on AWS::Serverless::StateMachine
An intrinsic DefinitionUri (Fn::Sub, Ref, ...) with no literal Bucket/Key
carries neither key, so samUriToS3Location passes it through unchanged and
the SAM transform accepts it silently. CloudFormation later collapses the
intrinsic into a TextNode and CloudFormationResourceProvisioner throws
"DefinitionS3Location requires Bucket and Key" at provisioning, one step
later than real AWS's own change-set-time failure.
* fix(cloudformation): reject an intrinsic DefinitionUri on AWS::Serverless::StateMachine
samUriToS3Location passes an object DefinitionUri through unchanged when it
carries neither Bucket nor Key, so an intrinsic value (Fn::Sub, Ref, ...)
reached DefinitionS3Location unresolved. CloudFormation then collapsed it
into a TextNode, and CloudFormationResourceProvisioner only caught the
missing Bucket/Key once provisioning started, one step later than real
AWS's own change-set-time failure.
expandServerlessStateMachine now accepts DefinitionS3Location only when it
resolves to a literal Bucket and Key, and rejects both the textual and the
object shape with the SAM transform's own wording, matching the FAILED
change set AWS reports for either.
Also drops the SamTransformProcessorTest case that pinned the old
pass-through behaviour for an intrinsic DefinitionUri (it asserted the
exact defect this fixes: the value surviving unsplit into
DefinitionS3Location) and adds a companion case for an object DefinitionUri
that names Bucket but not Key, closing the boundary the new guard leaves
otherwise untested.
* test(cloudformation): pin DefinitionUri rejection for a null Key, a non-string/object shape, and HttpApi
expandSamTemplate_stateMachineWithNullKeyDefinitionUriIsRejected and
expandSamTemplate_stateMachineWithArrayDefinitionUriIsRejected pin real AWS's rejection of a
DefinitionUri whose Key is an explicit null and of a DefinitionUri that is neither a string nor
an object (array, number, boolean); today's guard silently accepts both.
expandSamTemplate_httpApiWithIntrinsicDefinitionUriIsRejected replaces
expandSamTemplate_httpApiPreservesIntrinsicDefinitionUriForProvisioning:
both assert an HttpApi DefinitionUri with no literal Bucket/Key, but the one it replaces asserted
the value was preserved unresolved for the provisioner, a behaviour measured against real AWS
(us-east-1, create-change-set) to be wrong. AWS rejects it with the object-form wording, the same
one the StateMachine arm already carries.
samHttpApi_intrinsicDefinitionUriIsRejected replaces
samHttpApi_intrinsicDefinitionUriCreatesApiGatewayV2Routes: the test it replaces asserted the
opposite outcome, that routes were successfully created from a real spec uploaded to S3 and
imported through the intrinsic DefinitionUri, which real AWS does not accept for this shape.
expandSamTemplate_httpApiWithObjectDefinitionUriMissingKeyIsRejected and
expandSamTemplate_httpApiWithArrayDefinitionUriIsRejected pin the same two shapes on the HttpApi
arm; the array case is measured directly against real AWS via create-change-set.
* fix(cloudformation): reject every unresolvable SAM DefinitionUri, on both StateMachine and HttpApi
samUriToS3Location's object branch checked has("Bucket") && has("Key") on its own passthrough
copy of DefinitionUri, so a Key present as an explicit null (YAML's Key: with no value) counted
as resolved; and a DefinitionUri that was neither textual nor an object (array, number, boolean)
matched neither disjunct of the guard, so nothing was thrown and no definition was set at all.
Both callers now go through one guard, applyDefinitionUri: samUriToS3Location returns null
whenever it cannot produce a literal, non-null Bucket and Key, and applyDefinitionUri throws for
every non-null return with the wording definitionUriRejectionReason selects from the shape of
DefinitionUri, matching real AWS (measured against us-east-1 via create-change-set) for all three
JSON shapes. The predicate for "an S3 location is a Bucket and a Key" lives once, in
samUriToS3Location.
This also closes the split between the two callers: the HttpApi arm used to preserve an
unresolved DefinitionUri (an intrinsic, or an object missing Key) as BodyS3Location for the
provisioner to fail on later, or silently emit no definition at all for a non-object,
non-string DefinitionUri. It now rejects every one of those shapes at transform time, the same
as the StateMachine arm, matching AWS's own transform-time rejection (measured directly for the
array/number/boolean shape via create-change-set, not previously measured on this branch).
* test(cloudformation): pin the missing Definition/DefinitionUri mutual-exclusion cases
expandSamTemplate_stateMachineWithNeitherDefinitionNorDefinitionUriIsRejected and
expandSamTemplate_stateMachineWithBothDefinitionAndDefinitionUriIsRejected pin real AWS's
rejection (measured via create-change-set) of a StateMachine declaring neither Definition nor
DefinitionUri, and of one declaring both; today's expandServerlessStateMachine handles neither
case, emitting a definition-less resource for the first and a resource carrying both Definition
and DefinitionS3Location for the second.
expandSamTemplate_httpApiWithBothDefinitionBodyAndDefinitionUriIsRejected pins the equivalent
HttpApi rejection, with AWS's own reversed property order in the message; the else at
expandServerlessHttpApi's DefinitionBody check hides this shape today, always preferring
DefinitionBody with no error.
expandSamTemplate_httpApiWithLocalDefinitionUriIsRejected and
samHttpApi_definitionUriCreatesApiGatewayV2Routes are coverage additions, not new pins: both
pass unmodified against the previous commit's production code. The first mirrors the existing
expandSamTemplate_stateMachineWithLocalDefinitionUriIsRejected on the HttpApi arm, the most
common real shape (an unpackaged sam template) and previously untested there. The second
restores the only end-to-end proof that a literal s3://bucket/key DefinitionUri creates routes,
lost when an earlier commit on this branch replaced
samHttpApi_intrinsicDefinitionUriCreatesApiGatewayV2Routes with
samHttpApi_intrinsicDefinitionUriIsRejected.
* fix(cloudformation): enforce Definition/DefinitionUri mutual exclusion on SAM StateMachine and HttpApi
expandServerlessStateMachine copied Definition and resolved DefinitionUri independently, so a
StateMachine declaring both ended up with one native resource carrying both Definition and
DefinitionS3Location, and one declaring neither expanded to a resource with no definition at
all. Real AWS (measured via create-change-set, us-east-1) rejects both shapes before a single
resource is provisioned. expandServerlessHttpApi's DefinitionBody check silently preferred
DefinitionBody over DefinitionUri with no error when a resource declared both; AWS rejects that
too, naming DefinitionUri first, the reverse of the StateMachine wording.
Both arms now check presence of their two definition-source properties up front and share a
rejectBothDefinitionSources helper for the "not both" wording; the StateMachine arm additionally
rejects "neither". A neither-property HttpApi is left alone: measured against real AWS via
create-change-set, that shape is accepted and expands to an empty ApiGatewayV2 API, unlike the
StateMachine arm.
Renames applyDefinitionUri to resolveDefinitionUriOrThrow, naming the effect its old name left
unstated (it either sets the target property or throws), and inlines its lone-caller helper
definitionUriRejectionReason: the merged function stays a handful of decision points, well under
the cognitive-complexity budget, and reads as one "resolve or throw" unit instead of two.
Both callers now guard DefinitionUri's presence before calling resolveDefinitionUriOrThrow, so
its own absent/null guard, and the duplicate of the same guard at the top of samUriToS3Location,
were both unreachable; deletes both and rewrites the javadoc that claimed a caller-side check
already existed for the state machine arm, which it did not.
SamTransformProcessorTest fixture updates: four pre-existing StateMachine tests exercising
Metadata/DependsOn/Tags/intrinsic-property preservation declared neither Definition nor
DefinitionUri, a shape the new guard now rejects; each gains a minimal literal DefinitionUri so
its own assertions keep exercising what they always asserted.
* refactor(cloudformation): collapse rejectBothDefinitionSources booleans and duplicated presence checks
rejectBothDefinitionSources took two independent booleans read only as their
conjunction; because && is commutative, swapping them at a call site went
undetectable, while swapping the two property name strings would silently
reverse AWS's own wording. Both callers now pass the conjunction they already
compute, so the signature no longer promises a per-argument correspondence the
body never used.
copyRenamed and isPropertyPresent asserted the identical "not missing, not
null" presence check in two places; copyRenamed now delegates to
isPropertyPresent so the predicate lives once. expandServerlessStateMachine's
Definition copy re-tested a presence its own hasDefinition guard already
established; it now copies the already-known-present node directly.
Reworded the HttpApi DefinitionBody/DefinitionUri comment: "Neither X nor Y is
accepted too" read as its own opposite of the fall-through it documents, where
an HttpApi declaring neither property is accepted and still expands to a bare
AWS::ApiGatewayV2::Api and its default Stage.
Realigned two continuation lines that sat one column past their opening paren
to the file's own prevailing continuation style.
Behaviour-neutral: no assertion or error message changes.
* test(cloudformation): pin AWS::Serverless::Api DefinitionBody/DefinitionUri expansion
Pins the RestApi Body/BodyS3Location expansion an AWS::Serverless::Api's
DefinitionBody or DefinitionUri must produce, the rejection of a
local-path DefinitionUri, and that the declared Name survives a
DefinitionBody carrying a different info.title, all currently unmet.
* fix(cloudformation): materialize AWS::Serverless::Api DefinitionBody/DefinitionUri
expandServerlessApi carried only Name and Description onto the emitted
AWS::ApiGateway::RestApi, silently dropping a declared OpenAPI document
so the stack reached CREATE_COMPLETE with an API serving no method.
The transform now maps DefinitionBody to Body and DefinitionUri to
BodyS3Location, rejecting both together or a local-path DefinitionUri,
mirroring the AWS::Serverless::HttpApi arm. The REST API provisioner
resolves that document (renaming the ApiGatewayV2-only resolver into
resolveRestApiOpenApiDocument, now shared by both API Gateway
versions) and runs it through the existing putRestApi/applyOpenApiSpec
OpenAPI materializer, then re-applies the resolved Name since
putRestApi overwrites it from the document's info, which real AWS
does not do.
* test(cloudformation): pin AWS::Serverless::Api both-Definition rejection wording
Measured against real AWS, us-east-1, create-change-set: an Api
declaring both DefinitionBody and DefinitionUri is rejected with
DefinitionUri named first. Nothing pinned this sentence's property
order, so it could be transposed silently; rejectBothDefinitionSources
already enforces it, this only adds the missing regression test.
* refactor(cloudformation): rename ApiGatewayV2BodyS3Location to OpenApiBodyS3Location
parseOpenApiBodyS3Location now feeds both the ApiGatewayV2 and the
native/SAM ApiGateway RestApi provisioning paths; its return type kept
the V2-only name after the parser itself was renamed, leaving one
representation of an S3 body location claiming to be v2-only. No
behaviour changes, five sites in one file, all within this record's
own declaration and its own callers.
* test(cloudformation): pin AWS::ApiGateway::RestApi Body materialization outside SAM
A native RestApi's Body was ignored before the provisioner started
resolving it for AWS::Serverless::Api's DefinitionBody, since both
paths share provisionApiGatewayRestApi. Nothing covered the
hand-written-template shape; this pins that a declared Body's OpenAPI
document creates its resources and methods, not only a SAM-expanded
one.
* test(cloudformation): pin SAM Api Description reapply and DefinitionBody materialization together
samApi_declaredNameSurvivesDefinitionBodyTitle only proved the Name-reapply
line against a partial revert, so it passed even with the entire fix
reverted: a provisioner that never reads DefinitionBody at all trivially
never overwrites Name either. Renamed and rewritten so it also asserts the
declared Description survives putRestApi (which overwrites Description from
DefinitionBody's info exactly the way it overwrites Name) and that the
/hello method from DefinitionBody actually materializes, so a provisioner
that skips DefinitionBody cannot pass. Red against both production files
reverted to cbdebe10: item.path doesn't match, expected a collection
containing "/hello", actual [/].
* refactor(cloudformation): rename resolveRestApiOpenApiDocument to resolveOpenApiDocument
The method is also the OpenAPI-document resolver for AWS::ApiGatewayV2::Api
(reconcileApiGatewayV2BodyRoutes), never called for a RestApi in that path:
"RestApi" in the name reintroduces the exact naming defect commit 7da9a7c4
existed to fix. No caller or behavior changes.
* fix(cloudformation): reapply Description after putRestApi overwrites it from DefinitionBody
putRestApi overwrites both Name and Description from the DefinitionBody's
info, but only Name was re-applied afterward: an undeclared Name falls back
to the generated physical name (a text field, never null), while an
undeclared Description resolves to null, and Map.of rejects a null value,
so the previous single-entry patch could not carry a Description operation
at all. Reapplies both through a HashMap-backed replace op that allows null,
clearing an undeclared Description rather than leaving whatever putRestApi
last wrote. Narrows the comment above the reapply to what the create-
change-set probe actually measured (the processed template keeps Name and
Description separate from Body.info) rather than a runtime-preference claim
the probe never tested, since create-change-set never executes the change.
Isolated red (only the Description reapply removed, Name reapply and
materialization intact): item.find { it.name == '<apiName>' }.description
doesn't match, expected the declared description, actual
"description-from-document".
* style(cloudformation): drop em-dash from committed test comment
AGENTS.md:314 forbids an em-dash or en-dash on any added line, and CI does
not catch it. Comment text only, no assertion changes.
* refactor(cloudformation): extract shared DefinitionBody/DefinitionUri handling, fix stale docs
Extracts the identical DefinitionBody/DefinitionUri resolution (reject-both
check plus the Body/BodyS3Location assignment) duplicated between
expandServerlessApi and expandServerlessHttpApi into applyDefinitionSource,
called from both arms. Updates the four javadoc caller lists that named
expandServerlessHttpApi as the sole AWS::Serverless::Api-adjacent caller of
rejectBothDefinitionSources, samUriToS3Location and
resolveDefinitionUriOrThrow, now inaccurate with applyDefinitionSource as
the actual (shared) caller. Corrects the expandServerlessApi comment on an
Api declaring neither DefinitionBody nor DefinitionUri: AWS does synthesize
a default Body in that case, floci does not, and the comment now says so
while noting the runtime outcome (no method reachable) is the same either
way, rather than claiming AWS leaves Body unset.
No behavior change: both arms' existing tests pass unedited.
* docs(cloudformation): drop the corpus size from the state machine javadoc
The unhandled-properties note carried a count a reader cannot verify. State
what was measured instead.
---------
Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
|
||
|
|
7095641e25 |
fix(cloudformation): set Fn::GetAtt attributes the schemas declare (#2761)
* fix(cloudformation): set Fn::GetAtt attributes the schemas declare An attribute a provisioner never sets is invisible at runtime: GetAtt resolution returns the literal "LogicalId.Attr" when a resource has no such attribute, so a template referencing one receives that string as a value instead of failing. Auditing every migrated type against its registry schema found 24 such attributes across 15 types. Sets the three whose correct value is unambiguous: AWS::SNS::Topic gains TopicArn, the attribute aws-sns-topic.json actually declares. Arn stays alongside it, since templates written against earlier releases reference it. AWS::S3::Bucket gains DualStackDomainName, in the same form as the RegionalDomainName it already builds. AWS::CodePipeline::Pipeline gains Arn, which the schema describes as the pipeline's ARN and which is constructible from the region, account and name already in hand. The remaining 21 are recorded in getatt-attribute-gaps.tsv, each with a reason. Most are attributes Floci cannot set because it does not emulate the behaviour behind them, such as VPC CIDR associations or pipe lifecycle timestamps. A few are simply undecidable from the schema alone, and inventing a value would be worse than leaving the gap recorded. CfnSchemaCoverageTest makes the set a ratchet rather than a snapshot: closing a gap requires deleting its row, introducing one requires adding a row with a reason where a reviewer sees it, and a row that stops being real fails until it is removed. * test(cloudformation): await the async stack operations in the VPC gateway test The test asserted the results of CreateStack and DeleteStack immediately. Both are asynchronous: CloudFormationService submits them to a background executor and the HTTP call returns as soon as the work is queued, so each assertion only passed while the executor happened to win the race. The delete assertion lost that race on CI. Adding a test class elsewhere in the suite re-partitioned the deterministic CI shards, which moved this class to different neighbours and changed the timing it had been relying on. Both assertions now poll to a deadline, matching the awaitStackStatus pattern the other CloudFormation integration tests use. A genuinely unperformed detach still fails, just ten seconds later, so this removes the timing sensitivity without hiding a real regression. * fix(cloudformation): scope the GetAtt coverage scan per resource type The scan read each provisioner as a whole file, so a class serving several types credited every one of them with what any single arm sets. That is a false negative in the only direction that matters: the gap the ratchet exists to record stops being reported. It was hiding a real one. Ec2NetworkAclCfnProvisioner sets Id for NetworkAcl and never for NetworkAclEntry, whose schema declares Id as its primaryIdentifier and sole readOnlyProperty, so Fn::GetAtt on it resolved to the literal "LogicalId.Id" while the audit reported clean. Set it to the composite physical id so the attribute agrees with Ref. The scan now walks the switch on getResourceType() in provision, takes each arm plus the same-class methods it transitively calls, and adds whatever provision writes outside the switch to every type, since that is the shared path. Two shapes need the care: - Only a switch in statement position is a dispatch. A switch expression such as `boolean ingress = switch (r.getResourceType())` picks a value on one shared path. Reading its arms as per-type paths reported SecurityGroupIngress and SecurityGroupEgress Id as gaps when both are set after the switch. - A class with a dispatch switch but no arm for a type it owns now fails the scan, so an unrecognised shape cannot quietly fall back to the class-wide reading it replaced. Raised by pgermosen in review. |
||
|
|
ab26a42096 | feat(cloudformation): provision Route 53 hosted zones (#2722) | ||
|
|
961d82dda9 | fix(cloudformation): provision AWS::Scheduler::ScheduleGroup (#2796) | ||
|
|
afa5960709 |
fix(docker): PortAllocator also checks ports other containers already publish on the host (#2805)
* fix(docker): PortAllocator also checks ports other containers already publish on the host isPortFree binds a ServerSocket in floci's own process, which is the container's network namespace when floci runs containerized: a host port another container already publishes via -p looks free, the allocation succeeds, and the sibling container's start then fails with 'port is already allocated'. allocate() now also consults the Docker API's view of published host ports before committing to a candidate. The DockerClient is optional: the no-arg constructor leaves it null and keeps every existing caller's behavior unchanged, and a Docker API failure is fail-permissive, matching isPortFree's posture. * perf(docker): snapshot the container list once per allocate() The per-candidate isPortBoundByAnyContainer check made one listContainersCmd() round-trip for every candidate that passed the cheap checks, serialized inside the lock every consumer of the shared allocator blocks on. allocate() now snapshots the published host ports once per invocation and checks each candidate against that set; the snapshot was only ever as fresh as the start of allocate() anyway. Fail-permissive posture unchanged: no client or a Docker API failure still skips the check entirely. |
||
|
|
3b7ba5c687 |
feat(batch): add UpdateComputeEnvironment and DeleteComputeEnvironment (#2857)
Mirrors the existing UpdateJobQueue/DeleteJobQueue pair. DeleteComputeEnvironment requires DISABLED state and rejects deletion while still referenced by a job queue's computeEnvironmentOrder, matching AWS; updating computeResources is a partial merge (only the sent fields change), not a full replace. Both UpdateComputeEnvironment and CreateComputeEnvironment now validate state is ENABLED or DISABLED, so an invalid value can never be persisted and later block deletion. CloudFormation stack-delete wiring for AWS::Batch::ComputeEnvironment/ JobQueue/JobDefinition (currently a silent no-op on stack teardown) is left for a follow-up that migrates all of Batch's CFN handling into a per-service provisioner, rather than adding more cases to the legacy switch. Closes #2293, closes #2803. |
||
|
|
906af8c632 |
feat(ec2): support standalone network interface create/attach/detach (#2843)
* feat(ec2): support standalone network interface create/attach/detach
CreateNetworkInterface returned UnsupportedOperation unconditionally,
blocking every root that attaches a standalone ENI: the attach-eni and
override-default-eni examples in terraform-aws-server, the with-elb
example in terraform-aws-asg, and vpc-blackhole-routes in
terraform-aws-service-catalog (floci-kt9 in the floci-harness compat
survey).
Adds CreateNetworkInterface, DeleteNetworkInterface,
AttachNetworkInterface and DetachNetworkInterface, backed by a new
standalone ENI store separate from the implicit primary interface each
instance already carries. DescribeNetworkInterfaces now merges both
without double-counting. RunInstances also accepts a pre-existing
standalone ENI as an instance's primary interface via
NetworkInterface.1.NetworkInterfaceId, the shape Terraform's
network_interface { network_interface_id = ... } block sends for
override-default-eni.
* fix(ec2): keep a standalone ENI's own record when it is attached
Review found two ways the attachment state ended up recorded on only one side.
AttachNetworkInterface updated the standalone ENI and stopped there, so
DescribeNetworkInterfaces reported an attachment that DescribeInstances denied —
and the device-index conflict check, which reads the instance's own interface
list, could never see anything this operation had attached: two interfaces could
take device index 1 on the same instance. The instance now carries the interface
too, and DetachNetworkInterface removes it again.
RunInstances took the opposite approach and deleted the standalone record,
leaving the interface represented only inside the instance. Terminating that
instance then made a caller-created ENI vanish -- InvalidNetworkInterfaceID.
NotFound rather than returning to "available" -- so it could not be reused. AWS
attaches a pre-existing interface with deleteOnTermination false precisely so it
outlives the instance. The standalone record is now kept and marked attached,
and terminate releases it; describeNetworkInterfaces skips the instance-side
copy of any id the standalone store owns, so it is still reported exactly once,
from the side that knows its real attach time and its deleteOnTermination.
Also braces a single-line conditional, per AGENTS.md.
* fix(ec2): release an ENI whose instance died without TerminateInstances
TerminateInstances is not the only way an instance reaches "terminated": a
container-backed launch that fails or is cancelled ends there asynchronously,
inside Ec2ContainerManager, which has no access to the interface store. An ENI
the launch had already marked in-use therefore stayed pinned to an instance that
no longer runs, and every later attempt to reuse it failed with
InvalidNetworkInterface.InUse.
Rather than chase each terminal transition, the attachment is reconciled when
the interface is next read: an attachment naming an instance that is gone or
terminated is cleared, and the interface reports "available" again. That covers
attach, launch, delete and describe through the one path they share.
* fix(ec2): let a dead instance release its copy of a reclaimed ENI
Releasing the standalone record alone left the terminated instance still
reporting the interface, so once the ENI was reused two instance records claimed
it and nothing in DescribeInstances picks a winner. Reclaiming now clears both
sides, and the unit test asserts the instance no longer lists it.
Also drops the em-dashes from the comments and docs this branch adds, per
AGENTS.md.
* fix(ec2): drop the instance's copy on the TerminateInstances path too
The previous commit fixed only the reclaim-on-read path. TerminateInstances
released the standalone record while leaving the mirrored interface on the
terminated instance, so reusing the ENI still produced two instance records
claiming it. Both paths now clear the instance's copy, and the integration test
asserts DescribeInstances no longer mentions the interface before the same ENI
is handed to a second launch.
|
||
|
|
7828ab2430 |
fix(docker): translate misleading disk-quota error for keyring exhaustion (#2797)
* fix(docker): translate misleading disk-quota error for keyring exhaustion crun/runc report the kernel session-keyring quota (kernel.keys.maxkeys) as "join keyctl ...: Disk quota exceeded", which reads as an actual disk-space problem. Under high concurrent container counts this is common on podman machine's default Fedora CoreOS sysctls (200 keys per uid), and sends operators looking in the wrong place. Both container-start call sites in ContainerLifecycleManager now go through a shared helper that recognizes this specific OCI runtime error and rethrows with the actual cause and the sysctl fix, leaving every other DockerException untouched. Fixes floci-io/floci#2243 * fix(docker): route the shared-volume init helper through the translated start path pgermosen review on PR #2797: initSharedVolumeRoot's helper container start bypassed the keyring-quota translation, so it still surfaced the raw, misleading "Disk quota exceeded" message when this specific start call hit the crun keyring error. The failure is caught as a plain RuntimeException by ensureSharedVolume's computeIfAbsent and only logged, never rethrown, so this exact call site's routing is what decides which message ends up in that log line. startContainer is now package-private so the new test can verify this call site actually invokes it (via a spy), since the swallowed exception itself is not observable from ensureSharedVolume's public contract. |
||
|
|
bed27043ef |
fix(ec2): report a NAT gateway's addresses, not just its allocation id (#2892)
* fix(ec2): report a NAT gateway's addresses, not just its allocation id CreateNatGateway and DescribeNatGateways returned natGatewayAddressSet entries carrying an allocationId and nothing else. Real AWS also returns publicIp, privateIp, networkInterfaceId, associationId and status, and aws_nat_gateway exposes the first three as resource outputs -- Gruntwork's VPC modules re-export nat_gateway_public_ips from them, so the omission does not stop at a diff, it propagates empty values into every module downstream. A gateway now gets an interface in its subnet with a private address from the same allocator instances use, and a public one additionally reports the Elastic IP it was created with and an association id for it. A private gateway has no Elastic IP, so it reports neither publicIp nor associationId, which is what AWS returns for one. The addresses are stored on the gateway rather than derived at serialization time, so the private address and interface id stay put across reads instead of changing under a client that refreshes. A gateway restored from a store written before this change has no address list but still knows its allocation id, and reports that much rather than an empty set. * fix(ec2): refuse an Elastic IP on a private NAT gateway ConnectivityType=private with an AllocationId was accepted, and the response then reported a public IP and an association on a gateway that has no route to the internet and nothing to attach one to. AWS refuses the combination, so this does too, before the allocation is looked up or any address is minted. Also drops the em-dashes from this branch's comments, per AGENTS.md. |
||
|
|
0cf3144f5e |
feat(ec2): honour AmazonProvidedIpv6CidrBlock on a VPC (#2891)
* feat(ec2): honour AmazonProvidedIpv6CidrBlock on a VPC CreateVpc ignored the parameter, and no response carried an ipv6CidrBlockAssociationSet at all, so aws_vpc's assign_generated_ipv6_cidr_block never converged: Terraform asks for a block, reads none back, and plans the same change on every run. CreateVpc and AssociateVpcCidrBlock now both accept AmazonProvidedIpv6CidrBlock -- the provider uses the first when the flag is set at create and the second when it is turned on for an existing VPC, so implementing only one would fix half the configurations. The block is a /56 out of Amazon's pool, which is Amazon's to choose and not something a caller can predict; what a client depends on is that one comes back at all and that it is stable across reads. IPv6 associations are kept in their own set rather than joining cidrBlockAssociationSet: AWS keeps the two apart, with different member names inside each, and a client reading the IPv4 set must not find IPv6 blocks there. DisassociateVpcCidrBlock takes an association id from either set, as AWS does -- it never asks which family the id belongs to. Subnet-level IPv6 (Ipv6CidrBlock on CreateSubnet) is deliberately out of scope; this is the VPC-level association only. * style(ec2): drop em-dashes from the IPv6 association comments AGENTS.md forbids them anywhere; commas and colons instead. |
||
|
|
e8eb4f2ff0 |
feat(cloudwatch): implement the dashboard operations on both protocols (#2888)
* feat(cloudwatch): implement the dashboard operations on both protocols
CloudWatch served no dashboard operations at all, so terraform-aws-monitoring's
cloudwatch-dashboard example failed on apply with "api error UnsupportedOperation:
Operation PutDashboard is not supported by CloudWatch Query" - the Query
handler's default branch, reached because PutDashboard had no case.
Adds PutDashboard, GetDashboard, ListDashboards and DeleteDashboards, backed by
a new CloudWatchDashboardsService. Dashboards are pure metadata: the
DashboardBody is stored opaquely and returned verbatim, matching AWS. Put
overwrites an existing name, Get on a missing name is ResourceNotFound,
ListDashboards honours DashboardNamePrefix, DeleteDashboards checks every name
before deleting any so it is all-or-nothing, and responses carry DashboardArn.
Both CloudWatch protocols are wired, since which one a caller uses depends on
its SDK: the Terraform provider sends the Query protocol (form-encoded Action,
routed by credential scope through AwsQueryController), while the AWS CLI and
SDK v3 send JSON 1.0 with X-Amz-Target: GraniteServiceVersion20100801.*, routed
by AwsJsonController. The monitoring service descriptor already declared both,
so no new dispatch was needed - only the four cases in each handler, plus the
new action names in AwsQueryController's CLOUDWATCH_ACTIONS so the no-auth
action-inference path resolves them to CloudWatch too.
* fix(cloudwatch): reject a dashboard body that is not a JSON object
PutDashboard checked only that a body was present, so a malformed document was
stored and answered with success. AWS parses the body and returns
InvalidParameterInput, and the difference matters: a client that sends broken
JSON otherwise learns nothing until the dashboard renders as nothing.
The body is still stored and returned verbatim; this validates that it parses
and is an object, and does not inspect what is inside it.
* fix(cloudwatch): reject a dashboard body with trailing content
readTree stops at the end of the first value, so a body of "{} and then some"
validated as the leading object and the rest was dropped, storing a document AWS
rejects. FAIL_ON_TRAILING_TOKENS makes the reader require exactly one document.
* fix(cloudwatch): make DeleteDashboards best effort, as AWS documents it
The all-or-nothing behaviour was backwards. AWS says the opposite, verbatim: "If
there is an error during this call, the operation attempts to delete as many
dashboards as possible." Deleting ["a", "missing"] where a exists removes a and
errors on missing; this removed neither, so a caller retrying with the same
batch made no progress.
Every name is now attempted, including ones after the first miss, and the first
missing name is reported afterwards. Whether a missing name errors at all is the
part that stays uncertain: DeleteDashboards' own Errors list does not name
ResourceNotFound the way GetDashboard's does, which hints at a silent skip
without establishing one, so the error is kept as the conservative reading.
* feat(cloudwatch): support PutDashboard's Tags, and tag ops on a dashboard ARN
Tags were accepted and dropped, which is the failure mode this emulator is meant
not to have. They are now stored on the dashboard, and CloudWatch's own tag
operations reach it: ListTagsForResource, TagResource and UntagResource take one
ARN for every taggable resource CloudWatch owns, so both protocol handlers route
a dashboard ARN to the dashboards service instead of the alarm store that
answered before.
Tags apply on create only, as AWS documents. A Put that replaces an existing
dashboard keeps the tags that dashboard already had, so an update cannot retag a
resource sideways through an operation that is not a tag operation. More than 50
tags is refused.
|
||
|
|
3a212d8360 |
fix(s3): shrink getObject's lock to a cheap seqlock check, not the I/O (#2901)
|
||
|
|
9bf93b94c2 |
fix(elbv2): drop access logs from a Gateway Load Balancer's attributes
Only deletion_protection.enabled and load_balancing.cross_zone.enabled are supported by every load balancer type; access_logs.s3.* is an Application and Network Load Balancer attribute. Adding it unconditionally handed a Gateway Load Balancer a schema AWS never returns for one, which is as wrong as omitting a key that does belong. |
||
|
|
910e64e726 |
fix(elbv2): report the attribute defaults, not only what was modified
DescribeLoadBalancerAttributes and DescribeTargetGroupAttributes answered with an empty list for a resource nobody had modified: a key appeared only once something had explicitly set it. AWS always returns the full set, and a key is absent only when the resource type does not have it. The Terraform provider reads these on every refresh, into aws_lb's idle_timeout, enable_http2, enable_deletion_protection and access_logs, and into aws_lb_target_group's stickiness, deregistration_delay and load_balancing_algorithm_type, so an empty list left every one of them a permanent diff on every ALB and NLB. Which keys apply is decided the way AWS decides it, by load balancer type and target group protocol rather than one flat list: an NLB has no idle timeout, an ALB has no proxy protocol, a Lambda target group has neither. Stored values win over defaults, so a modified key still reports what it was set to. An existing test pinned the old behaviour by asserting the modified key was the only one returned; it now asserts that key is among the set, which is what it was really trying to establish. |
||
|
|
10192f05d5 |
feat(translate): add Amazon Translate mock service (#2879)
* feat(translate): add Amazon Translate mock service JSON 1.1 stub for Amazon Translate covering the three self-contained sync operations: TranslateText, TranslateDocument, ListLanguages. Follows the existing Comprehend/Textract stub pattern (stateless, echoes input, AI_MOCK_CONFIG override for TranslateText). - TranslateText echoes Text, enforces the 10,000-byte limit, allows any language pair; an auto source is reported back as en. - TranslateDocument echoes the base64 Content and enforces the English-pivot rule, the ContentType allow-list, valid base64, and the 100 KB cap (InvalidRequestException, matching the operation's error model). The encoded length is checked before decoding so an oversized payload cannot force a large allocation. - ListLanguages returns a fixed ~35-language catalog; DisplayLanguageCode is validated, pagination inputs are accepted but ignored. Untrusted request values are truncated before being echoed into error messages. * chore(translate): remove em-dashes per AGENTS.md style guide Replace em-dashes in the Translate doc page and Java comments with colons, commas, or periods, and the ellipsis in the error-message preview helper with "...". Addresses the Greptile review note on PR #2879. |
||
|
|
c32f8b5a24 |
fix(ec2): place a subnet in the zone its request names, not always az1 (#2890)
* fix(ec2): place a subnet in the zone its request names, not always az1 CreateSubnet never read AvailabilityZoneId, and hardcoded every new subnet's zone id to the region's first zone. Two consequences, and the second bites even a caller that never mentions a zone id: a subnet asked for us-east-1-az2 came back in us-east-1-az1, and a subnet placed correctly by zone *name* still reported az1, contradicting its own availabilityZone. Anything that selects subnets by zone id therefore saw one zone -- Terraform's aws_subnet.availability_zone_id, and any client that pairs subnets against the DescribeAvailabilityZones list it just read. AvailabilityZoneId is now honoured, and the zone id is derived from the zone rather than fixed. The derivation is the mapping DescribeAvailabilityZones and the seeded default subnets were already using independently; all three now come through one helper, so a subnet's zone id agrees with the zone list by construction instead of by coincidence. A zone and a zone id that disagree are refused with InvalidParameterCombination rather than silently resolved to one of them -- Terraform's aws_subnet forbids setting both, so a request carrying both contradictory values is a bug in the caller, not something to guess at. A malformed zone id is refused too. * fix(ec2): refuse a zone id this region does not publish The first version resolved any well-formed zone id, so us-east-1-az4 created a subnet in a zone DescribeAvailabilityZones does not list. That is the same inconsistency the hardcoded az1 produced, only quieter: a client pairing subnets against the published zone inventory still cannot resolve the subnet's zone. The three modelled zones are now one constant that DescribeAvailabilityZones, the seeded default subnets and this validation all read, so they cannot drift, and the error names the range rather than only rejecting. Also logs the tolerated NumberFormatException instead of swallowing it, and drops this branch's em-dashes, both per AGENTS.md. |
||
|
|
2a637d3e05 |
fix(apigatewayv2): provision integration, route and stage on quick create (#2877)
* fix(apigatewayv2): provision integration, route and stage on quick create CreateApi's `target` parameter (quick create) was accepted but silently ignored: no AWS_PROXY integration, no "$default" route, and no "$default" stage were ever created. Without a stage, ApiGatewayExecuteApiHostFilter.stageExists() throws "Stage not found", the filter returns without rewriting the request, and it falls through to whichever other virtual-hosted-style filter claims the host next (S3's, in the common case) instead of reaching the API. Provision the AWS_PROXY integration, "$default" route, and auto-deploy "$default" stage that real API Gateway creates for quick create, using the existing createIntegration/createRoute/createStage helpers. Fixes #1902 * fix(apigatewayv2): use HTTP_PROXY for HTTP URL quick-create targets Quick create hardcoded AWS_PROXY regardless of target shape, so an HTTP URL target got routed through Lambda ARN parsing and failed invocation instead of reaching the configured endpoint (spotted by review). Detect the target kind (arn: prefix vs HTTP URL) and pick AWS_PROXY/POST or HTTP_PROXY/ANY accordingly, matching real API Gateway's quick-create behavior. Also drop the em-dashes from the new comment and Javadoc per AGENTS.md's style rule, and split the single test into one covering each target kind. --------- Co-authored-by: Karan-Tekuncorked <karan@tekuncorked.com> |
||
|
|
2bf9b57bd9 |
fix(lambda): omit Environment when no variables are set (#2838)
* fix(lambda): omit Environment when no variables are set
Real AWS omits the Environment member entirely from CreateFunction,
GetFunction, GetFunctionConfiguration and ListFunctions responses when a
function has no environment variables. Floci always emitted it, as an
empty object.
The Terraform provider reads a present-but-empty Environment back as an
environment {} block in state, so any function declared without variables
plans a removal on every run and never converges. On Lambda@Edge, where
environment variables are not permitted at all, the block can never
legitimately exist and each no-op apply also republishes the function.
Layers, KMSKeyArn, FileSystemConfigs and VpcConfig in the same response
builder already omit-when-empty; Environment was the outlier.
* test(compat): correct Environment assertions to match live AWS
Three assertions in the Python and Java SDK compatibility suites required
an Environment block that real AWS does not send:
- test_get_function_configuration_environment_always_present
- test_update_environment_variables_round_trip (the cleared case)
- LambdaFunctionConfigTest.getFunctionConfigurationHasDefaults
Measured against the live service in both directions: a function created
without variables comes back with no Environment member, and clearing to an
empty Variables map removes it again. The tests encoded Floci's previous
behaviour rather than the API's, which is why they went green.
Also corrects the wording of the Java clear case. It sends an Environment
with no Variables member, which is 'leave unchanged', not 'clear' — live AWS
keeps the existing variables, as Floci already did. The assertion now pins
that instead of describing a clear that never happened.
|
||
|
|
db182b3048 |
fix(efs): implement UpdateFileSystemProtection and report protection on describe (#2842)
A file system's replication overwrite protection was missing in two ways that
compound: the operation that sets it did not exist, and the field that reports
it never reached the wire.
UpdateFileSystemProtection had no route, so the terraform AWS provider's PUT to
/2015-02-01/file-systems/{id}/protection fell through to the S3 handler and came
back as an XML error body, which the SDK reported as "deserialization failed,
invalid character '<'". Every consumer of gruntwork's terraform-aws-data-storage
EFS module hits this rather than only those who opt in, because the module emits
the aws_efs_file_system `protection` block unconditionally.
Separately, protection was never reported. createFileSystem left the field null,
and FileSystem's accessor was named getFileSystemProtectionDescription() -- the
*shape* name. Under UpperCamelCaseStrategy the accessor name is the JSON key, so
even a populated field would have gone out as FileSystemProtectionDescription
rather than the member name FileSystemProtection that FileSystemDescription
actually declares.
So:
- add UpdateFileSystemProtection (PUT .../{FileSystemId}/protection), returning
FileSystemProtectionDescription, 404 for an unknown file system
- default new file systems to ENABLED, which is what AWS documents
- apply that default on read as well, so file systems in a store written before
protection was modelled describe the same as one created today
- rename the accessor to getFileSystemProtection()/setFileSystemProtection()
Authority: efs/2015-02-01/service-2.json -- operations.UpdateFileSystemProtection,
shapes.FileSystemDescription.members.FileSystemProtection.
Verified three ways: EfsIntegrationTest 13/13; a real AWS SDK round trip
(create -> describe reports ENABLED -> update DISABLED -> describe reports
DISABLED), which only passes if the wire names match the model; and
terraform-aws-data-storage/examples/efs, previously FLOCI_UNIMPLEMENTED at
apply, now OK through destroy.
|
||
|
|
14f99a5123 |
feat(ec2): support VPC peering connections (#2654)
* feat(ec2): support VPC peering connections CreateVpcPeeringConnection was entirely unimplemented, returning UnsupportedOperation and blocking all three VPC-peering examples in terraform-aws-vpc (vpc-peering, vpc-peering-cross-accounts, vpc-peering-external). Adds CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, ModifyVpcPeeringConnectionOptions and DeleteVpcPeeringConnection, matching the resources those examples actually use (aws_vpc_peering_connection, aws_vpc_peering_connection_accepter, aws_vpc_peering_connection_options). Connections start pending-acceptance and only move to active via an explicit accept, same as real AWS; Terraform's auto_accept convenience is provider-side, not API-side, so no same-account special-casing is needed here. CreateRoute now also accepts VpcPeeringConnectionId as a target and reports it back on DescribeRouteTables - every one of the three examples routes traffic through the peering connection via aws_route, and without this the provider would see permanent drift on the route resource it just created. * fix(ec2): enforce cross-account peering identity and fix route target bugs Addresses Greptile's 0/5 review of #2654: - AcceptVpcPeeringConnection now resolves the connection across every account's storage partition (findAnyAccountEntry, same pattern as Ec2IpamService's RAM-shared IPAM lookups) and rejects a caller that is not the connection's accepter, instead of only ever finding a connection the accepting account itself created. - DescribeVpcPeeringConnections, ModifyVpcPeeringConnectionOptions and DeleteVpcPeeringConnection get the same cross-account resolution, and Describe now filters to connections visible from the caller's account and region instead of leaking every account's connections in every region. - CreateRoute rejects a VpcPeeringConnectionId combined with another target, matching the existing EgressOnlyInternetGatewayId check. - ReplaceRoute accepts VpcPeeringConnectionId as a target, so a peering route created by CreateRoute can actually be repointed. Adds a cross-account integration test covering acceptance identity, region-scoped visibility, and the two route-target fixes. * fix(ec2): record the actual caller as peering requester, enforce region on mutations Two more issues from Greptile's re-review of #2654: - CreateVpcPeeringConnection recorded requesterVpcInfo.ownerId as the emulator's configured default account rather than the account that actually made the request. A non-default requester could never describe, modify or delete its own connection, while the unrelated default account was treated as the requester and granted those operations. Same fix applied to the accepter-owner fallback when PeerOwnerId is omitted (same-account peering). - AcceptVpcPeeringConnection, ModifyVpcPeeringConnectionOptions and DeleteVpcPeeringConnection now enforce the same regional-visibility invariant Describe already did: an endpoint in a region belonging to neither side of the connection reports it as absent instead of acting on it. Extends the cross-account integration test to cover both: the actual requester managing its own connection while the default account cannot, and mutations issued from an unrelated region being rejected. * fix(ec2): enforce per-endpoint ownership on ModifyVpcPeeringConnectionOptions Greptile's third pass on #2654: a participant that is legitimately part of a connection could still set the *other* side's DNS-resolution option, e.g. the requester setting AccepterPeeringConnectionOptions. AWS scopes each option block to that side's own VPC owner, not to participation in the connection generally. ModifyVpcPeeringConnectionOptions now checks the caller against the specific side's owner for whichever option block(s) the request actually sets, and rejects a cross-endpoint attempt with OperationNotPermitted. Adds a test covering both directions (requester setting the accepter's option and vice versa). * fix(ec2): resolve the peer VPC's real owner instead of trusting PeerOwnerId Greptile's fourth pass on #2654: CreateVpcPeeringConnection recorded the requester-supplied PeerOwnerId as the accepter's identity without checking it against the peer VPC's actual owner. Since AcceptVpcPeeringConnection authorizes against that recorded value, a requester could name another account's real VPC while claiming itself (or anyone) as PeerOwnerId and self-authorize acceptance of a connection it doesn't actually control. The peer VPC is now resolved across every account's partition, same as a peering connection's own id lookup. When it's known locally, that storage partition is authoritative and overrides any conflicting PeerOwnerId; the claim is trusted only for a genuinely external/cross-account peer this store never seeded, where there's nothing to validate against. Adds a test creating the peer VPC under a real "victim" account and confirming the forging account can't accept the connection while the real owner can. * fix(ec2): take the per-connection lock in DeleteVpcPeeringConnection Greptile's fifth pass on #2654: accept and modify already synchronized on lockFor(vpcPeeringConnectionId) before loading and saving the connection, but delete did not take that lock at all. A delete could run between one of those mutations' load and its unconditional save, and that save would resurrect the row delete just removed. Wraps delete's lookup, visibility check, and removal in the same lock. * fix(ec2): surface peeringOptions in VPC peering connection responses CreateVpcPeeringConnection, AcceptVpcPeeringConnection, and DescribeVpcPeeringConnections never echoed the DNS-resolution setting under requesterVpcInfo/accepterVpcInfo, even though it's a real field there in AWS's own examples. ModifyVpcPeeringConnectionOptions stored it correctly, but Terraform's aws_vpc_peering_connection_options resource reads the value back via Describe on every plan, not by re-issuing Modify, so a config setting DNS resolution would show permanent drift. Flagged in review: https://github.com/floci-io/floci/pull/2654#pullrequestreview-5054115075 * fix(ec2): reject a peer VPC named with the wrong PeerRegion CreateVpcPeeringConnection resolved the peer VPC only within the region the requester supplied, and treated a miss as "external peer, trust PeerOwnerId". That left the ownership forgery closed on the previous commit reachable again: name another account's real VPC, point PeerRegion at a region that VPC is not in, and the requester's own claimed PeerOwnerId is recorded unchallenged -- after which AcceptVpcPeeringConnection authorizes the requester against it. Real AWS resolves the peer VPC globally and answers InvalidVpcID.NotFound when the named region is not the one it lives in, so a lookup miss now falls back to trusting PeerOwnerId only when the id is absent from every region. A genuinely external peer VPC -- one this emulator has never seen -- behaves as before. |
||
|
|
b4aab999f7 |
fix(s3): make GetObject atomic against concurrent same-key overwrites (#2874)
* fix(s3): make GetObject atomic against concurrent same-key overwrites
A GetObject racing PutObject overwrites of the same key could return a
torn response assembled from two object versions: Content-Length, ETag,
and checksum headers from one version with body bytes from another.
When the newer body was longer than the advertised Content-Length, the
surplus bytes stayed on the wire and corrupted the keep-alive
connection's HTTP/1.1 framing (clients then log "Unsolicited response
received on idle HTTP channel", and the next request on that pooled
connection breaks). AWS S3 gives a concurrent read exactly one complete
version, never a mix.
Two gaps combined into the tear:
- S3Service.getObject read metadata and data as two unlocked reads,
while writers install them as two separate stores (objectStore, then
writeFile) under the bucket monitor. Take the same monitor around the
read pair so it can never straddle a write.
- S3Controller resolved response headers from a headObject snapshot but
streamed the body lazily at entity-write time via openObjectStream,
re-reading whatever data the key held by then. Serve both the full
and Range responses from the byte[] captured atomically with the
metadata, and fail loudly if a snapshot's data ever disagrees with
its declared size instead of corrupting the response framing.
The website index path now uses getObject so the served snapshot
carries its matching body as well.
Regression test: S3ConcurrentWriteReadTest#
concurrentOverwriteNeverPairsMetadataWithAnotherVersionsBody alternates
two fixed bodies of different lengths under concurrent readers and
asserts every read returns one complete version whose size and ETag
match its bytes. It fails on the previous code within seconds
("declared size=300 but body has 256 bytes") and passes with the fix.
Verified end-to-end with an AWS SDK Go v2 raced GET/PUT reproduction:
torn bodies, CRC checksum mismatches, and unsolicited-response warnings
on floci/floci:1.7.0; zero across 4 runs (~900k reads) on the patched
build. S3 suite: 1070/1070 green.
Change-Id: I4f4dbef49d85e0cdf13aaaca66dc8592db0fbed0
Signed-off-by: Thomas Kosiewski <tk@coder.com>
* fix(s3): serve conditional GETs and website requests from one snapshot
Review follow-ups on the torn-GET fix:
- Conditional GETs evaluated If-Match/If-None-Match/If-(Un)Modified-Since
against a separate headObject fetch and then served a later getObject
snapshot, so an overwrite landing between the two could return a
version the precondition never approved. Preconditions are now
evaluated against the same atomic snapshot that is served, making the
decision and the returned version consistent by construction.
- Website HEAD requests loaded the index document's bytes only to
discard them (headOnlyResponse strips the entity). The website
resolution carries metadata only again; the controller fetches the
atomic metadata+body snapshot just for GET renders, and HEAD builds
its headers without touching the data. Shared response-header
construction is extracted into objectResponseHeaders.
Change-Id: Ia116b6c6886febfde2bdabe3b4e2b4695617ab4f
Signed-off-by: Thomas Kosiewski <tk@coder.com>
---------
Signed-off-by: Thomas Kosiewski <tk@coder.com>
|
||
|
|
46283f3209 | fix(rds-data): fixing empty array response from statement (#2880) | ||
|
|
19013b8b63 |
fix(ecs): apply cluster settings given on CreateCluster (#2845)
handleCreateCluster read clusterName and tags and nothing else, and EcsService.createCluster had no settings parameter, so settings sent at creation were dropped. Real AWS accepts them on CreateCluster itself, not only through UpdateClusterSettings, and handleUpdateClusterSettings two methods away already parses them the right way. The effect was permanent drift for any client that configures a cluster at creation. terraform-provider-aws sends its setting block on create, then reads DescribeClusters back without it and proposes the same change on every plan after apply, forever. Parse settings in the handler the way the update handlers do, and pass them through a new createCluster overload. The existing overloads delegate, so the CloudFormation caller is untouched. Closes #2806 |
||
|
|
90d1a19310 |
fix(elasticache): report transit encryption, not the auth-token flag (#2844)
TransitEncryptionEnabled was serialized as `authMode == PASSWORD` in both the replication-group and the member-cache-cluster views. An auth token does force encryption in transit, but the reverse does not hold: CreateReplicationGroup already accepts TransitEncryptionEnabled=true with no token and records it as AuthMode.IAM, and every read then reported that group as unencrypted in transit. Terraform's aws_elasticache_replication_group reads transit_encryption_enabled back on every plan, so such a group showed permanent drift. DescribeCacheClusters had a second, narrower version of the same problem: AtRestEncryptionEnabled was a hardcoded false on the member view, so it contradicted DescribeReplicationGroups about one group's own storage encryption. It now reports what the group stores, which is the value CreateReplicationGroup already parsed and kept. |
||
|
|
ca4c84c9e0 |
fix(lambda): delete only the named version when DeleteFunction has a Qualifier (#2824)
* fix(lambda): delete only the named version when DeleteFunction has a Qualifier DeleteFunction accepted a Qualifier and dropped it: the controller never bound the query parameter, so every call took the unqualified path and removed the function, $LATEST and every other version. A caller pruning one old version silently lost the whole function, with a success response and no warning. The qualified path now removes that version alone. Error behaviour follows the live service rather than the reference, which documents none of it: deleting $LATEST by qualifier and naming an alias are both InvalidParameterValueException, a version an alias references is a ResourceConflictException, and a version that does not exist is a silent success rather than a 404. Closes #2819 * test(lambda): cover qualified DeleteFunction through the AWS SDK The integration test drives the endpoint over raw HTTP, so nothing exercised the qualified delete through a real SDK client. Adds SDK coverage for the four cases: deleting one version leaves the function and its other versions, $LATEST cannot be deleted by qualifier, a version an alias references is refused, and an absent version is a no-op. * fix(lambda): pattern-validate the DeleteFunction qualifier Character.isDigit accepts non-ASCII decimal digits, so a full-width or Arabic-Indic digit was read as a version number and answered with a silent 204 instead of being rejected. The live service pattern-validates the qualifier before anything else and its constraint is ASCII-only; that check now runs first, and the digit test no longer relies on Character.isDigit. |
||
|
|
7473c57720 |
fix(ses): return DeliveryOptions from v1 DescribeConfigurationSet (#2841)
PutConfigurationSetDeliveryOptions already persisted the TLS policy — v2 GetConfigurationSet returned it correctly — but the v1 projection never read it back, omitting the DeliveryOptions member even when deliveryOptions was named in ConfigurationSetAttributeNames. The Terraform provider reads aws_ses_configuration_set through the v1 DescribeConfigurationSet, so the missing member made every plan re-add a delivery_options block that apply never converged. The two APIs spell the enum differently and the write path already normalises v1 Require/Optional to the stored REQUIRE/OPTIONAL; the read path converts back, so each API answers in its own casing. |
||
|
|
44629631ca |
fix(lambda): honour ListLayers and ListLayerVersions query parameters (#2817)
* fix(lambda): honour ListLayers and ListLayerVersions query parameters CompatibleRuntime, CompatibleArchitecture, MaxItems and Marker were accepted and ignored, and NextMarker was never emitted, so a client paginating with MaxItems saw a single page and silently got the whole list, while a runtime or architecture filter returned layers that do not match it. Both actions now filter, paginate and emit NextMarker. Validation follows the live service rather than the API reference: range and enum failures accumulate into one ValidationException in a fixed member order, a non-integer MaxItems is a SerializationException that short-circuits validation, and a Marker the service did not issue is InvalidParameterValueException "Invalid pagination key.". Under a filter, LatestMatchingVersion is the newest version that matches rather than the newest overall, so ListLayers needs every version of each layer rather than the latest of each. Closes #2808 * fix(lambda): sign layer pagination markers The tag identifying a Marker as Floci's was a fixed string, so a caller could base64 a cursor of their own with the same prefix and have it accepted. That cursor was then applied to the page, silently skipping results or emptying the list where AWS rejects an unissued token. Markers now carry an HMAC over the cursor, keyed per process, so a fabricated or edited token fails the check. A marker from an earlier run is stale for the same reason, which is what AWS does with an expired one. * test(lambda): cover layer listing parameters through the AWS SDK AGENTS.md prefers SDK clients over raw HTTP for management-plane validation. The integration test covers the parameters through the wire protocol; this adds the same filtering, pagination and enum rejection through @aws-sdk/client-lambda, so a marshalling regression that only the SDK would notice does not pass unseen. |
||
|
|
afe26c6ad1 |
fix(elb): route Classic (v1) requests to a dedicated handler instead of ELBv2 (#2619)
* feat(elb): implement Classic (v1) Elastic Load Balancing Classic ELB (2012-06-01) and ELBv2 (2015-12-01) share an endpoint host and an `elasticloadbalancing` credential scope, but they are different APIs. Every Classic request was reaching the ELBv2 handler, which rejected a well-formed one with `ValidationError: Name is required for load balancer.` — because the name arrived as `LoadBalancerName`, the Classic parameter — and answered a request that guessed `Name` with an ALB object in the 2015-12-01 namespace, a shape Classic has no concept of. Route on the API version. Every Query-protocol request carries the version it speaks as the `Version` form parameter, and both service models declare it, so that is the discriminator: 2012-06-01 to the new Classic handler, 2015-12-01 to ELBv2. This is the same in-case split the `rds` scope already uses to separate RDS, Neptune and DocumentDB. Requests that omit `Version` fall back to their parameter shape — an action unique to one API, else `LoadBalancerName` / `LoadBalancerNames` selecting Classic, else ELBv2 as before. Classic state is its own model, not the v2 one: keyed by name, no ARN, listeners inline, and one structured attribute record. Responses follow the 2012-06-01 model's wrapper and element names — `CreateLoadBalancerResult` carries `DNSName` and nothing else. Scope is what the AWS provider drives for `aws_elb` and for an Auto Scaling group attached to one: Create/Delete/DescribeLoadBalancers, the listener operations, ConfigureHealthCheck, Register/DeregisterInstances, DescribeInstanceHealth, Modify/DescribeLoadBalancerAttributes, the subnet, availability-zone and security-group operations, and tagging. The stickiness and backend-server policy operations, and SetLoadBalancerListenerSSLCertificate, answer `UnsupportedOperation` in the 2012-06-01 namespace rather than a fabricated result. There is no Classic data plane: listener ports are recorded but no socket is opened. Health is checked per instance from the single `HealthCheck.Target` string — `HTTP:`/`HTTPS:` probed with a request, `TCP:`/`SSL:` by connecting — with the same counters and thresholds ElbV2HealthChecker uses. An ASG naming Classic load balancers in `LoadBalancerNames` now registers and deregisters its instances with them, so a `min_elb_capacity` wait can be satisfied. * docs(elb): register ElbClassicQueryHandler in services.yaml Unblocks 'make docs-check', which fails on rebase without this — the handler was never registered when the Classic ELB feature landed. * fix(elb): register ElbClassicService for native init, deregister stale ASG instances from Classic ELBs ElbClassicService's SecureRandom field wasn't declared under --initialize-at-run-time, which fails GraalVM native image builds (image-heap Random instances have cached seeds). Registers it alongside the other services/*.Service entries in application.yml. Also closes a gap Greptile flagged: removeStaleInstances() pruned an ASG's dead instance references without deregistering them from target groups or named Classic load balancers first, unlike the terminating- and scale-in paths, leaving orphaned registrations visible through DescribeLoadBalancers/DescribeInstanceHealth. * fix(elb): return the documented 409 for a Classic multi-VPC subnet set CreateLoadBalancer's own Errors table puts InvalidConfigurationRequest at HTTP 409; the Classic path raised it at 400. The error code was already right, so a client that retries on 409 but fails hard on 400 got the wrong signal from the one place the two can be told apart. Covered by a unit test that asserts the status, not just the code. Also from review: the empty-Listeners ValidationError carried a message copied from an unrelated subnet/AZ check, and the new cross-reference to the Classic docs page split elb.md's opening sentence mid-paragraph instead of following it. |
||
|
|
a7b2b79492 |
fix(lambda): honour Publish on CreateFunction and UpdateFunctionCode (#2825)
The Publish flag was never read on either path, so no version was ever created unless the caller made a separate PublishVersion call, and both actions reported Version as $LATEST. Terraform reads Version and qualified_arn straight from that response, so every aws_lambda_function with publish = true recorded $LATEST — which Lambda@Edge cannot use. Both actions now publish and report the new version. The ARN they return differs, following the live service rather than the reference, which does not distinguish them: CreateFunction keeps the unqualified FunctionArn while UpdateFunctionCode returns the qualified one, as PublishVersion does. Closes #2820 |
||
|
|
3aaf74520e |
fix(cognito): enforce user pool password policies (#2070)
* fix(cognito): enforce user pool password policies Closes #2066 * fix(cognito): close remaining password-policy review gaps on #2066 Addresses the three items left open on this PR's review: - Password reuse now raises PasswordHistoryPolicyViolationException instead of InvalidPasswordException, matching the shape AWS declares for it on AdminSetUserPassword, ChangePassword, ConfirmForgotPassword, RespondToAuthChallenge and AdminRespondToAuthChallenge (all funnel through updateUserPassword here). - Fixed the off-by-one in PasswordHistorySize: AWS counts the current password as one of the n, so only n-1 prior passwords are blocked alongside it, not n. Both the check and what gets retained in history are corrected together. - adminResetUserPassword no longer bypasses PasswordHistorySize: it now archives the outgoing password hash before clearing it, the same way an ordinary password update does. - CreateUserPool now fills in AWS's per-field password policy defaults (MinimumLength 8, all four character-class requirements, Temporary- PasswordValidityDays 7) for any field left unset in a supplied PasswordPolicy. Deliberately scoped to a policy that is present but partial, not to a pool with no PasswordPolicy at all -- every other pool-creating test in this codebase relies on that meaning no validation, and defaulting one into existence would enforce it on all of them retroactively. The broader "no Policies at all" case stays a separate follow-up. New tests: passwordHistoryCountsTheCurrentPasswordAsOneOfN, adminResetUserPasswordDoesNotBypassPasswordHistory, createUserPoolDefaultsAnUnsetMinimumLengthToEight. Updated passwordHistoryRejectsARecentlyUsedPassword's assertion for the new exception code, and createUserPoolWithFullConfig's expectation for the normalized policy shape. * fix(cognito): stop admin reset from shrinking the password-history window greptile caught a real bug in the previous commit: updatePasswordHistory always capped retained history at PasswordHistorySize - 1, on the assumption that a current password always occupies one of the n slots. That's true for an ordinary password change, but not for adminResetUserPassword, which clears the current password without replacing it -- so capping at n-1 there dropped the oldest still- protected entry a reset alone should not age out. Both updatePasswordHistory and validatePasswordAgainstPolicy now check whether a current password hash exists at the moment they run (the mutation callers apply before archiving/checking) to decide whether n or n-1 entries are live. adminResetUserPassword is reordered so the hash is actually cleared before archival runs, matching what the check now expects. New test: adminResetUserPasswordDoesNotShortenTheHistoryWindow, which pins the exact PasswordHistorySize: 2 / three-password / reset scenario greptile's finding described, including that the window correctly shrinks back to n-1 once a new password re-occupies the current slot. --------- Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> |
||
|
|
62dbd9ddf9 | fix(apigateway): report RestApi as available (#2816) | ||
|
|
968ff78e25 |
fix(lambda): make the code-volume populate concurrency configurable (#2830)
Concurrent first-time code-volume populates are capped by a semaphore sized Math.max(2, availableProcessors() / 2). The JVM honours the container's cgroup CPU quota, so a CPU-constrained Floci container derives 2 permits and concurrent cold starts of *distinct* large functions complete in waves of two instead of in parallel. Measured on main, six distinct functions with 41MB packages, all cold, fired concurrently, varying only the quota on Floci's own container: unlimited (16 cpu) -> 8 permits -> one wave of 6 -> 8.3s --cpus=8 -> 4 permits -> waves of 4, 2 -> 13.2s --cpus=4 -> 2 permits -> waves of 2,2,2 -> 19.2s The wave sizes track the formula exactly, which rules out generic CPU starvation - that would slow all six uniformly rather than produce discrete equal-size waves. The populate is IO-bound (creating a helper container and streaming a tar into it), so CPU count is a weak proxy for how many the Docker daemon can absorb. The cap itself is still worth having: the daemon overload it was added to prevent is real. What was missing is a way to decouple it from the CPU allocation, so this adds floci.services.lambda.code-volume-populate-concurrency (FLOCI_SERVICES_LAMBDA_CODE_VOLUME_POPULATE_CONCURRENCY) and leaves the derived default untouched. Values below 1 fall back to the derived default with a warning: zero permits would deadlock every populate, and a negative Semaphore count would make acquire() block until that many releases arrived. The semaphore becomes an instance field so the permit count can come from config. Floci runs a single @ApplicationScoped launcher, so it is still one gate for the whole emulator. Refs #2050 |
||
|
|
63a2a60a30 |
fix(stepfunctions): let a mocked response with no attempts start the execution (#2823)
A MockedResponses entry with no attempt keys was rejected at StartExecution, so a generated mock file failed the whole execution when the collection it was built from was empty. Step Functions Local starts the execution and fails it with States.Runtime only when the state that names the entry is entered. An empty entry is a lookup that finds nothing, not a malformed entry. Floci already accepts a mock that defines attempt 1 but not attempt 0 and fails the same way at run time. Every other malformed entry keeps its 400 at StartExecution, which stays stricter than Step Functions Local. Verified against amazon/aws-stepfunctions-local:2.0.0. Refs #2523 |
||
|
|
b0fe8311a0 |
feat(ses): support v2 tenant-scoped sending with association gate (#2815)
* feat(ses): support v2 tenant-scoped sending with association gate * fix(ses): guard tenantForSending against a null TenantName and pin the raw-test charset * fix(ses): validate an inline bulk template before the tenant gate |
||
|
|
5b363ffa2d |
fix(lambda): implement GetLayerVersionByArn (#2812)
* fix(lambda): implement GetLayerVersionByArn
GET /2018-10-31/layers?find=LayerVersion&Arn={arn} is GetLayerVersionByArn,
but only ListLayers was bound to that path and it ignored both query
parameters. A GetLayerVersionByArn call was therefore answered with a
ListLayers body and HTTP 200: an SDK deserialises that against the
GetLayerVersionByArn output shape, finds none of its members, and hands the
caller an empty result instead of the layer version or a
ResourceNotFoundException.
AWS gives the two actions the same method and path, discriminated only by
`find`, and JAX-RS cannot route on a query parameter, so the branch lives in
the handler.
The semantics below were measured against the live service rather than
inferred from the reference:
find=LayerVersion&Arn=<present> 200 + LayerVersion object
find=LayerVersion&Arn=<absent> 404 ResourceNotFoundException
find=LayerVersion, no Arn 400 ValidationException, must not be null
find=LayerVersion&Arn=junk 400 ValidationException, pattern in message
find=Nonsense 200 + ListLayers body
find=layerversion 200 + ListLayers body (match is case-sensitive)
The Arn pattern enforced here is the one the live service reports in its own
ValidationException, not the one the API reference publishes: it constrains
the region segment more tightly and additionally accepts the AWS-managed
arn:<partition>:lambda:::awslayer:<name> form, which the reference omits.
The response reuses the builder GetLayerVersion already returns, and resolves
Content.Location against the layer's own region rather than the caller's,
matching the lookup resolveLayerByArn already keys on.
* fix(lambda): scope GetLayerVersionByArn to the caller's account
resolveLayerByArn keys on region, layer name and version. Storage is already
partitioned per account, so that lookup runs inside the caller's own partition
— an ARN naming a different account did not reach that account's layers, but it
did resolve to the caller's own same-named layer and return it.
Measured on main, without this action: account B publishes
arn:...:111111111111:layer:acct-probe:1, then calls CreateFunction with
Layers=[arn:...:000000000000:layer:acct-probe:1]. The call succeeds and the
function records account A's ARN while B's own layer is what resolves. Account
B never sees account A's layer — GetLayerVersion by name and ListLayers both
return nothing for it — so this is a wrong-resource answer, not a cross-account
read.
GetLayerVersionByArn is the one layer action that takes an account explicitly,
so it honours it: an ARN outside the caller's account is a 404, which is what
the caller already gets from GetLayerVersion for a layer it cannot see. No
layer can be shared cross-account here — layer permissions are unimplemented —
so a foreign account is always a miss, and the check is the place sharing would
hook in if that changes.
The same account-blindness reaches CreateFunction and UpdateFunctionConfiguration
through validateLayersResolvable, and the container launcher through the same
resolver. Those are pre-existing on main and change behaviour for existing
actions, so they are left for a separate change rather than folded in here.
* fix(lambda): reject a layer ARN naming another partition
The account guard compared only the account, and resolveLayerByArn drops
the partition as well as the account, so an ARN in another accepted
partition with the same account, region, name and version resolved to
the caller's local layer and was returned under the foreign-partition
ARN. The live service rejects those outright with
InvalidParameterValueException.
|
||
|
|
426fbcb284 |
feat/redshift auth proxy (#2751)
* feat(redshift): add auth proxy port range and endpoint-host config * feat(redshift): add containerHost/containerPort/proxyPort to Cluster model * feat(redshift): add RedshiftAuthProxy reusing the RDS PostgreSQL protocol handler * feat(redshift): add RedshiftProxyManager registry with shutdown hook * feat(redshift): front new clusters with an auth proxy and advertise it * feat(redshift): stop/update proxy on delete/modify, start it on snapshot restore * feat(redshift): keep proxy port stable across reboot and adopt-on-startup * test(redshift): integration coverage for JDBC through the auth proxy * test(redshift): reinstate JDBC connectivity check now that the proxy exists * docs(redshift): document the cluster auth proxy and its config * fix(redshift): prevent minor port leak when proxy fails to start * fix(redshift): rollback container on proxy failure and surface teardown errors * fix(redshift): stop auth proxy on rollback to prevent listener collisions * fix(redshift): ensure proxy shutdown failure does not abort container and port cleanup * fix(redshift): add proper logging for intentionally ignored cleanup exceptions * fix: Wait for Redshift database readiness before proxying Previously, RedshiftContainerManager just slept for 3 seconds before marking the container as started. On slower CI environments, the PostgreSQL database might take longer to initialize, resulting in Connection Refused when the RedshiftAuthProxy forwards connections. Now, RedshiftContainerManager polls the database using psql until it's ready, up to 60 seconds. * fix(redshift): prevent proxy port reallocation on shutdown failure Addresses a review comment indicating that if a Redshift auth proxy fails to shut down during rollback or deletion, its port must not be released into the available pool. Reassigning a still-bound port would cause subsequent cluster creations to fail with a BindException. Instead, we now tolerate proxy shutdown errors but intentionally leak the port allocation to prevent collisions. * fix(redshift): fix failing tests due to proxy changes 1. RedshiftOperationsTest checked for a hardcoded port 5440, but the RedshiftService now allocates dynamic proxy ports. Removed the exact port assertion. 2. RedshiftContainerManager's psql readiness check was connecting via local Unix socket, which succeeded before PostgreSQL was actually ready to accept remote TCP connections from the proxy. Added '-h 127.0.0.1' to enforce TCP readiness. * test(redshift): use Awaitility to connect to proxy Use Awaitility to retry the initial connection in RedshiftProxyIntegrationTest to prevent transient 'Connection attempt failed' errors on slower CI environments. * chore(redshift): use proper imports instead of fully-qualified class names in tests * fix(redshift): fix compiler errors introduced during import cleanup * fix(redshift): resolve proxy lifecycle bugs and CI network issues - Throw RuntimeException from RedshiftProxyManager.stopProxy if proxy is not found. This allows RedshiftService to catch it and intentionally leak the port, preventing port collisions if a proxy fails before registration. - Force RedshiftProxyIntegrationTest to connect via 127.0.0.1 instead of the endpoint address, which resolves to host.docker.internal in CI environments and causes UnknownHostException. * fix(redshift): prevent proxy port exhaustion on startup failures Instead of blindly assuming missing proxies denote a leaked port, RedshiftProxyManager now tracks proxies that failed their socket cleanup during startup. stopProxy throws an exception only if the socket is known to be leaked. This allows RedshiftService to safely release ports after clean proxy startup failures, addressing Greptile's feedback about port exhaustion. * fix(redshift): retain proxy reference to allow retry on close failure As identified by Greptile, stopProxy previously removed the proxy from the registry before calling proxy.stop(). If stop() threw an exception, the proxy reference was lost, preventing any subsequent retry from ever finding it and attempting to close it again. stopProxy now only removes the proxy from the registry after stop() returns successfully. Additionally, failedCleanups is now retained instead of cleared, ensuring retries continue to safely leak the port if cleanup remains impossible. * fix(redshift): abort cluster deletion if proxy fails to stop As highlighted by Greptile, previously deleteCluster would swallow proxy shutdown failures and delete the cluster metadata anyway. This eliminated the retry path, stranding the unclosed proxy and its port reservation until the process exited. Now, if stopProxyAndReleasePortSafely fails, deleteCluster throws an exception to preserve the cluster metadata so the deletion can be retried. * test(redshift): lock in proxy lifecycle failure-recovery behaviors Bổ sung test cho ba hành vi hardening chưa được cover, để refactor sau không âm thầm phá vỡ: - stopProxy giữ lại proxy trong registry khi close() ném, cho phép retry gọi lại đúng instance và chỉ deregister sau khi stop sạch - marker leak khi startup cleanup thất bại được retain qua mọi retry và chỉ bị xoá bởi một lần start mới thành công - deleteCluster abort với InternalFailure, giữ nguyên container + metadata khi proxy không stop được; retry sau đó hoàn tất khi proxy stop OK Đồng thời bỏ "-p 7100-7199:7100-7199" trong compatibility.yml: proxy bind 0.0.0.0 trong container floci và sdk-test-java chạy trên compat-net nên JDBC đi container-to-container qua alias "floci", không cần publish port ra host. Giữ lại FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST=floci. * fix(redshift): keep an unclosable proxy reachable for later retry Theo phản hồi mới của Greptile: khi start/replace proxy thất bại và cleanupFailedStart cũng không đóng được listener, code cũ chỉ lưu relayKey vào một Set rồi vứt object RedshiftAuthProxy. stopProxy sau đó ném vĩnh viễn mà không còn cách nào chạm tới listener để thử đóng lại, khiến cluster không xoá được và port bị giữ mãi trong dải hữu hạn. Thay Set<String> failedCleanups bằng Map<String, RedshiftAuthProxy> unclosableProxies. cleanupFailedStart giữ lại chính proxy đó; stopProxy và stopAll thử đóng lại, chỉ gỡ entry khi stop thành công. startProxy không còn xoá marker khi start mới — chỉ một lần stop thành công mới gỡ, vì listener cũ có thể vẫn đang bound. * fix(redshift): retry proxy port bind to absorb reboot rebind race rebootCluster giữ nguyên proxy port của cluster để endpoint ổn định, nên listener cũ bị đóng rồi bind lại đúng port đó chỉ vài ms sau. Dưới tải (CI runner ARM) kernel có thể chưa nhả port và SO_REUSEADDR không giúp được khi accept loop cũ đang teardown -> BindException -> RebootCluster trả 500. Đây là nguyên nhân test RedshiftOperationsTest. testClusterAndSnapshotLifecycle fail chập chờn. start() giờ retry bind tối đa ~1s, chỉ nuốt BindException; IOException khác vẫn propagate ngay. Thêm test dựng cảnh port bị chiếm tạm thời rồi nhả, xác nhận proxy vẫn bind được. * fix(redshift): tear down proxy and release port when rebootCluster fails Nếu startProxy/restoreSnapshot ném sau khi proxy đã (re)start trong rebootCluster, hai nhánh catch chỉ set status "failed" rồi rethrow — proxy mới vẫn chạy và port vẫn nằm trong usedPorts, không nhánh nào dọn. Giờ cả hai catch gọi stopProxyAndReleasePortSafely như createCluster và restoreFromClusterSnapshot đã làm; proxyPort được hoist ra ngoài try với sentinel -1 để rollback an toàn kể cả khi chưa cấp port. Thêm test: restoreSnapshot ném -> proxy được stop lại, AwsException nổi lên. * fix(redshift): serialize createCluster/deleteCluster/restoreFromClusterSnapshot modifyCluster và rebootCluster đã synchronized nhưng create/delete/restore thì không, dù cả năm method đều chạy chuỗi container + proxy + port nhiều bước trên cùng một cluster. deleteCluster(x) chạy song song rebootCluster(x) có thể để lại metadata mồ côi trỏ tới container/proxy đã dừng. Thêm synchronized cho ba method còn lại để nhất quán. * fix(rds,redshift): close backend socket when the auth handshake fails handleConnection mở kết nối TCP tới container Postgres trước khi gọi handleAuth. Chỉ nhánh thành công (bridge) và vài nhánh lỗi có kiểm soát mới đóng backend; nếu handleAuth trả về sớm ở một probe trần (SSLRequest không kèm startup) hoặc ném IOException (client ngắt giữa handshake), catch cũ chỉ đóng client -> mỗi health-check TCP làm rò một connection tới Postgres, ăn dần max_connections. Chuyển việc đóng socket sang finally, đóng cả client lẫn backend (idempotent, nhánh thành công đã đóng sẵn). Áp cho cả RdsAuthProxy vì RedshiftAuthProxy được copy từ đó. Thêm test: client drop giữa handshake -> backend nhận EOF. * fix(redshift): stop replacement container and keep dump on failed reboot Rollback của rebootCluster (b44fd1e3) mới chỉ stop proxy + release port, để container thay thế chạy tiếp sau một cluster "failed", và finally vẫn xoá tempDump. Vì container gốc đã stop và không có volume, tempDump là bản sao duy nhất của data -> mất data không khôi phục được (bug có sẵn, giờ mới lộ). rollbackReboot() giờ stop luôn container thay thế (như createCluster/ restoreFromClusterSnapshot). tempDump chỉ bị xoá khi reboot thành công; khi fail thì giữ lại và log đường dẫn để khôi phục thủ công. * fix(redshift): make reboot rollback phase-aware to protect the original Commit trước cho rollbackReboot stop container vô điều kiện. Nếu reboot fail ngay ở takeSnapshot hoặc stopProxy — lúc container gốc (chứa data, không volume) VẪN đang chạy — thì rollback lại force-remove chính nó, huỷ bản sao data hoàn chỉnh duy nhất và chỉ còn dump rỗng/dở. Thêm hai cờ: - originalTornDown: đã stop proxy + container gốc -> rollback mới được đụng vào proxy/port - replacementStarted: đã start container thay thế -> rollback mới được stop container Fail trước hai mốc đó: không đụng gì, trạng thái gốc còn nguyên. Thêm test: takeSnapshot ném -> cm.stop và stopProxy không được gọi. * fix(redshift): clean an orphan replacement container on failed reboot containerManager.start có thể tạo container Docker rồi mới ném ở waitForReady, nên cờ replacementStarted (set sau khi start return) bỏ sót trường hợp này -> orphan chạy dưới tên cluster. Bỏ replacementStarted, gate rollback theo mỗi originalTornDown: một khi proxy + container gốc đã stop thì container gốc chắc chắn biến mất, nên containerManager.stop (xoá theo tên) chỉ có thể chạm replacement — kể cả replacement do start() tạo dở rồi ném. Thêm test: start() ném -> rollback vẫn gọi cm.stop để dọn orphan. * fix(redshift): remove orphan cluster metadata on failed create/restore * fix(redshift): keep failed cluster metadata if proxy stop fails * fix(redshift): fix TooManyActualInvocations in proxy tests * fix(redshift): clear proxyPort on reboot rollback if port is released * fix(redshift): retain reserved port on reboot startup failure * fix(redshift): retain proxy port in reboot rollback and teardown failed startup recovery * fix(redshift): skip failing cluster and retaining dump if reboot fails before teardown |
||
|
|
f7f16cd2a3 |
fix(stepfunctions): bound $range allocation at the AWS memory limit (#2790)
* fix(stepfunctions): open a JSONata query evaluation cause with the AWS sentence evaluateField now wraps a thrown JSONata failure with "The JSONata expression '<expr>' specified for the field '<field>' threw an error during evaluation" before the existing tail, matching real AWS. The separator is ". " when the tail carries a JSONata error code and ": " when it is a bound message with none. evaluate() keeps producing the bare tail unchanged for its direct callers. evaluate() stays the only place the JSONata engine is called and the only catch around it: evaluateField calls it and enriches the failure it throws, rather than reaching the engine itself. QueryEvaluationFailure carries the separator across that throw, so a catch added to evaluate() later covers both entry points. All 11 AslExecutor call sites reach the evaluator through evaluateField or resolveTemplate, so a catch installed anywhere else would be dead on every real execution path. * fix(stepfunctions): catch Error from JSONata evaluation as States.QueryEvaluationError An OutOfMemoryError or StackOverflowError raised while parsing or evaluating a JSONata expression escaped JsonataEvaluator's catch (Exception) and reached AslExecutor's own last-resort catch (Error), failing the whole execution as States.Runtime before the state's own Retry and Catch ever ran. JsonataEvaluator.evaluate now also catches Error at the same seam and translates it into a FailStateException with States.QueryEvaluationError, so a Catch on the state (or on States.ALL) can recover, matching real AWS. Closes #2738 * fix(stepfunctions): match AWS on the JSONata expressions it refuses Four expression classes where Floci and AWS disagreed on whether the state fails at all, all measured against us-east-1 with test-state. The evaluation-depth ceiling drops from 500 to 100, which is AWS's own: five nesting shapes bisected one n at a time all put its last accepted evaluation at depth 100 and its first refusal at 101. An addition chain nests one level per term and AWS accepts 100 terms; parentheses, brackets and the chain operator nest one level more than their count and AWS accepts 99 of each; a non-tail-recursive $f(n) nests 3n+5 and AWS accepts n=31, depth 98, refusing n=32, depth 101. The memory an expression may hold is now bounded, which it was not: one value an evaluation step produces may hold 6,990,256 bytes, counting a number as eight and a character as one. The two shapes AWS was bisected on, [1..873782] and a string doubled 22 times, bracket a number at between five and nine bytes a character: with the bound at 873,782 numbers, anything in that range leaves 4,194,304 characters inside it and 8,388,608 outside, and four or ten does not. Eight is what a double costs, and it is inside the bracket. The check walks the value and stops at the bound, and a lazy range is counted from its length rather than materialised. $eval is unbound, as AWS disables it, so a call to it answers T1006 the way AWS does and $parse stays the replacement. A non-finite number the expression itself evaluates to comes back as the string AWS writes for it, since JSON has no literal for one: 1/0 and 1e308*10 are "Infinity" and $parseInteger("abc","0") is "NaN", where the first two raised D1001 and the third returned nothing and failed the field. One the library's arithmetic buries inside a value, as in [1/0], still fails the state, because the refusal is the only place the library leaves the value and it has already unwound what was being built; one a function answers nests like any other value. $formatNumber checks its picture string against the fourteen rules of XPath F&O 4.7.3 first, so $formatNumber(1, "x") fails with D3086 instead of answering "x1". Which of the fourteen codes AWS reports is what fixes the order the rules are read in: a picture with no digit breaks D3085 and D3086 at once and AWS reports the second, so the last rule broken names the failure rather than the first. Closes #2737 * fix(stepfunctions): bound $range allocation at the AWS memory limit AWS accepts $range(1, 360145, 1), all 360,145 elements, and refuses one element more on its own memory limit. Floci's $range had no such bound: it built the array in full before the memory check on the value ever ran, so a call far past AWS's limit spent gigabytes and either exhausted the heap or hung instead of failing the state cleanly. range() now refuses a call whose produced element count exceeds the measured bound before allocating, throwing the same States.QueryEvaluationError JException the held-memory check raises, whose message is now a single shared constant. Other built arrays keep the looser, byte-based bound. * test(stepfunctions): pin the number model of the execution input Measured against real AWS (test-state, 2026-08-30): a Pass state with Output {"v": "{% $states.input.amount %}"} answers {"v": 1} for input {"amount": 1.0} and {"v": 9.223372036854776E18} for input {"amount": 9223372036854775808}. That is exactly what routing the execution input through toJsonataValue/toJsonataNumber already produces, so these two tests pin it against silent regression. --------- Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |
||
|
|
ead70eae4d |
fix(stepfunctions): refuse the definitions AWS refuses, at both validation entry points (#2786)
* fix(stepfunctions): reject definitions with no terminal state, dangling targets or unsupported fields Enforce the ASL rules AWS applies at both ValidateStateMachineDefinition and CreateStateMachine: a workflow needs a terminal state (MISSING_END_STATE, top-level only, suppressing the unreachable-state reachability check but not a dangling-target check), every reachable state and every Next/Choices[].Next/Default/Catch[].Next target must exist (MISSING_TRANSITION_TARGET), recursing into ItemProcessor and Branches with structured paths, and TimeoutSeconds/Catch/Retry are refused outside the state types that support them (SCHEMA_VALIDATION_FAILED, "Field '<name>' is not supported"). CreateStateMachine's wire message always renders " at <location>", printing the literal "null" when there is none, matching AWS exactly; ValidateStateMachineDefinition keeps omitting the location field entirely when null, which is the correct, unchanged behavior for that API. Remove the now-dead Parallel TimeoutSeconds handling in AslExecutor: no definition carrying that field can reach execution anymore. * fix(stepfunctions): reject JSONata expressions that do not parse at definition time Report INVALID_JSONATA_EXPRESSION when a JSONata expression fails to parse, using the parser's own message with its S0xxx code prefix stripped, at the field's location. Also report UNSUPPORTED_JSONATA_EXPRESSION for '$$' and for '$states.errorOutput' outside a Catch entry's own Output or Assign. Previously these were accepted at ValidateStateMachineDefinition and CreateStateMachine time and only failed later, at execution, with States.QueryEvaluationError. Every message asserted was measured against real AWS us-east-1 with `aws stepfunctions validate-state-machine-definition`, including `phone %.other` and the empty expression, which AWS also refuses. The three booleans the definition walk threaded through every recursive call (insidePayload, isCatchEntry, insideCatchOutputOrAssign) travel as a single JsonataScope value, which drops collectTopLevelReferences back under the Sonar S3776 limit. --------- Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |
||
|
|
9f7b7117f1 |
refactor(cloudformation): move AWS::SNS::* into its own provisioner (#2759)
Migrates AWS::SNS::Topic and AWS::SNS::Subscription out of the switch, completing the Wave 1 leaf slices. Behaviour-preserving. The care here is the subscription's attribute encoding. FilterPolicy and RedrivePolicy are JSON documents that SNS expects as JSON strings, so they go through resolveJsonAttribute, while FilterPolicyScope and RawMessageDelivery are scalars that go through resolve. Using the scalar resolver on a document flattens it to an empty string and silently breaks message filtering, which is the failure this type has had before, so the test stubs the two resolvers with distinct semantics and asserts the serialized form rather than only that an attribute was set. The topic's physical id is the ARN rather than the name, because Ref on an SNS topic returns the ARN. |
||
|
|
6f123e83b8 | feat(batch): add update and delete job queue endpoints with corresponding service logic (#2807) | ||
|
|
2d724d15aa |
refactor(cloudformation): move Kinesis and CloudWatch to their own provisioners (#2758)
Migrates AWS::Kinesis::Stream and AWS::CloudWatch::Alarm out of the switch. Two unrelated services in one slice because each is a single service call with property mapping and no shared state; splitting them would cost two review cycles for one mechanical change. Kinesis carries an update path: an unchanged name reconciles stream mode, retention and tags rather than calling createStream again, which the service rejects with ResourceInUseException. It uses ctx.priorPhysicalId() for the same reason the log group slice does, since the body assigns the new id before it returns. sameNameExistingResource, deleteRenamedResource and parseIntProp are copied rather than shared: each still has callers in the monolith. addAlarmActions moves, since all three of its call sites are inside the alarm body. Both service fields leave the monolith; their constructor parameters stay until the endgame. The existing Kinesis and CloudWatch alarm integration tests are QuarkusTests resolved through CDI, so they exercise the new provisioners with no edit, which is the regression evidence for this slice. |
||
|
|
1d81cdd0d2 |
refactor(cloudformation): move AWS::Logs::LogGroup into its own provisioner (#2756)
* refactor(cloudformation): move AWS::S3::* into its own provisioner (#2754) Migrates AWS::S3::Bucket and AWS::S3::BucketPolicy out of the switch. Behaviour-preserving: bodies are ported verbatim apart from the mechanical rewrites onto ProvisionContext, so the bucket name, the five Fn::GetAtt attributes and the CORS XML are unchanged. The CORS and versioning helpers move with the slice; all four of appendCorsRuleElements' call sites are inside applyBucketCorsConfiguration, so nothing is left behind. Unlike the leaf slice, s3Service stays on the monolith: Lambda code from an S3 location and the ApiGatewayV2 OpenAPI body both still read through it. Only the two switch arms and the provisioning methods leave. Delete keeps its shape. A bucket policy has nothing to remove, and a non-empty bucket still raises BucketNotEmpty so the stack reports DELETE_FAILED as AWS does, rather than reporting a clean delete. * refactor(cloudformation): move AWS::Logs::LogGroup into its own provisioner Behaviour-preserving move of the log group's provision and delete paths. Unlike the earlier slices this one carries a real update path: the body decides between reconciling in place and replacing, from the prior physical id and the recorded FlociLogGroupNameMode, and it infers that mode from the physical id's shape for stacks persisted before the attribute existed. Uses ctx.priorPhysicalId() rather than reading it back off the StackResource. The two are equal on entry, but the method assigns the new physical id before it finishes, so a context-captured value cannot be invalidated by a later edit to the body. UPDATE_ROLLBACK_RESTORED_ATTR moves to CfnRollback, which exists for exactly this: it was package-private on the monolith and so unreachable from the provisioners package. The monolith's constant now delegates there, leaving CloudFormationService's two references untouched. reconcileLogGroup moves with the slice. isGeneratedName and its prefix helper are copied, because a type that has not migrated yet still calls them, and logsService leaves the monolith entirely. CloudFormationLogGroupProvisionerTest keeps testing through the dispatcher, now with the provisioner registered. That is load-bearing rather than decoration: with an empty registry the type would reach the stub arm and the test would assert against a synthetic id. Going through the dispatcher also covers the plumbing this migration changed, that existingPhysicalId and existingAttributes reach ProvisionContext. |
||
|
|
8034c13106 |
refactor(cloudformation): move AWS::S3::* into its own provisioner (#2754) (#2794)
Migrates AWS::S3::Bucket and AWS::S3::BucketPolicy out of the switch. Behaviour-preserving: bodies are ported verbatim apart from the mechanical rewrites onto ProvisionContext, so the bucket name, the five Fn::GetAtt attributes and the CORS XML are unchanged. The CORS and versioning helpers move with the slice; all four of appendCorsRuleElements' call sites are inside applyBucketCorsConfiguration, so nothing is left behind. Unlike the leaf slice, s3Service stays on the monolith: Lambda code from an S3 location and the ApiGatewayV2 OpenAPI body both still read through it. Only the two switch arms and the provisioning methods leave. Delete keeps its shape. A bucket policy has nothing to remove, and a non-empty bucket still raises BucketNotEmpty so the stack reports DELETE_FAILED as AWS does, rather than reporting a clean delete. |
||
|
|
26ae4ef78a |
fix(ec2): honour documented Describe* filters and stop ENIs inheriting instance tags (#2747)
* fix(ec2): honour documented Describe* filters and stop ENIs inheriting instance tags Six Describe* calls silently ignored documented filter inputs, each an instance of the same bug shape: an unhandled filter name fell through matchesFilter's default -> true arm (or, for DescribeAddresses, the filters parameter was never applied at all), so a filtered call returned the same unfiltered list as no filter - and Volumes[0]/Vpcs[0] reads depended on iteration order instead of the filter. - DescribeSecurityGroups: description - DescribeVpcs: cidr-block alias for cidr (verified against live AWS 2026-08-25: accepted, primary CIDR only) - DescribeVpcEndpoints: vpc-endpoint-state (renamed from the undocumented "state" key; no evidence AWS accepts "state") - DescribeVolumes: attachment.instance-id/device/status/ delete-on-termination - DescribeInstances: image-id - DescribeAddresses: all documented filters this store can back, plus the generic tag: family Also stops DescribeNetworkInterfaces copying the attached instance's tags into an interface's tagSet: an ENI's tags are its own, and AWS tags launch-created interfaces only via a RunInstances TagSpecification with ResourceType=network-interface, which RunInstances now honours. * fix(ec2): filter addresses on refreshed association state and classify eni- ids in DescribeTags DescribeAddresses now re-resolves an associated address before the filter pass, so a public-ip filter is judged against the address the response carries rather than the one persisted before an instance restart. And inferResourceType learns the eni- prefix, so a launch-time network-interface tag shows up under DescribeTags resource-type=network-interface instead of being classified unknown and dropped. * test(ec2): pin refresh-before-filter for DescribeAddresses and the ENI tag path through DescribeTags A public-ip filter now has a regression test across a simulated container restart: the current bridge IP must match and the pre-restart IP must not, which fails if filtering ever runs before the association refresh again. The launch-time ENI TagSpecification test asserts DescribeTags returns the tag under the interface's own resourceId with resource-type network-interface, exercising the full RunInstances path rather than the classification helper alone. |
||
|
|
9288769607 |
fix(stepfunctions): bound a running execution the four ways AWS does (#2782)
* fix(stepfunctions): enforce both TimeoutSeconds clocks The state machine's top-level TimeoutSeconds was read back by DescribeStateMachine and copied into activityScheduledEventDetails but never used as a deadline, so an execution ran to completion however long it took. Compute the budget once in doExecute, check it before every state and inside the Wait sleep, and end the execution TIMED_OUT with stopDate set, no error, no cause, and one ExecutionTimedOut event carrying States.Timeout and previousEventId 0. A Task's two bounds were swapped: HeartbeatSeconds acted as the total wait and TimeoutSeconds was decorative, so "TimeoutSeconds": 5, "HeartbeatSeconds": 60 failed at 60 seconds instead of 5. awaitToken now bounds the whole wait with TimeoutSeconds and the gap between heartbeats with HeartbeatSeconds. SendTaskHeartbeat only logged, so the gap bound needed a per-token timestamp: the service now records one when the token is registered and again on every heartbeat, and forgets it when the waiting task stops listening. Either clock ends the state as a TaskTimedOutException, which is what us-east-1 answers for a heartbeat expiry: an ActivityTimedOut event carrying error States.Timeout and no cause, then an execution reading FAILED with error States.Timeout and no cause key, over the six-event history ExecutionStarted, TaskStateEntered, ActivityScheduled, ActivityStarted, ActivityTimedOut, ExecutionFailed. A Catch still matches a heartbeat expiry under States.HeartbeatTimeout, so ErrorEquals matching now asks the failure which names it answers to rather than comparing one string. The Wait sleep stops at the execution deadline instead of sleeping its full duration first, which would have reported the timeout as many seconds late as the Wait outlasts the budget and left a WaitStateExited behind for a state AWS never finished. awaitToken discards its token on the way out; without that the token would stay pending for the life of the process and a later SendTaskSuccess would be answered as if someone were still waiting. Neither timeout carries a cause, so failExecution now reads a null cause as the failure having none and leaves the key out of both DescribeExecution and the ExecutionFailed event. The two other failures that reach it without a cause -- a Fail state with no Cause, and SendTaskFailure with no cause -- keep reporting an empty one, since AWS's shape for those is unmeasured. Refs #2733 * fix(stepfunctions): bound an execution's history and make StopExecution stop it AWS puts two bounds on a running execution that floci did not: it ends one that reaches 25,000 history events with States.Runtime, event 25,000 being the ExecutionFailed event itself, and StopExecution stops the worker rather than relabelling an execution that goes on to overwrite the status it wrote. Counting an event against that limit and numbering it in the published history are two meanings that one AtomicLong was carrying. They are separated here. producedEventCount counts every event the execution produces, the top-level flow's and those of its Parallel branches and inline Map iterations alike, and is what the limit judges. The published history numbers its own events: an event's id is its position in the list, which makes the list the only authority for the next id, where the counter and the seal in StepFunctionsService used to be a second one that agreed with it only at rest. A branch's events are counted and never built, so executeBranch no longer assembles HistoryEvent objects with full input and output JSON into a list it throws away. A Distributed Map runs each item as a child execution on AWS, and a child execution has a history of its own, so its items are counted against their own limit rather than the parent's: a Distributed Map over 13,000 items no longer fails the parent partway through with States.Runtime. The count is taken before it is judged. Reading it and then taking it let 40 concurrent inline Map iterations through the same check and spent more events than the execution had. StopExecution records its abort against a history that need not be in memory. Executions are stored and histories are not, so a restart in persistent mode brings a RUNNING execution back with nothing behind it, and the same window opens between a reset emptying the cache and emptying the store; the abort was written to the store and then thrown away as a 500. * fix(stepfunctions): end an execution that spends its budget waiting A state machine's TimeoutSeconds budget was read only between states and around the two pauses a definition asks for, a Wait and a Retry backoff. Every other way a state blocks outlasted it: a Task waiting for its token, a states:startExecution.sync or ecs:runTask.sync poll, and a Parallel or Map waiting for its branches. Those executions ended past their budget, and ended FAILED or SUCCEEDED rather than TIMED_OUT. Each of those waits now stops at the budget, and the Task path publishes no failure event for the state it cuts. Measured against us-east-1: a state machine with TimeoutSeconds 5 over an activity Task whose own TimeoutSeconds is 60 stops at exactly 5.000 s with status TIMED_OUT, and its history is ExecutionStarted, TaskStateEntered, ActivityScheduled, ExecutionTimedOut, with no ActivityTimedOut and no ExecutionFailed. --------- Co-authored-by: Facundo Paredes <naranjax@MAC-69786.local> |
||
|
|
2480daaa09 |
fix(athena): route database DDL to Glue (#2757)
* fix(athena): route database DDL to Glue * fix(athena): preserve DDL execution failures |
||
|
|
881695ea3b |
feat(apigatewayv2): OpenAPI import and Terraform-visible API/stage attributes (#2714)
* feat(apigatewayv2): implement ImportApi and ReimportApi
HTTP APIs had no PUT route on /v2/apis or /v2/apis/{apiId}, so ImportApi and
ReimportApi fell through JAX-RS matching to the S3 path-style handler and came
back as NoSuchBucket. Terraform's aws_apigatewayv2_api calls ReimportApi
whenever `body` is set, so any HTTP API defined by an OpenAPI document failed
to apply.
Add an OpenAPI importer for the v2 object model, reusing the swagger-parser
already used by ImportRestApi/PutRestApi on the v1 side. It materialises
routes, integrations and authorizers from x-amazon-apigateway-integration,
x-amazon-apigateway-authorizer, x-amazon-apigateway-any-method and
x-amazon-apigateway-cors, honouring document- and operation-level security.
ReimportApi replaces routes, integrations and authorizers as AWS does, but
leaves API settings an OpenAPI document cannot express (CORS when the spec
carries no x-amazon-apigateway-cors, tags, disableExecuteApiEndpoint) intact,
so a Terraform resource whose cors_configuration lives outside body does not
flap.
Both actions are wired for the restJson1 and JSON 1.1 protocols.
* fix(apigatewayv2): tag stages, not just APIs
TagResource, UntagResource and GetTags read the API id from the last segment of
the resource ARN, so a stage ARN (/apis/{apiId}/stages/{stageName}) yielded the
stage name as the API id and failed with "Invalid API id specified". Parse the
resource path by segment instead, and route the operation to the stage when the
ARN names one.
Stage had no tags field at all, so tags supplied to CreateStage were dropped and
never returned on read. Add it, populate it on create, and serialise it in both
the restJson1 and JSON 1.1 stage representations.
Terraform's aws_apigatewayv2_stage sets tags on create and then reconciles them,
so both halves were needed for a stage with tags to converge.
* feat(apigatewayv2): stage access logging, throttling and API version
Four attributes were accepted on write but dropped on read, so Terraform
re-proposed them on every plan and an aws_apigatewayv2_api/aws_apigatewayv2_stage
pair never converged:
- Api.version, also carried across from an imported document's info.version, as
AWS does
- Stage.accessLogSettings (CloudWatch destination and format)
- Stage.defaultRouteSettings and per-route Stage.routeSettings (throttling,
data trace, detailed metrics, logging level)
Throttling and logging fields are boxed rather than primitive: AWS omits unset
knobs instead of defaulting them, and emitting a zero would leave Terraform
seeing a changed value forever.
Stage also gains description, which CreateStage accepted and discarded.
Serialised for both the restJson1 and JSON 1.1 protocols.
* feat(apigatewayv2): honour basepath and failOnWarnings on OpenAPI import
ImportApi and ReimportApi accepted both documented query parameters and then
discarded them, so basepath=prepend or split produced routes at the wrong paths
with no error, and failOnWarnings never rolled anything back.
- basepath now resolves the base path the OpenAPI 3 way — a "basePath" server
variable first (the first one, if several are declared), otherwise the path
carried by server.url — and applies ignore, prepend or split. An unrecognised
value is a BadRequestException rather than silence.
- failOnWarnings turns swagger-parser messages into a 400. Parsing and
validation now happen before ReimportApi deletes anything, so a rejected
reimport leaves the existing routes, integrations and authorizers untouched
instead of gutting the API it was going to replace.
- The Api resource carries the warnings and importInfo the AWS model defines,
the latter noting definition properties the import ignored.
* fix(apigatewayv2): validate authorizers before reimport mutates, warn on unenforceable security
Two review findings on the OpenAPI importer:
- Authorizer resolution ran while the spec was being applied, so a definition
that parsed cleanly but declared an unsupported authorizer type — or a REQUEST
authorizer with caching and no identitySource — was rejected only after
ReimportApi had already deleted the previous routes, integrations and
authorizers. Resolution now happens in the planning phase, side-effect free, so
the rejection leaves the existing definition untouched. This mirrors
validateImportedAuthorizers on the v1 side.
- A security requirement naming a scheme with no AWS binding — a plain bearer or
apiKey scheme, or a misspelling — silently produced authorizationType NONE, so
a document that declares security could yield a publicly invokable route. That
now raises a warning naming the route and the schemes, which failOnWarnings
escalates to a 400.
Also adds the braces AGENTS.md requires to the conditionals introduced by the
earlier commits in this branch.
* fix(apigatewayv2): examine ANY-method routes and compound security on import
Two more review findings, both in the warning collection added by the previous
commit:
- The diagnostic passes walked PathItem.readOperationsMap(), which does not
include x-amazon-apigateway-any-method. An ANY route whose security named an
unbindable scheme therefore produced no warning, failOnWarnings could not
reject it, and it was still imported as NONE — the same silent-public-route
hole the previous commit closed for ordinary operations, left open for the
route type that matches every method. Route creation and both collectors now
share one forEachImportedOperation enumeration so they cannot diverge again.
- Several schemes inside a single SecurityRequirement is OpenAPI's AND. A route
carries one authorizer, so resolveSecurity enforced the first resolvable
scheme and dropped the rest silently. That now warns, naming the dropped
schemes and the one actually enforced.
* fix(apigatewayv2): report that imported AWS_IAM routes are not enforced
A sigv4 security scheme imports to an AWS_IAM route, which is what AWS records,
but HTTP API dispatch enforces only JWT and CUSTOM. A document declaring SigV4
therefore produced a route that looks authenticated and is not.
The route keeps AWS_IAM — downgrading it to NONE would misreport the definition
to anything reading the control plane — and the import now warns that the
emulator records the type without enforcing it. The dispatch gap itself predates
this change: CreateRoute has always accepted AWS_IAM unvalidated, and
ApiGatewayExecuteController already notes that v1 dispatch does not implement
AWS_IAM either.
* fix(apigatewayv2): validate jwtConfiguration shape before reimport mutates
jwtConfiguration was copied out of the authorizer extension unchecked, but
audience reaches the store as a List<String> and is cast as one. A scalar
audience — the form the extension is commonly written with — therefore threw a
ClassCastException inside createAuthorizer, after ReimportApi had already
deleted the previous routes, integrations and authorizers.
Normalise it during planning instead: a scalar audience becomes a single-element
list, a list is copied element-wise, and any other shape (or a non-string issuer)
is a BadRequestException raised before anything is deleted.
This was the last unvalidated field in authorizerSpecs; type, identitySource,
result-TTL caching and jwtConfiguration are now all resolved in the planning
phase, so no authorizer defect can reach the mutating half.
---------
Co-authored-by: local <local@example.com>
|
||
|
|
908d70db3d |
fix(apigatewayv2): propagate Lambda REQUEST authorizer context to HTTP API backends (#2715)
* fix(apigatewayv2): propagate Lambda REQUEST authorizer context to HTTP API backends A REQUEST authorizer's response context was parsed only to read isAuthorized or the policy Effect, then discarded. enforceRequestAuthorizerV2 returned a bare Response (null meaning "allowed"), so nothing could carry the context to buildV2ProxyEvent and the backend Lambda received no requestContext.authorizer at all. A real HTTP API delivers it under requestContext.authorizer.lambda, which is how an authorizer hands verified identity to the integration, so a backend that reads it sees an empty object and rejects every authorized request. This completes #1011 (issue #812), which added REQUEST authorizer invocation for HTTP APIs but only wired the allow/deny decision, and brings v2 in line with #581, which propagated the authorizer context on the v1/REST path. The WebSocket $connect path already does the same via WebSocketProxyEventBuilder, so HTTP APIs were the last of the three to drop it. Return a RequestAuthorizerResult carrying the context, mirroring the JwtAuthorizerResult the JWT path already threads through, and render it as requestContext.authorizer.lambda. Values are not flattened to strings the way the v1/REST path flattens its authorizer context: an HTTP API hands the context to the integration as JSON. The developer guide's own simple-response example returns a string, a number, a boolean, an array and a map, and all five now survive to the backend. principalId is deliberately left out - where AWS surfaces it in a 2.0 proxy event was not measured - and an authorizer that allows without returning a context leaves the authorizer node absent rather than rendering "lambda": null, for the same reason. Covered end to end in HttpApiRequestAuthorizerTest (IAM-policy and simple responses, nesting and scalar types, contextless allow) and at the builder in BuildV2ProxyEventLambdaAuthorizerTest. * chore(apigatewayv2): trim comments on the authorizer-context change Drops narration and change history, keeping only what is not recoverable from the code: the RequestAuthorizerResult contract, why the context is not flattened the way the v1/REST path flattens it, and the two intentional omissions (principalId, absent node rather than "lambda": null). Per AGENTS.md: prefer self-explanatory code over comments, document intentional deviations clearly. * fix(apigatewayv2): brace the authorizer error branch AGENTS.md requires braces on every conditional. --------- Co-authored-by: local <local@example.com> |
||
|
|
02f9754ac7 |
fix(ui): reconnect the UI sidecar without restarting Floci (#2718)
* fix(ui): reconnect the UI sidecar without restarting Floci The floci-ui sidecar's FLOCI_ENDPOINT is baked in at container-create time, but Floci's container IP changes on every restart. adoptExisting() took over a surviving sidecar verbatim and never compared its endpoint against the current one, so the sidecar kept polling the previous instance's address indefinitely. The dashboard reported "Not connected" with ECONNREFUSED and the only way out was to recreate the sidecar by hand -- in practice, by restarting the emulator alongside it. Detect that drift on adoption and recreate the sidecar instead, so recovery stays entirely within the sidecar's own lifecycle and never requires disturbing Floci. Two supporting changes: - status() re-arms ensureStarted() when the readiness probe fails. started was a one-way latch, so a sidecar that was removed, crashed, or turned out to be stale left Floci with no path back. The UI polls status continuously, which supplies the retry cadence. - UiServiceConfig gains endpoint() and insecureSkipTlsVerify(). With TLS on, the derived endpoint is https://<floci-container-ip>:<port>, which the sidecar's Node/Bun proxy rejects: the self-signed certificate has no IP SAN for Floci's own container address, so verification fails with ERR_TLS_CERT_ALTNAME_INVALID even once the CA is trusted. Trusting the CA alone is therefore not enough. endpoint() lets an operator point the sidecar at http://<ip>:<port> -- the same server, via the port's HTTP/HTTPS protocol detection, with TLS left enabled -- and insecureSkipTlsVerify() covers the case where https must be kept. A blank or malformed override is a hard error, not a silent fall back to the derived endpoint. * fix(ui): derive http for the sidecar when the host is a bare IP With TLS enabled the endpoint handed to the UI sidecar was derived as https://<floci's own container IP>:4566. That address can never appear in the self-signed certificate: it is assigned at container-create time and changes on every recreate, and the certificate is generated by a ConfigSource that runs before CDI, with no Docker client to ask what the address will be. Every connection therefore failed altname verification — not chain trust, so mounting the CA would not have helped either — and the dashboard sat at "Not connected" with no path back. Nothing in the manager notices: the sidecar is running, so the re-arm added in 8f4fd900 correctly declines to replace it, and the readiness probe only checks the sidecar's own port, never the hop that is broken. Floci's listener does HTTP/HTTPS protocol detection on the same port, so http:// reaches it with TLS left enabled. That is one hop on an internal Docker network, not the emulator, and it is the only scheme that works unattended on the default configuration. A named host such as host.docker.internal is a DNS SAN on the certificate and keeps https. So does an IP literal when insecure-skip-tls-verify is set, since the operator has said explicitly that they want TLS on this hop and verification is no longer the obstacle. isIpLiteral mirrors the iPAddress/dNSName distinction CertificateGenerator already draws, kept local so this package does not depend on the ACM service for one predicate. * fix(ui): bracket an IPv6 host so the sidecar endpoint parses The endpoint was built by concatenating host and port, which produces http://fd00::2:4566 when the resolver hands back an IPv6 literal — the port separator is indistinguishable from the address's own colons and no client can parse it. DockerHostResolver reaches that case through InetAddress.getLocalHost().getHostAddress() on an IPv6-only host. Bracket the authority host. Names and IPv4 literals are unchanged. * fix(ui): reset the async re-arm latch and stop swallowing pre-start failures Local code review (review-local.ts) against FlociUiManager.java found two HIGH-severity bugs before this branch reached a PR: - ensureStartedAsync()'s kicked latch was only reset after a FAILED start, never after a successful one. status()'s self-recovery path sets started=false and calls ensureStartedAsync() when the sidecar is gone, but after any prior successful async start that CAS always failed silently -- the documented "recovers without Floci being restarted" behavior could never actually fire. - findByName() and replaceIfEndpointDrifted() ran before ensureStarted()'s try/catch. A container-runtime failure there (e.g. an unreachable Docker socket) escaped uncaught to a synchronous caller, or vanished into a discarded Future on the async path, leaving status() reporting {started:false, ready:false, error:null} with no diagnostic. Reset kicked whenever status() re-arms a lost sidecar, and move the whole body of ensureStarted() into the try/catch so every failure is routed through lastError. A misconfigured endpoint override's own validation message (set by replaceIfEndpointDrifted before it rethrows) is preserved rather than overwritten by the generic describeStartFailure() message. * fix(ui): validate endpoint override authority and capture fresh-start errors - validateEndpointOverride() now rejects http:// URLs with no authority (e.g. "http://", "http:///path"), which previously passed the bare prefix check and were injected as an unreachable FLOCI_ENDPOINT. - ensureStarted()'s IllegalStateException handler now fills lastError when nothing more specific was already recorded, so a fresh start (no existing sidecar to adopt) with a blank/malformed endpoint override surfaces the validation message instead of error=null. - Document the new endpoint and insecure-skip-tls-verify settings in application.yml's floci.services.ui block. |
||
|
|
ff36141c19 |
perf(cloudformation): probe Lambda S3 code with headObject, not getObject (#2728)
Resolving an AWS::Lambda::Function whose Code points at S3 checked the object by calling getObject and discarding the result. S3Object.getData() is a materialised byte array, so that read the whole package into memory purely to answer whether it was readable, and LambdaService then read the same object again for real during CreateFunction. Every stack create or update paid for two full copies of every Lambda package it provisions. headObject answers the same question without the body: getObject is getObjectMetadata plus readFile, headObject is getObjectMetadata alone. Both resolve the object through that same metadata lookup, so a missing key or bucket still fails the resource exactly as before, and the failure behaviour added for #2648 is unchanged. Closes #2675 |