mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
cdb2c36dfe6237a86cee46dfd78bf37e7ffcef6e
1265
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
cdb2c36dfe |
fix(s3): isolate object byte storage between accounts (#2241)
* fix(s3): isolate object byte storage between accounts
Object bytes (S3Service.memoryDataStore in memory mode, or files
under dataRoot on disk) were keyed only by "bucketName/key", with no
account component — unlike bucketStore/objectStore, which get
automatic account prefixing from AccountAwareStorageBackend.
bucketStore only enforces name uniqueness within an account, so two
accounts can each own a bucket with the same name (real S3 disallows
this globally, which is a separate, pre-existing behavior difference
not addressed here); when they did, their object bytes collided:
- PutObject in one account's bucket could overwrite the bytes read
back by GetObject in another account's identically-named bucket.
- DeleteBucket in one account deleted the *shared* memoryDataStore
entries / on-disk directory, corrupting another account's
same-named bucket (surfaced as a 500 "S3 object data is missing").
Scope the physical key/path by the resolved account ID at the four
byte-storage entry points (writeFile/readFile/deleteFile and their
versioned counterparts) plus deleteBucket's cleanup and
openObjectStream's direct memoryDataStore lookups, which bypassed
those helpers. objectKey()/versionedKey() themselves are unchanged,
since they're also used as objectStore's own storage keys, which are
already correctly account-scoped via AccountAwareStorageBackend.
Added S3AccountIsolationIntegrationTest, reproducing both leaks
end-to-end (fails without this fix). Updated S3ServiceTest /
S3VersioningServiceTest disk-path assertions for the new
<accountId>/ path segment (these unit tests construct S3Service
directly with no RegionResolver, so paths fall back to the default
account "000000000000").
* fix(s3): migrate pre-existing objects from the legacy unscoped disk layout
Before this fix, every disk-mode S3 object lived at
dataRoot/bucketName/key.s3data, with no account segment — object
metadata (objectStore) was already account-scoped and unaffected by
an upgrade, but the physical bytes were not. Resolving only the new
account-scoped path meant an existing Floci installation upgrading
past the account-isolation fix would 404 on every object already on
disk.
resolveObjectPath()/resolveVersionedPath() now transparently relocate
a legacy-layout file to its new, account-scoped location on first
access, mirroring how AccountAwareStorageBackend.get() already
migrates a pre-multi-account storage key on read. Memory-mode storage
needs no equivalent fix: memoryDataStore is never persisted across a
restart, so there's no pre-existing state to migrate. Found by review.
* fix(s3): confine legacy-layout migration to reads, guarded and bounded correctly
The previous commit's naive migrateLegacyFileIfPresent() ran on every
path resolution — including writes and deletes — and MOVED the legacy
file into place. Review (Greptile + @pgermosen) surfaced several real
correctness gaps in that design, all addressed here in the final form:
- A legacy object predates any account concept, so it isn't actually
known to belong to whichever account happens to touch it first —
and two different accounts can legitimately own a same-named bucket
in Floci (bucket-name uniqueness is only enforced per account here).
Migrating on a write/delete let one account's operation destroy
another account's still-unmigrated data: the same cross-account
corruption this whole fix exists to prevent, introduced a different
way. Legacy fallback is now confined to resolveObjectPathForRead/
resolveVersionedPathForRead, used only by the read call sites
(readFile, readVersionedFile, openObjectStream); writeFile/
deleteFile/writeVersionedFile/deleteVersionedFile use the plain
scoped-path resolvers with no legacy involvement at all. The legacy
source is copied, never moved, so every account that reads it
independently gets its own copy instead of racing to claim it.
- Migration and a write/delete of the same path could still race each
other: a read could copy legacy bytes in, a concurrent write could
land its real content, and the read's install step could clobber
that write with the stale legacy content — a completed PutObject's
data silently reverting. A per-path ReentrantLock, striped across a
fixed-size (256) array rather than one lock per Path in an
unboundedly growing map, now guards copyLegacyFileIfPresent and
every write/delete of the same resolved path, making "does the
destination already exist" and "install it" one atomic step with
respect to every other disk operation on that path. This also made
an earlier temp-file + ATOMIC_MOVE approach unnecessary — with the
lock guaranteeing no concurrent writer, a plain, portable Files.copy
is sufficient, sidestepping both ATOMIC_MOVE's lack of universal
filesystem support and a temp filename that could exceed filesystem
component limits.
- Files.copy can still throw partway through (disk full, transient
I/O error) after already creating the destination with truncated
content. Left in place, that file would satisfy the exists-check on
every later attempt, permanently shadowing the still-intact legacy
source. The catch block now deletes the destination (best-effort,
logged per AGENTS.md) before rethrowing, still holding the lock.
Tests added: anotherAccountsWriteMustNotDestroyThisAccountsUnmigratedLegacyObject
(the cross-account corruption scenario), concurrentOverwriteNeverLosesToARacingLegacyMigration
(a completed write must never be clobbered by a racing migration),
concurrentFirstReadsOfTheSameLegacyObjectBothSucceed (concurrent reads
of a never-yet-migrated file), and migrationFailureIsNotPermanentAndDoesNotLeaveAFileBehind
(a retry after a transient failure recovers the intact legacy content —
note this last test's specific fault, permission denied on the source,
happens to fail before Files.copy ever creates a destination on this
JVM, so it doesn't reproduce a genuinely partial/truncated write; that
scenario isn't reliably forceable through portable java.nio.file APIs
for a file this small, so the cleanup's correctness there rests on the
delete being unconditional on any IOException, not on this test).
* fix(s3): reserve a namespace for account-scoped storage disjoint from bucket names
A 12-digit bucket name is valid on S3, so dataRoot/<accountId>/
<bucket>/<key>.s3data was not disjoint from the legacy
dataRoot/<bucket>/<key>.s3data layout: a legacy bucket literally named
e.g. "000000000000" with key "orders/report.csv" resolved to the exact
same path as account "000000000000"'s own, unrelated "orders" bucket,
key "report.csv". After upgrading, reading one could silently return
the other's bytes, and a write or DeleteBucket("orders") could
overwrite or delete the legacy object entirely — the same class of
cross-account corruption this whole fix exists to prevent, reintroduced
by the specific path-scoping scheme it chose. Found by review.
Account-scoped storage now lives under a reserved ACCOUNT_STORAGE_ROOT
(".accounts") segment: dataRoot/.accounts/<accountId>/<bucket>/...
A leading "." makes this namespace unreachable by any bucket name real
S3 accepts (bucket names must begin with a letter or number); since
Floci doesn't otherwise validate bucket name format at all,
createBucket() additionally rejects the one bucket name that would
collide with the root of this namespace itself (".accounts" exactly).
Added bucketNamedLikeTheDefaultAccountIdDoesNotCollideWithAccountScopedStorage
(the exact scenario above; confirmed it reproduces the corruption
without this fix by temporarily reverting it) and
bucketNamedLikeTheReservedAccountStorageRootIsRejected. Updated
existing S3ServiceTest/S3VersioningServiceTest/S3LegacyDiskLayoutIntegrationTest
path assertions for the new segment.
* style(s3): tighten comments to be concise and scoped to their code
No behavior change. Several comments introduced across this fix had grown into
paragraph-length essays restating context better left to the commit history;
trimmed them down to the non-obvious 'why' at the point they're placed.
|
||
|
|
bc21367cc4 |
feat(cloudformation): provision AWS::Events::EventBus as a real custom bus (#1807)
* feat(cloudformation): provision EventBridge event buses * fix(cloudformation): restore main's provisioner changes lost in the EventBus merge The previous conflict resolution took this branch's whole CloudFormationResourceProvisioner, which silently reverted five commits main had landed on that file since the merge base — including the DynamoDB/Lambda delete idempotency from #1803 and AWS::EC2::LaunchTemplate from #1973. Re-resolve from main's file and apply only this branch's EventBus additions on top: the ownership-tracking provisioner, its validation helpers, and the typed rethrow in deleteEventBridgeRuleSafe. main's provisionEventBusPolicy and inline Policy support are kept, with Policy added to EVENT_BUS_SUPPORTED_PROPERTIES so the inline form is no longer rejected. * fix(cloudformation): delete EventBus resources created before ownership tracking deleteEventBusSafe(StackResource) refused to delete whenever the FlociEventBusCreatedTime attribute was absent, treating "ownership not tracked" the same as "ownership changed". Stacks provisioned by an earlier Floci build are restored from cloudformation-stacks.json without that attribute, so the first DeleteStack after upgrading left them permanently in DELETE_FAILED. Only refuse when a recorded created-time actually disagrees with the live bus. A missing attribute falls back to the pre-tracking behaviour of deleting what the stack recorded it created. * fix(cloudformation): adopt untracked EventBus on update and record identity before the policy call Two provision-side defects, both surfaced in review: UpdateStack broke for stacks provisioned before FlociEventBusCreatedTime existed. Those resources are restored without the attribute, so the adoption guard's 'existingCreatedTime == null' arm re-threw ResourceAlreadyExists on every update, including no-ops. Same inverted guard the delete path already uses: only a recorded time that actually disagrees means the bus was recreated out of band. The bus also leaked when Policy application failed. r.setPhysicalId ran after putPermission, and rollbackCreatedResources skips resources whose physicalId is null, so a malformed policy left a live bus rollback could not find. Identity and ROLLBACK_OWNED_ATTR are now recorded before the policy call, matching how provisionIamRole marks a freshly created role. The attribute is cleared on the adoption path so rollback never deletes a bus this stack did not create. * chore: re-run CI Build and Test failed on RuntimeApiServerTest's extension/stop race, a pre-existing flake unrelated to this change (no CloudFormation test failed). Root-caused separately: test-timing half in #2141, server-side shutdown-ordering half filed as an issue. * fix(cloudformation): adopt tagged pre-tracking event buses * test(dynamodb): retain Quarkus port for cleanup * chore: rerun CI after download outage * fix(cloudformation): reject unsafe EventBus policy updates --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com> |
||
|
|
33ba5ac59c |
feat(apigateway): route execute-api hostnames for HTTP APIs (#2054)
* feat(apigateway): route execute-api hostnames for HTTP APIs
* fix(apigateway): disambiguate execute-api routing
* fix(apigateway): make the execute-api host filter idempotent
Host matching alone cannot tell whether a request has already been rewritten,
because the Host header still names the execute-api subdomain afterwards. If any
other filter rewrites first, this one rewrites again and produces
/execute-api/{apiId}/execute-api/{apiId}/... which routes to nothing.
Bail out when the path is already under /execute-api/. This keeps the filter
correct regardless of where it sits in the provider chain.
* fix(apigateway): enforce disableExecuteApiEndpoint on the direct execute-api path
The setting was only checked in ApiGatewayExecuteApiHostFilter, which sees the
host-based route (*.execute-api.localhost.*). A request to the direct
/execute-api/{apiId}/{stageName}/... form reaches dispatchV2 without passing the
filter, so the same disabled HTTP API answered 403 by host and 200 by path.
Move the check into dispatchV2, the single choke point both entry points funnel
through, so they cannot disagree. A missing API is left to findMatchingRoute's 404
rather than reported from here.
* test(dynamodb): retain Quarkus port for cleanup
* fix(apigateway): match disabled HTTP API response
---------
Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
|
||
|
|
e1f389f61b |
feat(lambda): support EFS file system configs (#2053)
* feat(lambda): support EFS file system configs * fix(lambda): prevent stale and shared EFS mounts * fix(lambda): isolate warm pools by version * test(dynamodb): retain Quarkus port for cleanup * fix(lambda): scope warm pool invalidation by environment --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com> |
||
|
|
ea74b979ae |
fix(lambda): scope resource-policy statements to the request Qualifier (#2129)
* fix(lambda): scope resource-policy statements to the request Qualifier
AddPermission, GetPolicy and RemovePermission ignored the Qualifier query
parameter. Every statement was stored against the unqualified function ARN, so
an alias-scoped permission could never be read back under its alias: GetPolicy
returned identical payloads with and without ?Qualifier, and the statement's
Resource had no qualifier suffix.
This is what stops Terraform's aws_lambda_permission with qualifier set from
converging — it creates the permission, polls GetPolicy?Qualifier=<alias>
forever, and a later apply then hits ResourceConflictException against a
statement its read could never confirm.
AWS keeps a separate resource policy per qualifier, so the qualifier is part of
a statement's identity. Declare @QueryParam("Qualifier") on the three policy
endpoints and thread it through the service, reusing the existing
resolveWithRegion() helper so a qualifier embedded in the function name
(arn:...:function:fn:ALIAS) is reconciled with the query-string value exactly as
the function-URL endpoints already do.
The scope is derived from the statement's own Resource rather than a new stored
field, so statements persisted before this change stay readable as the
function's unqualified policy. Consequently:
- AddPermission?Qualifier=X writes Resource <functionArn>:X
- GetPolicy?Qualifier=X returns only that qualifier's statements (404 if none)
- RemovePermission?Qualifier=X removes only within that qualifier
- the same StatementId may exist on the function and on each alias, and a
duplicate within one qualifier still conflicts
Qualifier existence is deliberately not validated — that is a separate behaviour
change, and the endpoints did not validate it before either.
Adds LambdaPermissionQualifierIntegrationTest (12 cases); 7 of them fail against
the unfixed code with the exact symptom from the report (Resource missing the
alias suffix). The existing LambdaPermissionTagLayerIntegrationTest (19) and
LambdaVersionIntegrationTest (6) stay green, covering the unqualified path.
* fix(lambda): clarify missing scoped policy error
|
||
|
|
2f5bc39680 |
fix(s3vectors): return cosine distance from queries (#2175)
* fix(s3vectors): return cosine distance from queries Convert cosine similarity to the AWS-compatible distance value and sort query results nearest-first. * fix(s3vectors): honor query distance response flag * test(s3vectors): request query distances explicitly |
||
|
|
34c9c6c0f5 | fix(cloudformation): honor stack status filters (#2244) | ||
|
|
f1c81977ec |
fix(cloudwatch): warn on unsupported Logs Insights filter operators (#2170)
parseFilter scans for the leftmost '!=', '==' or '=' outside a quoted
value, so the '=' inside '>=', '<=' and '=~' won. For '>=' and '<=' the
comparison character was absorbed into the field name ("@message >"),
which resolves to null for every row, and passesFilters treats null as
non-matching; for '=~' the value became the literal "~ /ERROR/". Either
way the query came back with no rows and no warning, because as far as
parseFilter was concerned it had found a valid operator.
Stop the scan when a position starts one of those three operators, so
control reaches the "Ignoring unsupported Logs Insights filter" warning
that '<', '>', 'like', 'not like' and 'in' already hit, and the stage is
dropped instead. Quote tracking is untouched, so a '>=' inside a quoted
value is still just part of the value.
The docs table describing how unsupported syntax degrades had the same
two cases inverted: '=~' listed as warn-and-drop when it mis-parsed, and
bare '<' / '>' as silent-zero-rows when they already warned. Folded into
the one row that now matches the code, and the compound and/or mis-parse
this change does not fix got its own row instead of staying implied.
Refs #2042
|
||
|
|
819bfedc6c |
feat(appsync): Phase 6 — Query Execution + HTTP Endpoint (#1884)
* feat(appsync): Phase 6 GraphQL HTTP execute endpoint
Expose POST /v1/apis/{apiId}/graphql with AppSync-compatible error
mapping, dual Content-Type, schema rehydrate on boot, and smoke
execution without Phase 8 DataFetchers.
* fix(appsync): initialize graphql IdGenerator at native runtime
Query execution pulls graphql.util.IdGenerator into the native image
reachability graph; its static Random must not be frozen in the heap.
* fix(appsync): cache GraphQL engines and always set x-amzn-errortype
Cache graphql-java GraphQL wrappers per apiId in SchemaRegistry (invalidate
on register/remove/rehydrate), and emit x-amzn-errortype on all data-plane
non-2xx responses for AWS parity with AppSync transport errors.
* fix(appsync): hide unexpected exception details on GraphQL 500
AppSync returns a fixed InternalFailure message for unexpected
errors; keep the real cause in server logs only.
* chore(appsync): drop redundant native-init comment
* fix(appsync): rehydrate schemas across all accounts on boot
Startup has no request context, so keys()/get() only saw the default
account. Mirror recoverOrphans with scanAllAccountsAsMap, persist SDL via
putForAccount in the worker, and drop the shared .atl/ gitignore entry.
* fix(appsync): keep non-404 AwsException on data-plane envelope
Avoid rethrowing AwsException from the GraphQL execute endpoint into
AwsExceptionMapper (__type). Map unexpected lookup failures to
InternalFailure with the AppSync errors[] shape instead.
* docs(appsync): point error formatter @see at $util.error docs
security-authz.html covers authorization types, not errorType/errorInfo.
Cite built-in-util-js.html where $util.error documents those fields.
* refactor(storage): type StorageFactory.create as AccountAwareStorageBackend
The factory always wraps every mode in AccountAwareStorageBackend; declaring
that return type removes unsafe casts at AppSync/CodePipeline/CloudFormation
call sites and updates test overrides/mocks to match production.
* fix(test): stub StorageFactory.create with AccountAware backends
thenAnswer stubs that returned bare InMemoryStorage ClassCast after
create() was typed as AccountAwareStorageBackend; align the remaining
service unit tests with the production return type.
|
||
|
|
a803626c17 |
fix(dynamodb): isolate item storage and locks between accounts (#2240)
* fix(dynamodb): isolate item storage and locks between accounts DynamoDbService kept item data (itemsByTable), per-item locks (itemLocks), and TransactWriteItems idempotency tokens in raw maps keyed only by "region::tableName" / "region::token", with no account component — unlike tableStore/itemStore, which get automatic account prefixing from AccountAwareStorageBackend. Two AWS accounts creating a same-named table in the same region therefore shared one underlying item map: PutItem in one account's table was visible via GetItem/Scan in another account's identically-named table. Scope every itemsByTable/itemLocks access by the resolved account ID. Also fixes two related gaps surfaced by the same code path: loadPersistedItems() only reloaded the default account's items after a restart (AccountAwareStorageBackend.keys() is request-scoped, and startup has no request), and the TTL sweeper's use of scanAllAccountsAsMap() collapsed same-named tables from different accounts into one map entry, silently skipping one account's expired items. Both are fixed via a new AccountAwareStorageBackend .scanAllAccountsRaw(), which preserves the account segment instead of stripping it. Added DynamoDbAccountIsolationIntegrationTest, reproducing the leak end-to-end (fails without this fix). * fix(dynamodb): scope item keys in non-account-aware fallback branches too loadPersistedItems() and deleteExpiredItems() call scopedItemsKey() for every access except their fallback branch (used when tableStore/ itemStore isn't an AccountAwareStorageBackend, e.g. some test-only constructors) — that branch stored/looked up itemsByTable entries under the bare, unscoped key, inconsistent with every other accessor in the class. Not reachable in production (StorageFactory always wraps backends in AccountAwareStorageBackend), but would silently orphan reloaded items / disable TTL sweeping for any future test using the plain-backend constructors. Caught in review. * fix(dynamodb): recover pre-multi-account data in scanAllAccountsRaw scanAllAccountsRaw() silently dropped any key with no account segment — data persisted before multi-account support existed. Unlike a per-key AccountAwareStorageBackend.get() call, which falls back to the bare unprefixed key and migrates it on read, a bulk startup reload via scanAllAccountsRaw() has no per-key caller to trigger that path, so loadPersistedItems() would silently lose such items on upgrade instead of surfacing them under the default account. Attribute slash-less keys to defaultAccountId instead of skipping them, consistent with how get() already treats them. Found by review. * fix(dynamodb): migrate legacy keys in scanAllAccountsRaw instead of leaving them stale scanAllAccountsRaw() attributed a bare legacy key to defaultAccountId but never migrated it in the underlying storage the way get()'s per-key migrate-on-read does. Concretely: after a restart, a legacy item loads and gets attributed to defaultAccountId in memory; a subsequent write to that table then persists under the properly prefixed key, but the original bare key is left untouched in storage. On a second restart, both the stale bare key and the fresh prefixed key map to the same effective key, and whichever the scan's iteration happens to visit last silently wins — reviving stale data with no deterministic outcome. Already-prefixed keys are now loaded first, so a legacy key can never win a collision against one that's since been written under its proper prefix; a superseded bare key is deleted outright instead of lingering to collide again later, and a genuinely-still-legacy key is migrated (written under its prefix, bare key deleted) rather than left in place. Found by review (Greptile + @pgermosen). * style(dynamodb): tighten comments to be concise and scoped to their code No behavior change. Trimmed comments introduced across this fix down to the non-obvious 'why' at the point they're placed. |
||
|
|
19a32ab51d |
feat(rds-data): adding data-api preparedstatement() support (#1887)
* feat(rds-data): adding data-api preparedstatement() support * feat(rds-data): addressing greptile comments * feat(rds-data): addressing PR review comments, fixing timestamp |
||
|
|
517094adc1 |
fix(eventbridge): boolean/numeric pattern values are matched correctly (#1889)
* fix(eventbridge): boolean/numeric pattern values are matched correctly * fix(eventbridge): fix scientific notation claim. Update styling. * fix(eventbridge): make null checks tighter. * fix(eventbridge): add check for if anything-but is a value, not object or array |
||
|
|
c21337c3b1 |
feat(iam): add GetAccountSummary support (#1986)
Adds all 34 documented SummaryMap fields: live entity counts (Users, Groups, Roles, customer-managed Policies, InstanceProfiles, PolicyVersionsInUse) plus IAM quota values, cross-checked against AWS's published service quotas and independently verified against moto's AccountSummary implementation. Resources Floci does not track (MFA devices, SAML/OIDC providers, server certificates, account password) report 0 rather than being omitted, so callers indexing into the full AWS field set don't hit a missing-key error. Part of #1938. |
||
|
|
59cb643d6e |
feat(stepfunctions): emulate distributed Map ResultWriter (S3 export + manifest) (#1823)
* feat(stepfunctions): export distributed map results to S3 * chore: re-run CI The Build and Test failure on the previous head was RuntimeApiServerTest's extension/stop race, a pre-existing flake unrelated to this change — it also failed on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it). Reproduced locally under `--cpus=1` and fixed separately. --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com> |
||
|
|
cd3588b517 |
feat(ses): honor ConfigurationSetName on CreateEmailIdentity (v2) (#1812)
* feat(ses): honor ConfigurationSetName on CreateEmailIdentity (v2) CreateEmailIdentity now reads the optional ConfigurationSetName and sets it as the identity's default configuration set, surfaced by GetEmailIdentity. Verified against AWS: a non-existent configuration set fails with NotFoundException before the identity is created (atomic), matching the deleted-default send behavior. * fix(ses): treat only an empty ConfigurationSetName as absent on CreateEmailIdentity A whitespace-only ConfigurationSetName was silently ignored (isBlank), diverging from the PutEmailIdentityConfigurationSetAttributes path, which routes such a name through name validation. Switch to isEmpty so both paths reject a whitespace-only name as invalid input (400), and add coverage for the empty (no default) and whitespace (400) cases. * test(ses): clarify that empty-string ConfigurationSetName handling deviates from AWS The comment on the empty-string CreateEmailIdentity test mentioned that AWS stores "" verbatim without stating that Floci deliberately diverges (treating "" as "no default"), which could read as if the assertion matched AWS. Reword to make the deviation and its rationale explicit. * docs(ses): correct the non-string ConfigurationSetName comment to match the actual response The comment claimed AWS returns a 400 with an empty body, but the code throws a SerializationException that AwsExceptionMapper renders as a JSON error body. Reword the comment to describe the actual response shape. * fix(ses): reject a non-string EmailIdentity on CreateEmailIdentity CreateEmailIdentity read EmailIdentity via asText, which coerces a non-string JSON value (e.g. 123 -> "123") and would silently create an identity named "123". Reject a non-string EmailIdentity with a 400 SerializationException, matching the ConfigurationSetName handling in the same method. * fix(ses): validate Tags before creating the identity on CreateEmailIdentity parseTagsArray ran after verifyEmailIdentity/verifyDomainIdentity, so a non-array Tags value (e.g. "Tags":"oops") returned 400 but left the identity created — a half-created state. parseTagsArray is pure, so hoist it above the create; the identity is now persisted only after both the ConfigurationSetName and the Tags shape have been validated, matching AWS. |
||
|
|
b6765b3056 |
feat(apigateway): API key management — UpdateApiKey, DeleteApiKey, UsagePlan custom-id, generateDistinctId (#1883)
* feat(apigateway): implement UpdateApiKey and DeleteApiKey
Adds the two missing API key lifecycle operations for API Gateway v1:
- UpdateApiKey (PATCH /apikeys/{apiKeyId}): applies replace patch
operations for /name, /description and /enabled, 404 when absent
- DeleteApiKey (DELETE /apikeys/{apiKeyId}): 202 on success, 404 when
absent
Also adds a description field to the ApiKey model so it can be set on
create, returned in responses and patched via UpdateApiKey.
Integration tests cover each patch path, the 404 cases and a repeated
delete. Service docs updated to move both operations out of the Not
Implemented list.
* feat(apigateway): persist and return UsagePlan tags
CreateUsagePlan accepted a tags map but discarded it, so tags never
appeared in CreateUsagePlan, GetUsagePlan or GetUsagePlans responses.
Tags are now stored on the UsagePlan model and emitted by the
controller.
A _custom_id_ tag sets a deterministic plan ID, mirroring the existing
createRestApi behaviour. Tag values are coerced through String.valueOf
rather than an unchecked cast so a non-string value in the request body
cannot produce a ClassCastException on later reads.
The tags field defaults to an empty map, so usage plans already
persisted without it deserialize unchanged.
* fix(apigateway): treat an absent generateDistinctId as id == value
CreateApiKey generated a distinct short-token id whenever
generateDistinctId was absent, so the emulator's default disagreed with
AWS. Only an explicit generateDistinctId: true produces an id that
differs from the key value; absent and false both yield id == value.
A blank supplied value now falls back to a generated UUID on the
distinct-id path too, matching the guard the shared-value path already
had.
Integration tests cover all three states — absent, explicit false and
explicit true — and the service docs gain a table for the behaviour.
* refactor(apigateway): route UsagePlan custom IDs through ReservedTags
The usage plan override read the raw _custom_id_ key directly, which
diverged from createRestApi after #2045 made floci:override-id the
reserved key. It now calls ReservedTags.extractOverrideApiId, so the
plan gets the same validation (non-blank, no whitespace, no control
characters, no /?#) and the same precedence when both keys are present.
Persisted tags go through stripApiGatewayReservedTags, so neither
override key survives into CreateUsagePlan, GetUsagePlan or
GetUsagePlans responses.
Tests assert the reserved keys are absent from the returned tags and
cover the deprecated key, the precedence rule and both rejection paths.
* fix(apigateway): stop deleted and disabled API keys authenticating
A UsagePlanKey stores its own copy of the API key value, and the data
plane resolves requestContext.identity.apiKey by matching the x-api-key
header against those copies. Neither revocation path reached them:
- DeleteApiKey removed the key from apiKeyStore but left every usage
plan association behind, so a deleted key stayed listed by
GetUsagePlanKeys and kept being recognised on the data plane. It now
detaches the key from every plan in the region first, matching AWS.
- resolveApiKeyForRequest never read enabled, despite its javadoc
saying it matched enabled keys, so patching /enabled to false changed
nothing about request handling. It now requires the key to still exist
and be enabled, via a new non-throwing findApiKey lookup.
Floci has no apiKeyRequired gate, so a revoked key yields a null
identity.apiKey rather than a 403; the docs now say so explicitly. The
new integration test pins both paths and fails on all three assertions
without these changes.
|
||
|
|
f17dd1ed81 |
feat(iam): support OIDC identity providers (#2106)
* feat(iam): support OIDC identity providers Implement CreateOpenIDConnectProvider, GetOpenIDConnectProvider, DeleteOpenIDConnectProvider, AddClientIDToOpenIDConnectProvider, RemoveClientIDFromOpenIDConnectProvider, UpdateOpenIDConnectProviderThumbprint and the provider tag actions, and back ListOpenIDConnectProviders with real data instead of a fixed empty list. A provider is identified by its URL, so the ARN is derived from it and the scheme is stripped: GetOpenIDConnectProvider reports the URL without https://, matching AWS. Creating the same URL twice returns EntityAlreadyExists. Thumbprints are stored and echoed back but never validated against the remote endpoint, since nothing here performs the TLS handshake they describe. Closes #2102 * test(iam): cover OIDC provider persistence and cap the provider URL Add IamServicePersistenceTest: IAM state is persisted through StorageFactory, so a restart must preserve providers along with their client IDs, thumbprints, tags and creation time. The model carries an Instant and two lists, so a broken serialization round trip would surface here first. Also enforce the documented 255-character limit on the provider URL, which was otherwise unchecked and would have produced an oversized ARN. * fix(iam): match verified AWS behaviour for OIDC providers Checked the emulated surface against a live AWS account and corrected where it diverged: AddClientIDToOpenIDConnectProvider and RemoveClientIDFromOpenIDConnectProvider are idempotent on AWS. Adding a client ID that is already present, and removing one that was never added, both succeed and change nothing; they previously raised EntityAlreadyExists and NoSuchEntity. Exceeding the thumbprint limit reports InvalidInput, not LimitExceeded. The client ID quota and duplicate-provider messages now use the AWS wording, and DeleteOpenIDConnectProvider reports its own not-found phrasing. Confirmed unchanged: the ARN is derived from the scheme-less URL, Get echoes the URL without its scheme, the URL is capped at 255 characters, the client ID quota is 100 with LimitExceeded, and URLs are not normalized, so a trailing slash or a case difference yields a separate provider. * fix(iam): reject missing required parameters on OIDC mutators A null ClientID read as "not in the client ID list", so RemoveClientIDFromOpenIDConnectProvider reported a no-op success for a request that never named one. DeleteOpenIDConnectProvider had lost its ARN check when it stopped routing through getOpenIDConnectProvider to report the not-found wording AWS uses for that action, so a request with no ARN came back as NoSuchEntity rather than a required-parameter error. Route every OIDC mutator through shared ARN and client ID checks so a malformed request fails as ValidationError before any lookup. * fix(iam): unbreak the reflective test fixture for the new constructor arity IamServiceTestHelper resolves the package-private IamService constructor reflectively against a hardcoded parameter list, so the extra storage backend broke it at run time with nothing failing at compile time. Every test using the fixture errored, and one of them blocks on a socket read rather than failing, which exhausted the CI job before it could report. Extend both lookups and both newInstance calls to the new arity. * fix(iam): reject empty tag collections on OIDC providers TagOpenIDConnectProvider with no Tags and UntagOpenIDConnectProvider with no TagKeys performed a no-op mutation and returned 200. AWS rejects both, as InvalidInput rather than ValidationError, with distinct messages for the map and the key list; checked against a live account. Validate the ARN on the tag path too, so a missing one fails before the lookup like the other mutators. --------- Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com> Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl> |
||
|
|
a79e04e4ec |
fix(firehose): build S3 object keys with AWS prefix expressions and name suffix (#1858)
* fix(firehose): build S3 object keys with AWS prefix expressions and name suffix
Delivered objects now follow the AWS key format
<evaluated prefix><stream>-<version>-<yyyy-MM-dd-HH-mm-ss>-<uuid> observed on
real AWS: default prefix yyyy/MM/dd/HH/ when no Prefix is set, literal
concatenation of the time prefix for expression-free prefixes,
!{timestamp:<pattern>} and !{firehose:random-string} evaluation, no .json
extension, and CustomTimeZone support. The non-AWS {year}/{month}/{day}/{hour}
placeholders are gone.
See floci-io/floci#1857 for the behavior captured against a real AWS account.
* refactor(firehose): cache the default time-prefix DateTimeFormatter
---------
Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
|
||
|
|
ea1231b8b4 |
fix(rds): restore Terraform RDS and RabbitMQ compatibility (#1951)
* fix(rds): support dbi resource id filter * fix(mq): omit RabbitMQ users from broker response |
||
|
|
a5daab6fb7 |
fix(lambda): reconcile code volumes against real Docker state and clean up superseded ones (#2208)
* fix(lambda): reconcile code volumes against real Docker state and clean up superseded ones Fixes #2164 Three problems in ContainerLauncher's per-function-version code volume management, all stemming from the same root cause: the "populated" bookkeeping was purely in-memory, never checked against or reconciled with Docker's actual state. - Stale volumes were never cleaned up on redeploy, only ever reclaimed by a user manually running docker volume prune. Now tracks each function's current volume and queues the superseded one for cleanup. - The in-memory "already populated" flag was trusted without ever re-checking Docker, so a volume removed out of band (manual docker volume rm, or an out-of-band prune) would silently mount an empty /var/task into the next container. ensureCodeVolume now also checks lifecycleManager.volumeExists() before trusting the flag. - Both of the above are really the same problem: no reconciliation against real Docker state. Fixed together by the same change. Cleanup is deferred rather than immediate: Docker auto-creates an empty named volume for a container mount that doesn't reference an existing one rather than failing, so a launch that resolved the old volume name just before a redeploy, but hasn't created its container yet, could be handed an empty /var/task by an immediate delete. A 60-second grace period, swept by a scheduled background task, crosses that window safely; removeVolume() also no-ops if the volume is still genuinely in use by then. * fix(lambda): rescue rolled-back code volumes and retry failed cleanup Addresses two review findings on the volume reconciliation fix: - The fast-path early return in ensureCodeVolume skipped the bookkeeping update entirely, so rolling back to a previous code version (v1 -> v2 -> v1) resolved v1's already-populated volume without pulling it back out of the pending-cleanup queue or marking it current again. The next sweep would delete the volume the function was actively using again. The bookkeeping reconciliation now always runs, whether or not the volume needed repopulating. - cleanupSupersededVolumes discarded a pending-cleanup entry unconditionally before attempting deletion, so a volume that Docker refused to remove (still in use by a slow-draining container that outlived the grace period) was silently dropped with no later sweep ever retrying it, permanently orphaning it. Now re-checks volumeExists after the delete attempt and re-queues with a fresh timestamp if the volume is still there. * fix(lambda): close the cleanup-vs-rollback race on code volumes Addresses a review finding: ensureCodeVolume's bookkeeping reconciliation and cleanupSupersededVolumes' claim-and-delete both touched volumesPendingCleanup with no mutual exclusion between them. If cleanup atomically claimed a superseded volume's entry a moment before a concurrent rollback resolved that same volume, the rollback would mark it current and hand it to a new container while cleanup proceeded to delete the real Docker volume out from under that launch - the exact empty /var/task failure mode the grace period exists to prevent, reached through the rescue path instead. Both methods now synchronize on the same per-volume-name lock (codeVolumeLocks) for their full resolve-or-claim-and-reconcile section, not just the expensive populate step. Whichever side wins the race, the other reliably observes the result under the lock rather than acting on stale state. Added a deterministic concurrency test using latches to force cleanup to block mid-deletion while still holding the lock, and assert a concurrent rollback blocks too rather than racing past it. Confirmed it fails against the previous commit (rollback completes immediately, racing past cleanup) and passes with this fix. * fix(lambda): stop pruning code-volume locks, closing a lock-identity race Addresses a review finding on the mutual-exclusion fix: pruning a volume's entry from codeVolumeLocks while a waiter elsewhere still held a reference to the removed entry's lock object let a third caller's computeIfAbsent create a replacement lock object for the same volume name. The original waiter (once granted the old lock) and that third caller (holding the new one) could then run their supposedly mutually-exclusive sections concurrently, reintroducing the exact cleanup-vs-rescue race the previous commit closed. The map is now never pruned. Each entry is a single Object keyed by volume name, bounded by the number of distinct function+code-version combinations ever launched, and negligible next to the disk space the rest of this fix reclaims - not worth the correctness risk of trying to bound it. Added a direct test verifying the actual invariant this depends on: a volume's lock entry survives a full populate-then-cleanup-delete cycle unchanged. The real interleaving that triggers this race needs precise JVM thread-scheduling control that isn't reliably forceable in a test, so this proves the fix by construction instead - confirmed it fails (both by compile error, since the accessor is new, and by a genuine runtime assertion failure when the removal is surgically reintroduced) without the fix and passes with it. * fix(lambda): give removeVolume a definitive success signal for cleanup retry Addresses a review finding: cleanupSupersededVolumes decided whether a deletion actually succeeded by making a second, separate call to volumeExists() afterward. That call's own exception handling treats a transient Docker API failure (a network blip, the daemon momentarily busy) the same as "confirmed does not exist", so a transient failure during that specific verification call, following an in-use no-op from removeVolume, would make cleanup wrongly conclude the volume was gone and drop it from the retry queue for good - the same permanent-loss bug fixed two commits ago, reachable through a different trigger. ContainerLifecycleManager.removeVolume now returns whether the volume is confirmed gone (removed, or already absent) rather than void. cleanupSupersededVolumes uses that return value directly instead of a second ambiguous check, so the failure mode described above can no longer happen: any removal attempt that isn't positively confirmed successful, for any reason, correctly retries on the next sweep. The other three real callers (EksClusterManager, MwaaEnvironmentManager, ContainerStorageHelper) all treat the call as fire-and-forget and don't need any changes; a void-to-boolean change doesn't break callers that ignore the return value. Verified with the full lambda and core.common.docker packages (550 tests, only the same pre-existing unrelated failures) plus the eks/mwaa/rds packages that call the other real usages of this method (one pre-existing, unrelated failure in RdsContainerManagerTest, confirmed identical against an unmodified upstream/main baseline in a throwaway worktree). * fix(lambda): protect in-flight code volumes from premature cleanup A launch that resolves its code volume name (ensureCodeVolume returns and releases the volume's lock) but hasn't yet called lifecycleManager.create() has no real Docker container-to-volume reference for removeVolume()'s own in-use check to protect. The fixed grace period isn't a safe upper bound on that gap either: create() itself has no proven bound on its duration (this file's own history notes it observed taking ~80s under daemon load, longer than the default 60s grace period). If a redeploy supersedes that volume and the grace period elapses while the original launch is still stuck before create(), a sweep can delete the volume out from under it, handing the container an empty /var/task once create() finally runs (Docker auto-creates an empty volume for a mount referencing a name that no longer exists rather than failing). Adds true in-flight reference counting instead of relying on elapsed time: ensureCodeVolume increments a per-volume counter before returning (still under the volume's lock, so a concurrent sweep that acquires the same lock next is guaranteed to observe it), and the caller releases it in launch() once create() succeeds - or in the existing catch-all failure handler if it never gets that far. cleanupSupersededVolumes re-queues rather than deletes any volume whose count is still nonzero, regardless of how long it's been queued. Verified: new test forces a second launch of an already-populated volume to block right before create() while a redeploy supersedes it and the grace period is made to elapse instantly; cleanup must skip it while the count is nonzero and only remove it once the delayed launch completes and releases its reference. Confirmed the test fails (cleanup deletes the volume mid-flight) with the guard temporarily disabled, and passes with it restored. Full lambda.launcher and core.common.docker package regression (174 tests) is green. * fix(lambda): serialize the current-volume transition per function pgermosen's review on this PR pointed out that functionCurrentVolume and volumesPendingCleanup are reconciled under the per-volume lock only. Two code versions of the same function resolve to two different volume names, so they acquire two different codeVolumeLocks entries and can run that reconciliation concurrently - which is fine for the populate work each guards, but not for this transition. Without a shared lock, a rapid back-to-back redeploy (v2 then v3) can have the two functionCurrentVolume.put() calls land out of order: whichever one happens to execute last wins as "current" regardless of which redeploy was actually latest, and the volume it displaces gets queued for cleanup using a "previous" value each thread captured locally right before its own put() - so if v2's full transition runs after v3's, v3 (briefly and correctly current) ends up queued for deletion while stale v2 is left recorded as current. Adds a per-function lock (functionVolumeTransitionLocks, keyed by function name rather than volume name) around just this transition. It doesn't and can't guarantee which redeploy "wins" when two race genuinely concurrently - that would need ordering information this method isn't given - but it does guarantee the bookkeeping itself stays self-consistent: whichever volume ends up current is never also left in the pending-cleanup set, and whatever it displaced is queued exactly once. Verified: the transition's three statements are plain map operations with no interception point inside them, so forcing the exact bad interleaving isn't reliably doable in a test. Instead added a test proving the fix's actual mechanism - a concurrent launch for a second code version of the same function blocks on the same per-function lock object while another launch holds it - the same style already used for the per-volume lock in cleanupAndAConcurrentRollback_areMutuallyExclusiveForTheSameVolume. Confirmed the test fails when the lock is swapped for an unshared one and passes with the real lock restored. Full lambda.launcher and core.common.docker package regression (175 tests) is green. |
||
|
|
6344852540 |
fix(lambda): reassemble container log lines split across Docker frames (#1953)
* fix(lambda): reassemble Docker log frames into complete lines Buffer stdout and stderr independently, emit complete UTF-8 lines, and finalize trailing tails only after Docker has stopped or its reader reaches a terminal state. * fix(codebuild): retain buildspec overrides when retrying builds Keep request-scoped buildspec overrides alongside transient build state so RetryBuild executes the same source-less build definition as the original request. * fix(ecs): finalize logs after force-removing tasks Keep Docker force removal available after stop failures and release task log handles once removal has terminated their transports. * fix(ecs): retain logs for containers that survive teardown Track ECS log handles by Docker ID so teardown finalizes only containers that have stopped, disappeared, or been force-removed. * fix(ecs): retry unresolved log stream teardown |
||
|
|
40e8aad55a |
feat(lambdamicrovms): AWS Lambda MicroVMs service module and its CloudFormation types (#2079)
* feat(lambdamicrovms): AWS Lambda MicroVMs service module Adds the Lambda MicroVMs control plane, a service AWS took GA on 2026-06-22: MicroVM images with a version and build lifecycle, the managed base-image catalog, MicroVM CRUD, and VPC egress network connectors. Two service models rather than one. Lambda Microvms (apiVersion 2025-09-09) carries images and MicroVMs under /2025-09-09; Lambda Core (2026-04-30) carries network connectors under /2026-04-04. Both sign as lambda, so their requests arrive under the existing lambda claim in ResolvedServiceCatalog and route by path. Neither prefix collides with anything LambdaController serves, and both are enabled by the lambda service rather than adding a toggle. Tagging rides the classic /2017-03-31/tags/ routes, so LambdaTagController learns the MicroVM ARN forms. Resources are stored per account and region. Floci resolves a per-request account in AccountContextFilter and these ARNs carry it, so region-only storage would let two accounts sharing a region read and mutate each other's images, MicroVMs and connectors. Wire shapes come from the vendored service models and, where the models are silent or disagree with the service, from responses recorded against live AWS. Several members the models mark optional are enforced in practice — a connector needs ClientToken, OperatorRole, NetworkProtocol and AssociatedComputeResourceTypes despite all four being optional in Smithy — and several resources are returned in a different projection per operation: an image in four shapes, a connector in four, with only the list summaries carrying Type. Builds converge instantly rather than on a timer, the usual emulator trade. Where that would otherwise produce an inconsistent body it is handled explicitly: a create or update reports the transitional state and does not name the version it is minting as active, because a client reading otherwise would launch a MicroVM off a version that does not exist yet. Auth tokens, the per-VM endpoint, and the idle and suspend timers are deliberately out of scope here; they belong to a full-fidelity MicroVMs emulator rather than to CloudFormation provisioning. Verified against a suite of responses recorded from live AWS (https://github.com/INTENTIUS/m80): 26 checks over the image, MicroVM and connector lifecycles, 0 failures. * feat(cloudformation): provision AWS::Lambda::MicrovmImage and AWS::Lambda::NetworkConnector Registers a CfnResourceProvisioner for the two MicroVM CloudFormation types against the LambdaMicrovmsService added alongside, so a template declaring either provisions and deletes rather than being skipped. Uses the CloudFormationResourceRegistry interface rather than the switch in CloudFormationResourceProvisioner, following SqsCfnProvisioner. * test(lambdamicrovms): AWS CLI compatibility coverage for images, MicroVMs and connectors * fix(lambdamicrovms): wire service state through StorageFactory Images, MicroVMs and connectors were held in plain in-memory maps, so in persistent mode a restarted Floci lost them while the CloudFormation stacks that created them survived. Those stacks then referenced resources that no longer existed and DeleteStack failed on the 404. The three stores are now StorageBackedMap over StorageFactory backends, keyed region/id. MicroVMs are delivered as part of the lambda service, so they share its storage key and therefore its configured mode and flush interval rather than declaring their own. The account half of the key is dropped from the service and left to the backend, which prefixes and strips the same account the RegionResolver returns, so region and account isolation are unchanged. StorageBackedMap only marks the backend dirty on put and remove, so every path that mutated a stored object in place now writes it back: image update, version status, version delete, rebuild, MicroVM settle and terminate, connector settle and update, and both tag paths. * style(core): import the lambda microvms controllers in the service catalog * fix(lambdamicrovms): register the persisted types for reflection Moving images, microvms and connectors into StorageBackedMap made their model classes persisted types, and PersistedModelReflectionTest fails on any that lack @RegisterForReflection because native-image persistence cannot rebuild them on restart. |
||
|
|
0cfffbea00 |
fix(kms): reject mismatched keys in decryption requests (#1893)
* fix(kms): reject mismatched keys in decryption requests * fix(kms): reject mismatched keys in reencryption requests * fix(kms): verify if key is usable for cryptographic operations |
||
|
|
15d6ce8429 |
fix(s3): DeleteObjects honours empty key list (#2201)
Fixes : #2198 Co-authored-by: Krishnan Mahadevan <kmahadevan-bidgely@users.noreply.github.com> |
||
|
|
f417164d42 |
fix(rds): advertise reachable endpoints (#2074)
RDS endpoints currently expose the proxy's container port even when Docker publishes it on a random host port. That works when the host can route to the container network, but fails with VM-backed Docker runtimes. Resolve the current container's published port when an external endpoint host is configured while preserving the internal proxy port used by the listener. |
||
|
|
28e9f6ed63 |
fix(apigatewayv2): encode binary Lambda request bodies (#2203)
* test(apigatewayv2): cover binary Lambda request payload Change-Id: Iae344954b576b49826164e0f5e68964f86198cd4 * fix(apigatewayv2): encode binary Lambda request bodies Change-Id: I5e32fe304c932878afdbf5be0c3c773595364ff0 * test(apigatewayv2): cover request body encoding matrix Change-Id: Id16e0cc81f6806afa50d8db8c6ac1cb7897af6f6 * fix(apigatewayv2): accept UTF-8 text media parameters Change-Id: Ibf82062b9345ebd80d722b497a15e60d62dce86d * test(apigatewayv2): make binary payload cleanup best effort Change-Id: Ib62dc80c73eb1836007b4492ccfda965da03f6ac * revert(apigatewayv2): keep measured AWS media matrix Change-Id: Ibbf8d8bca8d9967bf84628773cc08a991ffea6a1 |
||
|
|
bd01c1a70b |
feat(ses): implement SendCustomVerificationEmail for v1 and v2 (#2191)
* feat(ses): implement SendCustomVerificationEmail for v1 and v2
Add the SendCustomVerificationEmail action on both the v1 Query API and the v2 REST
JSON API (POST /v2/email/outbound-custom-verification-emails). The service renders the
stored custom-verification-email template into the inspection mailbox and the SMTP
relay, returns a MessageId, and registers the recipient as a pending-verification
identity, matching AWS. A missing template is the v1-native
CustomVerificationEmailTemplateDoesNotExist (remapped to NotFoundException on v2), with
the v1 send message ("Template <name> does not exist") verified against AWS.
* test(ses): log custom-verification compat cleanup failures instead of swallowing them
The @AfterAll cleanup deleted templates and identities in best-effort try/catch
blocks that swallowed every exception, so a real deletion failure would leave
state behind with no diagnostic. Log the affected template/identity and the
exception message, per AGENTS.md's rule against silently discarding exceptions.
|
||
|
|
ac4b865a34 |
feat(ec2): support managed prefix lists (#2105)
* feat(ec2): support managed prefix lists Implement CreateManagedPrefixList, DescribeManagedPrefixLists, GetManagedPrefixListEntries, ModifyManagedPrefixList and DeleteManagedPrefixList. Entries are versioned: a list starts at version 1 and every modification that changes entries stores a new version, so GetManagedPrefixListEntries can serve an earlier TargetVersion. Renaming or raising MaxEntries does not create a version, CurrentVersion makes a modification conditional, and removals apply before additions so one call can replace an entry's description. The AWS-managed gateway-endpoint lists are now built once and served by both DescribeManagedPrefixLists and the existing DescribePrefixLists, so the two surfaces cannot report different CIDRs for the same list. They are read-only. Closes #2100 * fix(ec2): validate prefix list input and keep tag copies in sync Three defects in the managed prefix list surface: ModifyManagedPrefixList only checked the resulting entry count against MaxEntries, so a zero or negative MaxEntries on an empty list passed the check and persisted an impossible capacity. CreateTags and DeleteTags update the generic tag store and then mirror the result onto the resource, but updateResourceTags had no arm for prefix lists, leaving the copy on the model stale for describe responses and tag filters. MaxEntries and TargetVersion were converted with Integer/Long.valueOf, so malformed input escaped as an unchecked NumberFormatException and became a 500 rather than a structured EC2 client error. * fix(ec2): reject a missing PrefixListId and infer the prefix-list tag type A null PrefixListId reached List.of() inside describeManagedPrefixLists and threw NullPointerException, so DeleteManagedPrefixList, GetManagedPrefixListEntries and ModifyManagedPrefixList answered a request that never named a list with a 500 rather than a client error. Guard the lookup and raise MissingParameter. inferResourceType had no pl- arm, so tags on a prefix list were stored but reported as resourceType "unknown" and were invisible to a DescribeTags filter on resource-type. The existing test only covered describe and tag: filters, which is why this went unnoticed. Also cover the accepting branch of the address-family check, which until now was only reached by the rejecting case. * fix(ec2): treat a blank numeric parameter as malformed rather than absent intOrNull and longOrNull returned null for a present but blank value, which the callers read as "parameter not supplied". For CurrentVersion that silently downgraded a conditional ModifyManagedPrefixList to an unconditional one, so a request that asked to be gated on a version was applied anyway. Only an absent parameter is null now; a blank one reaches the parse and surfaces as InvalidParameterValue. * fix(ec2): report PrefixListVersionMismatch for a stale CurrentVersion A conditional ModifyManagedPrefixList that loses the version check returns PrefixListVersionMismatch on AWS, not IncorrectState; verified against a live account, which also supplies the message. The Terraform provider keys its retry handling on that code, so the previous one would have left a caller unable to recognise a losing conditional update. --------- Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com> |
||
|
|
3ce5041c71 |
fix(cognito): reject invalid refresh tokens in InitiateAuth REFRESH_TOKEN_AUTH (#2132)
* fix(cognito): reject invalid refresh tokens in InitiateAuth REFRESH_TOKEN_AUTH InitiateAuth with AuthFlow=REFRESH_TOKEN_AUTH silently fell back to minting fresh tokens for a fake "unknown" user whenever the supplied REFRESH_TOKEN failed to parse or didn't resolve to a real user, instead of failing like GetTokensFromRefreshToken already does. Fixes #2113 * test(cognito): add regression tests for invalid refresh token rejection Cover InitiateAuth REFRESH_TOKEN_AUTH with a garbage token and with a well-formed token encoding a nonexistent user; both must fail with NotAuthorizedException rather than returning an AuthenticationResult. * test(cognito): add regression test for non-numeric refresh token issued-at Covers a well-formed refresh token whose issued-at field is not a number; must fail with 400 NotAuthorizedException rather than the 500 NumberFormatException that surfaced before the parse was guarded. * fix(ec2): make network interface pagination tests order-independent describeNetworkInterfacesWithMaxResultsNoNextToken and describeNetworkInterfacesMultipagePagination assumed a fixed/low ENI count, but other tests in this class are not isolated and can leave ENIs behind depending on JUnit's tie-breaking order among tests sharing @Order(92). Use MaxResults=1000 for the single-page case and measure the actual ENI baseline before asserting page counts for the multipage case. |
||
|
|
50fe67dde6 |
feat(eventbridge): deliver events to event-bus targets (#1814)
* feat(eventbridge): deliver events to event-bus targets * fix(eventbridge): skip null resources when republishing to event-bus targets * fix(eventbridge): validate Detail and resolve account for bus targets readTree accepts any well-formed JSON value, so an input override producing "hello" or [1,2] passed the guard and reached the target bus as a scalar detail, with putEvents reporting success — a silent malformation rather than the intended warn-and-drop. The pass-through arm had the same hole. Both arms now share one isObject() check. Bus targets also went through the two-arg putEvents overload, which passes a null accountId, so a cross-account bus ARN resolved in the caller's account and surfaced only as a warning. Thread the ARN's account through, as SQS targets already do via the queue URL. Same-account and account-less ARNs still forward null: only that path carries the legacy-key fallback in AccountAwareStorageBackend.get(). * docs(eventbridge): document event-bus target behavior and limits * fix(eventbridge): cap bus-to-bus forwarding at one hop, matching AWS |
||
|
|
f34e0b5655 |
fix(apigateway): create the stage when CreateDeployment carries a stageName (#2130)
CreateDeployment ignored the stageName parameter: the deployment was created but no stage was, so GetStages stayed empty and invoking the deployed API returned {"message":"Stage not found"}. Calling CreateStage explicitly afterwards was the only way to make the API reachable.
CreateDeployment creates the named stage pointing at the new deployment. When the stage already exists, repoint it while preserving its other settings so repeated Terraform applies remain usable. The API does not document this collision behavior. Stage variables from the request are applied either way, and omitting stageName still creates no stage.
Adds ApiGatewayDeploymentStageNameIntegrationTest (7 cases) following the reproduction from the report: the stage appears in GetStages, the deployed route answers 200 instead of "Stage not found", a redeploy moves the same single stage to the new deployment id, and no-stageName is unchanged.
|
||
|
|
7e5afae61b |
feat(eks): support IRSA with a real OIDC issuer and JWT validation (#2108)
* feat(eks): support IRSA with a real OIDC issuer and JWT validation
Every EKS cluster now gets an OIDC identity provider, so the full IRSA flow
works end to end without mocked or hardcoded tokens.
CreateCluster generates an RSA-2048 keypair and an AWS-shaped issuer URL,
returned by DescribeCluster as identity.oidc.issuer. The issuer is a faithful
string for building trust policies but is never dereferenced: STS resolves the
signing key in-process via a new OidcIssuerKeyLookup port, declared in
core.common so services.iam does not depend on services.eks.
Key material lives in storage separate from the Cluster model. Cluster is
serialized straight onto the DescribeCluster wire response, so a private key
carried there would leak; @JsonIgnore would instead lose it across restarts and
break tokens minted earlier.
sts:AssumeRoleWithWebIdentity previously accepted any non-blank token and
returned a hardcoded subject. It now verifies, but only for issuers Floci hosts:
- RS256 signature against the cluster's public key
- iss matches the issuer exactly
- aud contains sts.amazonaws.com
- exp / nbf, with 60s of clock-skew tolerance
- the role's trust policy, via a new WebIdentityTrustPolicyEvaluator matching
Principal.Federated and the Condition block
The response now carries the token's real claims in
SubjectFromWebIdentityToken, Provider, and Audience. Bad tokens return
InvalidIdentityToken (400); a trust policy that does not permit the subject
returns AccessDenied (403) — a check the web-identity path was missing entirely.
Tokens from an issuer Floci does not host stay permissive, since Floci cannot
verify a third-party signature. Existing behaviour is therefore unchanged and no
configuration flag is required.
WebIdentityTrustPolicyEvaluator is a sibling of AssumeRolePolicyEvaluator rather
than an extension of it: that evaluator serves sts:AssumeRole, hardcodes that
action, reads only Principal.AWS, and ignores conditions. Condition values are
compared with exact, case-sensitive equality instead of the existing
globMatches, which lowercases both operands — case-folding an OIDC subject would
silently admit a different service account.
Because Floci has no kubelet to project a token into a pod, a local-dev harness
can mint one via POST _floci/eks/clusters/{name}/oidc-token and write it to the
file named by AWS_WEB_IDENTITY_TOKEN_FILE. Signing stays server-side so the
private key never leaves Floci. OIDC discovery and JWKS routes are served under
the same _floci namespace, for fidelity rather than because anything fetches
them; the AWS-shaped issuer path is not resolvable by Floci's embedded DNS and
would collide with S3's path-style catch-all.
Adds 51 tests: unit coverage for the verifier, the trust-policy evaluator, and
the OIDC service, plus an end-to-end integration test covering the mint ->
assume -> credentials path and its negative cases (wrong service account,
tampered signature, wrong audience, expired, alg:none).
* fix(iam): close two web-identity validation gaps and backfill cluster OIDC state
Three defects found in review of the IRSA change.
An unsigned "header.payload." token bypassed validation entirely. verify()
split with a -1 limit so a trailing empty segment was preserved, but
parseClaims() — which backs peekIssuer() — did not. Java drops trailing empty
strings by default, so such a token split into two parts, its issuer went unseen,
and STS classified it as an opaque third-party token: signature, claim, and
trust-policy checks were all skipped and credentials were issued for a JWT that
was never signed. Both split sites now pass -1.
StringLike and StringNotLike on an OIDC condition key folded case. They
delegated to IamPolicyEvaluator.globMatches, which lowercases both operands, so
a trust policy scoped to one service account or namespace would admit another
differing only in case — the exact hazard the StringEquals branch was written to
avoid. Adds a case-sensitive glob and uses it for both operators. Action matching
still uses globMatches, which is correctly case-insensitive.
Clusters persisted before this feature never gained an issuer or key, so after an
upgrade DescribeCluster reported no identity.oidc.issuer, minting returned 400,
and the JWKS routes 404'd until the cluster was recreated. EksService now
backfills on startup, and re-runs ensureKey for clusters that already have an
issuer so a restart cannot leave a known issuer without its signing key.
Each fix has a regression test confirmed to fail without it.
* fix(eks): keep IRSA OIDC state scoped to the cluster's owning account
The startup backfill read clusters across every account via scanAllAccounts() but
wrote them back with the request-scoped put(), which resolves to the default
account outside a request context. A cluster owned by any other account kept its
issuer-less record while a duplicate appeared under the default account, leaving
DescribeCluster and the IRSA endpoints broken for the owner. The backfill now
takes the account from the cluster record and writes with putForAccount, per the
pattern StorageFactory documents for work running outside a request.
The same root cause affected key lookup more seriously. findVerificationKey used
the account-scoped scan(), so an issuer owned by a non-default account went
unresolved — and an unresolved issuer is treated as a third-party provider, so
STS accepted the token with no signature, claim, or trust-policy check at all.
It now scans every account, which is correct regardless: an issuer URL is
globally unique, and the account calling AssumeRoleWithWebIdentity need not be
the one that owns the cluster.
deleteKey and findKeyByCluster stay account-scoped; both are only reached from
request-scoped paths (DeleteCluster and the JWKS route), where the caller's
account is the right scope.
Both fixes have a regression test confirmed to fail without them.
|
||
|
|
4a5fae4dcd |
fix(cloudformation): apply AssumeRolePolicyDocument when adopting an existing IAM role on update (#2143)
provisionIamRole's adoption path (triggered by EntityAlreadyExists when a same-stack UpdateStack retries against a role that already exists) fetched the existing role via getRole() but never applied the template's current AssumeRolePolicyDocument. A changed trust policy was silently dropped while the stack still reported UPDATE_COMPLETE. Routes the adoption path through the existing IamService.updateAssumeRolePolicy helper, mirroring how createRole() already applies the document on first create. If a later step in the same attempt fails (e.g. a bad ManagedPolicyArns entry), the whole resource update fails and CloudFormation reports UPDATE_ROLLBACK_COMPLETE - the trust policy must actually roll back too, not stay on the new value. Captures the role's prior trust policy before applying the update and restores it in the existing failure-cleanup path alongside policy detachment. Does not re-fetch the role after applying the trust policy: nothing downstream reads anything affected by that update (Arn, RoleId, AttachedPolicyArns are unchanged by it), and a failing re-fetch there would escape before the restoration catch block, leaving the new trust policy active despite a rolled-back update. Adds an ID-verified updateAssumeRolePolicy(name, doc, expectedRoleId) overload in IamService: a role deleted and recreated under the same name between the earlier identity check and this write would otherwise silently receive an update meant for the role this stack actually owns. Both the primary write and the failure-triggered restore use this overload - restoring a trust policy is just as consequential as applying one, so both directions get the same identity guarantee. Fixes #2084. |
||
|
|
a2b20cc085 |
fix(dynamodb): compare Value when legacy Expected supplies Exists (#2125)
* fix(dynamodb): compare Value when legacy Expected supplies Exists
A legacy Expected entry that supplies both Exists:true and a Value was
evaluated as an existence check only — the supplied Value was silently
discarded, so any stale value passed the condition.
This is the wire form emitted by version-guarded writes, where the caller
pairs Exists:true with the version it last read:
"Expected": {"version": {"Exists": true, "Value": {"N": "5"}}}
Because the guard was present on every request and ignored on every
request, conflicting writes were accepted with no visible symptom.
Per the documented ExpectedAttributeValue semantics, Exists:true always
carries a Value and means the attribute must exist AND equal it, which is
the same check as a bare Value. Only Exists:false is a pure absence check.
The three combinations DynamoDB documents as invalid now raise
ValidationException instead of being silently accepted:
- Exists:true with no Value
- Exists:false alongside a Value
- Exists combined with ComparisonOperator / AttributeValueList
Validation runs over the whole Expected map before any condition is
evaluated. PutItem, DeleteItem and UpdateItem all route through
evaluateLegacyExpected, so the change applies to all three.
* fix(dynamodb): compare collection values in legacy EQ conditions
The EQ comparison used by legacy Expected, QueryFilter and ScanFilter
reduced a non-scalar attribute value to an empty string, so any two
values of the same collection type compared as equal. A stale
expectation on an SS, NS, BS, L or M value was therefore always
satisfied and the guarded write was applied.
EQ now delegates to the existing attributeValuesEqual helper — the same
one the ConditionExpression path uses. It is type-strict, compares
numbers via BigDecimal, recurses into M and L, and treats set types as
unordered.
* fix(dynamodb): compare number set members numerically in equality
Number set equality put the members in a HashSet<BigDecimal>, so
membership went through BigDecimal.equals, which is scale-sensitive: 1
and 1.0 were treated as different members. Because NS elements are
normalized on write while a supplied condition value is not, an
otherwise valid condition on a numerically equivalent set was rejected
and the guarded write blocked.
Membership now goes through a TreeSet, whose contains uses compareTo, so
members compare numerically. Applies to both the legacy Expected /
QueryFilter / ScanFilter EQ path and ConditionExpression, which share
this helper.
* fix(dynamodb): compare collection values in legacy NE conditions
NE had the inverse of the collapse the previous commit fixed for EQ: it
compared the scalar projections of both values, which are empty strings
for non-scalar types, so any two collections of the same type looked
equal and NE was always false. A condition asserting an attribute
differs from a set it genuinely differs from blocked the write.
NE now negates attributeValuesEqual, mirroring EQ. Null handling is
unchanged: a missing attribute or a missing comparison value still
satisfies NE.
* test(dynamodb): pin type-strict equality in legacy conditions
EQ and NE compare attribute types as well as values, so a string "5"
does not match a stored number 5. Nothing pinned that, which left room
for a refactor to reintroduce equality via scalar string projections
without any test failing.
* fix(dynamodb): match DynamoDB validation for legacy Expected entries
Verified the legacy Expected rules against DynamoDB itself and aligned
the validation with what the service actually returns.
Error messages now carry the "1 validation error detected: " prefix and
the exact wording, including "Exists and ComparisonOperator cannot be
used together", which differed from the message used before.
Two rules were missing:
- AttributeValueList without a ComparisonOperator is rejected, and
that check takes precedence over the Exists rules. It applies
whether or not Exists is present.
- An entry with neither Exists nor Value is rejected as well,
reported as "Value must be provided when Exists is null".
DynamoDB reports only the first offending entry even when several are
invalid, so validation still stops at the first error.
|
||
|
|
91b6a40bc7 |
fix(elasticache): clean up container by id on readiness-timeout rollback (#2090)
* fix(elasticache): clean up container by id on readiness-timeout rollback start() registers the container in activeContainers before its waitForBackendReady() probe, and that probe throws on timeout. When it does, start() propagates without ever returning a handle, so the service's rollback saw handle == null, skipped the container stop, and left it running (only reaped at shutdown). A readiness timeout is the most likely provisioning failure, not an edge case. Add an idempotent stopByGroupId(groupId) that looks the container up in activeContainers, falling back to the deterministic container name for one that failed before registration. Call it unconditionally from rollbackReplicationGroup instead of gating containerManager.stop(handle) on handle != null. Mirrors the same fix already merged for Neptune in #1742. * fix(elasticache): stop by handle when known, only fall back to stopByGroupId Greptile flagged (PR #2090 review): rollbackReplicationGroup called containerManager.stopByGroupId(groupId) unconditionally, even when the handle from this request's own start() was already known. If a concurrent CreateReplicationGroup for the same group id raced ahead and overwrote the activeContainers entry before this rollback ran, stopByGroupId's fresh lookup would fetch and stop the other request's container instead of this one's. Restore the precise containerManager.stop(handle) path whenever handle is non-null (the common case — every failure after the container itself started successfully) and only use stopByGroupId as the by-id fallback for the one case that actually needs it: a readiness timeout, where start() never returns a handle at all. * fix(elasticache): guard against concurrent creates for the same group id Reviewer follow-up on PR #2090: the handle-less rollback path (a readiness timeout, where start() never returns a handle) still cleans up by looking up whatever containerManager currently has registered for the group id. If a second CreateReplicationGroup for that same id raced in and started its own container before the first request's rollback ran, that lookup would fetch and stop the second request's container instead of the first's — the existing "already exists" check only guards against a *persisted* group, not one still being provisioned, so nothing previously prevented two concurrent creates for the same not-yet-existing id from both proceeding. Add a provisioningGroupIds guard: claim the id before provisioning starts and hold it until createReplicationGroup returns or throws (rollback included), rejecting a concurrent second create for the same id with the same ReplicationGroupAlreadyExistsFault used for an already-persisted group. This closes the race at its root rather than narrowing it — a second request for the same id can never reach containerManager.start() while the first is still in flight, so the by-id rollback fallback can never observe a container it doesn't own. Added a concurrency test using real threads + latches to prove a second create for an in-flight id is rejected immediately rather than racing ahead. * refactor(elasticache): trim comments to one-liners |
||
|
|
11d527547a |
fix(memorydb): clean up container by id on readiness-timeout rollback (#2092)
* fix(memorydb): clean up container by id on readiness-timeout rollback start() registers the container in activeContainers before its waitForBackendReady() probe, and that probe throws on timeout. When it does, start() propagates without ever returning a handle, so the service's rollback saw handle == null, skipped the container stop, and left it running (only reaped at shutdown). A readiness timeout is the most likely provisioning failure, not an edge case. Add an idempotent stopByClusterName(name) that looks the container up in activeContainers, falling back to the deterministic container name for one that failed before registration. rollbackBackend now calls it unconditionally instead of gating containerManager.stop(handle) on handle != null. Fixing this also required splitting the proxy-stop and container-stop steps into isolated try/catch blocks (previously shared one try, so a throwing stopProxy skipped the container cleanup entirely) and guarding the proxy stop with the same handle != null precondition the container stop already had. Without that isolation, the by-name cleanup could still be skipped in the exact scenario it exists to handle. Mirrors the same fix already merged for Neptune in #1742. * fix(memorydb): stop by handle when known, only fall back to stopByClusterName Same issue flagged by greptile on the sibling ElastiCache PR (#2090): rollbackBackend called containerManager.stopByClusterName(name) unconditionally, even when the handle from this request's own start() was already known. If a concurrent createCluster for the same name raced ahead and overwrote the activeContainers entry before this rollback ran, stopByClusterName's fresh lookup would fetch and stop the other request's container instead of this one's. Restore the precise containerManager.stop(handle) path whenever handle is non-null (the common case — every failure after the container itself started successfully) and only use stopByClusterName as the by-name fallback for the one case that actually needs it: a readiness timeout, where start() never returns a handle at all. * fix(memorydb): guard against concurrent creates for the same cluster name Same fix as PR #2090 for ElastiCache: the handle-less rollback path looks up whatever containerManager currently has registered for the name, which a concurrent createCluster for the same name could overwrite first. Claim the name for the whole provisioning attempt so a second concurrent create is rejected immediately instead. |
||
|
|
2594705f9c | feat(elbv2): honor preserve_host_header parameter (#2109) | ||
|
|
c8403ac6fc |
feat(iam): add service-linked role create, delete and deletion status (#2179)
* feat(iam): add service-linked role create, delete and deletion status aws_iam_service_linked_role calls CreateServiceLinkedRole directly, and one unsupported operation fails a whole account-bootstrap module. Delete and GetServiceLinkedRoleDeletionStatus come with it, because create alone leaves terraform destroy broken. The role lands under /aws-service-role/<principal>/ with a trust policy for that principal, and is readable by GetRole afterwards, which is what the issue asks for. The role NAME is a deterministic stand-in, not AWS's. The prefix is chosen by the linked service and is not computable from the principal — AWS turns lex.amazonaws.com into AWSServiceRoleForLexBots — so this derives a name from the principal's labels instead: es.amazonaws.com becomes AWSServiceRoleForEs. Every label contributes, because rds.amazonaws.com and rds.application-autoscaling.amazonaws.com are separate roles on AWS and a config declaring both must not collide on one name. A CustomSuffix is joined with an underscore, which is the separator callers parse back out; Terraform recovers custom_suffix by splitting the role name on it, and that attribute forces replacement, so any other join never converges. Deletion is synchronous, so the returned task id is already complete and its status is SUCCEEDED. Task ids use the documented task/aws-service-role/<principal>/<role>/<uuid> shape and are held in a StorageFactory-backed store, so they are account-scoped and survive a restart like every other IAM record. Closes #2122 * fix(iam): classify service-linked roles by origin, not by path CreateRole accepts the /aws-service-role/ prefix, so a role sitting at a well-formed service-linked path is not necessarily one. Path-based classification let DeleteServiceLinkedRole delete an ordinary role that merely lived there. Roles minted by CreateServiceLinkedRole now carry a marker, and the delete path keys on that instead. The field is additive, so a role persisted before this change reads as not service-linked, which is correct. * fix(iam): protect service-linked roles from ordinary role mutations DeleteServiceLinkedRole could answer 409 DeleteConflict, a code absent from that action's published error list (LimitExceeded, NoSuchEntity, ServiceFailure). It got there by routing through deleteRole, which refuses a role that still has policies attached — and nothing stopped a caller from attaching one to a service-linked role first. AWS never reaches that state. It publishes UnmodifiableEntity (400) on twelve role actions, and the message names the linked service to go through instead. So refuse the mutation rather than handle the conflict it would otherwise cause. This guards the eleven the emulator implements — AttachRolePolicy, DetachRolePolicy, PutRolePolicy, DeleteRolePolicy, Put/DeleteRolePermissionsBoundary, UpdateRole, UpdateAssumeRolePolicy, Add/RemoveRoleFromInstanceProfile and DeleteRole; UpdateRoleDescription is the twelfth and has no handler here. Several were silent: DeleteRole removed a service-linked role at 200, UpdateAssumeRolePolicy rewrote its trust policy, and AddRoleToInstanceProfile attached it to an instance profile. TagRole and UntagRole stay open, matching AWS. DeleteServiceLinkedRole now removes the role directly, since deleteRole refuses it. Also validate CreateServiceLinkedRole's own inputs. CustomSuffix must match [\w+=,.@-]{1,64}, as AWS constrains it — a suffix containing '/' previously produced a role name outside RoleName's own pattern, leaving an ARN whose name segment cannot be recovered. And a derived name over 64 characters is rejected, because AWS caps RoleName at 64 on every action that takes one and on the Role this action returns. Document the three deviations that remain: the role name is derived locally and will not match AWS for most services, deletion is synchronous so the deletion status is always SUCCEEDED, and CreateRole accepts the /aws-service-role/ path that AWS reserves. |
||
|
|
d78520d5cb |
feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2) (#1914)
* feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2)
Adds the kinesisanalyticsv2 service (X-Amz-Target KinesisAnalytics_20180523.*):
a control-plane state machine plus a real Apache Flink JobManager container spun up
as a sidecar on StartApplication, modeled on the AmazonMQ->RabbitMQ pattern.
- CreateApplication -> READY, StartApplication -> STARTING -> RUNNING via a readiness
poller, StopApplication -> READY, DeleteApplication -> removed
- Container image chosen from the requested RuntimeEnvironment (FLINK-1_15..1_20 ->
apache/flink:1.x) via KinesisAnalyticsRuntimes, with an optional operator override;
unsupported runtimes (SQL / Zeppelin) rejected with InvalidArgumentException
- Container naming via ContainerStorageHelper.resourceName (floci-kinesisanalytics-<name>)
- Registered in ResolvedServiceCatalog, dispatched by AwsJson11Controller; container
teardown wired into EmulatorLifecycle.onStop
- Tests: service + handler unit tests, @QuarkusTest integration, Java SDK compatibility test
- Docs: service page, services index, README, environment-variable reference
* fix(kinesisanalytics): enforce delete/update state and version/timestamp guards
Addresses review feedback (self-review + Greptile) on the Managed Flink service:
- DeleteApplication rejects a non-READY (RUNNING/STARTING) application with
ResourceInUseException; the caller must StopApplication first (Greptile P1)
- DeleteApplication validates the required CreateTimestamp against the stored value
- UpdateApplication validates CurrentApplicationVersionId (ConcurrentModificationException
on mismatch, InvalidArgumentException when absent)
- StopApplication error message reads 'RUNNING or STARTING' to match the guard
- Readiness poller @PreDestroy awaits termination (bounded) before returning so a
mid-flight write cannot race the shutdown storage flush
- Drop the unused Tags field from FlinkApplication (full tag support tracked as a follow-up)
- Compat test @AfterAll logs tolerated teardown failures (AGENTS.md) and stops before delete
Tests updated accordingly and verified live against the packaged jar.
* feat(kinesisanalytics): deploy and run the application JAR on the Flink cluster
Implements real job submission for Managed Service for Apache Flink, so the AWS
'deploy a JAR' flow actually runs the job (previously only a bare JobManager reached RUNNING):
- CreateApplication parses and stores ApplicationConfiguration (ApplicationCodeConfiguration
S3ContentLocation + ParallelismConfiguration); DescribeApplication echoes it back as
ApplicationConfigurationDescription
- StartApplication reads the JAR from Floci's local S3 (via S3Service), starts a JobManager plus a
TaskManager (sharing the JobManager network namespace for localhost RPC), then uploads and runs the
JAR via the Flink REST API (new FlinkRestClient); the app reaches RUNNING when the Flink job is RUNNING
- StopApplication cancels the job and tears down both containers
- Applications created without code still come up as a bare cluster
- Docs + README updated; unit tests for config round-trip; verified live end-to-end against the
packaged jar (S3 JAR -> RUNNING Flink job -> stop/delete cleanup)
Not yet emulated: EnvironmentProperties injection, snapshots/savepoints, in-place code updates.
* fix(kinesisanalytics): align Flink runtimes with AWS and add the 2.x line
The runtime map now mirrors the runtimes AWS Managed Service for Apache Flink actually offers:
- Add FLINK-2_0 / 2_1 / 2_2 / 2_3 -> apache/flink:2.0/2.1/2.2/2.3 (the Flink 2.x line; FLINK-2_2 is in
the AWS SDK RuntimeEnvironment enum and the whole 2.x line has published apache/flink images)
- Remove FLINK-1_16 / FLINK-1_17 -> AWS does not offer these runtimes, so Floci should reject them too
rather than accept versions real AWS refuses
Supported set: FLINK-1_15, 1_18, 1_19, 1_20, 2_0, 2_1, 2_2, 2_3. Tests + docs + README updated.
* test(kinesisanalytics): cover both Flink 1.18 and 2.3 in the SDK compat test
Refactor the single-runtime compat test into an abstract ordered lifecycle run against two
runtimes, so the suite guards both the Flink 1.x and 2.x lines (Flink 2.0 changed the config
system and boots slower):
- AbstractKinesisAnalyticsV2LifecycleTest: PER_CLASS instance state + the create->start->RUNNING->
list->stop->unsupported->delete lifecycle, parameterized on an abstract runtime()
- KinesisAnalyticsV2Flink118Test (FLINK-1_18) and KinesisAnalyticsV2Flink23Test (FLINK-2_3)
- FLINK-2_3 is passed as a string (newer than the pinned SDK 2.44.14 enum) and asserted via
runtimeEnvironmentAsString(); RUNNING wait bumped to 300s for Flink 2.x's slower boot
Verified live: both subclasses boot real apache/flink:1.18 and :2.3 clusters and reach RUNNING
(0 skipped). CI now exercises two clusters; both skip gracefully when Docker is unavailable.
* fix(kinesisanalytics): preserve AwsException from a bad application-code S3 location
StartApplication's catch(RuntimeException) wrapped every failure from startCluster into
InternalFailureException (HTTP 500) — including the AwsException that readJar throws when the
application-code S3 object is missing/empty/unreadable. A client's bad S3 code location therefore
surfaced as a 500 server error instead of the intended InvalidArgumentException (400).
Now AwsException propagates as-is (preserving its error code and message); only unexpected
RuntimeExceptions (e.g. Docker unavailable) become InternalFailureException. Addresses Greptile P1.
* feat(kinesisanalytics): add resource tagging (TagResource/UntagResource/ListTagsForResource)
Adds Tags support to CreateApplication plus TagResource, UntagResource, and
ListTagsForResource, dispatched as regular JSON1.1 actions under the same
KinesisAnalytics_20180523 target prefix as every other action — verified
against the real botocore kinesisanalyticsv2 model that this API has no
separate REST tagging endpoint (protocol is pure "json"/1.1 with all
operations on POST /), unlike REST-JSON services (EKS, MWAA) that use the
shared /tags/{arn} controller.
Tags is a list of {Key, Value} objects on the wire (not a map), same shape
MemoryDB's handler already uses for its own tagging actions; mirrored that
parse/build pattern rather than the map-shaped TagHandler interface. Tags
are stored on FlinkApplication but, matching the real API, never echoed in
ApplicationDetail (CreateApplication/DescribeApplication) — only
ListTagsForResource returns them. TagResource enforces AWS's 50
user-defined-tag ceiling (TooManyTagsException) on both CreateApplication
and TagResource.
docs/services/kinesisanalytics.md's action table is auto-generated from the
handler source (tools/docs/regen_action_docs.py) — regenerated it and filled
in the three new rows' hand-written descriptions.
* feat(kinesisanalytics): inject EnvironmentProperties into the Flink cluster
CreateApplication now accepts ApplicationConfiguration.EnvironmentProperties
.PropertyGroups and writes them to /etc/flink/application_properties.json in
both the JobManager and TaskManager containers before the job runs — the
same well-known path and JSON shape (a list of {PropertyGroupId, PropertyMap}
objects, matching the AWS API's own PropertyGroups shape) real Managed
Service for Apache Flink uses, so a JAR written against
KinesisAnalyticsRuntime.getApplicationProperties() picks them up unmodified
against Floci. DescribeApplication echoes them back under
ApplicationConfigurationDescription.EnvironmentPropertyDescriptions
.PropertyGroupDescriptions.
/etc/flink does not exist in the stock apache/flink image, and the
container's non-root "flink" user (uid 9999) can't create it directly under
/etc (confirmed live: mkdir -p /etc/flink fails with permission denied as
that user). The fix, also verified live: name the tar entry
"flink/application_properties.json" and extract into the existing /etc
rather than targeting /etc/flink directly — the daemon-level copy API can
create the missing subdirectory as part of unpacking the archive even
though the in-container user couldn't, landing as root:root 775 (so it's
still world-readable by the flink user). A real apache/flink:1.18 container
was used to verify both the failure mode and the fix before writing the
Java implementation.
* feat(kinesisanalytics): add application snapshot (savepoint) support
Adds CreateApplicationSnapshot/DescribeApplicationSnapshot/ListApplicationSnapshots/
DeleteApplicationSnapshot. Triggers a real Flink savepoint of the running job and
polls it to completion the same way StartApplication polls job readiness. Snapshot
files land on a persistent named Docker volume mounted at /opt/flink/savepoints in
the JobManager container, so they survive a Stop/Start cycle; the volume is only
removed on DeleteApplication.
* feat(kinesisanalytics): support in-place application code updates
UpdateApplication with a new ApplicationCodeConfigurationUpdate (or
ParallelismConfigurationUpdate) now redeploys onto an already-running application
without tearing down its JobManager/TaskManager containers: the current job is
cancelled and the new JAR is uploaded and run on the same cluster, transitioning
RUNNING -> STARTING -> RUNNING the same way StartApplication submits a fresh job.
Updating a READY application just stores the new code location for the next
StartApplication. Attaching code to a running bare cluster for the first time is
not yet supported and is rejected with InvalidRequestException.
* fix(kinesisanalytics): use AWS's documented generic InternalFailure code
startApplication and updateApplication's redeploy-code path threw an invented
"InternalFailureException" for unexpected Docker provisioning failures — not a
shape kinesisanalyticsv2's model declares (no operation in this API declares any
5xx shape at all). AWS documents "InternalFailure" (no "Exception" suffix, HTTP
500) as the generic error common to every service's API; it's also already the
default used elsewhere in this codebase (JsonErrorResponseUtils, KMS, Pricing,
SES, CloudControl, EventBridge, and others).
* feat(kinesisanalytics): add CreateApplicationPresignedUrl and SnapshotsEnabled
CreateApplicationPresignedUrl returns a URL to the running application's Flink
Dashboard (UrlType: FLINK_DASHBOARD_URL only; Zeppelin/Studio isn't supported).
Floci has no real session/proxy layer for this, so it returns the JobManager
container's own REST/dashboard URL directly, while still validating UrlType and
SessionExpirationDurationInSeconds against AWS's documented constraints.
ApplicationSnapshotConfiguration.SnapshotsEnabled (default true, matching real
AWS) is now honored on CreateApplication and toggleable via UpdateApplication's
ApplicationSnapshotConfigurationUpdate; CreateApplicationSnapshot rejects the
request with InvalidRequestException while disabled.
* fix(kinesisanalytics): persist flinkJobId as soon as the job is submitted
The readiness poller only called putApplication when advanceToRunning reported
RUNNING, not when it merely assigned flinkJobId after submitting the job (which
returns false until the job state catches up). pendingJars — a separate,
in-process-only cache — is already cleared by that point, so an emulator
restart between job submission and reaching RUNNING would leave the
application stuck: no persisted flinkJobId to resume polling, and no cached
JAR left to resubmit.
|
||
|
|
3b760bd8e5 |
fix(kinesis): resolve LATEST shard iterator position at GetShardIterator time (#1901)
* fix(kinesis): resolve LATEST shard iterator position at GetShardIterator time A LATEST iterator recomputed its start position as the shard tip on every GetRecords call, so records written between obtaining the iterator and the first poll were skipped forever. Snapshot the tip once when the iterator is created (matching DynamoDbStreamService) and encode it in the iterator's index slot. GetShardIterator now also fails fast with ResourceNotFoundException for an unknown shard, as on AWS. Fixes #1900 * test(kinesis): add regression tests for tailing with a LATEST iterator Reproduce issue #1900: a record written after the iterator is obtained must be returned, both on the first GetRecords call and when polling via NextShardIterator. * test(kinesis): cover unknown shard validation for LATEST iterators GetShardIterator must return ResourceNotFoundException when the shard does not exist instead of deferring the failure to GetRecords. * docs(kinesis): document shard iterator semantics Describe the supported iterator types and the LATEST tip-snapshot behavior; remove a stray empty Examples heading. * fix(kinesis): validate shard existence for all iterator types in GetShardIterator AWS rejects an unknown shard at GetShardIterator time for every iterator type, not just LATEST. Apply the shard lookup unconditionally instead of deferring the failure to GetRecords. Addresses review feedback on #1901. * test(kinesis): cover unknown shard validation across all iterator types |
||
|
|
c4f4181c3d |
fix(cognito): HMAC-sign refresh tokens to prevent forgery (#2139)
* fix(cognito): HMAC-sign refresh tokens to prevent forgery Refresh tokens were plain poolId|username|clientId|issuedAt|familyId strings, base64-encoded with no signature or encryption. Anyone who knew a pool id, client id, and a valid username could hand-craft a token accepted by InitiateAuth REFRESH_TOKEN_AUTH / GetTokensFrom RefreshToken, unlike real Cognito, which documents refresh tokens as encrypted and opaque. buildRefreshToken now appends an HmacSHA256 signature over the payload, keyed by a random secret generated and persisted per pool (mirroring the existing lazy RSA JWT signing key pattern). parse RefreshToken verifies that signature with a constant-time comparison before returning any decoded field, and rejects the token (same as today's null-parse contract) on any mismatch, tampering, or unknown pool. * fix(cognito): reject invalid refresh tokens in REFRESH_TOKEN_AUTH instead of impersonating "unknown" handleRefreshToken fell through to minting real, correctly-signed AccessToken/IdToken JWTs for a hardcoded "unknown" user whenever parseRefreshToken returned null (or adminGetUser failed). With refresh tokens now HMAC-verified, every forged/tampered/garbage token takes that null path, so this fallback would have kept handing out valid signed tokens for exactly the forgery attempts this fix is meant to close off. parseRefreshToken returning null is now treated the same way it already is in getTokensFromRefreshToken: NotAuthorizedException / "Invalid Refresh Token". * fix(cognito): guard non-numeric issued-at and drop unused variable in handleRefreshToken Static analysis flagged two issues in the handleRefreshToken rewrite: Long.parseLong(parts[3]) could throw an uncaught NumberFormatException, and tokenClientId was parsed but never read. Wrap the parse and reject with the same NotAuthorizedException/"Invalid Refresh Token" used elsewhere in this method, and drop the dead variable. |
||
|
|
8d2a5bdd46 |
fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them (#1969)
* fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them CreateStack now applies each entry of an IAM role's Policies array as an inline role policy (PutRolePolicy semantics), resolving intrinsics inside the policy document. Failures propagate so a policy that cannot be created fails the stack instead of reporting CREATE_COMPLETE without it. Fixes #1952 * refactor(cloudformation): move AWS::IAM::Role into its own provisioner Continues the per-service decomposition started with SQS (#1825) by taking the resource type this branch touches out of the CloudFormationResourceProvisioner switch, carrying the #1952 inline-Policies fix with it. - IamRoleCfnProvisioner owns provision and delete for AWS::IAM::Role: name resolution and same-stack adoption, managed-policy attachment with its rollback, the inline Policies of #1952, and the former deleteRoleSafe, whose only caller was the role delete arm. - CfnRollback holds what both halves of the migration need instead of duplicating it: the __FlociRollbackOwned attribute that CloudFormationService reads to decide rollback deletion, and attemptIamCleanup, still used by the AWS::IAM::Policy and AWS::IAM::ManagedPolicy arms. - ProvisionContext gains resolveStringList next to the resolveOptional and generatePhysicalName it already lifts from the monolith. - IamRoleCfnProvisionerTest covers the inline policies and the delete path with one mocked service; the existing role rollback tests keep running through the public provision entry point, now with the provisioner registered. Role provisioning behavior is otherwise unchanged. * fix(cloudformation): inline role policies fail loudly and unwind on failure Three review findings on the IAM role provisioner. A Policies entry with a null or absent PolicyDocument was skipped, so the stack reached CREATE_COMPLETE without the declared inline policy — the same silent drop this PR set out to fix, one level in. It is a ValidationError now. The inline-policy loop sat outside the block that unwinds a failed provision. When putRolePolicy failed after createRole succeeded, the resource went CREATE_FAILED, and because rollback only deletes resources that reached CREATE_COMPLETE, the role, its managed attachments and any inline policies already written were left behind. The loop now runs inside that block. A failed update that adopted an existing role kept whatever the half-applied attempt had granted. Inline writes are recorded with the value they replaced, so unwinding restores the previous document, or removes the policy when this attempt introduced the name. A role the stack did not create is not deleted. * fix(cloudformation): reconcile role policies an update stopped declaring An inline policy or managed attachment written by a previous execution and absent from the new template stayed on the role while the stack still reported UPDATE_COMPLETE. Both sets are now recorded on the resource and reconciled on the success path, so what the template drops is removed. Only names a previous execution recorded are touched, which leaves out-of-band policies alone. PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same policy a fresh name on every execution, so an update accumulated copies instead of replacing it. A missing PolicyName is now a ValidationError, matching what this resource already does for a missing PolicyDocument. * fix(cloudformation): skip reconciliation of a role policy already removed deleteRolePolicy and detachRolePolicy both raise NoSuchEntity on an absent target, so a tracked policy removed out of band between executions failed an update whose desired end state already held. Reconciliation now skips what the role no longer carries. |
||
|
|
6d829ff7a4 |
feat(s3): resolve index documents for static-website directory requests (#1815)
* feat(s3): resolve static website index documents * fix(s3): drop the query string from the website folder redirect Verified against a live S3 website endpoint in us-east-1 rather than inferred: a bucket with photos/index.html answers GET /photos?code=abc&state=xyz -> 302, Location: /photos/ with a bare Location. Same for HEAD and for nested prefixes (/a/b?x=1 -> /a/b/). An earlier commit added query-string preservation on the strength of a review comment asserting AWS behaved that way; the probe shows it does not, and LocalStack's website_hosting.py agrees with the probe. An SPA whose OAuth callback lands on a slash-less folder loses its parameters on real AWS too, so the emulator matches rather than improving on it. |
||
|
|
41d2a3cd19 |
test(lambda): wait for the parked poll in the extension shutdown stop race (#2141)
extensionShutdown_racedAgainstStop_isNeverOrphaned still raced stop() against a Thread.sleep(5), the pattern #2131 replaced in its sibling extensionRegister_racedAgainstStop_eventuallyDeliversShutdown but left in place here. A fixed sleep only assumes the poll parked; on a loaded runner it expires first, stop() closes the listening socket while the request is still in flight, and the client sees EOFException instead of the SHUTDOWN the test is asserting. Reuse the awaitExtensionParked helper #2131 already added, so the race is set up against a poll that has provably landed. Reproduced by running the class under 'docker run --cpus=1' to emulate a contended runner: fails on the unpatched tree, 45/45 green on the patched one across repeated runs. Unconstrained it passes either way, which is why it only ever showed up in CI. |
||
|
|
cb06a73b78 |
fix(lambda): disable HTTP/2 cleartext on the runtime API server (#2181)
RuntimeApiServerTest.extensionRegister_racedAgainstStop_eventuallyDeliversShutdown flaked intermittently with an EOFException from the JDK HTTP/2 client, surviving #2156's fix for the write-vs-close ordering bug. stop() already waits for each parked write's flush to complete before closing the httpServer, but that only confirms the bytes were locally flushed, not that the peer received them before the connection is torn down - multiplexed HTTP/2 stream-completion bookkeeping on the same connection can still race that close. Real AWS's Runtime/Extensions API is plain HTTP/1.1; nothing here needs HTTP/2. Disabling h2c removes the class of multiplexed-connection races entirely and the JDK HttpClient falls back to HTTP/1.1 automatically, no client-side change required. Fixes #2180. |
||
|
|
396ef55512 |
fix(ses): pass the custom-verification-email store in the list-management test (#2182)
main does not compile. SesServiceListManagementTest calls a SesService
constructor that no longer exists, so `mvn test` fails at testCompile before a
single test runs.
Two SES changes landed three minutes apart and collided semantically. #1875
added this test against the twelve-store constructor; #1840 then added a
thirteenth store for custom verification email templates and updated the five
sibling tests it could see, but this one did not exist on its branch. Neither
change conflicts textually, both were green on their own branch, and the break
only exists once both are present.
Add the missing argument in the same position as the five siblings.
Verified by checking out
|
||
|
|
fa8f8d78a4 |
fix(sqs): delayed FIFO message no longer blocks its message group (#2112)
Only in-flight messages (claimed, within their visibility timeout) lock a FIFO message group. claimFifo() used !isVisible() as the lock predicate, which also matches messages still waiting out DelaySeconds, so a newly sent delayed message made already-visible messages in its group unreceivable. Require a receipt handle as well, the same delayed-vs-in-flight discriminator messageCounts() already uses. Fixes #2104 |
||
|
|
cd3c6b54b2 |
fix(dynamodb): order Query by full composite sort key (#2114)
* fix(dynamodb): order Query by full composite sort key Query ordered results using only the first RANGE attribute returned by getSortKeyName(). For an index with a composite sort key (more than one RANGE attribute, e.g. "state RANGE, createdAt RANGE"), the remaining components were ignored: when the first component tied across rows, the stable sort left items in base-table storage order and ScanIndexForward =false merely reversed that order, so the secondary component (e.g. createdAt) never drove ordering. Sort by the full sort key instead, comparing each RANGE attribute in key-schema order and short-circuiting on the first non-equal component, then reverse for ScanIndexForward=false. Single-sort-key indexes are unaffected (one-element list preserves previous behavior). Adds getSortKeyNames() to GlobalSecondaryIndex, LocalSecondaryIndex and TableDefinition, and a regression test whose base-key order deliberately disagrees with the secondary sort component. Fixes #1675 * fix(dynamodb): paginate composite sort-key Query by full key The composite-sort-key ordering fix sorted by every RANGE attribute, but pagination still used only the first RANGE component (getSortKeyName()). LastEvaluatedKey construction and ExclusiveStartKey matching therefore dropped the later components, so a cursor no longer uniquely identified the row a page stopped on — rows sharing the first RANGE value could be skipped or duplicated across pages. Thread the full sort-key list (getSortKeyNames()) through buildKeyNode() and buildItemKeyFromNode(): the emitted cursor now carries every sort-key component, and cursor matching compares the full composite key. Single sort-key indexes and the scan/table-key paths keep the previous behavior via the retained single-key overloads. Addresses PR review comment r3710297799 ("Composite pagination loses key identity"). Adds paginated regression tests over the composite index that fail without this change. Refs #1675. --------- Co-authored-by: Nikola Gencic <nikola.gencic@centiglobe.com> |
||
|
|
02288abc11 |
fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe* (#1740)
* fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe* DescribeDBInstances/DescribeDBClusters returned an empty 200 when the identifier parameter matched nothing; real AWS faults for the parameter form and returns an empty list only for the Filters form. Track whether the identifier came from the parameter and fault when it matched nothing, with error codes, messages, and 404 status matching live AWS. * fix(rds,docdb,neptune): ARN identifiers and Filters-form parity for Describe* Review follow-ups: - RDS, DocDB, and Neptune list methods accept an ARN (the identifier parameter and the db-instance-id/db-cluster-id filters both allow ARNs per the AWS model). The ARN is matched against each resource's stored ARN, so a cross-account or cross-region ARN does not resolve a same-named local resource. - DocDbQueryHandler and NeptuneQueryHandler fault only for the identifier parameter, not the Filters form, which returns an empty list (mirror of the RDS fix). * test(rds): expect NotFound faults after delete in SDK compat tests The Go and Java compat suites asserted the old emulator behavior — an empty 200 when describing a deleted instance/cluster by identifier. Real AWS faults DBInstanceNotFound/DBClusterNotFoundFault there, which is what the deletion waiters key on, and the emulator now does the same. |
||
|
|
d943e09a73 |
feat(ec2): add ReplaceRoute (#2178)
Terraform calls ReplaceRoute whenever an existing route changes target, so route tables could be created but never updated; the only workaround was to destroy and recreate the table. The action replaces the target of the route matching DestinationCidrBlock. AWS takes exactly one target per call, so the target a request does not name is cleared rather than carried over; a merge would leave a route holding two targets at once, which AWS cannot produce. Only GatewayId and NatGatewayId are modelled by Route, plus LocalTarget, which needs no new field because `local` is the gateway id a route table's built-in route already carries. The other ten AWS targets keep the UnsupportedOperation they returned before this action existed rather than being accepted and silently clearing the route they were meant to repoint. Errors follow the EC2 reference: InvalidRoute.NotFound when no route matches the destination, MissingParameter when DestinationCidrBlock is absent (an IPv6 or prefix-list request), and InvalidParameterCombination for two targets or none. Closes #2087 |