PersistentPathValidator now logs the effective storage mode once at
INFO, making memory-mode data loss visible instead of silent.
* Fix#2225
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* fix(apigateway): only emit the greedy path parameter for greedy resources
REST (V1) proxy events carried a "proxy" key in pathParameters on every
request, not just for greedy resources. The value came from the controller's
own JAX-RS binding - the class is mounted at @Path("/{proxy: .*}"), so
`proxy` is non-empty for every request regardless of which API Gateway
resource matched.
AWS emits pathParameters.proxy only when the matched resource itself declares
a greedy parameter. For /datasets/{datasetId} it sends {"datasetId": "..."}
and nothing else. Integrations that validate the event against a strict
schema (JSON Schema additionalProperties: false) therefore rejected every
request to a parameterised resource, which made every findOne/updateOne/
deleteOne style route unusable behind such an integration.
The two meanings of "proxy" coincide only for a root-level /{proxy+}
resource, which is why this went unnoticed: that is the shape the code was
originally written for. extractPathParams already skips greedy params
deliberately, and the V2 builder derives them from the route key, so V1 was
the odd one out.
Replace the unconditional put with putGreedyPathParam, which:
- adds the parameter only when the matched resource declares a greedy
segment;
- takes the value from the remainder after the literal prefix, so
/files/{proxy+} matching /files/a/b/c yields "a/b/c" rather than the
whole request path; and
- reads the parameter name from the template, since {proxy+} is only the
conventional spelling and AWS permits any name.
The now-unused JAX-RS capture is dropped from the buildProxyEvent signature
so it cannot leak into the event again.
* fix(apigateway): route greedy resources named other than {proxy+}
AWS does not reserve the greedy path parameter name - "you can use any
string for the greedy path parameter name" - and /parent/{name+} matches
every descendant below that parent.
buildProxyEvent already reads the name from the template, but the REST
router still keyed on the literal {proxy+} in three places: the exclusion
in the template-match arm, the guard in the greedy-match arm, and the
parent-prefix extraction used by both that arm and its specificity sort.
A resource such as /assets/{rest+} therefore only half routed. It fell to
the template arm, where pathMatchesTemplate compares segment counts and
treats {rest+} as an ordinary single-segment wildcard, so /assets/foo
matched while /assets/img/logo.png - the whole point of a greedy resource
- matched nothing at all. A quick manual check passes, which is why the
unit test added with the previous commit stayed green: it calls
buildProxyEvent directly and never exercises routing.
Recognise a greedy segment by its trailing "+" rather than by name, via
greedyParentPrefix, and route on that. Only a terminal greedy segment
counts, matching AWS, where a greedy parameter is allowed solely as the
last segment of a resource path. Specificity is unchanged: exact beats
template beats greedy, and greedy resources still sort by longest parent
prefix.
extractPathParams already generalised on the trailing "+", so it needed no
change. putGreedyPathParam becomes greedyPathParam, returning a map like
its extractPathParams companion and sharing the same terminal-segment
detection instead of scanning for the first greedy part.
Tested through the real request path, per AGENTS.md: the new
ApiGatewayGreedyPathParameterIntegrationTest stands up /assets/{rest+}
with a MOCK integration and drives it over HTTP. Without this change its
multi-segment and deeply-nested cases fail while the single-segment case
passes, reproducing the half-routing exactly. ApiGatewayProxyMatchTest
adds five routing assertions for non-proxy greedy names, four of which
fail without it.
* fix(apigateway): emit the greedy path parameter to mapping templates too
The same rule the previous two commits applied to the Lambda proxy event
was wrong in the two mapping-template paths, in opposite directions.
invokeAwsIntegration built its pathParameters from the JAX-RS capture,
exactly as buildProxyEvent used to, so $input.params('proxy') and a
method.request.path.proxy mapping resolved on every request rather than
only for a greedy resource, and carried the whole request path instead of
the remainder after the prefix.
invokeMock had the opposite gap: it used extractPathParams alone, which
deliberately skips greedy parameters, so $input.params('proxy') was empty
for a greedy resource where AWS supplies the captured remainder.
Both now compose extractPathParams with greedyPathParam, matching
buildProxyEvent, so the three paths agree on what a matched resource
declares. AGENTS.md asks for compatibility to be checked across alternate
protocol paths; these are the alternates for this behaviour.
As with buildProxyEvent, the JAX-RS capture was invokeAwsIntegration's only
use of the proxy argument, so it is dropped from the signature rather than
left available to leak back in.
ApiGatewayGreedyPathParameterIntegrationTest now asserts the captured value
over HTTP and not merely the route: its MOCK response template echoes
$input.params('rest'), so the greedy value must arrive under the name the
template declares. All three assertions fail without this change.
Support [n] bracket-index segments in ResultPath so a path such as
$[1].payload merges into the addressed array element instead of
discarding the array input; an out-of-bounds index raises
States.ResultPathMatchFailure. Also support the single-quoted bracket
field name form ($.abc.['def ghi']) AWS documents for a field name a
dotted segment cannot carry.
* Fix#3479
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* fix(storage): load each backend once and close WAL writers on shutdown
StorageFactory.shutdownAll() ran the final flush after the WAL backends had
been shut down. A WAL flush compacts and reopens the writer, so every WAL
backend was left with an open writer after shutdown. loadAll() also reloaded
backends that create() had already loaded, replaying live stores and opening
a second WAL writer on top of the first.
create() now owns the initial load of a backend, loadAll() only loads
backends that have not been loaded yet, and shutdownAll() flushes before it
shuts the backends down. Memory, persistent and hybrid behavior is unchanged.
* chore: retrigger CI
EmulatorLifecycle.onStop ran its cleanup steps as one straight sequence. A
RuntimeException from any step skipped everything after it, including the
final storage shutdown, so WAL and hybrid stores were left unflushed and
open whenever a proxy, container or UI manager failed to stop.
Each step now runs in isolation: a failure is logged with its stack trace
and the resource name, the remaining steps still run, and storage shutdown
always runs last. The step order is unchanged.
* fix(sqs): keep DLQ messages when a move task cannot deliver them
StartMessageMoveTask removed a message from the source queue before knowing
whether it could be delivered. With no DestinationArn, a message without a
recorded original source queue, or whose original source queue was deleted,
was dropped or parked in a queue nobody could receive from, and a delivery
failure lost the message outright.
The move worker now checks that the target queue exists before taking the
head message off the source (under one lock hold), restores the message at
the head when delivery fails so the source keeps its order, and resolves
the target queue by the account in its URL because the worker runs outside
any request scope. Without that, only the first message of a queue owned by
a non-default account was moved.
* fix(sqs): deliver a copy on redrive so a failed move restores the source unchanged
* fix(sqs): roll back the in-memory add when a queue persist fails
* test(sqs): share the failing-store service helper
AWS::RDS::DBCluster templates set these fields but the provisioner
never read them, so CFN-provisioned clusters kept the defaults.
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
CreateEnvironment stored and GetEnvironment echoed back
AirflowConfigurationOptions, but nothing translated it into the
container's actual configuration, so a DAG reading a custom
conf.get("section", "key") value at import time or task-run time got
nothing back, even though GetEnvironment reported the option as
configured.
Added MwaaEnvironmentManager.airflowConfigurationOptionsEnv, which
converts each AWS "section.key" entry into the AIRFLOW__SECTION__KEY
environment variable real Amazon MWAA sets for the same option, and
wired it into startAirflowContainer's env list. A malformed key (no
"section.key" dot on both sides) or one that would collide with a
variable Floci itself manages (PROTECTED_ENV_VARS: the executor,
database connection, security keys) is skipped and logged rather than
silently breaking the environment's required wiring.
Since this map now genuinely does something instead of being inert,
also added the validation CreateEnvironment's botocore model declares
for it (a 1-64 character key matching [a-z]+([a-z0-9._]*[a-z0-9_]+)?,
a 1-65536 character printable-ASCII value) as a server-side
ValidationException: the AWS SDKs enforce this client-side, but Floci
is also reachable via raw HTTP/CLI --cli-input-json, which bypasses
that, and an oversized or malformed entry should be rejected before
Docker container creation rather than passed through.
Fixes#3436
CreateDBCluster accepted these fields but DbCluster never stored them,
so DescribeDBClusters always reported defaults and Terraform saw
permanent drift on Aurora-shaped clusters.
* Fix#2559
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
Reading a table's partition indexes failed as an unsupported action, which
makes a Glue table unmanageable as infrastructure: the Terraform AWS
provider reads the indexes after creating a table and again on every
refresh, so the create reports an error and every later plan fails on the
same call. The table itself is fine - only the read of its indexes is
missing - so the resource lands in state and then cannot be planned.
Return an empty descriptor list. No index can exist while CreatePartitionIndex
is unsupported, so empty is the accurate answer rather than a placeholder,
and it is the answer a client reading a table's indexes needs. The table is
resolved first so that a missing one is reported as missing rather than as a
table that happens to have no indexes.
Fold rootDirectory (or the access point's own root when
accessPointId is set) into the shared EFS named volume's identity,
so different roots on the same fileSystemId no longer collide.
* Fix#2563
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* fix(athena): read a projecting table's partition paths, not its whole location
A table that projects its partitions was read by globbing its location, so
anything else stored beside the data was read as though it were table data.
Athena does not do this: it builds the partition paths from the projection
configuration and reads only those, which is the point of projection.
The common way this bites is a workgroup whose results live under the
table's own root. The first query succeeds, its output CSV lands inside the
read path, and every query after it fails parsing that CSV as table data -
a data source that works once and then breaks, on a file the engine wrote
itself.
Derive the read path from storage.location.template when it is set, and
otherwise from the default column=value layout over the partition keys.
Values stay wildcards: narrowing them to the partitions a query actually
needs requires that query's predicates, which are not available where the
view is built, so the read stays wide and the query does the filtering. A
table that does not project its partitions is read exactly as before.
Also reject a query that names a projecting table but leaves an injected
partition column unmentioned. An injected column has no generatable range -
its values come from the query - so Athena requires an equality condition on
it. Deciding whether a condition is a static equality one needs the query's
predicate tree, so this checks only whether the column is mentioned at all:
strictly narrower than the real rule, never rejecting a query Athena would
accept, but catching the case that silently reads every partition.
* fix(athena): scope the injected-column check to WHERE clauses
The check matched the column name anywhere in the query text, so a query
that names the column without filtering on it passed. `SELECT tenant,
count(*) FROM audit_events GROUP BY tenant` has no WHERE clause at all and
still satisfied it, on the strength of the SELECT list and the GROUP BY -
which is the case the check exists to catch.
Look only inside WHERE clauses, a subquery's included. A clause runs from
the keyword to whatever ends it: the next clause keyword, the paren closing
the subquery that holds it, a statement terminator, or the end of the query.
Parentheses opened inside the clause are part of it, so a predicate carrying
its own subquery is not cut short.
Single-quoted literals and comments are blanked first. A column name spelled
inside either constrains nothing, and reading them as code made the same
false pass by another route. Double-quoted and backquoted identifiers stay:
those are references to the column.
Still narrower than Athena's rule, which wants a static equality condition
rather than a mention, so it continues to reject nothing Athena accepts.
* fix(ec2): capture the instance file system in CreateImage
CreateImage recorded only metadata. It registered a new id and set
image.setSourceImageId(resolveLaunchableImageId(region, source.getImageId()));
so the AMI pointed at the *base* image the source instance was launched
from. Launching it started that base image, and everything provisioned on
the source instance was silently discarded.
This was worse than an unimplemented operation. A full Packer amazon-ebs
build ran green against Floci -- keypair, security group, launch, SSH,
provisioner, stop, CreateImage, cleanup -- and produced an AMI reporting
state "available" that contained nothing:
==> amazon-ebs.floci: PROVISIONED_BY_PACKER
==> amazon-ebs.floci: AMI: ami-42ba1c3d9f8023703
Build finished after 1 minute 41 seconds.
$ # launch that AMI, then:
$ cat /etc/floci-probe
cat: /etc/floci-probe: No such file or directory
Anyone building a golden AMI locally would have believed it worked.
Per API_CreateImage, CreateImage "creates an Amazon EBS-backed AMI from an
Amazon EBS-backed instance that is either running or stopped", and the
resulting AMI is a point-in-time capture of the instance's volumes. The
contract is that state at capture time is preserved.
CreateImage now commits the source container to a Docker image
(floci-ami/<ami-id>:latest) and stores that reference on the Image.
RunInstances prefers it, walking the CreateImage chain so an AMI captured
from an instance that was itself launched from a capture still resolves.
The guest runtime (systemd vs minimal, cloud-init) still comes from the
ancestor, since committing a layer does not change how the guest boots.
Capture is best-effort by design: if the daemon refuses the commit, the
AMI keeps its sourceImageId and behaves exactly as before rather than
failing the API call. Skipped entirely in mock mode, where there is no
container.
Ec2ContainerManager gains commitInstance() and removeCommittedImage(); the
latter exists so captures can be reclaimed when the owning AMI is
deregistered, rather than accumulating on disk.
Verified end to end against a real Packer 1.16.0 build on this branch: the
build succeeds, and launching the resulting AMI and reading the file the
provisioner wrote returns PROVISIONED_BY_PACKER. The committed image is
visible as floci-ami/ami-295129250f0c23320:latest.
Tests cover the capture itself with a mocked Docker client: that the
reference is split into repository and tag (passing it whole would create
a repository literally named "floci-ami/ami-123:latest"), that a missing
container captures nothing, that a daemon failure yields null rather than
propagating, and that removing an absent or never-captured image is not an
error. 8 tests, all green.
Not addressed here: reclaiming the committed image on DeregisterImage,
which needs the DeregisterImage work to land first.
* feat(ec2): implement DeregisterImage and CopyImage
Both actions returned UnsupportedOperation:
$ aws ec2 deregister-image --image-id ami-... --endpoint-url http://localhost:4577
An error occurred (UnsupportedOperation) ... Operation DeregisterImage is not supported.
$ aws ec2 copy-image --source-region us-east-1 ...
An error occurred (UnsupportedOperation) ... Operation CopyImage is not supported.
The rest of the AMI lifecycle already worked -- RegisterImage, CreateImage,
DescribeImages, and RunInstances from a created AMI -- so the gap sat at the
end of it. DeregisterImage is what Packer calls under force_deregister to
clear the AMI holding the name it is about to reuse; without it the second
run of any iterative build dies on InvalidAMIName.Duplicate and the build is
one-shot. CopyImage is the build-in-one-region, promote-to-the-others
pattern that several Gruntwork AMI modules use.
The cause was only the missing `case` arms in Ec2QueryHandler's dispatch
switch, whose default is UnsupportedOperation. EC2_ACTIONS in
AwsQueryController is not on this path for a signed request: resolveService()
takes the service from the SigV4 credential scope and only falls back to
inferServiceFromAction() when that fails. CreateImage is likewise absent from
EC2_ACTIONS and works fine. All three are added anyway so the unsigned/raw
client fallback agrees with the dispatcher.
DeregisterImage. "Deregisters the specified AMI. A deregistered AMI can't be
used to launch new instances", and it does not delete "Instances already
launched from the AMI" (API_DeregisterImage). The image is therefore
tombstoned with the documented AMI state `deregistered` rather than dropped
from the store: DescribeImages stops reporting it, its name is released so
the rebuild can claim it, RunInstances rejects it with
InvalidAMIID.Unavailable, but an instance launched from it keeps resolving
its ancestry to a guest image, so a stop/start still comes back on the right
one. Keeping the tombstone is also what lets a repeat call answer
InvalidAMIID.Unavailable ("has been deregistered and is no longer available")
instead of InvalidAMIID.NotFound ("The specified AMI doesn't exist") -- a
retry can tell the two apart. Deregistering a catalog AMI, which is owned by
amazon rather than by the caller, is AuthFailure: "trying to use an AMI for
which you do not have permissions". Snapshots are kept unless
DeleteAssociatedSnapshots is set ("Default: The snapshots are not deleted"),
and one shared with another AMI is reported `skipped` rather than deleted,
since "if a snapshot is associated with multiple AMIs, it won't be deleted
even if specified for deletion, although the AMI will still be deregistered."
CopyImage. "The copy operation must be initiated in the destination Region",
and for a Region-to-Region copy "the destination Region is the Region in
which you initiate the copy operation" (API_CopyImage) -- so the request's
own region is the destination and only the source is looked up under
SourceRegion. That matters here because Floci keys registered AMIs by
(region, id) and describeImages filters on the stored region, so a source id
that exists in us-east-1 is genuinely absent when SourceRegion names another
region; that case is InvalidAMIID.NotFound. The copy is an independent image:
its own id, its own snapshot ids (sharing the source's would make deleting
either look like it took the other's backing with it), owned by the caller.
State: AWS reports the copy as `pending` until the backing snapshots finish.
Floci's store is in-memory and the copy completes inside the call, so it is
`available` immediately -- matching what CreateImage and RegisterImage
already return rather than inventing a state machine that nothing would ever
advance. A caller polling for `available` returns on its first poll.
Concurrency. registerImage's duplicate-name check is a read-modify-write over
the whole image store, and CopyImage now reaches it too. The stripe is taken
on (region, name), not on an image id -- the id does not exist yet and is
unique by construction, whereas the name is the invariant. deregisterImage's
check-then-tombstone takes the (region, id) stripe. Both are the striped-lock
pattern already used by modifyVpcEndpoint.
Tests are driven through the service, not over HTTP, for the concurrency
cases: requests through the test server serialize enough to hide a lost
update, the same trap called out in
Ec2ModifyVpcEndpointTest.concurrentAssociationsAllSurvive. Both race tests
were confirmed to fail with their lock removed -- 6 of 24 concurrent copies
claimed one name, and one AMI was deregistered twice -- which is also why the
name race pads the store first: the window that has to be hit is the scan,
and against an empty store the test passes with or without the lock.
The rest of the coverage is over HTTP: that DeregisterImage answers
return=true and the AMI then vanishes from DescribeImages, that unknown,
already-deregistered and not-owned ids get the three distinct documented
errors, that the freed name can be registered again (the force_deregister
loop), that an instance launched from the AMI keeps running while a new
launch is refused, snapshot retention and the shared-snapshot skip, and for
CopyImage that the copy lands in the caller's region and not the source's,
is available and owned by the caller, gets its own snapshots, is launchable
where it landed, and rejects a missing or deregistered source.
Not implemented: the Encrypted/KmsKeyId, CopyImageTags, TagSpecification and
ClientToken parameters of CopyImage, and Outpost/Local Zone destinations.
* fix(ec2): release an AMI's captured image when it is deregistered
CreateImage captures the source instance's file system as a committed
Docker image (floci-ami/<ami-id>:latest). Those are real disk. Nothing
released them, so an iterative build -- Packer with force_deregister, or
any loop that rebuilds the same AMI -- left one committed layer behind per
iteration, indefinitely.
DeregisterImage now releases the capture. The AMI record itself is still
kept as a tombstone, as the DeregisterImage implementation requires for
ancestry resolution; only the Docker image is reclaimed.
The exception is the one that matters for correctness. AWS keeps instances
launched from a deregistered AMI running, and DeregisterImage's own
documentation notes that already-launched instances are unaffected -- they
can still be stopped and started. Removing the layer such an instance
boots from would break exactly that, so reclamation is skipped while any
non-terminated instance still resolves to the capture, and the tombstone
keeps its reference. Correctness before disk: the worst case is a layer
that outlives its AMI, not an instance that cannot start.
Terminated instances deliberately do not pin a capture. They can never
boot again, and treating them as live would mean nothing is ever reclaimed
in a long-running emulator.
Tests drive the real CreateImage path rather than building a fixture by
hand -- the image store returns detached copies, so setting the captured
reference on a returned Image never reaches the store and the test would
silently assert nothing. They needed two further pieces of care worth
noting:
- The shared test configuration sets floci.services.ec2.mock=true, which
skips all container work, so both capture and reclamation would be
dead code under test. A QuarkusTestProfile turns it off; the container
manager is still mocked, so no Docker is involved.
- Outside mock mode, termination is delegated to the container manager.
With that mocked, an instance stays "running" forever, which would
have made the terminated-instance assertion vacuous. The mock now
performs the same state transition the real path does.
* fix(ec2): make a capture survive the copy, and fail loudly when it cannot
Six review findings on the image-capture stack, all of which end in the same
place: an AMI that reports itself available while its file system is not what
the caller asked for.
CopyImage copied the flattened ancestry but not the capture, so launching a
copy silently started the base image. The copy now carries the reference, and
because a Docker reference is global to the daemon, reclamation counts another
AMI carrying the same tag as a live user.
A capture that could not be made was reported the same way as "there was
nothing to capture", so a refused commit produced an immediately-available AMI
that booted the ancestor. commitInstance now throws, and CreateImage drops the
half-built AMI and fails: InternalError when the commit was refused,
IncorrectInstanceState when the instance has no container to capture. Floci
commits inline, so there is no later state transition a poller could observe
and no honest way to report this asynchronously.
Two races shared one cause: the invariants over the image registry are whole
set scan-then-mutate sequences, and the three operations that hold them ran
under three different monitors. RegisterImage locked a name stripe while
DeregisterImage locked an id stripe, so a registration could reuse a snapshot
between the shared-reference scan and the delete. RunInstances took no image
lock at all, so a launch could resolve a captured tag, pause before storing its
instance, and have deregistration remove the tag underneath it. Both now run
under one imageRegistryLock; RunInstances holds it only to resolve the AMI and
publish its instances, with the container launches outside it. The lock is
single rather than striped because the capture invariant is not region-scoped:
a copy shares its source's layer across regions.
removeCommittedImage suppressed docker errors while the caller cleared the
reference regardless, so a transient failure leaked the layer permanently.
It now reports whether the layer is gone, and the reference survives a refusal.
Finally, a capture retained for a live instance was never reclaimed, because
reclamation only ran during deregistration and a second deregistration is
rejected. Termination now reclaims what deregistration had to keep.
Ec2ServiceTest builds a container-backed service with a bare container-manager
mock, so its instances have no container and every CreateImage there would now
be rejected for a reason those tests are not about; they get a commit stub.
* fix(ec2): reject a mid-launch deregistration before the launch persists anything
RunInstances checks the AMI tombstone twice: once on entry, and once under the image
registry lock, because DeregisterImage releases the captured layer as soon as no live
instance resolves to it, and a launch that had resolved the layer but not yet stored
its instance would lose it underneath.
The second check fired too late. By the time it ran, the launch had already written a
root volume per instance, the instance tags, a subnet IP, and the attachment on a
caller-supplied ENI. The reservation was never returned, so no caller had an id to
clean any of that up with, and the interface stayed in-use for good.
Move the build loop inside the same locked section, after the check, so the launch
persists nothing until it knows it is allowed to proceed. Rollback was the other
option and is worse: the subnet IP counter has no free list to return an offset to,
and a rollback path only runs once something has already gone wrong. The lock is not
meaningfully wider, since what moved inside it is in-memory record construction; the
slow part, the container launch, still runs outside.
The regression test holds the registry lock itself, so the launch parks at a known
point and the tombstone lands there on purpose rather than racing for the window.
Its file is renamed to *IntegrationTest, matching what the rest of the repo calls a
@QuarkusTest.
* test(ec2): name the captured image reclaim QuarkusTest an IntegrationTest
607 of the 736 @QuarkusTest classes on main end in IntegrationTest, and this one
starts a full application like the rest of them. Ec2CreateImageCaptureTest is left
alone: it drives a plain Ec2Service with Mockito and is not an integration test.
hasAirflowContainerExited only inspected the Airflow container. If the
sibling Postgres container dies instead (out of memory, its volume
filling up), Airflow keeps running but never reports metadatabase
healthy, so the environment sat at CREATING exactly as before this
existed, the same failure mode #3446 fixed for the Airflow container
alone.
Generalized into hasAnyContainerExited, backed by a shared per-container
helper, checking both Environment.getDbContainerId() and
getAirflowContainerId(). checkReadiness and its log messages updated to
match; behavior for a lone Airflow-container failure is unchanged.
Follow-up from hectorvent's review on #3446.
MwaaEnvironmentManager.pythonTagFor parses AirflowVersion with a bare
Integer.parseInt. resolveAirflowVersion only checked that the requested
version was present in the operator-configured supported-versions list,
so a misconfigured entry (e.g. a stray "latest") would pass that check
and reach pythonTagFor, surfacing as an internal NumberFormatException
out of container startup, well after Postgres had already been created
for the environment, rather than a clean 400 at CreateEnvironment.
resolveAirflowVersion now also validates the version's shape (a numeric
major.minor, with an optional patch) before checking list membership, so
a malformed value is rejected immediately as ValidationException.
Follow-up from hectorvent's review on #3445.
* fix(dynamodb): match AWS UpdateItem response and validation gaps
UPDATED_NEW on a nested SET returned the whole parent map. It now returns
only the changed fragment, and the diff recurses into maps.
A REMOVE with UPDATED_NEW returned an empty Attributes. AWS omits the
field, since nothing was set to a new value.
An invalid ReturnValues also reports one error rather than aggregating
with ReturnConsumedCapacity, which is what AWS answers.
Closes 2 TIER 1 and 1 TIER 3 cases in the dynamodb-conformance suite.
* fix(dynamodb): reject an empty binary value on a secondary index key
An empty binary index key value was stored. AWS rejects it the same way
as an empty string, with the put wording that names the index and key,
and the shorter update wording for UpdateItem.
Closes 3 TIER 3 cases in the dynamodb-conformance suite.
* fix(dynamodb): reject expressions over 4096 bytes
AWS caps every expression parameter at 4096 bytes and checks the raw
text before the table lookup and before syntax. Floci accepted any size.
The wording follows what eu-west-2 and us-east-1 return. Write APIs wrap
the error in the validation envelope, read APIs do not, and only the
Scan FilterExpression reports the measured size.
Closes 5 TIER 3 cases in the dynamodb-conformance suite.
* fix(dynamodb): reject arithmetic results outside the number range
SET with + or - and ADD stored any result. AWS rejects a result it
cannot store with "Number overflow. Attempting to store a number with
magnitude larger than supported range", and uses that one wording for a
magnitude that is too small or too many significant digits as well.
Closes 1 TIER 3 case in the dynamodb-conformance suite.
* fix(dynamodb): reject attribute values nested deeper than 32 levels
AWS counts a top-level attribute as level 1 and rejects an item or an
ExpressionAttributeValues entry whose leaf sits below level 32, before
the table lookup. Floci stored any depth. The check now runs on the
PutItem item and on ExpressionAttributeValues for PutItem, DeleteItem,
UpdateItem, Query and Scan.
Closes 2 TIER 3 cases in the dynamodb-conformance suite.
* fix(dynamodb): apply the size and nesting limits to batch and transact writes
BatchWriteItem and TransactWriteItems now reject a Put item nested deeper
than 32 levels, and TransactWriteItems rejects an oversized UpdateExpression
or ConditionExpression, all before the table lookup.
AWS reports these without the validation envelope, and the transact
ConditionExpression carries the measured size like the Scan filter does.
A too deep ExpressionAttributeValues entry in a transact Update is a
cancellation on AWS, not a top-level error, and is left as is.
* fix(dynamodb): cancel a transaction on a too deep Update value
AWS checks the depth of a transact Update's ExpressionAttributeValues as
part of that member. A leaf below level 32 cancels the transaction with a
ValidationError reason and the message "Nesting Levels have exceeded
supported limits". A ConditionCheck value is not checked, so its condition
simply runs.
A cancellation reason can now carry its own message. Reasons without one
keep "The conditional request failed".
* fix(dynamodb): validate request numbers before the table lookup like AWS
* fix(dynamodb): check nesting depth in legacy value containers like AWS
* fix(dynamodb): return UPDATED_NEW and UPDATED_OLD by touched path like AWS
* fix(dynamodb): check the TransactGetItems projection size before the table lookup
* fix(dynamodb): reject and cancel on a too deep PartiQL parameter like AWS
CopyObject and UploadPartCopy only checked s3:PutObject on the
destination, letting a write-only caller copy any source object it
could not otherwise read via x-amz-copy-source.
* Fix#2333
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
CustomOriginConfig now echoes OriginKeepaliveTimeout and OriginReadTimeout
with their AWS-documented defaults (5s, 30s), and Origin always emits
ResponseCompletionTimeout (0 when unset). OriginSslProtocols parsing
validates Quantity against the Items it declares, matching the sibling
CustomHeaders parser. OriginReadTimeout (1-120s) and OriginKeepaliveTimeout
(1-300s) now fail with CloudFront's own InvalidOriginReadTimeout /
InvalidOriginKeepaliveTimeout error codes when out of range or malformed,
and the ResponseCompletionTimeout >= OriginReadTimeout cross-check now
falls back to the 30s default when OriginReadTimeout is omitted.
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* Fix#3221
docker start only launches the entrypoint and returns immediately, so a
startup script or `airflow db migrate` failing partway through never
surfaced anywhere: the readiness poller only checked isReady() and had no
path back to a failure status, so the environment reported CREATING
forever instead of CREATE_FAILED.
MwaaEnvironmentManager.hasAirflowContainerExited inspects the container's
running state (docker-removed counts as exited too), and the readiness
poller (extracted into checkReadiness for direct testability) now marks
CREATE_FAILED when isReady() is false and the container has exited.
Two things this needed to stay safe under concurrency and partial
failure, both of which isReady() already handles and this had to match:
- isReady()/hasAirflowContainerExited() are blocking Docker/HTTP calls,
wide enough for a concurrent DeleteEnvironment (which sets DELETING on
the same Environment instance before tearing down its containers) to
have moved the environment past CREATING in the meantime. checkReadiness
re-checks the status immediately before writing, in both branches, so it
can't resurrect a just-deleted environment into storage with a status
decided from stale, pre-delete information.
- hasAirflowContainerExited only treats NotFoundException (the container
is actually gone) as exited; any other Docker error is inconclusive and
must not propagate, since the readiness poller shares one loop across
every CREATING environment and an uncaught exception from one
environment's check would otherwise skip every other environment for
that poll tick, the same failure mode isReady()'s own catch-all already
avoids.
Fixes#3437
* feat(datasync): add the DataSync management plane
Emulates the AWS DataSync management API over JSON (X-Amz-Target
FmrsService.<Action>, signing name datasync): agents, the eleven
CreateLocation/DescribeLocation/UpdateLocation trios plus the shared
ListLocations and DeleteLocation, tasks, and resource tagging.
Each DescribeLocation* projects the create request that produced the
location, so the configuration that went in is the configuration that comes
back, and LocationUri is derived from that request per the scheme AWS
documents for the type. DescribeAgent reports ONLINE and DescribeTask reports
AVAILABLE from the first read, which is what the Terraform provider's
aws_datasync_task waits on. Credential members (Password, SecretKey,
SasConfiguration, the Kerberos files and the nested Protocol.SMB.Password)
are dropped before the configuration is stored, as AWS never reads them back
either. Errors use InvalidRequestException, the only client error the
DataSync model declares.
The task-execution data plane (StartTaskExecution, DescribeTaskExecution,
ListTaskExecutions, CancelTaskExecution, UpdateTaskExecution) transfers real
bytes between real storage systems and keeps raising UnknownOperationException
rather than a stub success.
* fix(datasync): default VerifyMode from the task mode
The DataSync model documents two VerifyMode defaults, not one:
POINT_IN_TIME_CONSISTENT for a BASIC task and ONLY_FILES_TRANSFERRED for an
ENHANCED one, which also cannot use POINT_IN_TIME_CONSISTENT at all. CreateTask
applied the BASIC default to every task, so an ENHANCED task created without an
explicit VerifyMode read back wrong.
The default now follows TaskMode, and a VerifyMode the mode does not support is
rejected with InvalidRequestException, the only client error this API declares.
UpdateTaskRequest carries no TaskMode, so a task keeps the mode it was created
with and UpdateTask applies the same rule against the stored mode. An
unrecognized TaskMode is rejected rather than silently treated as BASIC.
* test(datasync): add the SDK compatibility test
Drives an agent, an S3 and an NFS location, both task modes and the tag round
trip through the AWS SDK v2 DataSync client, which is the one piece of real-SDK
verification the RestAssured tests do not cover. It asserts the VerifyMode
default for a BASIC and an ENHANCED task, and that an ENHANCED task rejects
POINT_IN_TIME_CONSISTENT on create and on update.
---------
Co-authored-by: lex00 <artigues.dev@gmail.com>
Real Amazon MWAA runs every Airflow version through 2.10.x on Python 3.11,
and only 2.11.0 onward (and every 3.x release) on Python 3.12. Floci
hardcoded apache/airflow:<version>-python3.12 for every supported version,
so a requirements.txt built the way AWS documents (a --constraint file
matching the real Airflow/Python pairing, e.g. constraints-3.11.txt for
2.9.x) resolves dependencies for the wrong Python minor version.
Fixes#3438
CloudFormationTemplateEngine#resolveNode now resolves {{resolve:ssm:...}}
and {{resolve:secretsmanager:...}} syntax in any textual result, not only
the RDS master-credential properties CfnDynamicReferences was previously
wired into. The dynamic-reference stage now lives inside resolve() itself,
so every scalar property resolution goes through it, including plain
property lookups such as ProvisionContext#resolveOptional that call
resolve() directly rather than through resolveNode. ssm-secure stays
rejected everywhere except RDS MasterUsername/MasterUserPassword, which
now skip the general dynamic-reference stage via
resolveWithoutDynamicReferences and resolve it separately with the
permission only those two properties are allowed.
* Fix#2213
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* feat(bedrock): add guardrail lifecycle and versions
Amazon Bedrock control plane over REST JSON: CreateGuardrail through
DeleteGuardrail, CreateGuardrailVersion, ListGuardrails with pagination, and
resource tagging on /tagResource, /untagResource and /listTagsForResource.
Guardrails report READY on the first read, so the Terraform provider's status
poll for aws_bedrock_guardrail completes without a transition.
The control plane and bedrock-runtime both sign as "bedrock". The runtime
descriptor keeps that credential scope, and the new descriptor routes through
its resource class, which ServiceEnabledFilter checks first.
Policy blocks are stored under the read-shape member names, so a *Config
submitted on create or update reads back unsuffixed. ListGuardrails honours
maxResults and nextToken, and DeleteGuardrail rejects a guardrailVersion that
is not a GuardrailNumericalVersion.
* fix(bedrock): enforce guardrail length caps and resolve kmsKeyId to a key ARN
The AWS model caps description at 200 characters and both blockedInputMessaging
and blockedOutputsMessaging at 500, each with a minimum of 1. None of those were
checked, so an over-long value was stored and read back. name was already bounded
by its [0-9a-zA-Z-_]{1,50} pattern.
kmsKeyId on CreateGuardrail and UpdateGuardrail is a KmsKeyId: a key id, a key
ARN, an alias name or an alias ARN. kmsKeyArn on the read shapes is a KmsKeyArn,
which is only ever the full key ARN. The request value was echoed back verbatim,
so a bare key id or an alias produced a response that does not match the shape
GetGuardrail declares. It now resolves through KmsService.describeKey, the same
way RDS, DocDB and ElastiCache already resolve their KmsKeyId, and a key that is
missing, disabled or pending deletion is rejected with ValidationException.
* test(bedrock): drive the guardrail lifecycle from the AWS SDK v2 client
Adds the bedrock SDK module to the compatibility project, a BedrockClient
factory on TestFixtures, and a BedrockGuardrailTest covering create, read,
update, versioning, listing, tagging and delete. The test also submits kmsKeyId
as a bare key id and as an alias and asserts both read back as the same full KMS
key ARN.
* fix(bedrock): enforce the guardrail tag caps from the AWS model
The AWS model gives TagList a max of 200 items, and that shape backs the tags
member of both CreateGuardrail and TagResource. TooManyTagsException, declared
on both operations, documents a separate limit of 50 tags per resource counted
over the tags already on the resource together with the ones in the request.
parseTagList now rejects an array over 200 items with ValidationException, and
it moved to BedrockService so both entry points share it. CreateGuardrail and
TagResource raise TooManyTagsException once the total the guardrail would be
left holding passes 50, carrying resourceName as the model declares.
* feat(appintegrations): add data and event integrations
Amazon AppIntegrations over REST JSON, registered under the app-integrations
signing name: event integrations on /eventIntegrations, data integrations on
/dataIntegrations, and resource tagging through the shared /tags/{resourceArn}
dispatcher. Terraform's aws_appintegrations_event_integration and
aws_appintegrations_data_integration now round-trip against Floci instead of
failing on an unimplemented signing scope.
Event integrations are keyed by name, data integrations by generated id, and
both accept their own ARN wherever the API takes an identifier. The two PATCH
operations apply only the members present in the request body, matching how AWS
treats an optional member the caller did not send. Both tag writes answer 200,
which is what the 2020-07-29 model gives them.
* test(appintegrations): add an SDK compatibility test
Adds the appintegrations AWS SDK v2 module, a TestFixtures client factory,
and an AppIntegrationsTest that drives both integration types and the tag
round trip through the real SDK client.
* feat(globalaccelerator): add the Global Accelerator management plane
Emulates the AWS Global Accelerator management plane over JSON 1.1 under the
GlobalAccelerator_V20180706 target prefix, signing name globalaccelerator:
accelerators, listeners, endpoint groups, accelerator attributes and resource
tags, 22 actions in all.
Global Accelerator is a global service, so ARNs carry an empty region segment
and listener and endpoint group ARNs extend the accelerator ARN. Nothing is
keyed by the signing region, so a caller that signs outside us-west-2 sees the
same accelerators. Accelerators report DEPLOYED and endpoints HEALTHY from the
first read, so SDK and Terraform waiters complete on their first poll.
Enum and range members are validated against the API model, and
UpdateAcceleratorAttributes rejects an update that would leave FlowLogsEnabled
true with no destination bucket.
* fix(globalaccelerator): enforce the list caps and HealthCheckPath format from the API model
The scalar ranges were already checked against globalaccelerator/2018-08-08, but the
array-count caps were not. PortRanges, EndpointConfigurations and PortOverrides each
declare max 10, and IpAddresses declares max 2 for the BYOIP case. All four were
unbounded. HealthCheckPath declares max 255 and the pattern
^/[-a-zA-Z0-9@:%_\+.~#?&/=]*$, which was not checked at all.
The new failures reuse InvalidArgumentException and the message shape the existing
scalar validations already use, so they are indistinguishable in kind from those.
* test(globalaccelerator): add the SDK compatibility test
Adds the globalaccelerator SDK module, a TestFixtures client factory and a
GlobalAcceleratorTest that drives accelerator, listener and endpoint group
lifecycles through the AWS SDK v2 client, including the new PortRanges cap.
---------
Co-authored-by: lex00 <artigues.dev@gmail.com>
GetIntegration returned only type, httpMethod, uri and passthroughBehavior,
and GetIntegrationResponse only statusCode and selectionPattern. The mapping
configuration Floci stores and honours at invoke time - requestParameters,
requestTemplates, integrationResponses, responseParameters and
responseTemplates - was never returned, so infrastructure-as-code tools that
diff against these reads saw it as absent and reported drift that never
converged.
Three further corrections in the same area:
- UpdateStage stored method settings under the JSON-Pointer-escaped resource
path ("~1pets/GET"), so the escaped spelling AWS sends produced a key that
nothing could look up. Both spellings now normalise onto "pets/GET", which
is what AWS reports.
- An integration.response.header.X-Foo mapping was resolved case-sensitively,
so it silently yielded null whenever the backend used different casing.
Header names are case-insensitive per RFC 9110.
- An integration with no "type" - which an OpenAPI import can produce - threw
a NullPointerException inside the dispatch switch instead of reporting the
misconfiguration.
Partition parallel scans by hashing the partition key attribute rather than filtering by result list index. This ensures stable, deterministic segment assignment that is unaffected by concurrent mutations or deletions in earlier segments.
Adds uniform-scaling reshard support via existing splitShard/mergeShards
machinery, with the documented double/half, 10000-shard, and 10-scales-per-24h
limits enforced as LimitExceededException/InvalidArgumentException/ValidationException.
The half-shard-count minimum rounds up for an odd current count, which is
Floci's own call since AWS documents only "below half" with no stated
rounding direction; the separate 10 TPS call-rate limit AWS documents on this
action is not simulated, matching Floci's lack of real-time request
throttling elsewhere. Both are now called out explicitly in the docs and code.
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* Fix#3064
* fix(transfer): isolate servers and users by account and region
* ci: retrigger transfer checks
* fix(transfer): migrate legacy resources by scope
* test(transfer): cover unscoped legacy tags
Views built from the Glue catalog selected *, so the column names came from
whatever the underlying files happened to spell rather than from the table.
For a JSON table whose bodies use camelCase keys, a view over a table
declaring lowercase columns still reported camelCase, and a client reading
the declared names found nothing.
Athena reports a table's declared column names: the catalog owns the schema
and the SerDe maps the data onto it. A client written against that contract
reads `tenantid` where the file says `tenantId`, gets no match, and sees an
empty result with no error anywhere - the query succeeds, the rows are
there, and every field is blank.
Project the declared columns explicitly instead. Identifier resolution is
case-insensitive here, so a declared name still binds to an inferred one
differing from it only by case. Partition keys are projected alongside the
data columns: they are part of the table's schema and are what partition
predicates filter on. A partition key repeating a data column is projected
once, since binding it twice would make the view ambiguous.
A table that declares no columns keeps *, leaving inference in charge, so
catalogs that never declared a schema are unaffected.