mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
225233c19256b4e62f7c43e0131d3cf5d2d263dd
380
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
46283f3209 | fix(rds-data): fixing empty array response from statement (#2880) | ||
|
|
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 |
||
|
|
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> |
||
|
|
6f123e83b8 | feat(batch): add update and delete job queue endpoints with corresponding service logic (#2807) | ||
|
|
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> |
||
|
|
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>
|
||
|
|
e2e69f65f5 |
feat(core): add configurable mock responses for stub AI services (#2765)
* feat(core): add configurable mock responses for stub AI services Adds AiMockConfigLoader, a shared mock-response config file (path via AI_MOCK_CONFIG env var or floci.ai-mock-config-file) that lets callers override Textract/Comprehend/Rekognition's fixed stub responses on a per-call basis, so application logic that branches on detection results (e.g. "escalate if sentiment is NEGATIVE") can be exercised end-to-end against floci. Mirrors Step Functions' SFN_MOCK_CONFIG mechanism (same mtime-cached reload without restart), but is shared across three services and never throws: a missing file, unset env var, or no matching entry all fall back to the existing default stub, since mocking here is opt-in on top of an always-available default, not the only way to invoke an action. Lookup keys: Comprehend keys on the exact Text value; Textract and Rekognition key on "<Bucket>/<Name>" from S3Object (a Bytes-backed image/document has no such key, so mocking only applies to S3Object-based calls). CompareFaces keys off SourceImage only. The Textract async Start*/Get* job flow does not support mocking. Closes #2764 * fix(core): catch unchecked exceptions when loading AI mock config Path.of(path) throws InvalidPathException (unchecked) for a malformed path string, and filesystem access can raise other unchecked exceptions IOException alone doesn't cover. load() only caught IOException, so a bad AI_MOCK_CONFIG value would propagate past the loader and turn a normal Comprehend/Textract/Rekognition request into a 500 — the exact opposite of this loader's contract (mocking is optional; it must never break the default stub). Wrapped the load logic in an outer catch (RuntimeException) that falls back the same way the existing IOException cases already do. Addresses review feedback on #2765. |
||
|
|
0b46d804c0 |
feat(codegurureviewer): repository association lifecycle with tagging (#2741)
* feat(codegurureviewer): repository association lifecycle with tagging AssociateRepository, DescribeRepositoryAssociation, DisassociateRepository and ListRepositoryAssociations over CodeGuru Reviewer's REST JSON protocol, with TagResource/UntagResource/ListTagsForResource served on the shared /tags path. The Repository union is validated as AWS validates it (exactly one provider, Owner/ConnectionArn for third-party providers, KMSKeyId required for CUSTOMER_MANAGED_CMK), duplicate associations report ConflictException, and an association is Associated from the first read so provider waiters complete immediately. * fix(codegurureviewer): paginate ListRepositoryAssociations, register the model for reflection, generate the action table ListRepositoryAssociations now honours MaxResults and NextToken with real pagination (the filter query keys stay singular - ProviderType, State, Name, Owner - matching the wire mapping the API reference documents for the plural request fields). RepositoryAssociation carries @RegisterForReflection so native-image persistence survives a restart. The docs page now uses the generated action-table markers, has its service-matrix row, and maps the hyphenated codeguru-reviewer signing name to its doc slug. * fix(codegurureviewer): reject a malformed MaxResults with ValidationException, not 404 A JAX-RS Integer binding fails during parameter conversion, so MaxResults=abc surfaced as 404 before the handler ran. The parameter is now bound as a String and parsed in the controller, routing bad values through the modeled 400 ValidationException. |
||
|
|
eaecb36425 |
fix(eks): implement cluster restoration after restart to maintain state (#2780)
Signed-off-by: Matheus André <matheusandr2@gmail.com> |
||
|
|
cfe8566511 |
fix(cloudwatch): evaluate alarms over CloudWatch's wider evaluation range (#2771)
Querying exactly EvaluationPeriods buckets fell back to TreatMissingData as soon as one was empty. Real datapoints reaching further back now decide the state first, and the premature-transition rule is honored. Fixes #2700 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
2a014d2add |
fix(s3): accept the log-delivery-write canned ACL (#2653)
PutBucketAcl/PutObjectAcl rejected x-amz-acl: log-delivery-write with "Unsupported x-amz-acl value", even though it is a standard AWS canned ACL (Terraform's aws_s3_bucket_acl / access-logging modules send it to grant the S3 log-delivery service group permission to write access logs into a bucket). Of the eight AWS canned ACL values, this was the only one missing from cannedObjectAclXml's switch - the rest were already handled. Add the log-delivery-write case, translating it to WRITE and READ_ACP grants for the well-known LogDelivery group URI (http://acs.amazonaws.com/groups/s3/LogDelivery), following the same groupGrant pattern used for public-read/public-read-write. |
||
|
|
7b6266e902 |
feat(connect): instance management (CreateInstance family, attributes, storage configs, tags) (#2740)
* feat(connect): instance management (CreateInstance family, attributes, storage configs, tags) Amazon Connect control plane: CreateInstance/DescribeInstance/ListInstances/ DeleteInstance, instance attributes, instance storage configs, and resource tagging over REST JSON, registered under the connect signing name. Instances report ACTIVE from the first read so the Terraform provider's status poll completes immediately. 17 integration tests cover the lifecycle, attribute validation against the AWS InstanceAttributeType/DirectoryType/InstanceStorageResourceType enums, storage-config association, and tag round-trips. * docs(connect): register connect in the action-table catalog The Action-tables CI gate requires every service registered in ResolvedServiceCatalog to have an index row and a generated action table; connect's page was hand-written and unregistered. * fix(connect): validate boolean instance attribute values UpdateInstanceAttribute stored any nonblank string while the inbound/outbound flags coerced it to boolean, so an invalid value read back inconsistently across DescribeInstanceAttribute and DescribeInstance. Reject anything but true/false with InvalidParameterException and store the canonical lowercase form. |
||
|
|
fc3c28323a |
feat(ses): support v2 tenant suppression attributes and tenant-scoped suppression list (#2743)
* feat(ses): support v2 tenant suppression attributes and tenant-scoped suppression list * fix(ses): guard runWithTenant against a null TenantName * fix(ses): collapse an absent TenantName to the service-level message on tenant suppression ops * fix(ses): collapse an absent TenantName to the service-level message on the remaining tenant ops * fix(ses): collapse an empty TenantName to the service-level message on GetTenant/DeleteTenant |
||
|
|
b76eadc98e |
docs(cloudformation): generate the supported resource-type table (#2739)
The "Supported Resource Types" table was hand-maintained, and had drifted: ten provisioned types were undocumented, including the whole CloudFront row, Lambda's Permission/MicrovmImage/NetworkConnector, RDS DBProxy and DBProxyTargetGroup, ECS capacity providers, EC2 VPCEndpoint and ApiGatewayV2 Authorizer. Generate it from the provisioner inventory TSV that CfnResourceInventoryTest already pins to the CDI-resolved registry, so the table cannot drift from what Floci actually provisions. Wired into docs-sync and docs-check, with the inventory path added to the workflow filters: it lives under src/test/resources, which src/main/** did not cover, so a slice that moved a type between owners would have skipped the gate. The table is prose as much as data, so presentation stays configurable in cfn_resource_types.yaml: service labels, curated type order (types not listed there are appended alphabetically, so a new type still appears), per-type notes, and extra_types for capabilities that are real but are not provisioner types, each needing a stated reason. Nested Stack and the Custom::* wildcard are the two such entries; the wildcard cannot be an inventory type because the registry is keyed by exact type. The generator reads the TSV rather than the Java because several provisioners return Set.of(CONSTANT, CONSTANT) from resourceTypes(), which a source regex only partly sees. Also flags two things cheaply, before anyone waits on a Quarkus boot: a provisioner missing @ApplicationScoped, and a type claimed by both the legacy switch and a provisioner. |
||
|
|
ed167135ff |
feat(cognito): user pool domain operations (Create/Describe/DeleteUserPoolDomain) (#2742)
* feat(cognito): user pool domain operations (Create/Describe/DeleteUserPoolDomain)
Adds the domain family Cognito was missing, which blocks any estate using
aws_cognito_user_pool_domain (e.g. an ALB authenticate-cognito listener).
Supports both an Amazon Cognito prefix domain and a custom domain backed by
an ACM certificate ARN, matching the documented request and response shapes.
Domain names are globally unique across pools; a missing domain reports
ResourceNotFoundException on Describe/Delete, consistent with the rest of
the Cognito handler's not-found behavior.
* fix(cognito): refuse DeleteUserPool while a domain is configured
The DeleteUserPool API reference documents this refusal: a pool with a
hosted UI or custom domain answers InvalidParameterException ("User pool
cannot be deleted. It has a domain configured that should be deleted
first.") rather than deleting and stranding the globally-unique domain
name.
|
||
|
|
8a705d0aae |
feat(cloudformation): provision WAFv2 web ACLs and AWS Config rules (#2701)
* feat: provision WAFv2 web ACLs
* feat: provision AWS Config rules
* fix: adapt provisioners to current 3-arg CfnResourceProvisioner.delete()
* fix: preserve new-resource tracking when replacement cleanup fails, and stop dropping inline-object InputParameters
Local code review (review-local.ts) flagged two ordering bugs on the replacement
path in both provisioners: the new resource's physicalId/attributes were only
recorded after the old resource's delete call succeeded, so a delete failure
(e.g. WAFAssociatedItemException, or a Config rule still referenced elsewhere)
left the stack tracking the old resource while the newly created one leaked
untracked. Both now record the new resource first and treat old-resource
cleanup failure as non-fatal, matching the existing precedent in
Ec2LaunchTemplateCfnProvisioner.
Also fixed AWS::Config::ConfigRule.InputParameters being silently dropped
when a template supplies it as an inline JSON object (the common case) rather
than a pre-stringified JSON string: JsonNode.asText() returns empty string
for object nodes.
* fix(cloudformation): preserve intrinsic-resolved JSON fields on WAFv2 WebACL, log tolerated replacement-cleanup failures, add GetAtt coverage
raw() in WafV2CfnProvisioner used JsonNode#isEmpty(), which is true for every
scalar node, so any field CloudFormationTemplateEngine#resolveNode collapsed
into a TextNode (e.g. an Fn::Join-built DefaultAction) silently became null
instead of the literal JSON text. Mirror ConfigCfnProvisioner's existing
isTextual()-aware handling.
Also log (previously fully swallowed) exceptions when replacement cleanup of
the superseded WAFv2 WebACL or Config rule fails, so a leaked old resource is
diagnosable, and add an integration test asserting the exact Fn::GetAtt keys
for both provisioners resolve through CloudFormation to the real resource.
Config's PutConfigRule call being unconditional on every provision is correct
AWS upsert semantics ("Adds or updates" per the Config API), not a missing
create/update branch.
|
||
|
|
a1383fdd3d |
feat(redshift): implement Redshift emulation with snapshot and parameter group support (#2472)
* feat: add redshift domain models
* feat: add redshift service and test
* feat: add redshift query handler and routing
* feat(redshift): implement data plane container manager and wire storage
This commit implements Redshift Container Manager, wires the StorageFactory into RedshiftService, uses AwsException for error handling, implements Describe/Delete Clusters, and adds integration tests with AWS SDK in the compatibility tests project.
* feat: add redshift operations models and service logic
* fix: correct yaml indentation for redshift storage config
* fix: remove invalid redshift storage properties
* feat: implement pg_dump and psql for redshift snapshots
* feat: add redshift core operations query actions
* test: add redshift operations integration test
* fix(redshift): Write snapshot SQL dumps to file storage and add Parameter model
* docs: add redshift implementation plan, design spec, and PR description
* chore: remove superpowers working files
* fix(redshift): scope snapshots and cluster recovery per account, restore original password
- Scope snapshot SQL dump files under redshift-dumps/{accountId}/ so
same-identifier snapshots from different accounts no longer collide,
overwrite, or delete each other's data.
- Restore uses the source cluster's real master password instead of a
hardcoded value, falling back to "admin" only when the source cluster
no longer exists.
- Recreate Docker containers for all persisted "available" clusters on
startup, across every account (not just the default), fixing clusters
that were reloaded with stale endpoints but no running container.
- Add AccountAwareStorageBackend.accountId() accessor needed for the
account-scoped dump path.
* fix(redshift): add logging for cleanup failures in RedshiftOperationsTest
* fix(redshift): scope container identity per account, persist snapshot password
- RedshiftContainerManager now keys its in-memory container map and Docker
container name by accountId + clusterIdentifier, instead of just the
cluster identifier. Previously two accounts creating a cluster with the
same identifier would share (and clobber) the same Docker container,
so startup recovery for the second account silently skipped its own
cluster and left it advertised with a stale endpoint.
- Snapshot now captures masterPassword at snapshot-creation time, so
restoreFromClusterSnapshot can recover the original credential even
after the source cluster has been deleted, instead of falling back to
"admin".
- Clean up fully-qualified java.nio.file / commons-compress references in
RedshiftContainerManager in favor of imports.
* feat(redshift): implement adoptOrStart method to reuse existing containers
* chore: gitignore subagent-driven-development scratch workspace
* feat(redshift): add tagging support to RedshiftService
- Add tags field to Cluster, Snapshot, and ClusterParameterGroup models
- Inject RegionResolver into RedshiftService constructor
- Implement tag CRUD methods: createTags, deleteTags, describeTags, listTagsForResource
- Add resolveTagHandle ARN resolver for tagging operations
- Add 6 new unit tests covering tag operations and error cases
* feat(redshift): wire CreateTags/DeleteTags/DescribeTags into the query handler
* feat(redshift): store real parameter values on ClusterParameterGroup
* fix(redshift): use proper imports and preserve parameter metadata on modify
* feat(redshift): wire ModifyClusterParameterGroup, return real DescribeClusterParameters values
* feat(redshift): add ClusterSubnetGroup model and CRUD
* feat(redshift): wire ClusterSubnetGroup CRUD into the query handler
* feat(redshift): add ClusterSubnetGroupName/VpcSecurityGroupIds metadata to Cluster
* feat(redshift): add RedshiftContainerManager.alterUserPassword
* fix(redshift): prevent SQL injection in alterUserPassword via username validation
* feat(redshift): add RedshiftService.modifyCluster
* feat(redshift): add RedshiftService.rebootCluster (dump/restore based, no data loss)
* feat(redshift): wire ModifyCluster/RebootCluster into the query handler
* test(redshift): add compatibility coverage for tagging, subnet groups, modify/reboot
* fix(redshift): use imports and unique names in compatibility test
Follow this file's established conventions: proper imports instead of
fully-qualified SDK types, and TestFixtures.uniqueName() instead of
hardcoded resource names, matching the pattern used by the sibling
test methods.
* fix(redshift): address final whole-branch review findings
* fix(redshift): address PR review feedback and green the CI
Review comments:
- Translate three Vietnamese comments in RedshiftContainerManager and
RedshiftService to English (repo is English-only).
- alterUserPassword: reword the single-quote guard to cite the AWS
ModifyCluster MasterUserPassword constraint rather than the psql SQL
literal, and enforce the full documented set for parity — reject
' " \ / @, require length 8-64 and at least one upper/lower/digit.
- adoptOrStart: LOG.warnv on the container-gone branch so a fresh empty
cluster after a lost container is a searchable line, not a silent one.
- Move the .superpowers/ scratch ignore from the shared .gitignore to
.git/info/exclude (local tooling, not project output).
CI failures:
- Register redshift.model.Parameter for reflection so
PersistedModelReflectionTest passes and native-image persistence works
(fixes CI shard 3 and the native sdk-test-java compat run).
- Convert RedshiftQueryHandler.handle() from an if/else chain to
switch (action) so the docs action-table generator can extract the
action list, matching every other Query handler. Bodies unchanged.
- Register redshift in tools/docs/services.yaml, add docs/services/redshift.md
with the generated action table, and add the Service Matrix row in
docs/services/index.md (fixes Docs Action Tables / Action tables in sync).
* fix(redshift): reject path traversal in SnapshotIdentifier
createSnapshot spliced the request's SnapshotIdentifier straight into a
host path (<persistentPath>/redshift-dumps/<accountId>/<id>.sql). A value
with traversal segments or an absolute prefix escaped the account dump
directory: snapshot creation would write pg_dump output over an arbitrary
host file, and the resulting absolute path was persisted so a later
restore (arbitrary read into an attacker-controlled DB) or delete
(arbitrary unlink) trusted it.
- validateSnapshotIdentifier: enforce AWS's format (1-255 chars, leading
letter, letters/digits/non-consecutive hyphens) — rejects '.', '/', '\'
so no separator can appear.
- Keep a normalise + startsWith(dumpDir) containment check as defence in
depth.
- restore/delete now verify the stored sqlDump path still resolves inside
the account dump dir before touching it, so a path written by the
pre-fix code can't be acted on.
Also replace inline java.* fully-qualified names in RedshiftService and
RedshiftQueryHandler with top-of-file imports.
* fix(redshift): validate snapshot dump path before restore provisioning
The trusted-dump-path check added in the previous commit ran inside the
try block, after restoreFromClusterSnapshot had already persisted the
target cluster as "creating" and started its container. Rejecting an
untrusted path then left the container running and a "failed" cluster
record behind, blocking a retry with the same identifier
(ClusterAlreadyExists).
Move the check ahead of all provisioning — right after the snapshot is
loaded, before clusters.put and containerManager.start — so a rejected
restore creates no resources.
---------
Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
|
||
|
|
08e532ab1a |
feat(cloudformation): CDK Provider-framework custom resources and changeset/SSM param fidelity (#2688)
* feat(cloudformation): changeset diffs, stack params, SSM attributes CDK's deploy loop reads all three: DescribeChangeSet now returns computed Add/Modify/Remove resource changes instead of an empty list (an empty list makes CDK skip ExecuteChangeSet on updates), DescribeStacks echoes the stack's merged parameters, and AWS::SSM::Parameter resources expose Value/Type/Name attributes so Fn::GetAtt resolves the bootstrap version (cherry picked from commit 80ac80063e84ef1be977fe625334e722cc1ed8bb) * feat(cloudformation): resolve SSM-typed stack parameters AWS::SSM::Parameter::Value<String> template parameters resolve through SSM for the stack's account and region; missing parameters fail with the real ValidationError message. Landing Zone Accelerator's security and logging stacks depend on this typed-parameter resolution. The IAM password-policy and S3 replication-config changes from the same source commit ship separately in the iam and s3 branches. (cherry picked from commit 10dbabbf5e31d763a398fc1fff16ab0484958af0) * feat(cloudformation): drive CDK Provider framework custom resources The CDK Provider framework defers its ResponseURL callback to a Step Functions waiter that polls framework.isComplete on a Retry cadence until the resource is ready. The custom-resource provisioner only waited the synchronous single-lambda budget for a ResponseURL PUT, so the waiter-driven PUT never landed. A framework.onEvent ServiceToken is now awaited on a bounded async budget so that PUT is captured; onEvent-only and single-lambda resources are unchanged. The engine-side half of the original commit -- a Task-only Retry implementation for the ASL executor (ErrorEquals/IntervalSeconds/ MaxAttempts/BackoffRate/MaxDelaySeconds) -- is dropped here: upstream #2455 ("feat(sfn): support Retry policies in Task, Parallel, and Map states") landed a broader Retry implementation independently (Task, Parallel, and Map states; JitterStrategy; $$.State.RetryCount; Retry-before-Catch ordering), a strict superset of what this commit needed. The full stepfunctions suite (411 tests) is green against it on this branch, and CustomResourceProviderFrameworkTest (a hermetic test of the provisioner's own detect-and-wait logic, no Step Functions involved) is unaffected by the drop. (cherry picked from commit 5b3502d8c9dddf3766ca3f94fe7f146042dc00fd) * docs(cloudformation): document CDK provisioning Documents the CDK Provider-framework custom-resource support and folds its cross-reference into upstream's existing "Retry policies" section in step-functions.md rather than duplicating it with a separate "State Retry" section (upstream #2455 already documents the Retry engine itself). * feat(cloudformation): budget custom-resource waits by idleness, not total time The async custom-resource wait was a fixed 3-minute total budget. That is a property of the emulator, but the time a CDK provider-framework resource needs is a property of the work: Custom::CreateOrganizationAccounts creates exactly one account per 15s waiter poll, so a 3-account org finishes in ~45s while a 15-account org needs ~195s. Past the budget the Lambda is guillotined mid- success -- the accounts all exist, but the resource reports CREATE_FAILED, the stack rolls back, and CDK's readback then surfaces the misleading "NoStack: CloudFormationStack object does not hold a stack". Measure idleness instead. The provisioner already embeds its callback token in the ResponseURL it puts on every event, and the framework echoes that event into each framework.isComplete poll, so a poll arriving at LambdaService is proof of progress for a specific pending resource. Each poll resets the budget, which makes the wait proportional to the work without CloudFormation needing to know what the work is -- and a genuinely hung resource still fails after 3 idle minutes exactly as before. CustomResourceLiveness lives in core.common so the Lambda service can report progress without depending on CloudFormation; the dependency already runs the other way. (cherry picked from commit 14087c992ebb75d109999153a9e8af7e3c2d79f4) (cherry picked from commit 51349e4e017ed08d90e6e71212414e2f306c826b) * fix(cloudformation): call the caller-scoped getStackOrThrow overload that exists The changeset-diff commit re-derived onto main carried a call to a three-arg getStackOrThrow(name, region, accountId) overload that only existed on the account-scoping commit deliberately skipped as superseded by upstream. Upstream's resolveStack already scopes to the caller's account, so the two-arg form is equivalent and compiles. * fix(cloudformation): honour an arrived custom-resource response past its budget A synchronous custom-resource handler PUTs to the ResponseURL from inside the invoke the provisioner is blocked on, so its response can already be delivered by the time await() is entered. Two independent flaws then threw it away. The idle clock started at register(), before the invoke. A provider-framework onEvent-only handler that took 75s to return -- two nested cold container starts -- had spent its 10s CR_RESPONSE_TIMEOUT six times over before await was reached, so the very first deadline check was already negative. Idleness of the wait cannot include time the handler spent working; the clock now starts when the caller starts waiting. The deadline guard also threw without ever consulting the future, so a response that had completed it was discarded as a timeout. Observed on AccessAnalyzerServiceLinkedRoleCreateServiceLinkedRoleResource: the handler logged its response at 15:52:11.768 and the resource was failed 24ms later. An arrived response outranks the clock. Both are pinned by red-first tests. The existing idle-timeout guarantees are unchanged: nothing arriving still times out, and a resource that stops reporting liveness still dies on schedule from its last touch. (cherry picked from commit 7dc8bbca7d47b2a029b5656a89421a556b8296be) (cherry picked from commit 77b71b31a634ae27d7460a078b52dac250d67dc7) * refactor(cloudformation): extract Provider-framework detection from the provisioner The CDK Provider-framework `framework.onEvent` detection and the longer idle budget it earns lived in CloudFormationResourceProvisioner, adding ~55 lines to a class that is being dismantled rather than grown. Move the concern to ProviderFrameworkDetector: it owns the two waiter marker env vars, the best-effort environment probe, the 3-minute async budget and the test seam that shortens it. CustomResourceResponseStore — which already owns the idle-timeout concept via touch/await — gains an await overload that resolves the budget for a ServiceToken and delegates to the existing one, so the provisioner only passes the token through and appends the store's timeout detail to its error. Behaviour is unchanged. (cherry picked from commit 5f93439f409a32012a01b996c5edd0c29d23b260) * fix(stepfunctions): report custom-resource liveness on waiter polls A CDK provider-framework waiter's framework.isComplete poll is itself a Lambda Task the state machine invokes, so it goes through AslExecutor.invokeResource -> LambdaExecutorService directly, bypassing LambdaService.invoke() and the liveness hook it carries. A long-but- progressing custom resource's idle budget in CustomResourceResponseStore ticked down as if no polls were arriving, even while they kept landing. AslExecutor now reports liveness the same way LambdaService does: extract the callback token from the invoke payload and touch() it before invoking. * perf(core): avoid materializing the full payload string in tokenIn CustomResourceLiveness.tokenIn() ran on every Lambda invoke once liveness reporting is wired in, decoding the whole invoke payload as a UTF-8 String even though the overwhelming majority of invokes carry no callback URL at all. Scan the raw bytes for the ASCII "/cfn-response/" marker instead, and only allocate a String for the small token substring when one is found. * fix(cloudformation): compute accurate changeset resource diffs computeChangeSetChanges never read cs.getParameters(), so an update that only changed parameter values reported an empty diff and CDK skipped execution, leaving the old parameter-derived config deployed. It also diffed a SAM change set's raw template against the stack's expanded deployed template, reporting spurious Modify/Remove on every SAM-generated resource for a no-op update, and hardcoded Replacement=False even when a resource's Type changed. Now the diff expands a SAM change set's template before comparing, marks a resource Modify when it references a changed parameter, and reports Replacement=True when a resource's Type changes. * fix(cloudformation): restore last-successful parameters on update rollback executeTemplate overwrote the stack's live parameter map with an update's attempted values before resolving SSM-typed parameters, which can fail. A failed resolution rolled the stack back, but the update snapshot never captured parameters, so DescribeStacks reported the failed update's attempted values instead of the last successfully deployed ones. StackUpdateSnapshot now captures the stack's parameters alongside its template body, and rollbackFailedUpdate restores them together. * fix(cloudformation): log tolerated wait-slice timeouts in custom-resource poll loop Each slice of the custom-resource poll loop below the outer idle budget hit an intentionally-tolerated TimeoutException that was swallowed with only a comment, against the repo's convention of logging deliberately caught exceptions. * fix(cloudformation): honor Parameters.member.N.UsePreviousValue extractParameters never read UsePreviousValue, so submitting it without a ParameterValue stored an empty string for that key. The new parameter-diff logic in computeChangeSetChanges ( |
||
|
|
0dfec3cf3c | fix(cloudfront): separate DEVELOPMENT and LIVE function stages (#2622) | ||
|
|
67f75c7e1d |
feat(ses): support v2 tenant resource associations (#2710)
* feat(ses): support v2 tenant resource associations * fix(ses): reject nameless association ARNs and stop key-suffix resource matching |
||
|
|
2a7c94b04d |
feat(applicationautoscaling): evaluate target-tracking and step-scaling policies against ECS (#2692)
Adds a generic CloudWatch alarm evaluator plus an ECS CapacityAdjuster, so a firing policy calls UpdateService to change desiredCount instead of sitting inert. Adds DescribeScalingActivities to observe the result. Closes #2565 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
cf6fede453 |
feat(rekognition): add Amazon Rekognition sync image-analysis actions (#2706)
* feat(rekognition): add Amazon Rekognition sync image-analysis actions Implements DetectLabels, DetectFaces, DetectText, CompareFaces, and DetectModerationLabels as fixed AWS-shaped stub responses over the real JSON 1.1 wire protocol (X-Amz-Target: RekognitionService.*). Image/SourceImage/TargetImage input is required and validated (must specify Bytes or S3Object) but never decoded, matching the pattern already used for Textract's Document input. Content-listing operations (DetectLabels, DetectText) always return one canned entry, matching TextractService's stub precedent. Face and moderation operations (DetectFaces, CompareFaces, DetectModerationLabels) return empty results by default rather than fabricating biometric attributes or a moderation flag for content that was never analyzed, matching ComprehendService's PII-detection precedent. Face-collection persistence, custom-model training, live video (StreamProcessor), async video jobs, and Face Liveness sessions are out of scope for this PR. Closes #2705 * fix(rekognition): reject wrong-typed Bytes/S3Object as SerializationException requireImage() only checked field presence via hasNonNull(), so a wrong-typed Bytes (e.g. a number) or S3Object (e.g. a string) was silently accepted instead of rejected, same class of bug as the Comprehend Text/LanguageCode type-coercion fix. Bytes must now be textual and S3Object must be an object when present, both rejected as SerializationException (a shape/marshalling mismatch) otherwise. Content-level validation (well-formed base64 in Bytes, S3Object's Bucket/Name presence, rejecting both Bytes and S3Object together) is intentionally not added: S3Object has no required members in AWS's own model, and nothing in the model declares supplying both fields invalid — documented as intentional deviations. Addresses review feedback on #2706. |
||
|
|
5600d21f32 |
feat(stepfunctions): emit task history events and chain previousEventId (#2703)
A Task state now emits Scheduled, Started, and Succeeded or Failed events. Service integrations get Task* events. Direct Lambda ARNs get LambdaFunction* events. Activity ARNs get Activity* events. taskScheduledEventDetails carries the resolved Parameters or Arguments as a JSON string. previousEventId now chains every event to the one before it. The first state's Entered event points to 0, matching real AWS. Details now include inputDetails and outputDetails where AWS has them. Event shapes were verified against real AWS. Fixes #2520 |
||
|
|
13664e7693 |
fix(ecs): report schedulingStrategy, deploymentController and availabilityZoneRebalancing on services (#2482)
AWS echoes all three on CreateService/UpdateService/DescribeServices; Floci dropped them, so clients that persist them saw drift. Terraform's aws_ecs_service reads all three and schedulingStrategy is ForceNew, which replaced the service on every apply. - EcsServiceModel: schedulingStrategy and availabilityZoneRebalancing alongside the existing deploymentController - CreateService parses schedulingStrategy, deploymentController.type and availabilityZoneRebalancing (400 InvalidParameterException on unknown values); UpdateService parses availabilityZoneRebalancing - Defaults match AWS: REPLICA / ECS, and availabilityZoneRebalancing is ENABLED on create; a service that never had a value reads as DISABLED - DAEMON is honoured, not just stored: rejected for the Fargate launch type and the CODE_DEPLOY/EXTERNAL controllers (AWS's rule), otherwise the reconciler keeps exactly one task per ACTIVE container instance and derives desiredCount from the instance count Co-authored-by: Hisham Mohammed <hisham.ma.mohammed@gmail.com> Co-authored-by: Priamo <pgermosen@gmail.com> |
||
|
|
aaae99282f |
feat(kinesisanalytics): emit MSF-style JSON CloudWatch logs from Flink (#2656)
* feat(kinesisanalytics): emit MSF-style JSON CloudWatch logs from Flink
The JobManager/TaskManager now start with a log4j-console.properties
that formats every log line as a single JSON object matching real
Managed Service for Apache Flink's CloudWatch Logs schema
(applicationARN, applicationVersionId, locationInformation, logger,
message, messageSchemaVersion, messageType, threadName,
throwableInformation), instead of the stock image's default plain-text
pattern. Applies to Flink's own framework logs and anything a deployed
JAR logs through SLF4J/Log4j2, so a JAR that expects its logs to reach
CloudWatch (or asserts on this schema) sees the same thing here as on
real MSF.
Written into the container before the JVM starts -- log4j2 reads its
config at process boot, so copying the file in after start (the way
application_properties.json already is) would be too late. Required
splitting the JobManager/TaskManager container startup from
createAndStart into create + copyFileIntoContainer + startCreated,
mirroring the create-then-inject-then-start pattern
ContainerLifecycleManager already exposed for exactly this purpose.
* fix(kinesisanalytics): escape log4j2 pattern injection and fail loudly on log4j copy failure
ApplicationName flows unvalidated into the ARN baked into the JSON log
pattern, so a name containing '%' could be interpreted as a log4j2
conversion specifier and a '"' or '\' could break the emitted JSON.
Escape both before embedding, reusing the existing %enc{}{JSON}
wrapper to JSON-encode the value at log time.
Also stop silently swallowing a failed log4j-console.properties copy:
startCluster previously reported success and ran with the stock
(non-JSON) log format if the copy failed. The copy is now required,
so a failure rolls back the cluster the same way a create() failure
already does.
* fix(kinesisanalytics): validate ApplicationName, fix NPE, and block log4j2 Lookup injection
CI failure: startClusterLabelsJobManagerContainerWithResourceIdentity
built a FlinkApplication with no ARN set, and literalForLog4j2Pattern
NPE'd on the null value. Wrap both baked-in values with
String.valueOf() so a null degrades to the literal text "null"
instead of throwing.
Also validate ApplicationName against AWS's real CreateApplication
constraint (Pattern: [a-zA-Z0-9_.-]+, 1-128 chars) instead of only
requiring it non-blank -- this is both a genuine AWS-parity fix and
what keeps '%', '"', '\', or '$' out of the generated log4j2 pattern
in the first place.
Finally, close a gap the previous escaping missed: '$' wasn't
neutralized, so a name containing a log4j2 Lookup ('${env:...}',
'${sys:...}') would have it resolved against the process environment
at config-load time and baked into every emitted log line. Doubling
'$' the way '%' is doubled only defers the lookup to render time
rather than neutralizing it, so literalForLog4j2Pattern now drops '$'
outright.
* fix(kinesisanalytics): reject legacy invalid ApplicationName at StartApplication too
Greptile follow-up: an application persisted before the
ApplicationName validation existed (e.g. one with '$' in its name)
would bypass CreateApplication's new check entirely, and
StartApplication would silently generate a CloudWatch-log
applicationARN with the '$' dropped -- mismatching the real
ApplicationARN.
I verified empirically (a standalone harness against the actual
log4j-core jar) that there's no safe way to preserve '$' here: doubling
it or backslash-escaping it both still let log4j2 resolve the Lookup
and leak the referenced environment variable, so dropping it was the
only safe option. Given that, StartApplication now re-validates the
name and fails loudly for such legacy state instead of quietly
emitting a mismatched ARN -- real AWS could never have had this state
to begin with, so refusing to start it is the more AWS-faithful
outcome anyway.
* fix(kinesisanalytics): fix test compile error from Mockito generic inference
when(storageFactory.create(...)).thenReturn(store) failed to compile:
create()'s type parameter defaults to Object with no target-type
context to unify against the pre-declared, concretely-typed 'store'
variable, so thenReturn(store) rejected it as a type mismatch.
Switch to doReturn(store).when(storageFactory).create(...), matching
the same pattern already used for this exact scenario elsewhere in
this file (readinessPollerPersistsFlinkJobIdAssignedBeforeReachingRunning).
|
||
|
|
ff61c2b2a5 |
feat(stepfunctions): describe a distributed Map run after it finishes (#2694)
* feat(stepfunctions): describe a distributed Map run after it finishes DescribeMapRun was not implemented, and arn:aws:states:::aws-sdk:sfn:describeMapRun reached the end of the dispatch chain in invokeResource, so a distributed Map could not be inspected once it was over: the Map run ARN was minted from a fresh UUID, written into the S3 manifest, returned in the Map result and then dropped. A run is now retained where the ResultWriter mints that ARN, which is also the only place an ASL author reads it. The manifest is no shortcut to the counters, since it writes FAILED and PENDING as empty arrays and puts every item under SUCCEEDED, so the run carries the item count taken where the iterations complete. A Map fails on the first item that fails, so a retained run is one whose every item succeeded. That fixes the status, both tolerances and the redrive counters at the values us-east-1 reports for such a run, and leaves succeeded, total and resultsWritten as the item count. An unbounded Map, which ASL spells as MaxConcurrency 0 or by omitting it, is reported as Integer.MAX_VALUE. The Task integration recases the wire response rather than restating it, so the two renderings of a run cannot drift, and renders both dates as the SDK's ISO-8601. Closes #2671 * refactor(stepfunctions): close a Map run's window on the export that mints its ARN recordMapRun sampled the wall clock and then folded the child timings into both ends of the run's window, but the clock is read after MapIterationScheduler has joined every child and after applyResultWriter has exported, so it is at or past every child's stop. Math.max over the timings could therefore never move stop off that sample, and the javadoc promised a last-item stop the code never computed. The sampled value is the faithful one: AWS closes a Map run's window on the export rather than on the last item, and the sample is taken immediately after it. Only start is recovered from the timings, which is the one end the Map state records nowhere else. DescribeMapRun returns the same startDate and stopDate as before. * test(compatibility): cover DescribeMapRun through the AWS SFN SDK client StepFunctionsDescribeMapRunIntegrationTest only exercises the endpoint via RestAssured, leaving the SDK's own request serialization, endpoint routing and response deserialization untested, contrary to AGENTS.md's rule that management APIs be validated with AWS SDK clients. --------- Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |
||
|
|
ea11e67719 |
fix(stepfunctions): fail the state when a JSONata expression returns nothing (#2689)
* fix(stepfunctions): fail the state when a JSONata expression returns nothing An expression that returned nothing lost its key and the execution carried on down the happy path. Real AWS fails the state with States.QueryEvaluationError, names the field the expression was written in and a Catch on that error fires. Three of the positions changed control flow rather than data: a Choice took Default, a Wait did not wait, and a Task sent its request with the argument omitted. evaluateField evaluates one expression and fails the state on a missing node. resolveTemplate calls it at every leaf, carrying the field it is inside and extending it with /key per object key and [i] per array index, so the cause names Output/a/b[0][1] the way AWS does. Choices[n]/Condition, Seconds, Error, Cause, MaxConcurrency and Items call it directly. Three pieces go with it, all of them things a missing node used to need. An undefined array element was a States.Runtime special case with its own wording; AWS answers States.QueryEvaluationError and Output/values[0], the same shape as every other position. resolveTemplateNode existed to let resolveTemplate turn a whole field that returned nothing into a null, so the output would still serialize; there is no output to serialize once the state fails. And the two ResultWriter guards fired only on a key resolveTemplate had dropped, which can no longer happen. An explicit JSON null is a value and still succeeds, everywhere. Closes #2665 * fix(stepfunctions): name a Choice rule's and a Catch clause's own fields under their index A matched Choices[i] rule and a matching Catch[i] clause carry their own Assign and Output, and applyJsonataAssignAndOutput named them 'Output' and 'Assign' as if they were the state's. AWS names them under the rule or the clause: Choices[1]/Output/v, Choices[0]/Assign/x and Catch[1]/Output/v, each measured on the account. The index is the position in Choices or Catch, not the position among the entries that matched. The Catch label was unobservable until now. doExecute calls handleCatch from inside its own catch (FailStateException), so an expression failure raised while resolving the clause's own Output escaped both that clause and its sibling catch (Exception), reaching the method-level handler that answers States.Runtime with the raw message. The execution now fails with the clause's own error, which is what AWS reports and what the clause was catching no longer is. * test(stepfunctions): follow the field path through the crashing evaluator stub * test(stepfunctions): put the Catch clause under test on a Task, as AWS requires aCatchClauseNamesItsOwnOutputUnderTheClauseIndex carried Catch on a Pass state, which AWS refuses: validate-state-machine-definition answers SCHEMA_VALIDATION_FAILED, "Field 'Catch' is not supported" at /States/Boom. The label the test pins is right, Catch[1]/Output/v, and the state now fails on its own Arguments the way the measured execution did, so the definition is one AWS accepts. * docs(stepfunctions): drop the deviation this change removes The key dropped by an expression that returned nothing is no longer Floci's own behaviour: the state fails, as the section below records. --------- Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |
||
|
|
5534460492 |
fix(stepfunctions)!: reject JSONata top-level references at definition time (#2699)
* fix(stepfunctions)!: reject JSONata top-level references at definition time
A Step Functions JSONata expression is evaluated with no context item: the
execution input arrives as $states.input and an Assign variable as $name. A
path whose first step is a bare name reads a context item that does not exist,
and real AWS refuses the definition from CreateStateMachine,
UpdateStateMachine and ValidateStateMachineDefinition with
UNSUPPORTED_JSONATA_EXPRESSION: Reference to '<name>' at the top level is not
supported. Floci accepted those definitions and failed the execution instead.
Every JSONata string in a JSONata state is now walked before the state machine
is stored, and each distinct top-level name is reported with the message and
the /States/... location AWS prints. Only the first step of a path is read
against the top-level context, so later steps, predicates, sort terms and
group expressions stay legal; a lambda body keeps the defining context and is
walked. Syntax errors and $$ keep their current behaviour.
The parse tree of com.dashjoin:jsonata is package-private and Quarkus loads
application classes and dependency jars under different class loaders, so the
tree fields are read reflectively, resolved once at class initialization and
registered for native image.
BREAKING CHANGE: state machines whose JSONata expressions reference a bare
top-level name are now rejected at creation, as on AWS. Anchor the reference
with $states.input.<name> for input or $<name> for an Assign variable.
* fix(stepfunctions): parse a JSONata payload key named after an ASL field
The deny list of fields AWS does not parse as JSONata was applied to every
key at every depth, so a payload key named Next, Comment, Resource, Retry,
Default, ErrorEquals, Credentials, Branches, ItemProcessor or Iterator hid
its expression. AWS parses a payload whole: `Assign: {"Next": "{% phone %}"}`
and `Arguments: {"Payload": {"Comment": "{% phone %}"}}` are both refused
with `Reference to 'phone' at the top level is not supported.` The deny list
now stops applying once the walk enters Output, Assign, Arguments,
ItemSelector or BatchInput.
The same walk refused `ItemReader.ReaderConfig.CSVHeaders`, which holds
literal column names: `validate-state-machine-definition` returns OK for it
and `create-state-machine` stores the machine, so CSVHeaders joins the list.
---------
Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
|
||
|
|
14112b8ace |
feat(stepfunctions): dispatch the seven Task service integrations of #2663 (#2686)
* feat(sfn): support the aws-sdk:sfn:startSyncExecution task integration Calling an Express child workflow from a Standard parent goes through arn:aws:states:::aws-sdk:sfn:startSyncExecution, which reached the end of the dispatch chain and failed with "Unsupported resource". The integration reuses the existing StartSyncExecution service call and differs from the optimized states:startExecution.sync integration in two observable ways: the response envelope uses PascalCase field names with Output as a JSON string, and a child execution that fails is reported through Status instead of failing the calling task. * feat(stepfunctions): dispatch the six remaining Task service integrations events:putEvents, aws-sdk:sfn:startExecution, aws-sdk:sfn:sendTaskSuccess, aws-sdk:sfn:sendTaskFailure, aws-sdk:scheduler:createSchedule and aws-sdk:scheduler:updateSchedule reached the end of the dispatch chain in invokeResource and failed with "Unsupported resource", although Floci already serves all six APIs. Each branch maps the Task Arguments onto the client the direct call already goes through: putEvents onto EventBridgeHandler, and the scheduler pair onto the controller's own parse and SchedulerService. Two conventions of the aws-sdk: integrations, measured against us-east-1 through test-state, now hold for the whole family and correct the startSyncExecution envelope with them. A timestamp is the SDK's ISO-8601 rendering rather than the epoch seconds the wire response carries, and an error names the SDK exception class, so it always ends in Exception. SendTaskSuccess and SendTaskFailure report whether the token resolved a waiting task, which is what lets the Task integration fail with Sfn.InvalidTokenException instead of reporting a delivery that never happened. The direct API keeps tolerating an unknown token. Closes #2663 * fix(stepfunctions): make scheduler argument validation reachable for Retry and Catch parseScheduleRequest raises the same AwsException the scheduler service raises, so a Task whose Target.EventBridgeParameters is incomplete failed the execution with States.Runtime and skipped the state's Catch. It now runs inside the same translation as the service call and fails with Scheduler.ValidationException. * fix(scheduler): answer a malformed EcsParameters list with ValidationException A CapacityProviderStrategy, PlacementConstraints, PlacementStrategy or Tags list holding anything but objects made ObjectMapper.convertValue raise IllegalArgumentException, which CreateSchedule and UpdateSchedule answered with a server error and the aws-sdk:scheduler Task integration turned into States.Runtime. The conversion failure is now named per field and carries the 400 the rest of the parser's validations carry. * fix(scheduler): answer a malformed awsvpcConfiguration list with ValidationException Subnets and SecurityGroups went through a bare ObjectMapper.convertValue, so an element that is not a string left the same unhandled IllegalArgumentException the EcsParameters object lists left. They now read through a stringList sibling of mapList and carry the parser's 400. * test(stepfunctions): pass the scheduler and eventbridge dependencies to the executor under test * fix(scheduler): refuse a scalar in an awsvpcConfiguration list instead of coercing it * fix(scheduler): refuse a non-list EcsParameters field instead of dropping it * test(stepfunctions): catch a malformed scheduler list as the SDK exception AWS sends --------- Co-authored-by: Facundo Paredes <naranjax@MAC-69786.local> Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |
||
|
|
a155e66b15 |
feat(codepipeline): validate ListPipelineExecutions filters and PutApprovalResult inputs (#2696)
* feat: tighten CodePipeline P0 operation contracts * fix(codepipeline): reject malformed filters and stop stranding approvals on rename - ListPipelineExecutions: reject non-string succeededInStage.stageName, unknown filter/succeededInStage members, and non-integer maxResults instead of silently coercing them. - PutApprovalResult: reject non-string result.summary instead of coercing it, and split the "result is required" error from a clearer "result must be an object" error for wrong-typed payloads. - PutApprovalResult: look up the pending approval by token across the execution's own captured stage/action names before consulting the pipeline's current declaration, so renaming or removing a stage or action via UpdatePipeline no longer strands an in-flight approval behind a StageNotFoundException/ActionNotFoundException. - Replace fixed Thread.sleep(100) waits in CodePipelineIntegrationTest with polling helpers (waitForApprovalToken/waitForApprovalStatus) matching the existing waitForJob/waitForExecution pattern, removing test flakiness. |
||
|
|
48e0ecd809 |
fix(stepfunctions): keep a JSONata expression's explicit null in the output (#2684)
* fix(stepfunctions): keep a JSONata expression's explicit null in the output
A JSONata expression evaluating to JSON null lost its key, exactly as an
expression that returned nothing did. Real AWS answers {"v":null} to
Output {"v":"{% null %}"} and keeps the null in a nested object, in an
array, in Assign and in a Task's Arguments.
dashjoin flattens JSONata's null marker into a Java null unless
outputConvertNulls is off, which made the two indistinguishable inside the
evaluator. With it off, $states and the workflow variables bind through
toJsonataValue so an input null stays a null the expression can see, the
result is walked back with the marker mapped to a JSON null and a Java null
mapped to a missing node, and resolveTemplate drops only the missing node.
Closes #2664
* fix(stepfunctions): resolve a whole JSONata field that returned nothing to a null
A MissingNode is how the evaluator says "this expression returned nothing", and
resolveTemplate handed it straight to the executor when the whole Output or
Arguments field was that one expression. exec.setOutput writes the state output
with toString(), and a MissingNode writes itself as the empty string, so
DescribeExecution answered "output": "" instead of JSON.
resolveTemplate is now the boundary and answers a JSON value: a whole field that
returned nothing is a null, which is what it was before the marker existed. The
recursion moves to the private resolveTemplateNode, where "returned nothing" is
still itself in the two positions that read it, an object field it drops and an
array element it fails the state on.
AWS fails such a state with States.QueryEvaluationError; that is #2665 and stays
open.
* test(stepfunctions): read $string() with no argument as nothing, not as null
* docs(stepfunctions): mark the key dropped by an expression that returned nothing as a deviation
---------
Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
|
||
|
|
395401807b |
fix(stepfunctions): bound JSONata evaluation by time and depth (#2697)
JSONata evaluation ran unbounded. A recursive expression with no base case pinned a core and left the execution RUNNING for ever: the library optimises the tail call, so it loops rather than overflowing the stack and no Error ever reaches the executor. Deep non-tail recursion did throw, but a StackOverflowError the evaluator's catch cannot see. Bound each expression with Frame#setRuntimeBounds, which the library has and Floci never called. Either bound raises a JSONata error, so the existing catch turns it into States.QueryEvaluationError, and the state fails through the same path as any other evaluation error: catchable by Catch, retryable by Retry. Five seconds and 500 levels sit deliberately above AWS. Measured with test-state, AWS refuses a non-tail-recursive function at a nesting depth of 125 and accepts it at 95, and the widest sequence it accepts evaluates here in about 100 ms, so no expression AWS runs can reach either bound. Closes #2667 Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |
||
|
|
ac94232910 |
feat(cloudformation): CodeBuild/CodePipeline CFN provisioning (#2685)
* feat(cloudformation): provision CodePipeline pipelines and actions New CodePipelineCfnProvisioner handles AWS::CodePipeline::Pipeline, AWS::CodePipeline::CustomActionType, and AWS::CodePipeline::Webhook by lowering the PascalCase CloudFormation properties into the camelCase CodePipeline API shapes and delegating to the service, so stacks and the API produce identical pipelines. Ref resolves to the pipeline name (generated CloudFormation-style when Name is omitted), Fn::GetAtt Version and webhook Url are populated, an existing physical ID routes updates through UpdatePipeline instead of recreating, DisableInboundStageTransitions is applied after creation, and deletes tolerate already-removed resources. (cherry picked from commit 8007d0b7e872d573217309fccd756c66a2d339a4) * fix(cloudformation): bundle cfn-response into inline ZipFile Lambdas AWS injects the cfn-response (Node.js) and cfnresponse (Python) modules into functions created through CloudFormation's inline ZipFile property, and custom-resource handlers across AWS Solutions templates rely on that — Landing Zone Accelerator's installer stack fails its very first Custom::CreateUUID resource with 'Cannot find module cfn-response' without it. The bundled modules follow the documented AWS implementations but pick the transport and port from the ResponseURL instead of hardcoding https:443, because Floci's custom-resource callback URL is plain http on the emulator's port. (cherry picked from commit 7028f5a85daba6ba9d83032dc940cebe45c0b348) * refactor(cloudformation): extract inline ZipFile packaging CloudFormationResourceProvisioner is a monolith being dismantled, so the cfn-response bundling added there moves to its own InlineZipPackager, ready to travel with the eventual Lambda provisioner extraction. No behavior change. (cherry picked from commit d0d4bff84bda9c143606a8922500515dbe5bc0c0) * fix(cloudformation): keep CodePipeline action config keys verbatim Action and rule configuration maps carry provider-defined string keys (Owner, Repo, ProjectName, ...) that executors match exactly; the PascalCase-to-camelCase property transform was rewriting them, so CloudFormation-created pipelines could never run their GitHub source or CodeBuild actions. Configuration subtrees now pass through untouched. (cherry picked from commit 213e33d9f005ee4df6a66272a91f47ac67a3b7a3) * feat(cloudformation): provision CodeBuild projects AWS::CodeBuild::Project was falling through to the stub path, so CloudFormation-created pipelines referenced build projects that did not exist — Landing Zone Accelerator's installer pipeline failed its Install stage with 'Project not found'. The new provisioner lowers the PascalCase properties into the CodeBuild API shape (including the irregular all-lowercase buildspec field), supports update-in-place, and exposes Ref as the project name and Fn::GetAtt Arn. (cherry picked from commit 7d616b87c7fa58693537dfe7d9d86cd63437ea75) * fix(codepipeline): correct three CFN provisioning bugs in CodePipelineCfnProvisioner - DisableInboundStageTransitions is a declarative list: a stage removed from it on update must be re-enabled, not left disabled after UPDATE_COMPLETE. - CustomActionType has no update operation; a change to Category/Provider/Version is a replacement (create the new identity, delete the superseded one) rather than a silent physicalId swap with no corresponding service call. - Webhook's RegisterWithThirdParty must be read from the resolved/lowercased node, not the raw unresolved props, so intrinsics (Ref, Fn::If) are honored. * fix(codebuild): convert the JSON handler's Map entity instead of dropping it CodeBuildJsonHandler.handle(...) returns Response.ok(Map.of(...)), never a JsonNode, so the instanceof check in CodeBuildCfnProvisioner.handle always missed and silently fell back to an empty ObjectNode -- forcing the guessed ARN fallback even when the handler returned the real project ARN. Convert non-JsonNode entities with ObjectMapper.valueToTree, and close the Response. * fix(cloudformation): UTF-8 encode the injected Python cfn-response callback body http.client encodes a str request body as latin-1, raising UnicodeEncodeError for any response Reason/Data containing non-Latin-1 characters and failing the callback before it's sent. Encode the JSON body to UTF-8 bytes first. * docs(cloudformation): merge the duplicate Lambda resource-type row Two Lambda rows in the supported-resource-types table gave inconsistent descriptions (one had Version/Alias, the other the cfn-response detail). Consolidate into a single row. * fix(codepipeline): fix stage-transition and rename bugs found in re-review - Only re-enable stage transitions this stack previously disabled (tracked via a new __FlociCodePipelineDisabledStages attribute); a stage disabled externally (a manual gate, a human) and never listed in DisableInboundStageTransitions is no longer touched by an unrelated update. - Pipeline Name has no rename operation in CodePipeline; a template Name that differs from the tracked physical ID is now treated as a replacement (create under the new name, delete the old one) instead of calling UpdatePipeline against a pipeline that doesn't exist or belongs to someone else. - Webhook Name rename now deletes the previously-owned webhook after PutWebhook upserts under the new name, instead of orphaning it. * fix(codepipeline): handle legacy stage tracking and failed-replacement cleanup - A resource stored before __FlociCodePipelineDisabledStages existed has no tracking record; fall back to reconciling every declared stage on its first post-upgrade update instead of skipping reconciliation and leaving a removed entry disabled forever. - If stage-transition reconciliation fails after a rename's replacement (or a fresh create) already succeeded, best-effort delete the just-created pipeline before rethrowing. CloudFormation reverts this resource to its previous physicalId on a failed update, so without this the new pipeline is orphaned and a corrected retry hits PipelineNameInUseException. |
||
|
|
2a7ee7a605 |
fix(stepfunctions): write a large whole number in full in $string (#2683)
$string switched to exponent notation at Long.MAX_VALUE, so $string(1e20) returned "1e+20" where AWS returns "100000000000000000000". AWS's boundary is 1e21, on both signs. The execution succeeds either way, so a $string used as a MessageGroupId, an S3 key or a DynamoDB key wrote a different key on each engine without either reporting an error. $string is now bound on the evaluation frame next to the six functions of the Step Functions dialect, with the library's own signature so every arity and type error stays what it was. Below the boundary a double is replaced by the exact integer of the shortest decimal that reads back as it, which is the digit string AWS prints; the library formats everything else. Closes #2669 Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |
||
|
|
5c1b69c45f |
feat(comprehend): add Amazon Comprehend sync text-analysis actions (#2674)
* feat(comprehend): add Amazon Comprehend sync text-analysis actions Implements DetectSentiment, DetectKeyPhrases, DetectDominantLanguage, DetectPiiEntities, and ContainsPiiEntities as fixed AWS-shaped stub responses over the real JSON 1.1 wire protocol (X-Amz-Target: Comprehend_20171127.*). Input validation (Text and LanguageCode required, LanguageCode checked against Comprehend's supported set) matches real API behavior and raises InvalidRequestException/UnsupportedLanguageException per botocore's declared error shapes. The async job/model-training surface (DocumentClassifier, EntityRecognizer, Flywheel, Dataset, Endpoint) and DetectEntities/ DetectSyntax are out of scope for this PR. Real (non-stub) detection logic is planned as a follow-up once this lands. Closes #2660 * fix(comprehend): restrict PII detection to en/es language codes DetectPiiEntities and ContainsPiiEntities were validated against the full 12-language set shared with DetectSentiment/DetectKeyPhrases, but AWS's own operation docs for DetectPiiEntitiesRequest.LanguageCode state PII detection only supports English (en) and Spanish (es). Split the allowlist so the two PII operations reject other languages with UnsupportedLanguageException, matching real Comprehend behavior. Addresses review feedback on #2674. * fix(comprehend): reject non-string Text/LanguageCode as SerializationException getStringField() coerced any JSON value via asText() instead of enforcing the modeled string type, so a numeric or boolean Text/ LanguageCode silently succeeded instead of being rejected. Reuses the codebase's existing SerializationException convention (see JsonErrorResponseUtils.createSerializationErrorResponse()) since a wrong-typed field is a shape/marshalling mismatch caught before business logic runs, distinct from a missing field (InvalidRequestException, a modeled business error). Scoped to ComprehendJsonHandler only. Addresses review feedback on #2674. |
||
|
|
5033ace772 |
fix(rds): store and return the encryption and backup settings given on create (#2617)
* fix(rds): store and return the encryption and backup settings given on create DescribeDBInstances never returned StorageEncrypted, KmsKeyId, BackupRetentionPeriod or CopyTagsToSnapshot, and wrote both windows as constants. Store the six values from CreateDBInstance, apply the backup settings and windows from ModifyDBInstance, and emit them from the instance XML. A record persisted without them reads as AWS defaults. KmsKeyId is resolved against the KMS store in the request's region — a key ARN, key id, alias ARN or alias name — and stored as the key ARN, as a live account reports it; a key that does not exist or is not enabled is KMSKeyNotAccessibleFault. Validation follows a live account: KmsKeyId needs StorageEncrypted, window times are checked with AWS's wording, windows are at least 30 minutes and may not overlap; the retention period is not range-checked since AWS accepted 40 days. Closes #2611 * fix(rds): check window overlap against the windows that will be in effect A window given alone was not checked at all: the request's other window was null, so validate() skipped the overlap check although the instance kept its stored counterpart on modify and got a default on create. Check the pair that results from the request — on modify the stored other window, on create the default, swapped for an alternate default when the given window overlaps it, since AWS picks a random window clear of the given one. Verified on a live account: a modify overlapping the stored window is refused either way, replacing both at once checks only the new pair. * fix(rds): detect window overlap across the week boundary in both directions A Sunday backup window running past midnight lies beyond the end of the week, so comparing it with a Monday maintenance window needs the maintenance interval shifted forward as well as back. * fix(rds): derive the default counterpart window from the given one's end A fixed alternate default cannot be clear of every window a request can give — a 00:00-07:00 backup window covers it. When the window given on create overlaps the usual default, pair it with a 30-minute window that starts the minute the given one ends, which is clear of a daily window by construction; the overlap check stays as the backstop. * fix(rds): refuse a window given alone that leaves no room for the other, in AWS's words The derived counterpart is clear of any window that leaves a 30-minute gap (swept over every start and length in DbInstanceSettingsTest); a window longer than that has no clear counterpart, and a live account refuses it: "The specified backup window overlaps all available default maintenance windows. Shrink the backup window or specify a non-overlapping maintenance window." (mirrored for maintenance), and a maintenance window of 24 hours or more is "Maintenance window must be less than 24 hours." * refactor(rds): share the window checks with BackupWindows |
||
|
|
46d2f4e70f |
fix(docdb): refuse an engine version a live account does not list (#2682)
* fix(docdb): refuse an engine version a live account does not list CreateDBCluster and ModifyDBCluster derived a parameter group family from any engine version string and assigned "default.<family>" without checking that the family exists. The versions a live account lists for docdb are now the catalogue: 3.6.0, 4.0.0, 5.0.0, 5.0.1, 8.0.0, 8.0.1 and the major.minor form of one; anything else is refused before any change with "Cannot find version X for docdb". default.docdb8.0 joins the managed cluster parameter groups. Closes #2681 * test(docdb): refuse an unlisted engine version through the CLI |
||
|
|
3bd9bcc62b |
feat(acm): certificate validation records and revocation (#2655)
* feat(acm): add certificate revocation, renewal, options and email resend Adds RevokeCertificate, RenewCertificate, UpdateCertificateOptions and ResendValidationEmail, with a RevocationReason enum modelling the accepted values. Limitations documented in docs/services/acm.md. * test(acm): stop asserting global-empty state in the pagination filter test Other classes sharing the full-suite JVM revoke certificates of their own, so a REVOKED filter is not globally empty. Assert instead that none of this class's own certificates appear, which is what the test is actually about. * feat(acm): add ResendValidationEmail and certificate revocation reasons * fix(acm): validate Domain/ValidationDomain on ResendValidationEmail Domain and ValidationDomain were accepted verbatim after a null/blank check, so any value round-tripped as 200 OK - a client could resend against an unrelated domain and get success back. Domain must now match the certificate's DomainName or one of its SubjectAlternativeNames, and ValidationDomain must equal Domain or be one of its superdomains, matching botocore's InvalidDomainValidationOptionsException semantics for this operation. Also drops the now-unneeded manual UTF-8 byte encoding in the resend test now that RestAssuredJsonUtils configures the AWS content types. * fix(acm): require Options.Export=ENABLED to revoke a certificate revokeCertificate gated on Certificate.canExport(), which returns true for any PRIVATE or IMPORTED certificate regardless of its Export option - so an imported certificate with Export left at the default DISABLED could still be revoked, bypassing the export-enabled guard the operation is meant to enforce. Check Options.Export directly instead. * fix(acm): use ValidationException for a not-export-enabled revoke RevokeCertificate's own modeled Errors list is AccessDeniedException, ConflictException, InvalidArnException, ResourceInUseException, ResourceNotFoundException, ThrottlingException, and ValidationException. InvalidStateException isn't among them - it's modeled on UpdateCertificateOptions instead, which is likely where it got picked up from. ValidationException is the operation's own general "input failed to satisfy constraints" code, and the better fit here. |
||
|
|
97ff0bc3e9 |
feat(elasticache): support cluster-mode replication groups (#2633)
* feat(elasticache): support cluster-mode replication groups CreateReplicationGroup now provisions a real sharded Valkey cluster when the request asks for one (NumNodeGroups > 1, a cluster.on parameter group, or ClusterMode=enabled): one cluster-enabled container per node, formed via config epochs, MEET, slot assignment and replica attachment, each fronted by its own auth-proxy port announced to clients via cluster-announce-client-ipv4/cluster-announce-port so CLUSTER SLOTS and MOVED redirects point at reachable addresses. DescribeReplicationGroups reports the topology honestly (ClusterEnabled, NodeGroups with Slots, MemberClusters, Engine, ARN, AutomaticFailover), and replication-group members answer DescribeCacheClusters, which is where terraform-provider-aws reads node type, engine version and port from. Adds a terraform compatibility test that applies an aws_elasticache_replication_group with num_node_groups and replicas_per_node_group, asserts the data plane is a formed cluster running in cluster mode (INFO cluster / CLUSTER INFO over RESP through the proxy), and that a re-plan straight after apply is clean. * fix(elasticache): address cluster-mode review feedback and compat CI failure - bump compat-terraform aws-cli image to 2.34.32 so botocore models include ReplicationGroup.Engine (old pin silently dropped the field) - restore cluster-mode runtime state (ports, containers, proxies, cluster formation) after restart; mark groups create-failed on error - announce configured hostname to Valkey nodes so MOVED redirects and CLUSTER SLOTS return client-reachable endpoints - log swallowed socket-close failures in cluster formation * fix(elasticache): report restore-failed members and modeled node-group quota fault Review follow-up for cluster-mode support: - Member cache clusters mirror their group's status instead of a hardcoded "available", so a group marked create-failed by a failed restore no longer contradicts its own members in DescribeCacheClusters. CacheClusterStatus has no create-failed value, so failed members report the documented restore-failed. - NumNodeGroups above the 500 ceiling surfaces the modeled NodeGroupsPerReplicationGroupQuotaExceeded fault instead of a generic InvalidParameterValue. - Javadoc names ClusterMode=compatible handling and the cluster-mode-only restore scope as deliberate. * fix(elasticache): announce a client-resolvable hostname for cluster mode Cluster-mode nodes announced FLOCI_HOSTNAME verbatim, so the shipped Docker Compose deployment baked the Compose-only name 'floci' into MOVED/ASK redirects and topology responses, breaking cluster-aware clients connecting from outside the Compose network. Add FLOCI_SERVICES_ELASTICACHE_CLUSTER_ANNOUNCE_HOSTNAME (default: FLOCI_HOSTNAME) used for the announced name and the reported ConfigurationEndpoint, and set it to localhost.floci.io in docker-compose.yml — public DNS resolves it to 127.0.0.1 on the host while the network alias and Floci's embedded DNS resolve it to the Floci container from inside Docker. * fix(elasticache): restore cluster-mode groups without blocking startup Restoring persisted cluster-mode groups ran serially in the synchronous startup path, so a slow or unavailable Docker daemon could hold up emulator readiness by a container-readiness plus cluster-formation timeout per group, timing out readiness-dependent clients such as Testcontainers. restorePersistedRuntime now reserves each node's proxy port and marks groups creating synchronously - so no request can claim a persisted port or see a stale available status - then brings containers, cluster formation and proxies back in the background, flipping each group to available or create-failed as its restore finishes. --------- Co-authored-by: kurtmc <2661907+kurtmc@users.noreply.github.com> |
||
|
|
eb5134da2d |
feat(stepfunctions): add the JSONata functions of the Step Functions dialect (#2676)
Step Functions extends JSONata with $parse, $partition, $range, $hash, $random and $uuid. None of them exist in the JSONata language, so an expression calling one failed with "Attempted to invoke a non-function" and the execution failed with States.QueryEvaluationError. Bind the six on the evaluation frame next to $states and the workflow variables. Behaviour follows AWS on the cases a naive reading gets wrong: a non-integer argument rounds towards zero, several argument combinations evaluate to undefined instead of failing, $range collapses a single-element range to a bare number, $parse rejects the JSON AWS rejects, and $random(seed) reproduces java.util.Random. Verified with a 65-expression differential against real AWS Step Functions: 65 match, 0 differ. Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |