mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
908d70db3d13c41fa696fe57cd55f3e2976a032f
1296
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
908d70db3d |
fix(apigatewayv2): propagate Lambda REQUEST authorizer context to HTTP API backends (#2715)
* fix(apigatewayv2): propagate Lambda REQUEST authorizer context to HTTP API backends A REQUEST authorizer's response context was parsed only to read isAuthorized or the policy Effect, then discarded. enforceRequestAuthorizerV2 returned a bare Response (null meaning "allowed"), so nothing could carry the context to buildV2ProxyEvent and the backend Lambda received no requestContext.authorizer at all. A real HTTP API delivers it under requestContext.authorizer.lambda, which is how an authorizer hands verified identity to the integration, so a backend that reads it sees an empty object and rejects every authorized request. This completes #1011 (issue #812), which added REQUEST authorizer invocation for HTTP APIs but only wired the allow/deny decision, and brings v2 in line with #581, which propagated the authorizer context on the v1/REST path. The WebSocket $connect path already does the same via WebSocketProxyEventBuilder, so HTTP APIs were the last of the three to drop it. Return a RequestAuthorizerResult carrying the context, mirroring the JwtAuthorizerResult the JWT path already threads through, and render it as requestContext.authorizer.lambda. Values are not flattened to strings the way the v1/REST path flattens its authorizer context: an HTTP API hands the context to the integration as JSON. The developer guide's own simple-response example returns a string, a number, a boolean, an array and a map, and all five now survive to the backend. principalId is deliberately left out - where AWS surfaces it in a 2.0 proxy event was not measured - and an authorizer that allows without returning a context leaves the authorizer node absent rather than rendering "lambda": null, for the same reason. Covered end to end in HttpApiRequestAuthorizerTest (IAM-policy and simple responses, nesting and scalar types, contextless allow) and at the builder in BuildV2ProxyEventLambdaAuthorizerTest. * chore(apigatewayv2): trim comments on the authorizer-context change Drops narration and change history, keeping only what is not recoverable from the code: the RequestAuthorizerResult contract, why the context is not flattened the way the v1/REST path flattens it, and the two intentional omissions (principalId, absent node rather than "lambda": null). Per AGENTS.md: prefer self-explanatory code over comments, document intentional deviations clearly. * fix(apigatewayv2): brace the authorizer error branch AGENTS.md requires braces on every conditional. --------- Co-authored-by: local <local@example.com> |
||
|
|
02f9754ac7 |
fix(ui): reconnect the UI sidecar without restarting Floci (#2718)
* fix(ui): reconnect the UI sidecar without restarting Floci The floci-ui sidecar's FLOCI_ENDPOINT is baked in at container-create time, but Floci's container IP changes on every restart. adoptExisting() took over a surviving sidecar verbatim and never compared its endpoint against the current one, so the sidecar kept polling the previous instance's address indefinitely. The dashboard reported "Not connected" with ECONNREFUSED and the only way out was to recreate the sidecar by hand -- in practice, by restarting the emulator alongside it. Detect that drift on adoption and recreate the sidecar instead, so recovery stays entirely within the sidecar's own lifecycle and never requires disturbing Floci. Two supporting changes: - status() re-arms ensureStarted() when the readiness probe fails. started was a one-way latch, so a sidecar that was removed, crashed, or turned out to be stale left Floci with no path back. The UI polls status continuously, which supplies the retry cadence. - UiServiceConfig gains endpoint() and insecureSkipTlsVerify(). With TLS on, the derived endpoint is https://<floci-container-ip>:<port>, which the sidecar's Node/Bun proxy rejects: the self-signed certificate has no IP SAN for Floci's own container address, so verification fails with ERR_TLS_CERT_ALTNAME_INVALID even once the CA is trusted. Trusting the CA alone is therefore not enough. endpoint() lets an operator point the sidecar at http://<ip>:<port> -- the same server, via the port's HTTP/HTTPS protocol detection, with TLS left enabled -- and insecureSkipTlsVerify() covers the case where https must be kept. A blank or malformed override is a hard error, not a silent fall back to the derived endpoint. * fix(ui): derive http for the sidecar when the host is a bare IP With TLS enabled the endpoint handed to the UI sidecar was derived as https://<floci's own container IP>:4566. That address can never appear in the self-signed certificate: it is assigned at container-create time and changes on every recreate, and the certificate is generated by a ConfigSource that runs before CDI, with no Docker client to ask what the address will be. Every connection therefore failed altname verification — not chain trust, so mounting the CA would not have helped either — and the dashboard sat at "Not connected" with no path back. Nothing in the manager notices: the sidecar is running, so the re-arm added in 8f4fd900 correctly declines to replace it, and the readiness probe only checks the sidecar's own port, never the hop that is broken. Floci's listener does HTTP/HTTPS protocol detection on the same port, so http:// reaches it with TLS left enabled. That is one hop on an internal Docker network, not the emulator, and it is the only scheme that works unattended on the default configuration. A named host such as host.docker.internal is a DNS SAN on the certificate and keeps https. So does an IP literal when insecure-skip-tls-verify is set, since the operator has said explicitly that they want TLS on this hop and verification is no longer the obstacle. isIpLiteral mirrors the iPAddress/dNSName distinction CertificateGenerator already draws, kept local so this package does not depend on the ACM service for one predicate. * fix(ui): bracket an IPv6 host so the sidecar endpoint parses The endpoint was built by concatenating host and port, which produces http://fd00::2:4566 when the resolver hands back an IPv6 literal — the port separator is indistinguishable from the address's own colons and no client can parse it. DockerHostResolver reaches that case through InetAddress.getLocalHost().getHostAddress() on an IPv6-only host. Bracket the authority host. Names and IPv4 literals are unchanged. * fix(ui): reset the async re-arm latch and stop swallowing pre-start failures Local code review (review-local.ts) against FlociUiManager.java found two HIGH-severity bugs before this branch reached a PR: - ensureStartedAsync()'s kicked latch was only reset after a FAILED start, never after a successful one. status()'s self-recovery path sets started=false and calls ensureStartedAsync() when the sidecar is gone, but after any prior successful async start that CAS always failed silently -- the documented "recovers without Floci being restarted" behavior could never actually fire. - findByName() and replaceIfEndpointDrifted() ran before ensureStarted()'s try/catch. A container-runtime failure there (e.g. an unreachable Docker socket) escaped uncaught to a synchronous caller, or vanished into a discarded Future on the async path, leaving status() reporting {started:false, ready:false, error:null} with no diagnostic. Reset kicked whenever status() re-arms a lost sidecar, and move the whole body of ensureStarted() into the try/catch so every failure is routed through lastError. A misconfigured endpoint override's own validation message (set by replaceIfEndpointDrifted before it rethrows) is preserved rather than overwritten by the generic describeStartFailure() message. * fix(ui): validate endpoint override authority and capture fresh-start errors - validateEndpointOverride() now rejects http:// URLs with no authority (e.g. "http://", "http:///path"), which previously passed the bare prefix check and were injected as an unreachable FLOCI_ENDPOINT. - ensureStarted()'s IllegalStateException handler now fills lastError when nothing more specific was already recorded, so a fresh start (no existing sidecar to adopt) with a blank/malformed endpoint override surfaces the validation message instead of error=null. - Document the new endpoint and insecure-skip-tls-verify settings in application.yml's floci.services.ui block. |
||
|
|
ff36141c19 |
perf(cloudformation): probe Lambda S3 code with headObject, not getObject (#2728)
Resolving an AWS::Lambda::Function whose Code points at S3 checked the object by calling getObject and discarding the result. S3Object.getData() is a materialised byte array, so that read the whole package into memory purely to answer whether it was readable, and LambdaService then read the same object again for real during CreateFunction. Every stack create or update paid for two full copies of every Lambda package it provisions. headObject answers the same question without the body: getObject is getObjectMetadata plus readFile, headObject is getObjectMetadata alone. Both resolve the object through that same metadata lookup, so a missing key or bucket still fails the resource exactly as before, and the failure behaviour added for #2648 is unchanged. Closes #2675 |
||
|
|
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. |
||
|
|
6a1d86e43f | fix(cloudformation): resolve IAM assume role policy intrinsics (#2630) | ||
|
|
2e5935d764 |
fix(s3): prevent compliance retention downgrade (#2755)
* fix(s3): prevent compliance retention downgrade * fix(s3): allow updates after compliance expiry |
||
|
|
51edccacbf |
fix(cloudformation): adopt managed policy on stack update (#2717)
* fix(cloudformation): adopt managed policy on stack update A stack UPDATE whose template kept an AWS::IAM::ManagedPolicy's name unconditionally re-ran CreatePolicy, failed with EntityAlreadyExists, and rolled the whole stack back — LZA's second-pass OperationsStack died on exactly this (AWSAccelerator-SessionManagerLogging). Mirror the role provisioner's adopt path: when the stack already owns the policy ARN and identity matches the stored PolicyId, publish the new document as the default version instead, pruning oldest non-default versions at IAM's 5-version cap so repeated updates never hit LimitExceeded, and detach roles dropped from the template. Rollback cleanup now only deletes the policy when this attempt created it and never detaches attachments that predate the attempt. * fix(cloudformation): close managed-policy adopt gaps in update rollback Require PolicyId to match on adopt: a resource that predates PolicyId tracking would silently adopt any policy sharing its ARN, including one deleted and recreated under the same name by someone else. Also restore the prior default policy version and reattach detached-as-obsolete roles when a role attach fails mid-update, and treat NoSuchEntity on the obsolete-role detach as idempotent like the delete path already does. * fix(cloudformation): restore managed-policy rollback on obsolete-role detach failure A non-NoSuchEntity detachRolePolicy failure while dropping an obsolete role during a managed-policy update escaped before the attach loop's rollback ran, since it lives in an earlier try/catch in the same method. The policy's new default version and any already-detached roles were left unrestored even though the stack reported UPDATE_ROLLBACK_COMPLETE. Extract the attach loop's restore logic into restoreManagedPolicyOnUpdateFailure and call it from the detach loop's catch too, so any failure after the version bump restores the prior default version and reattaches roles detached so far in the same pass. * fix(cloudformation): surface failed managed-policy rollback cleanup as UPDATE_ROLLBACK_FAILED A compensating reattach/version-restore failure during a managed-policy update rollback was tracked in cleanupSucceeded but never written to UPDATE_ROLLBACK_FAILURE_ATTR, so the caller assumed the resource was fully restored and reported UPDATE_ROLLBACK_COMPLETE even when the new policy document or a role attachment was left in a partially-rolled-back state. * fix(cloudformation): recreate pruned policy version content on update rollback Pruning an old policy version to stay under IAM's 5-version cap happened before the fallible role attach/detach operations that can trigger a rollback. A failure there restored only the default version and deleted the stray new version, but never recreated the pruned version's content — the stack reported UPDATE_ROLLBACK_COMPLETE while having permanently destroyed a policy version that existed before the update. Deleting the stray version now runs after restoring the prior default (real AWS forbids deleting the current default version), which frees the slot needed to recreate each pruned version's document as a new non-default version, so a full rollback genuinely restores what existed before the update instead of just claiming to. |
||
|
|
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 |
||
|
|
12a6feb0c9 |
refactor(cloudformation): move the single-service types to provisioners (#2744)
Migrates the seven resource types whose provisioning is one service call: KMS Key and Alias, SSM Parameter, ECR Repository, Pipes Pipe, Kinesis Firehose DeliveryStream, and CDK Metadata. Behaviour-preserving move: the bodies are ported verbatim apart from the mechanical rewrites onto ProvisionContext, so physical ids, Fn::GetAtt keys and delete calls are unchanged. Each provisioner injects only the service it wraps, so five service fields leave the monolith. Their constructor parameters stay, unused, until the final cleanup drops them all at once; shrinking the signature now would churn the fixture for no gain. parseCfnTags, blankToNull and parseIntProp are copied rather than shared, because each still has callers in the monolith. ProvisionContext.resolveTags is deliberately NOT substituted for parseCfnTags: it skips a blank key that parseCfnTags keeps, orders entries by insertion rather than hash, and resolves the whole property so an Fn::If around the list works. Adopting it is a behaviour change and belongs in its own PR. CDK::Metadata gains a real provisioner rather than staying on the stub arm. The stub reports CREATE_COMPLETE with a synthetic id and a fake Arn attribute; the real type has no attributes at all. Tests assert the exact physical id and the exact Fn::GetAtt keys against each type's registry schema, plus delegated arguments and delete calls. Asserting status alone would pass against the stub arm. |
||
|
|
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.
|
||
|
|
fcc606799c |
fix(opensearch): address spawned domain containers by IP, not name (#2746)
Container-name DNS only resolves on a user-defined Docker network, and nothing guarantees the spawned OpenSearch container and floci land on one together; on the default bridge the name-based endpoint and readiness URL never resolve. Address the container via its resolved IP (EndpointInfo), the pattern Neptune/MemoryDB/RDS already use, probe readiness through the stored endpoint, and bind a host port only when running outside a container (releasing it if the start fails). |
||
|
|
895b59f1ee |
fix(rds): propagate ModifyDBCluster master-password rotations to the backend and every proxy (#2727)
* fix(rds): propagate ModifyDBCluster master-password rotations to the backend and every proxy ModifyDBCluster only updated the stored password: the backend container kept the original credential and the cluster's and every member endpoint's auth proxy held stale start-time snapshots, so after a rotation no endpoint accepted the new password. Reuse the ModifyDBInstance mechanism: exec the change into the backend while the old credential is still known, then swap the password snapshot in place on the cluster proxy and each member proxy, updating the members' stored passwords to match (AWS applies the cluster master password to every member endpoint). Also pass the Docker container name instead of the instance id into execUntilSuccess from rotateMasterPassword, matching the log convention of the other call sites (review follow-up from #2709). * chore: retrigger CI after main repair |
||
|
|
c6b9e4c34e |
fix(ecs): scope service tasks by owning service, not by caller-supplied group (#2731)
RunTask/StartTask let a caller set any group, so matching it against a service's name or ARN let an unrelated task be counted, stopped or registered as service-owned. Tasks now carry a reconciler-stamped owningServiceArn. Fixes #2716 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
47e064786f | fix(firehose): use request region in delivery stream ARN (#2719) | ||
|
|
89fd37a5c4 |
feat(organizations): add management account email configuration and tests (#2749)
Signed-off-by: Matheus André <matheusandr2@gmail.com> |
||
|
|
c18af5b68a |
fix(apigateway): support underscores in v2 path parameters (#2721)
* fix(apigateway): support underscores in v2 path parameters * fix(apigateway): align path parameter grammar |
||
|
|
bdfaa01c46 |
refactor(cloudformation): add the provisioner-migration enablers (#2732)
Groundwork for moving the remaining resource types out of CloudFormationResourceProvisioner into per-service provisioners. No behaviour change: every type is provisioned and deleted as before. Make a dropped type fail loudly. The provision switch's default arm stubs an unknown type with a fake ARN and reports CREATE_COMPLETE, so a type that fell out of both the switch and the registry would pass every test while provisioning nothing. Adds registeredTypes() on the registry, a LEGACY_SWITCH_TYPES constant, a throwing default arm for a declared type with no arm, and a checked-in inventory of all 112 types and their owner. The inventory test runs under QuarkusTest so it compares against the CDI-resolved registry, catching a provisioner written without @ApplicationScoped. Fix delete precedence. The registry lookup in delete(StackResource, region) sat after a Custom:: prefix branch and nine attribute-aware special cases, so migrating one of those types would leave its provisioner's delete unreachable. The lookup now runs first, the nine branches sit behind a DELETE_NEEDS_STACK_RESOURCE set that gates them, and a duplicated AWS::Events::Rule block is removed. Replace 13 positional constructions with one fixture. Every test built the provisioner with 30-plus positional nulls, so each constructor change edited all of them. CfnProvisionerFixture gives one named setter per argument; removing the already-dead sqsService argument now touches only that file. Add the helpers the slices will use: ProvisionContext.isUpdate() and resolveTags, CfnDeletes.safeDelete with explicit tolerated error codes, and CfnDynamicReferences, which extracts 189 lines of dynamic-reference handling so a future RDS provisioner injects one collaborator instead of two unrelated services. resolveTags migrates no call sites: the seven existing copies disagree on real behaviour and each adopts it in its own slice. Also fixes AslExecutorTaskHistoryEventsTest, which does not compile on main: #2703 added it and #2688 then added a CustomResourceLiveness parameter to AslExecutor without updating the call. |
||
|
|
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 ( |
||
|
|
09a05c2d77 |
fix(rds): propagate ModifyDBInstance master-password rotations to the backend and proxy (#2709)
* fix(rds): propagate ModifyDBInstance master-password rotations to the backend and proxy Rotating the master password only updated Floci's stored state. The backend DB container kept the original credential and the running auth proxy kept validating the master scramble against the password it was started with, so after a rotation no client could connect at all: the old password failed the proxy's (rotated) validator and the new one failed against the backend. On rotation, while the old credential is still known: - exec into the DB container and change the password there. MySQL and MariaDB run SET PASSWORD as the master user itself with the old password (changing your own password needs no privileges, and root's password is the creation-time one, unknown after earlier rotations). PostgreSQL runs ALTER ROLE over the trusted local socket. - restart the auth proxy on the rotated credential, the same stop/start the reboot path uses. Mock mode, cluster members and instances without a running container are unaffected. * fix(rds): swap the proxy password snapshot in place instead of restarting it An immediate stop/start of the auth proxy races the listener rebind: closing the server socket defers the port release while relay connections are still draining, so the restart failed with EADDRINUSE and ModifyDBInstance threw (caught by the sdk-test-java RdsJdbcCompatTest). Updating the snapshot on the running proxy avoids the race entirely and keeps live connections open, which is also what rotation should do. |
||
|
|
88bf0a2931 | fix(acm): correct wildcard validation record names (#2575) | ||
|
|
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> |
||
|
|
9b3aee6a03 |
fix(eventbridge): AWS-conformant InputTransformer from CloudFormation and PutTargets (#1885)
* refactor(eventbridge): parse InputTransformer via shared InputTransformer.fromJson * fix(eventbridge): substitute InputTransformer placeholders with AWS-conformant JSON representation * feat(cloudformation): carry AWS::Events::Rule target InputTransformer into the rule * test(eventbridge): verify native PutTargets InputTransformer delivers transformed body to SQS * chore(eventbridge): log swallowed escape failure and use idiomatic indexOf guard in transformer engine --------- Co-authored-by: Priamo <pgermosen@gmail.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>
|
||
|
|
0090739617 |
fix(rds): clear CLIENT_SSL before forwarding the TLS-terminated handshake response to the backend (#2698)
Real MySQL clients keep CLIENT_SSL set in the HandshakeResponse41 they send over the encrypted stream after the SSLRequest. The proxy terminates TLS itself and forwards that response to the plaintext backend verbatim, and a MySQL server treats any first packet carrying CLIENT_SSL as an SSLRequest: it waits for a TLS ClientHello that never comes while the proxy waits in relayConnectionPhase for an auth verdict that never comes. Every TLS connection through the proxy (mysql's default ssl-mode PREFERRED included) hung until the client timed out; only --ssl-mode=DISABLED worked. Clear the bit before the response reaches the backend, mirroring forceClientSslCapability on the server handshake. The TLS tests now send real-client-shaped responses (CLIENT_SSL set) and assert the backend never sees the bit; the assertion fails without this fix. |
||
|
|
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. |
||
|
|
09d813d13f |
fix(stepfunctions): resolve the substitutions in a JSONata error cause (#2687)
The dashjoin port renders a JSONata error message from a catalog in which the
word "function" was replaced by "Object" throughout, through a substituter that
fills the first two placeholders of a template and quotes every value it inserts.
A cause therefore names a function as `Object`, can end in a literal `{{type}}`
or `{{token}}`, and never carries the error code AWS puts in front of the message.
The cause is now composed in JsonataEvaluator from the code and the values
JException carries. T0412 and T2009, the only two templates with a third
placeholder, state what the exception hands over: the offending argument and the
element type for T0412, the two compared values for T2009. The error name stays
States.QueryEvaluationError, so a Catch matches exactly what it matched before.
Closes #2668
Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
|
||
|
|
f9d28c9649 |
fix(security): reject unregistered SigV4 access keys and unbound usernames (#2680)
* fix(security): reject unregistered SigV4 access keys and unbound usernames
SigV4Validator.java and RdsSigV4Validator.java both fell back to
`iamService.findSecretKey(accessKeyId).orElse(accessKeyId)` when the
access key wasn't registered. Since the attacker chooses accessKeyId
themselves, they can self-sign a token using secret == accessKeyId,
producing the exact signing key this fallback derives -- a full
signature-forgery auth bypass for any unregistered IAM key. Both now
fail closed when the key isn't registered.
SigV4Validator's ElastiCache username binding
(`expectedUsername != null && user != null && !expectedUsername.equals(user)`)
also skipped the check whenever the token simply omitted the User
query param, letting any expectedUsername through. Dropped the
`user != null` conjunct so a null user now correctly fails the check.
Each fix has a RED test proving the exploit against the unpatched
code (self-signed token with secret == accessKeyId; token missing
User) before asserting the fixed behavior.
RdsSigV4Validator's DBUser check was investigated but is not
vulnerable: DBUser is already required by the missing-parameters
check above it, so the null-skip path is unreachable via a crafted
token. PreSignedUrlFilter's well-known "test"/"test" credential and
its lack of a bucket-ownership check were also investigated and are
not presigned-URL-specific bugs -- see
issues/sigv4-review-remaining-findings.md for the evidence and for
everything else from the review pass deferred out of this PR.
* fix(security): restore well-known local-dev credential, sanitize log lines
The fail-closed fix in the prior commit broke the emulator's default
local-dev credential flow: AwsBasicCredentials.create("test", "test")
is used pervasively by SDK clients against RDS/ElastiCache IAM auth
(and S3) in this project's compat test suite, and was never actually
registered in IamService -- it only "worked" before because the
vulnerable fallback happened to derive the same secret ("test") from
the access key ID by coincidence (accessKeyId == secretKey == "test").
Carve out that exact, already-public pair explicitly in both
validators, mirroring the identical LEGACY_ACCESS_KEY_ID/SECRET_KEY
idiom already used by S3Service/PreSignedUrlFilter -- this does not
reopen the forgery bug, since it only ever matches the literal string
"test", never an attacker-chosen access key.
Also addresses two Copilot review comments: the debug logs added in
the fail-closed fix (and the pre-existing signature-mismatch log)
interpolated the attacker-controlled, URL-decoded accessKeyId with no
sanitization, allowing CR/LF-based log injection. Added a
sanitizeForLog helper (strips control characters) and applied it to
every log line that includes accessKeyId in both files.
* docs(security): update ledger after rebasing past PR #2657's merge
PR #2657 merged with the misleading "always fails the signature check"
comment in both SigV4Validator.java and RdsSigV4Validator.java (not
just the ElastiCache file, as first flagged). Rebasing this branch
onto upstream/main produced real conflicts on both files; resolved by
keeping the fail-closed fix and dropping the comment. Updated the
ledger from future-tense speculation to the resolved outcome.
|
||
|
|
acf88794ca |
fix(stepfunctions): end the execution when a state throws an Error (#2693)
doExecute caught Exception only, so an Error escaping a state left the execution RUNNING with no terminal status, no error, no cause and no ExecutionFailed event, and executeAsync dropped the Future that held it. The outer handler now catches Error as well, writes the same terminal FAILED an exception produces with the Error's toString() as the cause, and rethrows so the failure is not swallowed. executeAsync logs whatever escapes the worker with its stack trace. The Parallel branch handler unwraps an Error cause instead of rethrowing the ExecutionException wrapper, and the per-state runtime catch folds into the outer one so a single method writes every terminal failure. Closes #2666 Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com> |
||
|
|
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> |
||
|
|
e4c690351f |
fix(lambda): replace the extracted package instead of merging into it (#2672)
* fix(lambda): replace the extracted package instead of merging into it ZipExtractor wrote entries into the function's code directory without clearing it first, so each deploy was layered on top of the last. Nothing on the path resets the directory: CodeStore.delete runs only when a function is deleted, codeStore.exists() is never called, and every deploy of a function resolves to the same code path. Extraction was a merge where the domain requires a replace, so a file removed between two deploys survived and stayed loadable -- a handler pointing at a deleted module kept resolving and running stale code. Real AWS replaces the package wholesale. Extract into a sibling staging directory and swap it in once the whole archive has been read: on success the old tree is deleted and staging is moved into place, on failure staging is discarded and the previous deployment is left untouched. That also makes extraction all-or-nothing. Safe because the code directory is not bind-mounted into Lambda containers -- ContainerLauncher tar-copies it into /var/task at launch, and the only bind for task code is the hot-reload path, which uses a different directory that never goes through extractTo. Closes #2647 * fix(lambda): keep the previous package until the new one is installed The install deleted the live tree and then moved the new one into place, so a failure in the move left the function with no code at all and nothing to restore: a failed update destroyed a working deployment. Rename the old tree aside instead, move the new one in, and delete the old only once the new one has landed. Every failure path now ends with one complete package on disk. The interval in which the target is absent is two renames within a directory rather than a recursive delete followed by a move; it is narrowed, not closed, because POSIX cannot atomically exchange two directories, and the javadoc records that limit rather than implying atomicity. install() is package private so the failure path can be driven directly. It is unreachable through extractTo, because a rename between siblings does not fail under any condition a test can arrange there. * fix(lambda): do not fail a deployment that already installed Two failure paths in install() reported the wrong outcome. Deleting the superseded package threw out of install(), so a filesystem error at that point failed the deployment even though the new tree was already in place and serving. The caller then skipped its metadata and warm pool updates for code that was live. That deletion is now best effort: it logs and leaves the tree behind, because leaving a directory costs disk and is recoverable, while misreporting the outcome is not. Restoring the previous package after a failed move was itself unguarded. If the restore also threw, its exception replaced the original failure and the working package was left under a generated name nothing would look for. The restore is now guarded, the original failure stays the exception thrown, the restore failure is attached to it, and the stranded path is logged so it can be moved back by hand. The cleanup path has a regression test. The restore path does not: reaching it needs the install rename to fail while the restore rename also fails, and both are renames in one directory, so either both succeed or the first rename fails before install is reached. |
||
|
|
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. |