mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
7a228c532597fa073b395be4940df0e5fb82fc74
1790
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7a228c5325 |
refactor(apigateway,appsync): extract shared VTL $util functions into a common utility (#3583)
VtlTemplateEngine.UtilVariable (API Gateway) and AppSyncUtil (AppSync) each independently implemented the same ~49-line block of AWS $util VTL functions (escapeJavaScript, urlEncode, urlDecode, base64Encode, base64Decode, parseJson), flagged as duplicated by CPD. AWS specifies $util identically across both services' VTL mapping-template docs, so the two floci implementations risked silently disagreeing on edge cases over time. Extracted the shared functions into VtlUtilFunctions under core.common.vtl; both $util implementations now delegate to it. base64Encode keeps two overloads matching each service's real AWS signature: API Gateway's $util.base64Encode takes a string, AppSync's takes a Blob (byte[] in the Java model), so both overloads are preserved rather than collapsed into one. No behavior change. All existing VtlTemplateEngine and AppSyncUtil tests, plus the full ApiGateway and AppSync suites, pass unchanged. |
||
|
|
8d3fdbdd56 |
refactor(elasticache,rds): extract shared SigV4 request validation into a common utility (#3581)
SigV4Validator (ElastiCache proxy) and RdsSigV4Validator (RDS proxy, also reused by Redshift) each reimplemented the same ~60-line AWS SigV4 presigned-URL verification algorithm (query parsing, expiry check, secret resolution, canonical request, signing key derivation, signature comparison), flagged as duplicated by CPD. Extracted the shared algorithm into SigV4RequestValidator under core.common.auth; both validators now delegate to it, parameterized only by their genuine differences: the identity query parameter (User vs DBUser), whether that parameter is required to be present at all (RDS always requires DBUser; ElastiCache does not require User), and the exact string each signs as the canonical host header (cluster ID for ElastiCache, host:port for RDS). No behavior change. Public constructors and validate(...) signatures on both SigV4Validator and RdsSigV4Validator are unchanged, since existing unit tests construct them directly with an IamService and reflect on a declared sanitizeForLog method on each class; that method is kept (identically implemented, not delegated) on both wrapper classes specifically so those tests keep working unmodified. All existing SigV4 validator, ElastiCache, RDS, and Redshift tests pass unchanged. |
||
|
|
d1892e18a1 |
refactor(elasticache,memorydb): extract shared auth-proxy logic into a common base class (#3574)
ElastiCacheAuthProxy and MemoryDbAuthProxy each implemented their own copy of the RESP AUTH handshake, accept loop, and client/backend relay, ~87 duplicated lines flagged by CPD. MemoryDB's proxy is modeled on ElastiCache's (same wire protocol, same IAM-auth mechanism), so both now extend AbstractRedisAuthProxy, which owns the shared accept/handshake/relay plumbing behind two small hooks (authRequired, authenticate) that each subclass implements against its own validators. No behavior change: closeQuietly stays per-subclass since the two implementations genuinely differ (ElastiCache shuts down the socket's output side and logs at debug; MemoryDB just closes), and every other extracted method reproduces the original logic byte for byte. Also adds integration coverage for a path that existed before this refactor but had no automated test either way: a client that sends an explicit AUTH command on a connection where auth isn't required must still get +OK and stay usable, rather than being rejected. |
||
|
|
7d6e9588cd |
fix: support SSM PutParameter tags and ECS container healthCheck (#2567) (#3550)
* fix(ssm): support Tags and preserve tags on Overwrite in PutParameter (#2567) * fix(ecs): round-trip containerDefinition healthCheck (#2567) * style(ecs): replace em-dash with comma in test doc per AGENTS.md * fix(ssm,ecs): address review feedback on description, ARN parsing and ECS healthCheck command * test(ecs): pass HostVolumePolicy to EcsJsonHandler in healthCheck tests |
||
|
|
19917ed9ed |
fix(s3): enforce source resource policies on object copies (#3539)
* fix(s3): enforce source resource policies on object copies * fix(s3): combine source identity and resource policies --------- Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com> |
||
|
|
0f7df0fd19 |
refactor(cloudformation): move the AutoScaling types into a per-service provisioner (#3582)
Moves AWS::AutoScaling::AutoScalingGroup and AWS::AutoScaling::LaunchConfiguration out of the monolith switch into AutoScalingGroupCfnProvisioner. Monolith 4,988 to 4,702 lines, legacy types 31 to 29. The monolith side of the diff is pure deletion: nothing in it was edited, only removed. autoScalingService was exclusive to these two types, so the field and its constructor parameter leave with them. Seven private helpers leave too, having no caller left behind: sameNameExistingResource, deleteRenamedResource, parseIntProp, resolveAsgTags, resolveAsgTagPropagation, resolveMixedInstancesPolicy and parseOptionalInt. The first three were shared with RDS until batch 7 took RDS out, which is why they could not move before now. Reading the name and the prior entity goes through ProvisionContext rather than a copied helper: stablePhysicalName for the create-only name, reusesPriorEntity for the update-versus-replace decision, and resolveOptional and resolveStringList for the properties. That is behaviour-preserving because the engine sets the resource's physical id and the context's priorPhysicalId from the same value on the same call. Two gaps close with the move, each proved by a test that fails without it. AWS::AutoScaling::AutoScalingGroup declares exactly one readOnlyProperty in the registry schema, AutoScalingGroupARN, but the monolith recorded the ARN only under the key "Arn". Fn::GetAtt for the documented name therefore resolved to the literal string "LogicalId.AutoScalingGroupARN" and the stack still reported CREATE_COMPLETE. Both keys are now set: "Arn" stays because templates and an existing integration test read it. AWS::AutoScaling::LaunchConfiguration declares no readOnlyProperties, so it adds no attribute surface. #3494 added DesiredCapacityType, CapacityRebalance, MaxInstanceLifetime and DefaultInstanceWarmup to AutoScalingService but left the CloudFormation path passing AsgOptionalFields.none(), noting in its own description that the wiring belonged in a per-service provisioner rather than in the monolith. All four are registry schema properties, so a template setting them was silently dropped. They are read now, and absent stays null rather than false or zero, so an update overwrites only what the template set, matching applyToExistingGroup and the Query handler. Delete keeps the monolith's behaviour and does not wrap the calls in CfnDeletes.safeDelete. AutoScalingService raises ValidationError at 28 sites and only one of them means "not found", so tolerating that code would be the catch-all AGENTS.md rules out, swallowing a real delete failure and reporting DELETE_COMPLETE over it. Tests: 8 unit tests against a mocked service, plus the existing AutoScaling integration test extended to assert the schema attribute and the four fields end to end. Reverting each change makes the matching assertions fail, checked separately because RestAssured stops at the first failed expectation and one would otherwise mask the other. |
||
|
|
809ce40f1e |
fix(cloudformation): identify unsupported SAM Cognito authorizers (#3535)
Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com> |
||
|
|
36c8396f25 |
fix(cloudformation): validate WAFv2 WebACL and Config rule required properties (#3576)
Fail fast on missing required properties, read WebACL tags via ListTagsForResource, delete Config rules by name through CfnDeletes and keep absent ComplianceResourceTypes unset. * Fix #2711 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
569f9f55e4 |
perf(build): replace quarkus-jdbc extensions with plain JDBC drivers (#3465)
* perf(build): replace quarkus-jdbc extensions with plain JDBC drivers The RDS Data API and Redshift Data API open connections with DriverManager. They never used Agroal, Narayana or the datasource layer that quarkus-jdbc-mysql and quarkus-jdbc-postgresql pull in. Depend on mysql-connector-j and postgresql directly and hand-supply the native image config the extensions provided. * perf(build): cut unused JDBC driver paths from the native image Substitute driver code that cannot be reached against the databases Floci provisions, mirroring what quarkus-jdbc-mysql did for JMX and going a step further for authentication and multi-host URLs. * perf(build): keep the MySQL cleanup thread disabled in JVM mode quarkus-jdbc-mysql set com.mysql.cj.disableAbandonedConnectionCleanup at startup in JVM mode as well as at native build time. The first commit carried only the native build argument and a surefire copy, so quarkus:dev and the JVM Docker image started Connector/J's abandoned connection cleanup thread on the first MySQL Data API call. In dev mode that thread is recreated with every restart and pins the old classloader. * fix(rdsdata): reject PostgreSQL result types the Data API does not support Aurora PostgreSQL answers a result set that holds a point, interval, money, box, circle, line, lseg, path or polygon column with UnsupportedResultException and the message "The result contains the unsupported data type POINT." Floci returned the driver's toString of the value instead. Check the column type names before reading the rows and raise the same error. json and jsonb stay supported, and a column cast to text still reads as a string, which is the workaround AWS documents. * perf(build): drop the PGobject reflection entries pgjdbc builds point, interval, money and the geometric types through reflection only when a result set holds such a column. The Data API now rejects those columns before reading a row, and json and jsonb values are plain PGobject instances the driver creates directly, so none of the ten entries can be reached. * chore(rdsdata): name the tolerated ClassNotFoundException in OpenTelemetryUnavailable * perf(build): keep PGInterval registered for the Redshift Data API Redshift tables can hold INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND columns and the Redshift Data API returns them as strings. Floci serves that path from a PostgreSQL container through pgjdbc, which builds an interval value by reflection, so the entry stays. The Redshift Data compat test now reads two interval columns on the native image. * perf(build): keep the geometric reflection entries for the Redshift Data API Redshift refuses point, box, circle, lseg, path and polygon as column types but evaluates them in a select, and its Data API returns the values as strings, checked on a real ra3.large cluster. Floci serves that path through pgjdbc, which builds those values by reflection, so the six entries stay. line stays out because Redshift rejects it, and money never reaches PGmoney because pgjdbc reads it as a double. The Redshift Data compat test selects those expressions and expects the strings Redshift returned. JdbcDriverNativeSupportTest resolves every registered class name. * fix(redshiftdata): fail statements that produce line, json or jsonb like Redshift Redshift has none of these types. A select that names one fails with "ERROR: type "line" not yet implemented" or "ERROR: type "json" does not exist", checked on a real cluster. The PostgreSQL container behind Floci's Redshift evaluates them, so the Data API now checks the result column types and fails the statement with the same text. |
||
|
|
589b1aba9c |
fix(cloudformation): replace AWS RDSDBCluster when EngineMode or StorageEncrypted changes (#3555)
Signed-off-by: Matheus André <matheusandr2@gmail.com> |
||
|
|
e5bd8be405 |
feat(redshift): provision AWS::Redshift::Cluster through CloudFormation (#3427)
* feat(cloudformation): provision AWS::Redshift::Cluster (create path) * feat(cloudformation): AWS::Redshift::Cluster update and replacement * feat(cloudformation): force replacement on Redshift cluster createOnly property change * feat(cloudformation): force replacement on Redshift cluster DBName change * feat(cloudformation): provision Redshift parameter, subnet and security groups * chore(cloudformation): register Redshift provisioner in inventory and docs * test(cloudformation): end-to-end AWS::Redshift::Cluster stack * docs(redshift): document CloudFormation cluster provisioning * test(cloudformation): assert ClusterSubnetGroupNotFound error code on subnet group deletion * fix(cloudformation): correct attribute handling for Redshift security group provisioning * fix(cloudformation): apply Redshift parameter group Parameters and fix docs ClusterParameterGroup silently dropped Properties.Parameters on both create and update instead of calling ModifyClusterParameterGroup, and did not replace the entity when Description or ParameterGroupFamily changed, even though AWS marks both as replacement properties. Also remove the Id GetAtt claim from the Cluster docs: neither the provisioner nor AWS's own schema expose it for AWS::Redshift::Cluster. |
||
|
|
55ada9b8a3 |
feat(cloudformation): provision the AppSync resource types (#3424)
Adds AppSyncCfnProvisioner, serving AWS::AppSync::GraphQLApi, GraphQLSchema, DataSource, FunctionConfiguration, Resolver and ApiKey. Without it a template's AppSync resources fall to the dispatcher's stub arm, which reports CREATE_COMPLETE while creating nothing and resolves Fn::GetAtt to the literal "LogicalId.Attr". Two things are not simple property mapping. The AppSync control plane is REST-JSON with camelCase members, so every property is lower-camelised on the way in, with DynamoDBConfig as the one member that does not follow the rule (it is dynamodbConfig). And schema creation is asynchronous: while it is PROCESSING every other call for that API is refused with a 409, so the GraphQLSchema resource waits for a terminal status before completing, as CloudFormation does. Also carries the service-layer changes the provisioner needs: a PIPELINE resolver reaches its data through pipelineConfig and names no data source, which createResolver refused outright; CreateFunction and UpdateFunction now keep the runtime a JS resolver declares; and UpdateFunction applies a new name, which a CloudFormation rename goes through. |
||
|
|
10becc593f |
feat(cloudformation): provision AWS::Lambda::Url (#3423)
A function URL in a template was falling to the stub arm, so a stack exported the literal string "LogicalId.FunctionUrl" in place of a URL and nothing was listening on it. The physical id is the FunctionArn the URL is attached to, the alias ARN when Qualifier names one, which is the registry schema's primary identifier and enough to address the config again since a qualified ARN parses back into function and qualifier. TargetFunctionArn and Qualifier are create-only, so an update that moves the URL creates against the new function and removes the one it displaced. |
||
|
|
e8edc3d4b1 |
fix(apigateway): take the last value of a repeated query string parameter (#3548)
A REST proxy event built queryStringParameters from the FIRST value of a
repeated parameter, so ?x=1&x=2&x=3 reached the integration as "1".
Captured against a real REST API in us-west-2 with a Lambda proxy
integration: AWS collapses a repeated parameter to the LAST value,
yielding {"x":"3"}, while multiValueQueryStringParameters keeps every
value in order as ["1","2","3"]. A trailing empty value still wins, so
?x=1&x= yields "".
This is the same rule putSingleValueHeaders already applies to duplicate
request headers one method above, where the comment notes that taking the
first value diverged from AWS. Query strings were left on the old
behaviour; they now match.
Also pins two properties that were already correct, so they stay that
way: a bracketed name such as filter[status]=open reaches the integration
unchanged, and an absent query string nulls both maps.
putQueryStringParameters and putMultiValueQueryStringParameters become
package-private for the unit test, matching putSingleValueHeaders and
putMultiValueHeaders next to them.
HTTP APIs are untouched. Their payload formats join duplicates with a
comma rather than taking one value, which is a different rule and is not
measured here.
|
||
|
|
bfe2b71587 |
fix(s3): verify the SigV4 header signature when enforce-auth is enabled (#3573)
With FLOCI_SERVICES_S3_ENFORCE_AUTH=true, a request signed in the Authorization header, which is how every AWS SDK and the CLI sign ordinary calls, was authenticated by access key existence alone: isKnownAccessKey checked that the key id was registered and the Signature value was never recomputed. The presigned placements already had real verifiers (#1842 for the query string, #3081 for browser POST); this was the remaining one, so a fabricated signature naming a known key was accepted for any request. Add S3HeaderSignatureFilter beside PreSignedUrlFilter. It runs only with the flag on, for requests routed to S3Controller, and rebuilds the canonical request from the request as it arrived: raw path, canonical query string, the SignedHeaders with host resolved through S3VirtualHostFilter, and the signed x-amz-content-sha256. The signature is derived from the resolved secret and compared in constant time; when the declared hash is a real digest the body is hashed too and handed back unchanged. Rejections mirror S3's codes and order: AuthorizationHeaderMalformed for a structurally bad header or scope, AccessDenied for a missing date, InvalidRequest for a missing content hash, InvalidAccessKeyId for an unknown key or a temporary key without its session token, RequestTimeTooSkewed beyond fifteen minutes, SignatureDoesNotMatch for an unsigned host or a signature that does not verify, and XAmzContentSHA256Mismatch for a body that differs from its declared hash. PreSignedUrlFilter's crypto helpers go package-private so the new filter shares them. The entity stream is read directly rather than gated on hasEntity(), which RESTEasy Reactive implements as "has a Content-Type"; the AWS CLI sends bucket configuration bodies and put-object --body without one, and the first cut rejected those as hash mismatches. The enforce-auth tests all sent a fabricated Signature=test, which is the bug running green. A new testutil S3RequestSigner signs each request at send time the way an SDK does; the 103 fabricated headers become filter attachments with no assertion changed, and three new tests pin the forged, wrong-secret, unbound-host, tampered-body, stale-date, missing-hash, missing-date and malformed-header cases. Verified live with the flag on against the unmodified AWS CLI 2.36 (including an 8 MB multipart round trip) and the AWS Java SDK v2 compat suite, 143/143 across every S3 class. Closes #2332 |
||
|
|
126af73141 |
fix(ecs): enforce host-volume bind-mount safety fail-closed at register and run time (#3543)
* fix: enforce host-volume bind-mount safety fail-closed at register and run time Reject volumes[].host.sourcePath by default unless an operator opts in via floci.services.ecs.host-volume-roots or allow-unsafe-host-volumes. Block the Docker socket and any ancestor directory that contains it (/var/run, /run, /var) unconditionally, even with the unsafe flag set. Extract the check into HostVolumePolicy and enforce it again immediately before each bind mount in EcsContainerManager.startTask, not only once at RegisterTaskDefinition, to narrow the window for a swapped-in symlink and to cover task definitions persisted before this policy existed. * fix(ecs): protect the Docker socket Floci actually connects to The host-volume policy only blocked the literal /var/run/docker.sock and /run/docker.sock paths, so a task definition could bind-mount the daemon socket when Floci reached it through DOCKER_HOST or an active Docker context (Colima, OrbStack, Rancher Desktop, Podman). Resolve the daemon endpoint through the same DockerClientProducer path the Docker client uses and add its unix:// socket path to the protected candidates. The literal paths stay protected as defence in depth. |
||
|
|
3b31c5a663 |
fix(apigateway): enforce ApiKeyRequired on REST API methods (#3537)
* fix(apigateway): enforce ApiKeyRequired on REST API methods
A method with ApiKeyRequired=true accepted requests missing or using an
unrecognized x-api-key header instead of rejecting them with 403, since the
property was never read from PutMethod, the AWS::ApiGateway::Method
CloudFormation resource, or the execute-api data plane.
MethodConfig now carries apiKeyRequired (wired through putMethod, the PATCH
/apiKeyRequired path, and CloudFormation's ApiKeyRequired property), and
ApiGatewayExecuteController rejects the request with 403 {"message":"Forbidden"}
when the method requires a key and none resolves via the existing usage-plan
lookup.
Fixes #3507 (ApiKeyRequired half; the resource Policy gap remains open).
* fix(apigateway): validate patch operation and boolean value for /apiKeyRequired in UpdateMethod (#3507)
|
||
|
|
3c6568bac5 | fix(ec2): register all guest network addresses with IMDS (#3546) | ||
|
|
96707f6d5a |
feat(apigateway): support HTTP and HTTP_PROXY integrations on REST APIs (#3433)
* feat(apigateway): support HTTP and HTTP_PROXY integrations on REST APIs
PutIntegration already accepted type HTTP_PROXY and HTTP, but dispatch handled
only AWS_PROXY, AWS and MOCK and fell through to a 500 "Unsupported integration
type". A REST API fronting an HTTP microservice - the shape CDK's HttpIntegration
and addProxy emit - could be created but never invoked.
HTTP_PROXY is a passthrough: the request goes to the integration URI with {param}
placeholders resolved from the matched resource's path parameters, and the
backend's status, headers and body are relayed unchanged. AWS applies neither
request templates nor integration-response selection to HTTP_PROXY, so a backend
4xx or 5xx reaches the caller verbatim rather than being remapped into a gateway
error. An unreachable backend yields 502.
HTTP is the non-proxy form and transforms in both directions. The request body is
the rendered requestTemplates entry chosen by the incoming Content-Type, and only
headers and query parameters named by integration.request.* mappings are
forwarded - unmapped inbound headers are deliberately not passed through, which
is what separates it from HTTP_PROXY. The backend's reply then runs through the
method's integration responses, where selectionPattern is matched against the
backend's HTTP status code rather than against an error message as it is for
AWS/Lambda integrations.
Both reuse the existing v2 HttpProxyInvoker for transport, so hop-by-hop header
stripping, chunked decoding and the 502-on-failure behaviour are shared. The
request-template negotiation and integration-response mapping that AWS
integrations already performed are extracted so both types use one implementation.
* fix(apigateway): preserve repeated headers and query parameters through HTTP_PROXY
A REST HTTP_PROXY integration passes the request through, and AWS supports
multi-valued headers and query strings on that path. The adapter collapsed both
into one comma-joined value before handing the request to the shared transport,
so "?tag=a&tag=b" reached the backend as "tag=a,b" and a header sent twice
arrived once. Those are not interchangeable: most servers parse the joined form
as a single value containing a comma.
The relayed response had the same defect. A backend returning two Set-Cookie
headers produced one joined header, which the client cannot split back apart,
since an Expires attribute contains a comma of its own.
The transport already stored headers and query parameters as multimaps
internally; only its boundary types flattened them. RequestContext now carries a
multi-valued view alongside the single-valued one that $request.* expressions
resolve against, ProxyResult returns multi-valued headers, and the REST proxy
path emits one header line per value. An explicit integration.request.* mapping
still overwrites, replacing repeated inbound values with the mapped one.
Non-proxy HTTP is unchanged: its integration responses resolve
integration.response.header.X to a single value, so it collapses the backend's
headers at that point instead.
* fix(apigateway): preserve repeated parameters through HTTP API HTTP_PROXY too
dispatchHttpProxyV2 is the second entry point into the HttpProxyInvoker /
RequestContext / ProxyResult transport, and it still built its request context
from comma-joined single-value maps. So after the REST path was fixed, an HTTP
API (v2) with an HTTP_PROXY integration still sent "?tag=a,b" for "?tag=a&tag=b",
and repeated request headers still arrived joined: the transport's multi-value
support was there but never populated from here.
It now builds the same two views the REST path does. The multi-value maps are
what reaches the backend, and the joined single-value maps stay the lookup
surface for $request.header.X / $request.querystring.X, which resolve to one
value in AWS. The response relay already iterated multi-valued headers, so
repeated Set-Cookie was already correct on this path; it is pinned by a test
now rather than left implicit.
Also drops ProxyResult.firstHeader(), which nothing called, puts braces on the
conditionals in RequestContext.expand(), and imports LinkedHashMap in
ApiGatewayExecuteController instead of spelling it out in full at each use.
|
||
|
|
f38a384e51 |
fix(appsync): verify JWT signatures and SigV4 requests for GraphQL auth (#3541)
* fix(appsync): verify JWT signatures and SigV4 requests for GraphQL auth
Cognito and OIDC auth modes decoded JWT claims without checking the
signature, and AWS_IAM auth accepted any well-formed Credential= value
without verifying a real SigV4 signature. An unregistered IAM access
key also fell back to an account-root identity instead of being
rejected. Any of these let an attacker forge claims or an identity
for AppSync's GraphQL data-plane endpoint.
Cognito now verifies the token against the issuing user pool's own
RS256 signing key (alg, kid, issuer, expiry) instead of trusting the
decoded payload. OIDC verifies against the configured issuer's
published JWKS via OIDC discovery, reusing JwtSignatureVerifier (the
same verifier the HTTP API JWT authorizer uses), and fails closed on
an unreachable issuer or unsupported algorithm. AWS_IAM verifies a
real header-signed SigV4 request (service "appsync", fixed
/v1/apis/{apiId}/graphql canonical path): the Credential= access key
must resolve to a secret via IamService and the signature must match
the actual request, including its body. An unknown or unsigned key is
always rejected and never resolves to root; the legacy test/test pair
is still emulator-allow but must be signed like any other key.
JwtClaimsDecoder gained decodeHeader()/rawToken() so callers can check
alg/kid and hand the raw token to a signature verifier.
AuthRequestInfo carries the raw request body so IAM signature
verification can hash the real payload rather than trusting an
unsigned one.
* fix(appsync): bind session tokens to temporary IAM credentials
IamAuthValidator.resolveSecretKey resolved a temporary (ASIA...)
access key's session secret and verified the SigV4 signature, but
never checked X-Amz-Security-Token. A caller holding just the secret
could authenticate without presenting the session token AWS requires
to prove the credential is live and genuinely STS-issued.
checkSessionToken now mirrors ExecuteApiSigV4Authorizer: a temporary
key with no X-Amz-Security-Token header is rejected, a present token
is compared against the value IamService recorded at mint time with
MessageDigest.isEqual, and a session recorded before Floci tracked
tokens (no issued value to compare against) is not locked out by a
check it cannot satisfy. The token does not need to ride in
SignedHeaders; comparing it against the issued value binds it
regardless of where it rode.
Also drops the dead Date-header fallback in headerSignedRequest
(AMZ_DATE can never parse RFC 1123 output, so that branch never ran)
and fixes an em-dash in the AWS_IAM docs row.
* test(appsync): sign IAM data-plane requests in the auth integration test
Two AppSyncAuthIntegrationTest cases sent the bare Credential= header
that is enough for the management plane to the GraphQL endpoint and
expected 200. Now that AWS_IAM requests are verified as real SigV4,
that header is an unsigned request and gets 401, which is the intended
behaviour. Sign those two requests with AppSyncRequestSigner using the
legacy test credential; the cases that expect 401 for a dummy
signature are unchanged.
|
||
|
|
a40409f591 |
fix(wafv2): reject non-CIDR IPSet addresses (#3511)
CreateIPSet/UpdateIPSet now validate that every Addresses entry is a CIDR block matching IPAddressVersion, rejecting bare addresses and out-of-range prefixes with WAFInvalidParameterException. The IPAddressVersion check now runs even when Addresses is empty or null, and validation errors carry Field/Parameter/Reason as structured extendedData instead of a free-text message, matching the real ParameterExceptionField enum (IP_ADDRESS, IP_ADDRESS_VERSION). * Fix #3328 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
1af3b56683 |
fix(lambda): honor MaximumRetryAttempts and DestinationConfig.OnFailure for DynamoDB Streams ESM (#3263) (#3428)
* fix(lambda): honor MaximumRetryAttempts and DestinationConfig.OnFailure for DynamoDB Streams ESM (#3263) * test(lambda): pin the OnFailure payload's arrival timestamps to epoch seconds Seeds a known approximateCreationDateTime and asserts the exact approximateArrivalOfFirstRecord/LastRecord timestamps, using a value 46+ years away from its millis interpretation so a seconds/millis mix-up cannot accidentally pass. The prior tests only asserted the fields were present, which stayed green even with the epoch-millis bug fixed in the previous commit's Instant.ofEpochSecond conversion. * fix(lambda): track retries and trigger OnFailure when batch does not clear under ReportBatchItemFailures * fix(lambda): carry retry count across partial batch failures in DynamoDB Streams ESM |
||
|
|
2290247802 |
fix(apigateway): expose VTL authorizer and parameter maps (#3538)
* fix(apigateway): expose VTL authorizer and parameter maps * fix(apigateway): match AWS authorizer VTL values * fix(apigateway): pass authorizer context to MOCK templates --------- Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com> |
||
|
|
a5045d3aef |
fix(cloudformation): apply AWS::SQS::Queue tags from the template (#3532)
The registry schema declares Tags on AWS::SQS::Queue, but SqsCfnProvisioner never read the property, so a template that tagged a queue produced an untagged queue and nothing reported it. This is the first of the three follow-ups #2985 named for itself. Tags go through one reconcile used by both the create and the update path, rather than only being applied at create. CloudFormation drives a resource's tags to the template's desired state, so a key the template drops has to be untagged, and SQS has no replace-tags call to do that in one step. The removal is computed with ProvisionContext.staleTagKeys, the same shape AcmCfnProvisioner uses. On create listQueueTags is empty, so the shared path degenerates to a plain tag and a new queue and an updated one end in the same state for the same template. SqsService already had everything needed: tagQueue, untagQueue and listQueueTags. Create still calls the three-argument createQueue rather than the tags overload, which keeps one tag path instead of two and leaves the existing tests untouched. Three tests, each verified to fail before this change rather than assumed to. The second is the one that matters: it drops a key and asserts only that key is untagged, which is what a fix that just called tagQueue would get wrong. The third covers a template that drops Tags altogether, which the reconcile docstring promises and nothing pinned: it holds only because resolveTags answers an empty map rather than null. |
||
|
|
d90cb23c23 |
refactor(cloudformation): move the SecretsManager types into per-service provisioners (#3530)
Moves AWS::SecretsManager::Secret and AWS::SecretsManager::SecretTargetAttachment out of the monolith switch. The logic is carried over intact. What differs is the plumbing, plus the style the new files have to meet as new files: locals that were var now name their types, which matters most where an RDS and a DocumentDB lookup sit side by side returning different shapes, the inline fully-qualified ObjectMapper, ObjectNode and RandomPasswordGenerator are imported, and neither file keeps a private copy of resolveOptional now that ProvisionContext already offers the identical method the other 46 migrated provisioners call. Monolith 5,461 to 4,987 lines, legacy types 33 to 31. Two classes rather than one, because the two types do not want the same dependencies. The secret needs only SecretsManagerService. The attachment reads an RDS or DocumentDB endpoint to build the connection detail it writes into the target secret, so it needs three services and an ObjectMapper. Splitting keeps AGENTS.md's "inject only the service it wraps" true for the common case and confines the wide dependency to the type that genuinely has it. The repo already anticipated the split: SecretTargetAttachmentCfnProvisionerTest has existed for some time, named for a class that did not. This is the batch that finally takes RdsService out of the monolith. Batch 7 could not: dbInstanceConnection and dbClusterConnection were the last two rdsService call sites and both belong to the attachment. Three service fields leave with this change, SecretsManagerService, RdsService and DocDbService, along with their constructor parameters and imports, plus six RDS model imports that batch 7 left behind unused. SecretTargetAttachment is the first extracted type to leave DELETE_NEEDS_STACK_RESOURCE, which drops from 7 entries to 6. Its delete needs two create-time attributes no physical id carries: which secret fields the attachment managed, so only those are stripped, and which attachment owns the secret, so a second attachment's fields survive. That logic moves into the provisioner's delete(StackResource, String) override, and the set entry goes in the same commit because the registry is consulted first and leaving both claiming the type is exactly what CfnDeletePrecedenceTest exists to catch. The id-only delete keeps refusing the attachment with the same message, which a test asserts. The 34 SecretTargetAttachmentCfnProvisionerTest tests and the 5 attachment integration tests pass unchanged, which is the guard that the move preserved behaviour: both build through CfnProvisionerFixture, so they exercise the new provisioners without knowing they exist. Making the types provisioner-owned rather than LEGACY_SWITCH puts them under CfnSchemaCoverageTest for the first time, since it skips switch-owned types. One attribute surfaces: Fn::GetAtt Id on a secret is its ARN, which the provisioner already sets as the physical id and as Arn. It is recorded as a gap rather than set, to keep this commit a pure move. |
||
|
|
7d96799c5a |
fix(s3): honor x-amz-bypass-governance-retention in batch DeleteObjects (#3366)
* fix(s3): honor x-amz-bypass-governance-retention in batch DeleteObjects The batch delete path parsed the request body but never read the x-amz-bypass-governance-retention header, so the four-argument deleteObject overload was unreachable from DeleteObjects: every entry was deleted with bypassGovernance false. A client that sent the header and held s3:BypassGovernanceRetention still could not permanently delete a version under GOVERNANCE retention, and got AccessDenied instead. The singular DeleteObject path reads the header and checks the permission already, so the two paths disagreed on the same request. The controller now reads the header for the batch path, checks s3:BypassGovernanceRetention per entry when it is set, and passes the flag through a new deleteObjects overload. The two-argument overload is kept and delegates with false, matching the existing deleteObject overload ladder. A second correction in the same response path: an AwsException raised while deleting an entry was reported as InternalError, because the catch-all arm ignored the exception's own code. A refusal to delete a locked version is a per-object AccessDenied on AWS, not a server fault, and the flattened code hid the retention lock from any client that branches on it. AwsException now keeps its code; genuinely unexpected failures still report InternalError. The regression test covers both directions: without the header the locked version survives and is reported as AccessDenied, with it the version is permanently deleted and echoed in Deleted.VersionId. * fix(s3): scope batch governance bypass permission --------- Co-authored-by: dajiaohuang <dajiaohuang@users.noreply.github.com> |
||
|
|
f03a716e90 |
fix(apigateway): fall back to a parameterised sibling on method mismatch (#3399)
* fix(apigateway): fall back to a parameterised sibling on method mismatch
A literal resource that declares some methods but not the requested one
returned 405 even when a parameterised sibling could serve it. Resource
candidates are ordered exact, then parameterised, then greedy, and the
selection loop stopped at the first candidate with any methods configured.
For /users/me declaring only PATCH, GET /users/me therefore returned 405
instead of resolving against /users/{userId}, where "me" is an ordinary
parameter value. Adding a literal child for one method silently removes
every other method a parameterised sibling already served, so this surfaces
as a regression in an application that was working.
The stop was there for a narrower reason, which the existing tests pin: a
method mismatch on a concrete resource must not be absorbed by a greedy
/{proxy+} catch-all. That rule is kept. Only the concrete-to-concrete case
changes, so a literal now yields to a parameterised sibling that can serve
the method, while /devices declaring POST still returns 405 for GET rather
than falling through to /{proxy+}.
Extends ApiGatewayRoutingFallthroughIntegrationTest, which already covers
the greedy cases, with /users/{userId} GET alongside a literal /users/me
PATCH: GET /users/me resolves to the parameterised resource, PATCH still
prefers the literal, and an ordinary id is unaffected.
* fix(apigateway): resolve the method against every matching resource
The selection loop stopped considering less specific siblings once a
resource declaring methods had been passed, so a method mismatch on a
concrete resource was terminal for the greedy half of the rule.
Captured against a real REST API in us-west-2: AWS picks the most
specific resource that can serve the requested method, searching
literal, then path parameter, then greedy {proxy+}, and refuses the
request only when no candidate declares it.
Drop concreteWithMethodsSeen and the greedy break so both fallbacks
follow that single rule. /users/me declaring only PATCH no longer hides
GET /users/{userId}, and /devices declaring only POST now falls through
to GET /{proxy+}.
getDevicesReturns405 pinned the greedy half of the old behaviour and is
updated to assert the fallthrough. Adds compatibility coverage for the
sibling and greedy fallbacks from the same AWS repro.
The no-match response is unchanged: AWS returns 403 Missing
Authentication Token where floci returns 405, tracked separately.
|
||
|
|
28105c08ec |
fix(s3): enforce auth on bucket-level config writes when enforce-auth is enabled (#3536)
* fix(s3): enforce auth on bucket-level config writes when enforce-auth is enabled With FLOCI_SERVICES_S3_ENFORCE_AUTH=true, unsigned object reads are refused unless a policy or ACL makes them public, and since #2326 unsigned object writes are refused the same way. Bucket management was never covered: CreateBucket, DeleteBucket, and every PUT/DELETE on a bucket subresource (?policy, ?acl, ?cors, ?lifecycle, ?versioning, ?website, ?notification, ?logging, ?encryption, ?publicAccessBlock, ?ownershipControls, ?requestPayment, ?tagging, ?accelerate, ?replication, ?object-lock, ?metrics) behaved identically with the flag on or off. An anonymous caller could PUT ?policy a public-read grant onto any bucket and then read what the previous request had correctly refused. Authorization in S3Controller is opt-in per branch, and only the three newest subresources called authorizeBucketWrite. createBucket and deleteBucket now parse the request's credentials once and check every branch against the bucket's policy with the matching s3:* action before the mutator runs, and s3:DeleteBucket before the bare delete. CreateBucket gets its own authorizeCreateBucket: there is no policy to consult and AWS never accepts it anonymously, so an unsigned request is AccessDenied and a signed one must carry a known key; authorizeBucketWrite would have answered NoSuchBucket, the wrong code and an existence oracle. Nothing changes with the flag off. With it on, anonymous bucket management now fails with 403, as it does on AWS. The enforce-auth tests created their buckets and policies anonymously, which was this bug running green; those 38 setup calls now sign with the class's legacy key, and four new tests pin CreateBucket/DeleteBucket, the policy-rewrite exploit, every subresource, and the policy-granted anonymous case. Closes #2335 * fix(s3): never let a bucket policy grant PutBucketPolicy or DeleteBucketPolicy anonymously AWS lets only an identity in the bucket owner's account manage the bucket policy, so the policy itself can never grant s3:PutBucketPolicy or s3:DeleteBucketPolicy to an anonymous caller. authorizeBucketWrite honoured a Principal "*" grant for those two actions like any other, which would have let an unsigned caller rewrite or delete a policy that named them. Refuse them before consulting the policy, and pin it with a test that installs a self-granting policy and checks anonymous PUT and DELETE ?policy are still AccessDenied and the policy survives. Raised in review on #3536. |
||
|
|
e9454af855 |
feat(redshift): intercept Extended Query protocol (#3474)
* feat(redshift): decode Extended Query wire messages * feat(redshift): track Extended Query statements and portals * feat(redshift): coordinate Extended Query backend responses * refactor(redshift): share S3 COPY and UNLOAD transfers * feat(redshift): execute S3 transfers through Extended Query * fix(redshift): retain next-cycle pipelined portals * feat(redshift): intercept Extended Query statements * test(redshift): cover Extended Query JDBC compatibility * test(redshift): cover Extended Query SDK compatibility * docs(redshift): document Extended Query interception * feat(redshift): implement extended query execution handling in BackendResponseCoordinator and update related classes * feat(redshift): enhance ExtendedS3Exchange with client synchronization handling * fix(redshift): synchronize extended COPY failures * fix(redshift): tolerate backend ownership fragmentation * fix(redshift): forward extended query flush frames * fix(redshift): abort backend copy on unload failure * fix(redshift): preserve later extended query mutations * fix(redshift): return ready state after copy failure * test(redshift): cover later sync cycle rollback * fix(redshift): preserve independent mutations when rejecting a pipelined mutation ExtendedQuerySession.rejectFrom() restored the whole statements/portals map back to the rejected mutation's "before" snapshot and truncated the journal to the end, discarding any later, independent mutation that happened to run first. The coordinator already rejects one pipelined mutation at a time in journal order, so this only ever needs to undo that one mutation's own effect. Each journal entry now also records its own "after" snapshot at creation time, since reconstructing it later from the next entry's "before" or from the live maps goes stale once an earlier reject's cascading portal cleanup has already touched a key this mutation never itself changed. * fix(redshift): forward the real ReadyForQuery after a COPY/UNLOAD failure readClientSync(client) called the two-argument overload without its Flush-forwarding OutputStream, which did not compile. Every error branch in the Extended Query COPY/UNLOAD path sent CopyFail and Sync to the backend but never drained or forwarded the backend's resulting ReadyForQuery: the client waited on a frame nobody ever read off the wire. drainReadyForQuery already existed for exactly this but was never called. Wire it into every COPY and UNLOAD error branch. |
||
|
|
04f0c3b7fd |
fix(rds): scope event reconciliation and prune history (#3533)
Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com> |
||
|
|
34efd8957a |
fix(rds): register instances before starting auth proxy (#3467)
* fix(rds): register instances before starting auth proxy * fix(rds): keep provisioning instances in creating state --------- Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com> |
||
|
|
01ec7af8d5 |
fix(s3): route signed multipart requests by virtual host (#3464)
* fix(s3): route signed multipart requests by virtual host * fix(s3): recognize presigned virtual-host requests --------- Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com> |
||
|
|
043167793b |
feat(ec2): carry the remaining launch template data fields (#3493)
* feat(ec2): carry the remaining launch template data fields InstanceMarketOptions, InstanceRequirements and a network interface's ConnectionTrackingSpecification were the last three RequestLaunchTemplateData groups Floci accepted and threw away. A Terraform aws_launch_template that declared any of them read back nothing, so it reported an inconsistent result after apply or diffed forever. Ec2QueryHandler now parses all three off the Query wire and renders them into ResponseLaunchTemplateData, and LaunchTemplateData stores them. All 26 members of InstanceRequirementsRequest are covered, including the nested BaselinePerformanceFactors. CreateLaunchTemplateVersion inherits the new members the same way it inherits the existing ones. * fix(ec2): validate launch template instance requirements and connection tracking InstanceRequirements and ConnectionTrackingSpecification became writable in the previous commit, but nothing checked them. A block carrying only BurstablePerformance was stored, and so was a network interface asking for a one second TCP established timeout. The EC2 service model declares VCpuCount and MemoryMiB required on InstanceRequirementsRequest, and Min required on each of their range shapes, so a request missing any of them now fails with MissingParameter. The connection tracking timeouts have no min or max keys in the model; the ranges live in each member's documentation string, which gives TcpEstablishedTimeout 60 to 432000 seconds, UdpTimeout 30 to 60 and UdpStreamTimeout 60 to 180. A value outside one of those fails with InvalidParameterValue, matching the existing hop limit check. CreateLaunchTemplate and CreateLaunchTemplateVersion both validate before anything is stored. * fix(ec2): reject the launch template combinations InstanceRequirements forbids InstanceRequirements became writable two commits ago, and validation covered the required members and the connection tracking ranges but not the combinations the EC2 API reference rules out. Three of them were storable. The service model documents each rule in a member documentation string rather than in its constraints. RequestLaunchTemplateData says "If you specify InstanceRequirements, you can't specify InstanceType". InstanceRequirementsRequest says "If you specify AllowedInstanceTypes, you can't specify ExcludedInstanceTypes" and "Only one of SpotMaxPricePercentageOverLowestPrice or MaxSpotPriceAsPercentageOfOptimalOnDemandPrice can be specified". All three now fail with InvalidParameterCombination from the shared validation path, so CreateLaunchTemplate and CreateLaunchTemplateVersion are covered alike. CreateLaunchTemplateVersion validates the merged version as well as the request it received. The merge inherits every member the request does not restate and has no way to express removal, so a version naming only InstanceType against a source carrying InstanceRequirements would otherwise store a version holding both. That merged version is what AutoScaling and the fleet APIs read, so it is rejected rather than stored. Omitting SourceVersion starts from empty data and remains the way to move a template between the two selection modes. The instanceRequirementsRoundTrips test set both halves of two of these pairs. Its assertions are unchanged; the members that cannot share a template moved to a second template of their own. |
||
|
|
bc44fc9106 | fix(apigateway): decode the ~0 JSON Pointer escape in stage method-settings patch paths (#3526) | ||
|
|
a6f1751dfb |
fix(ec2): align catalog image owner filtering (#3463)
* fix(ec2): align catalog image owner filtering * fix(ec2): preserve catalog aliases in image filters * test(ec2): pin supported image owner selectors |
||
|
|
505b5d286e |
feat(ses): preserve raw message fidelity and envelope sender in the SMTP relay (#3522)
* feat(ses): preserve raw messages, envelope sender, and X-SES headers in SMTP relay
The raw relay reparsed each MIME message and rebuilt it from the text and
HTML parts alone, dropping every attachment and custom header. It now walks
the Mime4j tree and maps it onto the outgoing message: the first text/plain
and text/html parts become the body, every other leaf becomes an attachment
(inline when it carries a Content-ID, so cid: references still resolve), an
embedded message/rfc822 part is relayed whole, and display names on addresses
survive. Top-level headers are copied through apart from the MIME structural
ones, which the encoder regenerates for the re-built message.
Wire the envelope sender through to MAIL FROM, resolved in AWS's order: the
Return-Path MIME header, then the ReturnPath request field (v1) or
FeedbackForwardingEmailAddress (v2), then the source. The resolved value is
recorded on SentEmail so the inspection endpoint shows it.
Stamp relayed messages with <{MessageId}@{region}.amazonses.com>, matching the
MessageId returned to the caller, leaving a caller-supplied Message-ID alone.
Honour the X-SES-CONFIGURATION-SET and X-SES-MESSAGE-TAGS control headers on
raw sends, which previously parsed to nothing and left event publishing
silently inert for callers using the header form. Both are stripped from the
relayed message, as AWS consumes rather than forwards them. The tenant send
gate sees the same resolved configuration set, so one named only by header
cannot slip past the association check.
Fix tryBase64Decode, which decoded every raw message with the MIME decoder and
only fell back to plain text when it threw. That decoder skips characters
outside the base64 alphabet rather than rejecting them, so a plain-text RFC
5322 message decoded into garbage whenever the surviving alphabet characters
happened to form a valid length, wiping its headers. The alphabet is now
checked before decoding.
Replace the nine-argument SmtpRelay.relay with a RelayMessage record, and add
a ServerSocket-based SMTP test that drives a real MailClient end to end and
asserts on the negotiated envelope and the bytes on the wire, covering the
authentication and STARTTLS-OPTIONAL configuration branches.
* fix(ses): align SMTP relay with documented AWS header and tag semantics
Verified the relay against the SES documentation and corrected four
deviations.
AWS overrides a caller-supplied Message-ID with the id it assigned, and
rejects Message-ID outright as a custom header on Simple and Templated
content (SES header fields reference). The relay preserved a caller's value
instead; it now always stamps the id returned by the API.
AWS likewise overrides a caller-supplied Date with the time it accepted the
message. The relay copied the caller's Date through, so a stale timestamp
reached the recipient. Date is now regenerated with the rest of the headers
SES sets.
AWS uses only the request field's message tags when tags are supplied both
as a request field and as an X-SES-MESSAGE-TAGS header, and explicitly does
not join the two sets. The relay merged them, letting a header-only tag
survive a request that supplied its own. Header tags now apply only when the
request passes none.
The stamped Message-ID domain was region-scoped, which no AWS documentation
or observed output supports. Use the observed email.amazonses.com instead,
and record in the docs that only the local part, which is the returned
MessageId, is documented behaviour.
Also document that AWS delivers a Return-Path differing from the one
supplied, because it routes bounces through its own address, whereas Floci
has no bounce pipeline and puts the resolved address directly in MAIL FROM.
* fix(ses): align mime4j artifacts to unbreak the native build
The raw relay's new DefaultMessageWriter path failed GraalVM analysis with
an unresolved reference to Field.getSafeRaw(). apache-mime4j-dom was pinned
to 0.8.14 while the Quarkus BOM manages apache-mime4j-core at 0.8.12, so the
writer was compiled against a Field API the resolved core does not declare.
Nothing reached the writer before this branch, which is why the skew only
surfaced now, and only in native builds.
Drop the hardcoded -dom version so both artifacts track the BOM together,
and cover the embedded message/rfc822 branch that exercises the writer.
|
||
|
|
325bdfb30e |
feat(ec2): report instance credit specifications (#3492)
* feat(ec2): report instance credit specifications DescribeInstanceCreditSpecifications was not implemented, so the action Terraform's aws_instance resource reads credit_specification from always came back empty and every plan after an apply showed a credit_specification diff for an instance nobody had touched. CreditSpecification is not a member of the Instance shape DescribeInstances returns, per botocore's ec2 2016-11-15 model, so this dedicated action is the only way that value can reach a client. The credit option is the launch's explicit CreditSpecification.CpuCredits when the request named one, and the instance type family's documented default otherwise: standard for t2, unlimited for t3, t3a and t4g. The model's own InstanceType enum lists t1, t2, t3, t3a and t4g as the only T families, and t1 predates the credit model, so that table is complete. The default is resolved on read rather than frozen at launch, so a resize moves the instance onto its new family's default. The two request shapes mean different things and both are implemented. Naming instance ids reports exactly those instances, and an id with no credit option is an error rather than an omission, which is what the model documents for "an instance that is not a burstable performance instance". Naming no ids reports only the instances running unlimited, paginated by MaxResults and NextToken; AWS rejects MaxResults together with instance ids and so does this. DescribeInstanceTypes now reports burstablePerformanceSupported. Terraform checks that flag before it reads a credit specification at all, so without it the new action would never be called. ModifyInstanceCreditSpecification is deliberately left out. Describe stands on its own here: it fixes the read that produced the perpetual diff, and a launch can already set the option through RunInstances or launch template data. The modify path is a separate change. Tests: Ec2InstanceCreditSpecificationsIntegrationTest covers each burstable family default, a non-burstable type, an explicit launch-time override, an unknown instance id, the unfiltered form and the MaxResults combination error on the real Query wire. Ec2InstanceTypeCatalogTest covers the family table. Ec2RunInstancesPublicIpParamTest's mocked signature gains the new parameter. * fix(ec2): persist the instance credit option and report standard for non-burstable ids The first cut of DescribeInstanceCreditSpecifications had the documented behaviour backwards on two points. Both come from the operation's own documentation string in botocore's ec2 2016-11-15 model, which the constraint keys alone do not carry. "If you specify an instance ID that is not a burstable performance instance, Amazon EC2 returns the standard credit option." A named m5 was answered with InvalidInstanceID.NotFound, because effectiveCpuCredits() returned null for a type with no credit model and the named-id path treated that as an unknown id. It now reports standard. An id that names no instance at all is still InvalidInstanceID.NotFound, which is the only error that path raises. The unfiltered form returns burstable instances on the unlimited option "as well as instances that were previously configured as T2, T3, and T3a with the unlimited credit option. For example, if you resize a T2 instance, while it is configured as unlimited, to an M4 instance, Amazon EC2 returns the M4 instance." A launch without an explicit CreditSpecification stored null and the credit option was recomputed from the instance's current type on every read, so a t3 that defaulted to unlimited lost that option the moment it was resized onto an m5. The option is now resolved once, at the point the instance acquires it, and stored on the instance: Instance.creditSpecificationCpuCredits, written in runInstances from the request or the family default, and written again in modifyInstanceAttribute when a resize moves an instance with no option yet onto a burstable type. Reads return the stored value. The family default stays on the read path only as a fallback for instance records written before the option was stored. Tests: aNonBurstableInstanceIdReportsStandard replaces the regression that locked in the error. theUnlimitedOptionSurvivesAResizeOntoANonBurstableType, aResizeOntoABurstableTypeAcquiresTheFamilyDefault and aStandardOptionSurvivesAResizeOntoAnotherBurstableFamily cover the resize paths, and the unfiltered-form test now also asserts a non-burstable instance is absent. * fix(ec2): honor DryRun, Filter.N and the MaxResults range on DescribeInstanceCreditSpecifications The EC2 model declares more request behavior for this action than the handler accepted. All three gaps come from local/model-preflight.py ec2 DescribeInstanceCreditSpecifications, which prints the constraint keys and the documentation prose together. DryRun is a modeled member and the handler never probed it, so DryRun=true returned a normal response instead of DryRunOperation. The pagination parameters are now validated before the probe, matching the order the snapshot block public access handlers use, since AWS reports an invalid parameter ahead of DryRunOperation and only returns DryRunOperation once the request could otherwise succeed. Filter.N is a modeled member and was parsed nowhere. The model declares one filter name here, instance-id, which Ec2Service.matchesFilter already resolves for an Instance, so both request shapes now run their candidates through matchesFilters. Named ids still decide the base set and are still validated for existence, then the filters narrow that set with an AND, which is what the Filters member documents. An unrecognised filter name matches everything, following the default arm every other filtered EC2 Describe action in this service already takes. DescribeInstanceCreditSpecificationsMaxResults carries a min of 5 and a max of 1000, and any positive integer was accepted, so 1 and 1001 were treated as page sizes. Out of range now raises InvalidMaxResults with the message describeNetworkInterfaces already uses for the same range. Tests: maxResultsHonorsItsModeledRange covers 5, 1000, 4 and 1001, dryRunReturnsDryRunOperation and anInvalidMaxResultsIsReportedAheadOfDryRun cover the probe and its ordering, and four filter tests cover the unfiltered form, named ids, an unknown named id under a filter and an unrecognised filter name. |
||
|
|
24a8c8440b |
fix(lambda): resolve layer version ARNs by account (#2948)
* fix(lambda): resolve layer version ARNs by account Layer resolution dropped the ARN's account segment, so an ARN naming another account resolved inside the caller's own partition. Two consequences, filed separately as #2813 and #2809. A foreign ARN whose layer name and version happened to match one of the caller's own resolved to that layer: the function recorded an ARN it was not using, and the launcher mounted different content at /opt than GetFunctionConfiguration reported. resolveLayerByArn now scopes the lookup to the caller's account and partition, so a foreign ARN is a miss. A foreign ARN that matched nothing was rejected outright, which no AWS-managed public layer can ever satisfy: Powertools, the AppConfig extension and Datadog-published layers all live in AWS-owned accounts, and every Terraform stack attaching one failed at CreateFunction. Validation now applies the eager existence check only to the caller's own account and records a foreign ARN unresolved, warning that its content is not mounted. Measured against the live service in ap-southeast-1: CreateFunction, foreign ARN matching an own layer name/version -> AccessDeniedException, not a substitution CreateFunction, AWS-managed Powertools layer -> 201, ARN echoed verbatim on GetFunctionConfiguration CreateFunction, missing layer in the caller's own account -> InvalidParameterValueException: Layer version ... does not exist. The own-account message and status are unchanged, matching that third case exactly. The AccessDenied case is a known divergence: Floci implements no layer permissions, so it cannot tell a public layer from one the caller has no policy for, and accepts both. Closes #2813 Closes #2809 * fix(lambda): reject foreign-partition layer ARNs when attaching them GetLayerVersionByArn already answers a non-aws partition with InvalidParameterValueException, but CreateFunction and UpdateFunctionConfiguration accepted the same ARN and persisted it, so a function could carry a layer Floci's own lookup path calls invalid. Partitions are isolated, so no resource policy can ever make a cn or gov layer readable from the aws partition. That is what separates it from a foreign account, where a policy can, and where AWS-managed public layers live. Foreign accounts stay accepted; foreign partitions now reject with the message GetLayerVersionByArn already uses. Measured on CreateFunction in ap-southeast-1: a cross-partition layer ARN and a foreign-account layer ARN both fail with AccessDeniedException, so the live service does not distinguish them at this call. The split here is Floci's, on reachability grounds, and is documented as such. * fix(lambda): gate foreign-account layer ARNs behind a config flag Review asked for the accept-foreign-ARN behaviour to be opt-in rather than the default, on both PRs' reasoning that it broadens what CreateFunction accepts beyond AWS. It is now floci.services.lambda.accept-external-layer-arns, default false, env FLOCI_SERVICES_LAMBDA_ACCEPT_EXTERNAL_LAYER_ARNS. Off, a layer ARN naming another account is refused. On, it is recorded on the function verbatim and its content is not mounted, which is what a stack attaching Powertools or the AppConfig extension needs. A same-account ARN is unaffected either way: a missing layer is still the eager InvalidParameterValueException. The refusal is AccessDeniedException, 403, not the InvalidParameterValueException this branch previously used for the partition case. That was the second review finding: the live probe in this PR measured CreateFunction returning AccessDeniedException for a cross-partition ARN and the identical AccessDeniedException for a same-partition foreign account, so reporting a different error class than what was measured was an observable divergence presented as parity. Both now report what AWS reported. Cross-partition stays refused with the flag on. Partitions are isolated, so no resource policy can make an aws-cn layer readable from aws, and GetLayerVersionByArn already calls such an ARN invalid. Negative control, with the default flipped to true and the tests kept: LambdaLayerArnAccountIntegrationTest foreignAccountArnIsDeniedByDefaultAndTheFunctionIsNotCreated updateFunctionConfigurationIsDeniedAndLeavesTheExistingLayerInPlace Tests run: 7, Failures: 2 Also moves the two generic ARN ownership checks this branch was adding into AwsArnUtils as isForeignPartition and isForeignAccount, so the layer code keeps only the layer-shaped part. Review noted RdsService.targetGroupBelongsTo already carries its own copy and asked not to land a further one. The existing RDS, EKS and EC2 copies are deliberately left alone; this only avoids adding another. |
||
|
|
6790024abc |
feat(firehose): convert array, struct and map columns to Parquet (#3521)
* feat(firehose): convert array, struct and map columns to Parquet
Data format conversion rejected every complex Hive type up front, so a
stream whose Glue table carried an array<string> or a struct<..> routed
its whole batch to the error output as UnsupportedSchema. That covers the
ordinary Firehose-to-Athena schema, where a JSON event nests.
A column's type is now a recursive tree feeding DuckDB's read_json, and
values coerce the way real AWS's OpenX deserializer does (probed against
us-west-2 with a table of exactly these types):
- a value that is not an array is wrapped into a one-element array
- a struct takes its members from an object by name, dropping an
undeclared one and leaving a missing one null, and an array fills them
by position instead; a scalar fails the record
- a map accepts only an object, and its keys are lowercased
- member names match case-insensitively at every depth, and the scalar
coercions apply inside containers as they do at the top level
- a mismatch at any depth fails that record alone, with the message AWS
reports there
binary and uniontype stay unsupported, as does a type string the parser
cannot read; each still routes the batch to the error output.
* fix(firehose): refuse under HiveJsonSerDe what AWS refuses
The complex-type conversion applied OpenX's coercions whichever
deserializer was configured: a non-array wrapped into an array, an
array filling a struct by position, a string parsed into a numeric
column, a nested value serialized into a text column. AWS documents
the last two as things HiveJsonSerDe will not do, and a probe over a
Hive stream (us-west-2, twelve records over the same four complex
columns) confirmed it refuses all four and fails the record, with
messages now reproduced: "Start of Array expected", "Start of Object
expected", "Current token (VALUE_STRING) not numeric, can not use
numeric value accessors", and "One or more fields have incorrect
format. Exception when validating field (root)".
The two booleans threaded through the type tree became one SerDeRules
record built from the deserializer, with a third member for this. The
top-level scalar path shares ScalarType, so a string in a numeric
column now fails under Hive there too, which was a deviation before
this branch. Hive still coerces a number into a text column and treats
{}, missing and undeclared members as OpenX does, all probed. A map
column itself given a non-object, and a boolean column given a string,
were not probed; the docs say which way they fall.
|
||
|
|
b994d58e14 |
fix(s3): honor max-keys=0 and reject invalid max-keys values (#3510)
max-keys=0 was treated as "no limit", so ListObjects, ListObjectsV2 and ListObjectVersions returned every key instead of an empty page, and a negative value was accepted. AWS answers max-keys=0 with an empty page and IsTruncated=false, and rejects negative, non-numeric or overflowing values with InvalidArgument "Argument maxKeys must be an integer between 0 and 2147483647" plus ArgumentName and ArgumentValue. The parameter is now read as a string so a non-integer value produces that 400 instead of the 404 JAX-RS emits for a failed Integer conversion. The DynamoDB import path, which relied on 0 meaning unlimited, now asks for Integer.MAX_VALUE explicitly. |
||
|
|
34062f6383 |
fix(lambda): report real runtime errors instead of Function.TimedOut (#3505)
RuntimeApiServer now reports real init errors, crashed processes, and the actual FunctionError instead of Function.TimedOut, and retains the fault payload so a same-cause enqueue() rejection returns it instead of a generic ContainerStopped. * Fix #3314 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
9f9a828439 |
fix(core): accept only JSON objects as JSON protocol request bodies (#3509)
The JSON 1.0 and 1.1 dispatchers handed whatever Jackson parsed straight
to the handlers, so a body of null, [] or a scalar reached code that
expects an object and failed with an unhelpful 500 instead of the
SerializationException AWS returns. Both dispatchers now reject any body
that is not a JSON object with the standard 400 SerializationException.
An empty or whitespace only body is still read as {}. The awsJson1_1
protocol requires services to accept no payload for operations that
define no input, and clients rely on that for calls such as Organizations
DescribeOrganization.
|
||
|
|
76c1907214 |
fix(glue): bound DeleteSchemaVersions ranges before expanding them (#3508)
A Versions expression such as 1-9223372036854775807 was expanded into a list before the 25 version limit was checked, so a single request could exhaust memory. Reject any range that would expand to more than MAX_DELETE_SCHEMA_VERSIONS entries with InvalidInputException up front, and cover the exact 25 version boundary. |
||
|
|
2a4ca61baf |
fix(cognito): delete a user pool's records with the pool (#2949)
* fix(cognito): delete a user pool's app clients, revocations and codes #3419 took users and resource servers out with the pool, closing the half of #2864 that was reported. Three more record types are the same defect and were left behind: app clients, revoked token records and outstanding verification codes. On AWS a pool id is never reused, so nothing can inherit an orphan. Here floci:override-id makes ids caller-chosen and therefore reusable, and a pool recreated on a pinned id picks up whatever the deleted pool left. Reproduced by pinning us-east-1_orphanprobe1, populating it, deleting the pool and recreating it on the same id. The client leak is the serious one: the deleted pool's client id kept resolving against the new pool, carrying a secret the new pool's caller never saw. clients: ["c1"] describe-user-pool-client --client-id c1a93e3fc698451d96ed406adb -> c1 Clients are keyed by client id alone, so they are found by their userPoolId field rather than a key prefix. Revoked tokens and verification codes have their keys collected before deleting so the backing key set is not modified while it is being iterated. confirmSignUpNamesDeletedUserPoolInResourceNotFoundMessage, added by #2936, built its orphaned client by deleting the client's pool, which this cascade now prevents. It is renamed and reaches the same defensive path by dropping the pool record alone, and a second case pins the new behaviour: a client id from a deleted pool is gone with it. Refs #2864 * fix(cognito): bound the delete cascade by pool ownership, not key prefix floci:override-id makes pool ids caller-chosen, and validateOverrideId permits a colon. Two live pools can therefore be named so that one id plus the key separator is a prefix of the other, and the revoked-token and verification-code cascades deleted by the matched key, so deleting the shorter pool erased the longer one's records. For revoked tokens that reinstated tokens the surviving pool had revoked. Both records carry their own userPoolId, so ownership is now settled by that field rather than by the key prefix. The other cascades reconstruct the key from the pool id being deleted and so never reached across a boundary; they are left alone. A jti can itself contain a colon (global revocations use global:{username}), so bounding the prefix by the separator would not have been sufficient either. |
||
|
|
8a452116bf |
fix(s3): evaluate IAM policy on presigned URL and presigned POST requests (#3504)
Presigned URL and presigned POST both skipped IAM identity-policy evaluation. The POST-side check now also runs independent of S3's enforce-auth flag, matching the presigned-URL path, and now resolves the account from the parsed credential instead of the ambient request context set before the multipart body was parsed. * Fix #3195 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
b618fa9033 |
fix(cloudformation): expose the RDS resource-id GetAtt attributes (#3527)
AWS::RDS::DBCluster declares DBClusterResourceId readOnly and AWS::RDS::DBInstance declares DbiResourceId, and RdsService already assigns both. Neither reached the stack resource, so Fn::GetAtt on either resolved to the literal "LogicalId.Attr" rather than the id, the silent failure mode Fn::GetAtt has when an attribute was never mapped. Invisible until now: the types were LEGACY_SWITCH, and CfnSchemaCoverageTest skips those. Moving them to a provisioner is what surfaced it. The other 17 attributes that surfaced with them stay recorded as gaps, because Floci does not emulate what they describe: read replicas, multi-AZ secondaries, point-in-time restore windows, RDS Custom automation. Endpoint and ReadEndpoint are recorded too, for a different reason: the dotted Endpoint.Address, Endpoint.Port and ReadEndpoint.Address are already set, and that is the form AWS's GetAtt exposes for these types. Both assertions fail against the previous commit, returning null. |
||
|
|
5d0b0b44b1 |
fix(ec2): store and validate CreateVpcEndpoint SubnetConfiguration (#3491)
* fix(ec2): store and validate CreateVpcEndpoint SubnetConfiguration CreateVpcEndpoint accepted SubnetConfiguration.N and dropped it, so an interface endpoint took floci's own synthesized address in each subnet rather than the one the caller pinned. Terraform's aws_vpc_endpoint sends the subnet_configuration block on create and reads it back by following the endpoint to its network interfaces, so every plan after the apply saw an address it never asked for and proposed replacing the endpoint. SubnetConfiguration is request-only in ec2/2016-11-15. No output shape carries it, so the addresses are stored on the endpoint and consumed when its interfaces are built, and DescribeVpcEndpoints echoes nothing new. Ec2QueryHandler parses the flattened SubnetConfiguration.N list for CreateVpcEndpoint and for ModifyVpcEndpoint, which takes the same parameter. Ec2Service validates each entry against the named subnet, rejecting an IPv4 address outside its CIDR with InvalidParameterValue, and keeps the pinned address on the endpoint's interface in that subnet. A subnet named only through its configuration joins the endpoint's subnet set. Ipv6 is stored as given, since floci's subnets carry no IPv6 CIDR to validate against and its network interfaces have no IPv6 field yet. Adds Ec2VpcEndpointSubnetConfigurationIntegrationTest over the query wire and three Ec2ServiceTest cases for the create, modify and rejection paths. * fix(ec2): reject the subnet-reserved addresses in SubnetConfiguration validateSubnetConfigurations only checked that SubnetConfiguration.Ipv4 parsed and fell inside the named subnet's CIDR. For a 10.61.1.0/24 subnet that let 10.61.1.0, .1, .2, .3 and .255 through, and each became the private address of the endpoint's network interface. AWS keeps those five for itself, so none of them can be assigned to a resource and no real endpoint could ever report one. The rule is in ec2/2016-11-15 itself, in the CreateSubnet documentation: "Amazon Web Services reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for your use." CreateSecondarySubnet says the same for secondary subnets. No constraint key carries it, and no shape in the model states it for SubnetConfiguration. Ipv4Cidrs.isSubnetReserved is new; the EC2 service had no reserved-address helper to reuse. VpcNetworkManager.firstHostOffset looks close but is not the same rule: it reserves ten addresses of Docker-network headroom at the bottom of a block and nothing at the top, for allocation readability rather than AWS semantics. Small blocks need no special case. A /28, the smallest subnet AWS accepts, keeps 11 of its 16 addresses and a /29 keeps three. Both ends are clamped so they cannot cross in a block of four addresses or fewer, where every address is reserved. The check sits in the shared validator, so CreateVpcEndpoint and ModifyVpcEndpoint both refuse a reserved address with the InvalidParameterValue the containment check already raises. Tests cover all five reserved addresses and one ordinary host address on the create path, the modify path, a /28 subnet, and the query wire. --------- Co-authored-by: lex00 <artigues.dev@gmail.com> |
||
|
|
fe40e06938 |
feat(ec2): support snapshot block public access (#3490)
* feat(ec2): support snapshot block public access Adds EnableSnapshotBlockPublicAccess, DisableSnapshotBlockPublicAccess and GetSnapshotBlockPublicAccessState over the EC2 Query protocol. The setting is account-level state scoped to one region, so it lives in a small Ec2SnapshotBlockPublicAccessService keyed by region, mirroring Ec2EbsEncryptionService. The account-aware storage backend namespaces the keys by the calling credential's account. A region that was never configured reads back unblocked. Enable accepts only block-all-sharing and block-new-sharing, per the EC2 model, and rejects unblocked with InvalidParameterValue. Disable returns the resulting unblocked rather than the prior state. Only the Get response carries managedBy, always account, since Floci has no declarative-policy layer. * fix(ec2): honor DryRun on snapshot block public access EnableSnapshotBlockPublicAccess, DisableSnapshotBlockPublicAccess and GetSnapshotBlockPublicAccessState all model the standard DryRun parameter, but none of the three handlers checked it. Enable persisted the requested state, Disable persisted unblocked and Get answered 200, so DryRun=true had real side effects on both write paths. All three handlers now take the parameter map and call the existing checkDryRun(params). Enable validates State first, through a new validateEnableState on the service, because AWS reports an invalid parameter ahead of DryRunOperation and only returns DryRunOperation once the request would otherwise have succeeded. So State=unblocked with DryRun=true still fails with InvalidParameterValue, and a missing State still fails with MissingParameter. |
||
|
|
8963c665eb | fix(cloudformation): preserve SAM implicit API auth (#3501) | ||
|
|
cebb011a00 |
fix(autoscaling): round-trip the dropped Auto Scaling group fields (#3494)
* fix(autoscaling): round-trip the dropped Auto Scaling group fields CreateAutoScalingGroup and UpdateAutoScalingGroup accepted DesiredCapacityType, CapacityRebalance, MaxInstanceLifetime and DefaultInstanceWarmup and threw them away, so DescribeAutoScalingGroups never read them back. A mixed instances policy launch template override that selected instance types by InstanceRequirements instead of by name was dropped the same way, and because the override parser used InstanceType's presence as its only "is there another override" signal, such an override also truncated the whole Overrides list. The four scalar members now travel into AutoScalingService as one AsgOptionalFields record and are stored on AutoScalingGroup as boxed, uninitialised fields, so a group that never set one omits it from the Describe response rather than reporting a default. Update keeps its partial-update semantics: an absent member leaves the stored value alone. DefaultInstanceWarmup honours the documented -1 removal sentinel, MaxInstanceLifetime must be 0 or at least 86400, and DesiredCapacityType is checked against units, vcpu and memory-mib. LaunchTemplateOverrides.InstanceRequirements parses and echoes every member of the botocore shape except BaselinePerformanceFactors, and an override that sets both InstanceType and InstanceRequirements raises ValidationError as AWS does. Verified against botocore autoscaling/2011-01-01/service-2.json from awscli 2.35.24. * fix(autoscaling): enforce the attribute-based instance selection rules Two rules that botocore states but does not encode as constraints were missing. DesiredCapacityType is typed XmlStringMaxLen255 with no enum, and CreateAutoScalingGroupType.members.DesiredCapacityType.documentation carries the rule: "Amazon EC2 Auto Scaling supports DesiredCapacityType for attribute-based instance type selection only." Floci accepted vcpu and memory-mib for a group whose launch template names a fixed instance type. Both values now raise ValidationError unless the mixed instances policy left in effect by the request carries a launch template override with a non-empty InstanceRequirements. units is the documented default and stays legal everywhere, and an absent member is not validated. The effective policy is the one the request supplies on create. On update it is the policy the request supplies, the stored policy when the request names no launch source, or none when the request switches the group to a launch configuration or a plain launch template. The effective DesiredCapacityType is likewise the request value or, when absent, the stored one, so an update cannot strip attribute-based selection out from under a stored vcpu. shapes.InstanceRequirements.required is ["VCpuCount", "MemoryMiB"] and the shape documentation repeats it as "You must specify VCpuCount and MemoryMiB". An override carrying InstanceRequirements without both ranges was stored and returned 200; it now raises ValidationError. Both rules run on create and on update. createGroupCarryingEveryOptionalField is @Order(1) and seeds the group the later ordered tests reuse, so its setup moved from a launch template naming t3.micro to a mixed instances policy whose override sets VCpuCount and MemoryMiB. That makes its DesiredCapacityType=vcpu legal without relaxing any assertion, and the ordered updates that follow still see attribute-based selection in effect. |