mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
43eace4e026ba088a6583baccc68a161663b0170
101
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
9a2a89399a |
feat(firehose): convert JSON records to Parquet via the floci-duck sidecar (#3333)
* feat(firehose): convert JSON records to Parquet via the floci-duck sidecar Deliver data-format-converting streams for real: each flushed record is parsed and type-checked in Java against the stream's Glue table schema (per-record ParseError/MalformedData routing with AWS's probed message shapes), valid rows are staged as normalized NDJSON and written to the destination as Parquet by DuckDB's COPY, and failed records go to the evaluated ErrorOutputPrefix as AWS-shaped NDJSON error lines. Batch-level failures (missing Glue table, unsupported schema, sidecar errors) route every record to the error output instead of dropping them. Adds the floci.services.firehose.staging-bucket setting and replaces the PR-1-era unconverted-delivery warning. * fix(firehose): deliver a scheduled flush as the stream's own account A scheduled flush runs on the flusher thread, where no request context is active, so the Glue lookup, the staging writes, the destination writes and the sidecar all resolved the default account instead of the stream's owner. A stream owned by another account had its Glue table missed and its objects written to the wrong partition. The delivery now runs under RequestScopes, which the CUR scheduler already uses for the same reason, so every store the delivery touches agrees on the owner. The unconverted path gets this too. Cleanup failures in the compatibility test are logged rather than swallowed, per the repository rule on tolerated exceptions. * fix(firehose): cap the staging buffer size hints rows.size() * 128 overflows an int at about 16.7 million records, so a batch of many small records failed before writing any of them, and short of that it asked for a multi-gigabyte array. Both hints are computed as a long and capped at 8 MiB; the streams grow as needed, so this only affects the first allocation. * docs(firehose): state what a failed error-output write actually guarantees The comment claimed a failure of the error-output write leaves the converted rows in the staging bucket, but the enclosing finally removes the staged object however the method exits, and the Parquet bytes are read into memory before either destination write, so nothing is retained to recover from. What holds is that nothing is delivered and the flush fails as a whole, which is what it says now, along with where recovery does live: the source, which a Kinesis-backed stream has and a DirectPut buffer does not. The reverse ordering is documented rather than claimed away: the two destination writes are not atomic, so an error object can land and the Parquet write then fail, reporting the failed records while the converted ones are gone. |
||
|
|
2d5a8f705b |
fix(amazonmq): add configuration for AMQP and console host port ranges (#3315)
Signed-off-by: Matheus André <matheusandr2@gmail.com> |
||
|
|
53a84c8890 |
feat(iot): configurable DescribeEndpoint address for published AWS IoT ports (#3202)
* feat(iot): configurable DescribeEndpoint address for published AWS IoT ports AWS IoT's DescribeEndpoint returns a bare hostname and each client adds its own port (8883, 443 or 8443). Floci returns host:4566 because its HTTP data plane lives there and IoT Data clients build https://<endpoint> from it. Both are right for their callers, and Floci inside a container cannot tell whether the operator published the AWS ports. floci.services.iot.endpoint-address (FLOCI_SERVICES_IOT_ENDPOINT_ADDRESS) is returned as is for every endpoint type when set; unset or blank keeps the host and port of the base URL. EmulatorConfig.iotEndpointAddress() resolves it once for DescribeEndpoint and for the AWS-managed domain configurations, which now follow a changed address instead of keeping the value they were seeded with. The name joins the generated server certificate's SANs the way FLOCI_HOSTNAME does, so devices verify it on 8883 and 443. * docs(iot): DescribeEndpoint address when the AWS IoT ports are published Describe FLOCI_SERVICES_IOT_ENDPOINT_ADDRESS on the IoT page with the compose port layout it is meant for, note it on the TLS page next to the other names the server certificate covers, and list the IoT Core variables in the environment variable reference. * fix(tls): accept only host or host:port as the IoT endpoint certificate name A value with a query or fragment, such as host?x=1, still parsed to a host and was added to the server certificate. The name now has to be exactly the authority java.net.URI reads back, so anything beyond host[:port] is skipped with the same warning as a URL or a path. * test(iot): pin the address the concurrent seeding test asserts at the end Every caller had already been joined, so the final describe could not race, but setting the address explicitly before it makes that plain to read. |
||
|
|
ee2f55b784 |
feat(iot): MQTT over TLS listener on 8883 (#3142)
* feat(iot): floci.services.iot.mqtt.tls-port (default 8883) * feat(iot): key manager that follows the TLS registry's current default certificate * feat(iot): MQTT over TLS listener on 8883 Second MqttServer sharing the plaintext handlers, opened when floci.tls.enabled is true. Its key material is the TLS registry's default configuration through a reloading key manager, so a server certificate reissued for a learned hostname is presented on the next handshake without rebuilding the listener. Client certificates are requested and carried through the handshake, not yet verified. * docs(iot): MQTT over TLS on 8883 * feat(iot): keep retired server key material readable for the life of a handshake A retired generation of ReloadingKeyManager stays readable for 60 seconds after its replacement, longer than Vert.x's 10 second handshake timeout, and is dropped on the next reload after that. Any number of reloads between JSSE choosing an alias and reading its key and chain now resolve to matching material. * fix(iot): wait for a failed MQTT listener to close before reporting the start failure |
||
|
|
024bfa0a5c |
feat(docker): containers Floci launches trust the Floci CA (#3091)
* feat(tls): write a CA bundle for launched containers at boot
Containers Floci launches need to trust Floci's HTTPS endpoint from any runtime
without losing access to public HTTPS. A bundle that carries the JVM's public
roots followed by Floci's trust anchor makes that possible: the variables that
replace a runtime's trust store (SSL_CERT_FILE and friends) can then point at
it safely.
ContainerCaBundle writes {persistent-path}/tls/floci-ca-bundle.pem from the
JVM's default trust anchors plus the certificates in the anchor file: the local
CA, or the user-provided certificate file in custom-certificate mode. Only
certificates are copied out of that file, so a combined certificate-and-key
file never leaks its key into a container. The file is swapped in atomically
from a uniquely named temporary file. TlsConfigSource writes it in both
certificate modes; a failure is logged and never stops the boot.
hostPath(config) resolves the bundle in the directory the bootstrap used, so a
persistent path set only in application.yml cannot point it elsewhere, and
appendEnv(env) adds SSL_CERT_FILE, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE,
NODE_EXTRA_CA_CERTS and AWS_CA_BUNDLE without overriding a key the caller set.
The bootstrap now records its TLS directory in every TLS-on mode, not only when
it issues the leaf, so the CA producer and the bundle lookup read from the
directory the boot wrote to even when a persistent path is set in
application.yml alone. A missing bundle is reported once per process.
* feat(docker): every launched container gets the CA bundle and the trust variables
ContainerLifecycleManager.create is the single path every emulator-created
container passes through, so injecting trust there covers Lambda, ECS, MWAA,
Flink, RDS, ElastiCache, Batch and the rest at once.
With TLS on and the bundle present, create appends the five trust variables
after the spec's own environment (a value from a task or function definition
wins) and copies the bundle to /etc/floci-ca-bundle.pem in the created, not
yet started, container. A copy rather than a bind mount, because when Floci
itself runs in Docker its persistent path is not a host path the daemon can
mount. A failed copy is logged with its consequence and the container still
starts. With TLS off, or without a bundle, nothing changes.
* refactor(lambda): take container CA trust from the lifecycle manager bundle
The Lambda launcher no longer resolves, copies or announces the CA itself: the
lifecycle manager does that for every container. Its append-only policy
(NODE_EXTRA_CA_CERTS and AWS_CA_BUNDLE only, never SSL_CERT_FILE) existed
because a bare CA would have cut a function off from public HTTPS; the bundle
carries the public roots, so the policy and the test that guarded it go.
The Kubernetes launcher publishes the bundle in its ConfigMap instead of the
bare CA, mounts it at /etc/floci-ca-bundle.pem, and appends the trust
variables after the function's own environment so a function value wins, as
in the Docker launcher.
* test(docker): a launched container trusts Floci and public roots through the bundle
The unit tests pin the variables and the copy, not that a runtime reading them
actually trusts Floci and still reaches public HTTPS. A python:3.12-alpine
container launched through the lifecycle manager, with the image's own root
directory pointed away so only the bundle can supply roots, fetches
https://host.docker.internal:<port>/_floci/ca.pem and https://public.ecr.aws/
with no setup of its own. Skipped without a Docker daemon, like the other
*DockerIntegrationTest classes; the image is prefetched in CI with the
others.
* docs(tls): containers Floci launches trust the Floci CA
Describe the bundle every launched container receives, the five variables that
point at it, that a value set on the function or task definition wins, and
that the JVM ignores these variables so a Java workload still needs its own
trust store.
* fix(docker): recreate a container without the trust variables when the bundle cannot be copied
SSL_CERT_FILE, CURL_CA_BUNDLE and REQUESTS_CA_BUNDLE replace a runtime's trust
store, so a container whose bundle copy failed (an image without /etc) used to
start pointing them at a file that was not there, and lost every HTTPS
connection instead of only the ones to Floci. The lifecycle manager now removes
that container and creates it again without the variables, so it keeps the
image's own trust store. The host configuration, and with it any dynamic host
port, is built once and reused.
* fix(tls): serve only the certificate blocks of a user-provided file from ca.pem
In custom-certificate mode GET /_floci/ca.pem returned the configured
certificate file byte for byte, so a combined certificate-and-key file, the
form OpenSSL tooling produces, handed the server's private key to any caller.
The endpoint now goes through the same certificate-only parsing the container
bundle uses. TlsUserCertIntegrationTest boots on a combined file and asserts
the response holds the user certificate and the local CA and no key.
* test(cloudformation): wait for DeleteStack to finish before asserting on deleted resources
DeleteStack hands the work to an executor and answers at once. Seven tests in
CloudFormationIntegrationTest asserted on the deleted resources right after the
answer; one of them, deleteStack_ecs_leavesNoOrphans, failed shard 1 of this
pull request's CI 44 ms later with the cluster still ACTIVE, while the same
shard had passed on the previous push.
A shared awaitStackDeleted polls DescribeStacks until the stack reports
DELETE_COMPLETE or no longer exists, fails on DELETE_FAILED or after ten
seconds, and replaces the three inline copies of that loop as well.
* docs(tls): restore the learned-hostnames section and the ACM wording that #3079 dropped
#3079's docs commit (
|
||
|
|
c67e598594 |
feat(iot): real device certificates issued by the local CA (#3079)
* feat(iot): CreateKeysAndCertificate issues a real client certificate from the local CA certificateId is sha256(DER) in lowercase hex as on AWS; the returned RSA 2048 key pair matches the certificate. CreateCertificateFromCsr parses the PKCS#10, checks its self-signature and key strength (RSA 2048 or more, EC P-256/384/521), signs the CSR's key with the same CA and returns no private key, as on AWS. * docs(iot): describe the CA-issued device certificates * fix(iot): accept only the NIST curves AWS IoT names and never store a device private key The CSR key check reads the named-curve identifier instead of the field size, so secp256k1 and explicit curve parameters are refused as on AWS. The stored certificate record no longer carries the private key; it is returned once. * feat(iot): device certificates expire at the end of 2049 and DescribeCertificate reports validity AWS IoT-issued client certificates all carry notAfter 2049-12-31T23:59:59Z. CertificateGenerator gains an overload with an explicit validity window; DescribeCertificate adds validity.notBefore, validity.notAfter and certificateMode DEFAULT. The Java SDK compatibility test asserts the shape. * fix(iot): a device certificate never outlives its issuing CA A new local CA is valid until the end of 2050, past AWS's fixed 2049 device expiry; a CA created earlier (ten years) caps the device certificates it signs at its own expiry, so a chain never expires before its leaf. * fix(iot): derive CA and device expiry from creation time, never mint an expired certificate A CA created after 2050 lives ten years from creation instead of ending on the fixed date; after 2049 a device certificate lives a year, still capped at its CA. The Python compatibility suite now sends a real PKCS#10 request, since the placeholder it used is refused as on AWS. * docs(tls): the local CA now signs IoT device certificates * test(iot): pass the certificate authority to IotServiceTest's constructor |
||
|
|
0fce2d2407 |
fix(lambda): bound ZIP extraction resources (#3127)
* fix(lambda): bound ZIP extraction resources Limit Lambda ZIP compressed and expanded sizes and configurable entry counts for function and layer deployments. Preserve previous extracted code when a package exceeds a resource limit. * refactor(test): centralize ZIP fixture encoding * docs(test): explain ZIP fixture headers |
||
|
|
162211de0c |
feat(route53): support cross-account VPC associations (#3116)
* feat(route53): support cross-account VPC associations * test(route53): add SDK cross-account compatibility coverage * fix(route53): harden cross-account VPC ownership * fix(ec2): scope default resources by account |
||
|
|
67bbd2cf13 |
feat: serve custom domains over TLS as soon as they are created (#3086)
* feat(tls): record runtime-learned hostnames in the certificate metadata
* feat(tls): TlsCertificateManager.ensureHost grows the server certificate at runtime
Reissues the leaf from the local CA with the same key pair and the new SAN,
replaces certificate and metadata by atomic renames (the key file is never
rewritten), reloads the default TLS configuration and fires
CertificateUpdatedEvent so the HTTPS listener swaps immediately.
Names must be well-formed host names under a local suffix; anything else is
refused with a WARN and never throws.
* feat(tls): keep runtime-learned hostnames across a boot regeneration
* test(tls): ensureHost is visible to the next TLS handshake without a restart
* docs(tls): custom domains learned at runtime
* test(tls): pin the certificate contracts of a runtime reissue
The reissued leaf keeps the boot leaf's shape (subject, issuer, EKU, CA flag,
validity, new serial, configured names first), a wildcard covers exactly one
label, an IP allowed by the base URL becomes an iPAddress SAN, and a client
that verifies the server's identity for the new name (SNI plus RFC 6125
matching) fails before ensureHost, succeeds after it, and fails again after
reset, while the configured name keeps serving HTTPS throughout.
* fix(tls): retry a failed listener reload and keep served names across a boot
A name is known only once the HTTPS listener serves it: a reload that
returns false, a missing default TLS configuration or a failing listener
now leaves the in-memory state untouched, so the next ensureHost call for
that name writes and reloads again instead of reporting it as covered.
At boot, a SAN the served certificate carries beyond the metadata's
configured list is treated as learned, so a reissue whose metadata rename
did not complete cannot lose the name in a later regeneration.
The allow-list is checked after coverage, so a default SAN such as
host.docker.internal no longer logs a refusal on a no-op call.
Tests are split by concern: TlsCertificateManagerTest (reissue, reload,
reset, failure, races) and TlsCertificateManagerNameRulesTest over a
shared fixture; TlsConfigSourceLearnedHostnamesTest holds the boot paths.
* fix(tls): carry a name whose reload failed into later reissues and resets
The learned list now follows the files and the known set follows the
listener. A name written to disk but not yet served is kept by every
later reissue instead of being dropped when a second name is learned,
and a reset whose reload failed is retried by the next reset.
Two pre-existing em dashes in TlsConfigSource log messages replaced with
commas, as AGENTS.md asks.
* feat(acm): issue AMAZON_ISSUED and PRIVATE certificates from the local CA
RequestCertificate now returns a TLS server leaf (serverAuth and clientAuth)
signed by Floci's local root CA, and CertificateChain is that CA's PEM, the
same bytes GET /_floci/ca.pem serves. Certificate plus CertificateChain from
GetCertificate therefore build a chain that validates, as they do on AWS, for
both certificate types, and ExportCertificate returns the same chain. The
requested KeyAlgorithm is still honoured and DescribeCertificate reports the
CA as the issuer.
The bundled amazon-root-ca.pem and its startup check are gone: nothing Floci
issues chained to it, and the file was corrupt (its base64 payload could not
decode), so every GetCertificate handed out an unparsable chain.
AcmPaginationTest walks a store shared with every other ACM test class; its
page cap now leaves room for the suite to grow instead of failing once the
shared store passes fifty certificates.
* refactor(acm): drop the cosmetic Amazon issuer generator
CertificateGenerator.generateCertificate signed a leaf with its own key under a
CN=Amazon issuer DN that no client could ever verify. Its last production caller
now issues from the local CA, so the method and the DN are gone and the
self-signed builder no longer carries an issuer and CA flag that were always the
subject and true. Tests that only needed some certificate use the self-signed
generator; the ones that need a leaf that is not a CA issue it from a throwaway
CA.
* docs(acm): certificates chain to the local CA
Say that every issued certificate is signed by the local root CA, that
GetCertificate returns that CA as CertificateChain, and that trusting
/_floci/ca.pem once validates both the HTTPS endpoint and ACM certificates.
* test(acm): the SDK compatibility suite validates the certificate against its chain
GetCertificate's certificateChain() must contain the issuing CA and that CA
must verify certificate(), as on AWS. A chain that does not parse or does not
sign the leaf now fails the suite instead of passing a BEGIN CERTIFICATE check.
* docs(acm): say when the CA is created and what Issuer reports
ACM issuance now creates the local CA under {persistent-path}/tls/ on first
use, also with TLS off and in memory storage mode, and DescribeCertificate
reports the CA's name as Issuer where AWS reports Amazon. The CA javadoc no
longer calls ACM a later step.
* test(acm): pin key size, an imported chain and the persisted chain
The import fixture is now a server certificate from a throwaway CA, uploaded
with that CA as its chain, and GetCertificate must hand both back unchanged.
The RSA and EC chain tests also check the key size and curve, and the
persistence test checks the chain survives a restart.
* test(acm): the python compatibility suite verifies the certificate against its chain
The key-algorithm case checked the certificate's self-signature, which only
held while ACM certificates were signed by their own key under a cosmetic
issuer. On AWS, and now here, the signer is the issuing CA that GetCertificate
returns first in CertificateChain, so the case verifies that signature and the
issuer name instead.
* fix(acm): write EC private keys as PKCS#8 and classify keys by interface
JcaPEMWriter turned a JDK EC private key into a bare SEC1 structure with
no curve and no public half, which neither OpenSSL nor parsePrivateKey
could read, so every EC certificate stored an unusable key and
ExportCertificate on one failed. EC keys now go out as PKCS#8, RSA keys
stay PKCS#1 as AWS IoT hands them out, and a SEC1 key without a public
half parses through its private-key info.
Private keys are told apart by the ECKey interface rather than by name:
a BouncyCastle provider, when one is registered, names an EC key ECDSA.
* test(acm): AcmServiceTest pins issuance from the local CA
Service level, no Quarkus: every KeyAlgorithm yields a leaf of that key
signed by the CA with the CA PEM as chain and metadata read from the
certificate; PRIVATE is issued at once; a pending certificate already
holds its leaf and chain; an idempotent replay mints nothing; imports
keep their own chain; exports return the stored chain, also for EC
keys; sixteen concurrent requests each get their own valid certificate.
* feat(apigateway): serve a custom domain over TLS as soon as it is created
CreateDomainName hands the domain name to TlsCertificateManager.ensureHost
after the domain is stored, outside the uniqueness lock. The certificate
manager never throws, so the API response is unchanged.
* feat(iot): serve a customer-managed domain over TLS as soon as it is configured
CreateDomainConfiguration hands a customer-managed domain name to
TlsCertificateManager.ensureHost after the configuration is stored. A
configuration without a domain name describes the default endpoint and
registers nothing.
* feat(cognito): serve a custom domain over TLS as soon as it is created
CreateUserPoolDomain hands a custom domain to TlsCertificateManager.ensureHost
after the domain is stored. A prefix domain lives under amazoncognito.com on
AWS, a name Floci does not serve, and is left alone.
* docs: custom domains are served over TLS on creation
One sentence each in the API Gateway, IoT Core and Cognito pages, and the
TLS page now names the operations that add hostnames to the server
certificate.
* test(compat): custom domain reachable over TLS trusting only the ACM chain
RequestCertificate, CreateDomainName with regionalCertificateArn, then a TLS
handshake with SNI that trusts only the returned CertificateChain and
verifies the hostname. Probes for TLS on the endpoint host and port, because
the workflow hands the tests an http:// URL while Floci serves both, and
skips when the probe fails.
* docs(tls): say which ensureHost outcomes are logged as warnings
* test: pin the custom domain TLS hooks against the service contracts
Service tests for API Gateway, IoT Core and Cognito: the exact name is
handed over once, after the record is stored, with no service lock held
(a concurrent create must not wait for the TLS reload), and never for a
rejected request, an ENDPOINT configuration, an AWS-managed configuration,
a prefix domain or a later update or delete. A CloudFormation stack with
the three types registers every domain and a replacement, not an in-place
update or the delete. With TLS on, a client trusting only the ACM chain
reaches all three names by SNI with hostname verification, and a reset
takes them back.
* test(acm): build the InUseBy test service with the local CA
AcmInUseByTest landed on main with #3035 using the constructor that
predates the local CA; AcmService now takes the certificate authority
it issues from, so the test loads a throwaway CA in its temp directory
like AcmServiceTest does.
* test(cognito): request an issued ACM certificate in the custom domain TLS tests
Since #3035 a custom domain needs an issued ACM certificate, so the wire
test requests one and the service test stubs AcmService. Two new cases pin
that a certificate ACM does not know, or has not issued, is refused before
the hostname is registered.
* test(cognito): a concurrent create does not wait for the TLS reload
The custom domain hook sits after the domain lock #3095 introduced, so a
second create is not queued behind the HTTPS listener switch; pinned the
same way as for API Gateway and IoT Core. The routing test #3095 added
constructs the service with the certificate manager as well.
|
||
|
|
64f06e090f |
perf(docker): shrink image by 28% using ubi9-micro (109 MB to 78 MB compressed) (#3085)
* perf(docker): move the native image to ubi9-micro The binary needs only libc, and since #3037 the entrypoint needs only bash and coreutils. ubi9-micro has both at 7 MB compressed instead of ubi9-minimal's 40 MB. Measured on arm64 with the nightly-09042026 binary: 109 MB to about 78 MB compressed, 313 MB to 229 MB uncompressed. ubi9-micro has no useradd and no curl, so the user is one /etc/passwd line and the healthcheck is a bash /dev/tcp probe. Dockerfile.native gets the same runtime stage and loses its unused gosu tools stage. Dockerfile.compat needs microdnf, so it now starts from ubi9-minimal and copies /app out of the native image. * chore(docker): share the health probe and split the compat tools stage The bash health probe is now docker/healthcheck.sh, used by all three Dockerfiles. Dockerfile.compat gets a version independent tools stage; the aws CLI shim test and the cache warm job build target: tools, so they pull no floci image and their cached layers stay stable. ARG VERSION and the native RUN steps move so only the binary copy changes between builds. * fix(docker): copy healthcheck.sh into the compat image from the build context * ci(compat): build the whole compat image on pull requests and check it starts healthy |
||
|
|
3c6c005ff1 |
feat(tls): a local root CA that signs Floci's server certificate (#3078)
* refactor(acm): one issuer-signing primitive in CertificateGenerator
buildCertificate always signed with the subject's own key. signCertificate now
takes the issuer DN and key explicitly; generateCaCertificate and
generateIssuedCertificate sit on top of it, with serverAuth or clientAuth EKU on
leaves. Existing public methods keep their signatures and output; metadata now
follows ACM: colon-separated hex serial and the certificate's real signature
algorithm in upper case.
* refactor(cloudhsmv2): sign emulated hardware certificates through CertificateGenerator
Deletes the private generateCert copy; the shared primitive also marks the two
CA levels of the chain as CAs, which the old code did not.
* refactor(acm): normalize imported certificate metadata and check issued key relationships
ImportCertificate now stores the serial as colon-separated hex and the
signature algorithm in upper case, the same shape generated certificates
report. generateIssuedCertificate verifies the leaf against the issuer's
certificate and refuses a supplied key pair whose halves do not match.
* refactor(acm): refuse a supplied key pair that is not of the requested algorithm
* refactor(acm): match a supplied EC key pair by named curve, not field size
* feat(tls): FlociCertificateAuthority, a persistent local root CA
Loads or creates {persistent-path}/tls/floci-root-ca.{crt,key} with an
owner-only key, signs serverAuth and clientAuth leaves through
CertificateGenerator, and regenerates with a WARN when the pair is corrupt,
expired, not a CA, or the key does not match the certificate. A CDI producer
exposes the same pair to beans, using the directory the config bootstrap used.
* feat(tls): issue the HTTPS server certificate from the local CA
The leaf is floci-server.{crt,key}, signed by floci-root-ca; a pre-CA
self-signed leaf, a leaf from a regenerated CA and an expired leaf are replaced
on boot. Published through quarkus.tls.key-store.pem.0.* so the TLS registry
owns it and can reload it. The server key is written owner-only.
* feat: serve the local CA at GET /_floci/ca.pem
TlsLocalCaIntegrationTest boots the HTTP server on the TLS registry keys and
completes a handshake trusting only the PEM this endpoint serves.
* fix(lambda): inject the local root CA into containers instead of the server leaf
The leaf will be reissued as SANs grow; pinning it would break after the first
reissue. The CA is stable.
* docs(tls): trust the local CA once instead of disabling verification
* feat(tls): create private key files owner-only and log why a CA was regenerated
* feat(tls): serve the user certificate from ca.pem in custom-cert mode, log the CA fingerprint
With floci.tls.cert-path set, GET /_floci/ca.pem returns that file, the same
file the Lambda launcher mounts, and creates no local CA. The CA's SHA-256
fingerprint is logged at startup so an out-of-band copy can be checked, and a
file system without POSIX permissions gets a WARN instead of a silent default.
* feat(tls): ca.pem is a bundle in custom-cert mode; clear the bootstrap directory on every boot
With a user-provided certificate the endpoint returns that file followed by
the local CA, so both the HTTPS endpoint and anything Floci issues validate
from one file. TlsConfigSource resets its resolved directory on construction
so a later boot in the same JVM with TLS off or a user certificate never
reuses a stale value.
* docs(lambda): drop two em-dashes from the CA trust javadoc
* test(tls): cover an expired leaf, an expired CA, a missing CA key and the producer's directory choice
* docs(tls): describe IoT device certificates as a follow-up of the local CA
|
||
|
|
23728e0b75 |
feat(ecr): prefer locally present images over the loopback registry rewrite (#3022)
* feat(ecr): prefer locally present images over the loopback registry rewrite EcrRegistryManager.rewriteImageUri rewrote every AWS-shaped <account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag> URI to Floci's loopback registry unconditionally, so a container image Lambda function (or ECS task) whose image was built locally and tagged with its real ECR URI could never run: the launcher started the registry:2 sidecar and tried to pull from it, failing with "failed to resolve reference ..." (Lambda.InitError) even though the daemon already held the image. The rewrite now first asks the Docker daemon whether the image exists under the URI as given; if it does, the URI is used unchanged and the registry container is not started. Images the daemon does not have keep the existing rewrite-and-pull path, so CDK DockerImageFunction flows are unaffected. floci.services.ecr.prefer-local-images (FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES, default true) restores the old behaviour when set to false. Verified with a provided.al2023 Go image tagged 000000000000.dkr.ecr.ap-southeast-2.amazonaws.com/e2e/hello-image:local: Invoke fails on 2.0.1 and succeeds with this change, both with Floci as a host process and inside a container sharing the host's docker.sock; an image absent from the daemon still takes the rewrite path. * fix(ecr): inspect the image reference ContainerBuilder launches when preferring local images With floci.docker.image-registry-base set, rewriteImageUri inspected the bare AWS-shaped URI while ContainerBuilder later prefixed it, so a locally present image was reported as found and then missed at launch. Resolve the image through ContainerBuilder before asking the daemon so both paths agree. |
||
|
|
7fdd145c0c |
fix(lambda): honor configured function architecture (#2994)
* fix(lambda): honor configured function architecture * fix(lambda): isolate Docker images by platform * fix(lambda): reject unsupported architectures early * fix(lambda): require one function architecture Note: pre-existing full-suite flakes in EC2, Kinesis Analytics, and RDS Data passed in isolated reruns. * fix(lambda): preserve legacy architecture fallback * fix(lambda): reject malformed architecture fields * fix(lambda): reject invalid persisted architectures |
||
|
|
5dc0808bda |
feat(cloudformation): report a stubbed unsupported resource type instead of hiding it (#2971)
An unsupported resource type was stubbed at debug, so the stack reached CREATE_COMPLETE and a green stack did not prove its resources existed. The stub is now reported at warn, naming the type, and the resource carries a status reason saying nothing was created, which DescribeStackEvents returns. A new floci.services.cloudformation.allow-stub-unsupported-resource-types setting (default true) turns the stub into a stack failure for suites that need a green stack to mean every resource exists. An unexpanded SAM resource type warns on its own, and the delete path names the physical id it does not remove. Closes #2967 |
||
|
|
279f2776b7 |
docs: fix port ranges, OpenSearch default image and quick-start snippets (#2690)
Corrects the documented port ranges, the OpenSearch default image tag, the quick-start snippets and a duplicate CloudTrail nav entry so the docs match application.yml and EmulatorConfig. |
||
|
|
39b19d1c92 |
refactor(config): move max-request-size and ecr-base-uri into sub-mappings (#2902)
floci.max-request-size and floci.ecr-base-uri sat at the config root but belong with related settings. Relocate them: - max-request-size -> floci.protocols.max-request-size (ProtocolsConfig) - ecr-base-uri -> floci.services.lambda.ecr-base-uri (LambdaServiceConfig) A new FlociConfigRelocationsInterceptor (SmallRye ConfigSourceInterceptor, registered via META-INF/services) keeps the old flat keys and their FLOCI_MAX_REQUEST_SIZE / FLOCI_ECR_BASE_URI env vars working: the legacy key is consulted when the new key is requested, and iterateNames() rewrites it so config-mapping validation does not flag it as unknown. Future relocations are one entry in its RELOCATIONS list. ImageResolver, both application.yml files, the affected tests and the configuration docs are updated to the new keys. |
||
|
|
ec97063362 |
docs: use x.y.z in the pinned image example (#2863)
Every emulator README pinned a concrete version in its compose example and every one had gone stale: 1.5.11 against 1.7.0, 0.5.0 against 0.7.0, 0.9.0 against 0.11.0, 0.1.0 against 0.3.0. The channel table directly above each example already writes the pinned channel as x.y.z, so the example now agrees with its own table and cannot drift again. The line above it, image: floci/floci:latest, stays copy-pasteable and is the recommended one; the pinned line reads as the pattern. |
||
|
|
10ce6be8cd |
docs: state the release cadence in CONTRIBUTING and the docs site (#2850)
* docs: state the release cadence in CONTRIBUTING and the docs site Follow-up to the release-train documentation. CONTRIBUTING described how a release is cut but never when, and the published contributing page said nothing about releases at all, so the cadence was only discoverable from the README. - CONTRIBUTING: the 1st and 3rd Tuesday train leads the release section, and merging to main is stated not to cut a release. - docs/contributing.md: a Releases section, including why the commit type matters, since semantic-release derives the version from it. - docs/configuration/docker-images.md: the Channel table said release images publish "on every release", which explained nothing; it now names the train. Three corrections in the same table, all pre-existing: - The nightly row said 22:00 CT. nightly.yml is cron '0 23 * * *' pinned to America/Chicago, and observed runs land at 04:0x UTC, so it is 23:00 CT. - Dated nightly tags were described as fixed and never moving. The workflow accepts workflow_dispatch and pushes unconditionally, so a same-day rerun republishes that day's tag. Reproducibility is a release-tag property. - The pinned example was 1.5.11, six minor versions behind. Em-dashes in the touched files replaced with ordinary punctuation, per the documentation style rule in AGENTS.md. * docs: correct three points raised in review - Nightly availability was overstated. A merge after the nightly workflow starts misses that run, so the text no longer promises "that night's" image; it says the change reaches nightly on the next nightly build. - The published contributing page called CHANGELOG.md never hand-edited, omitting the changelog-edit label that the root CONTRIBUTING documents as the route for a genuine correction. - docker-images.md recommended 1.7.0 in the channel table while its Quick Reference still pinned 1.5.11. Each was fixed in all four emulators, not only where it was flagged. |
||
|
|
968ff78e25 |
fix(lambda): make the code-volume populate concurrency configurable (#2830)
Concurrent first-time code-volume populates are capped by a semaphore sized Math.max(2, availableProcessors() / 2). The JVM honours the container's cgroup CPU quota, so a CPU-constrained Floci container derives 2 permits and concurrent cold starts of *distinct* large functions complete in waves of two instead of in parallel. Measured on main, six distinct functions with 41MB packages, all cold, fired concurrently, varying only the quota on Floci's own container: unlimited (16 cpu) -> 8 permits -> one wave of 6 -> 8.3s --cpus=8 -> 4 permits -> waves of 4, 2 -> 13.2s --cpus=4 -> 2 permits -> waves of 2,2,2 -> 19.2s The wave sizes track the formula exactly, which rules out generic CPU starvation - that would slow all six uniformly rather than produce discrete equal-size waves. The populate is IO-bound (creating a helper container and streaming a tar into it), so CPU count is a weak proxy for how many the Docker daemon can absorb. The cap itself is still worth having: the daemon overload it was added to prevent is real. What was missing is a way to decouple it from the CPU allocation, so this adds floci.services.lambda.code-volume-populate-concurrency (FLOCI_SERVICES_LAMBDA_CODE_VOLUME_POPULATE_CONCURRENCY) and leaves the derived default untouched. Values below 1 fall back to the derived default with a warning: zero permits would deadlock every populate, and a negative Semaphore count would make acquire() block until that many releases arrived. The semaphore becomes an instance field so the permit count can come from config. Floci runs a single @ApplicationScoped launcher, so it is still one gate for the whole emulator. Refs #2050 |
||
|
|
97ff0bc3e9 |
feat(elasticache): support cluster-mode replication groups (#2633)
* feat(elasticache): support cluster-mode replication groups CreateReplicationGroup now provisions a real sharded Valkey cluster when the request asks for one (NumNodeGroups > 1, a cluster.on parameter group, or ClusterMode=enabled): one cluster-enabled container per node, formed via config epochs, MEET, slot assignment and replica attachment, each fronted by its own auth-proxy port announced to clients via cluster-announce-client-ipv4/cluster-announce-port so CLUSTER SLOTS and MOVED redirects point at reachable addresses. DescribeReplicationGroups reports the topology honestly (ClusterEnabled, NodeGroups with Slots, MemberClusters, Engine, ARN, AutomaticFailover), and replication-group members answer DescribeCacheClusters, which is where terraform-provider-aws reads node type, engine version and port from. Adds a terraform compatibility test that applies an aws_elasticache_replication_group with num_node_groups and replicas_per_node_group, asserts the data plane is a formed cluster running in cluster mode (INFO cluster / CLUSTER INFO over RESP through the proxy), and that a re-plan straight after apply is clean. * fix(elasticache): address cluster-mode review feedback and compat CI failure - bump compat-terraform aws-cli image to 2.34.32 so botocore models include ReplicationGroup.Engine (old pin silently dropped the field) - restore cluster-mode runtime state (ports, containers, proxies, cluster formation) after restart; mark groups create-failed on error - announce configured hostname to Valkey nodes so MOVED redirects and CLUSTER SLOTS return client-reachable endpoints - log swallowed socket-close failures in cluster formation * fix(elasticache): report restore-failed members and modeled node-group quota fault Review follow-up for cluster-mode support: - Member cache clusters mirror their group's status instead of a hardcoded "available", so a group marked create-failed by a failed restore no longer contradicts its own members in DescribeCacheClusters. CacheClusterStatus has no create-failed value, so failed members report the documented restore-failed. - NumNodeGroups above the 500 ceiling surfaces the modeled NodeGroupsPerReplicationGroupQuotaExceeded fault instead of a generic InvalidParameterValue. - Javadoc names ClusterMode=compatible handling and the cluster-mode-only restore scope as deliberate. * fix(elasticache): announce a client-resolvable hostname for cluster mode Cluster-mode nodes announced FLOCI_HOSTNAME verbatim, so the shipped Docker Compose deployment baked the Compose-only name 'floci' into MOVED/ASK redirects and topology responses, breaking cluster-aware clients connecting from outside the Compose network. Add FLOCI_SERVICES_ELASTICACHE_CLUSTER_ANNOUNCE_HOSTNAME (default: FLOCI_HOSTNAME) used for the announced name and the reported ConfigurationEndpoint, and set it to localhost.floci.io in docker-compose.yml — public DNS resolves it to 127.0.0.1 on the host while the network alias and Floci's embedded DNS resolve it to the Floci container from inside Docker. * fix(elasticache): restore cluster-mode groups without blocking startup Restoring persisted cluster-mode groups ran serially in the synchronous startup path, so a slow or unavailable Docker daemon could hold up emulator readiness by a container-readiness plus cluster-formation timeout per group, timing out readiness-dependent clients such as Testcontainers. restorePersistedRuntime now reserves each node's proxy port and marks groups creating synchronously - so no request can claim a persisted port or see a stale available status - then brings containers, cluster formation and proxies back in the background, flipping each group to available or create-failed as its restore finishes. --------- Co-authored-by: kurtmc <2661907+kurtmc@users.noreply.github.com> |
||
|
|
c96dc98065 |
feat(s3): opt-in global bucket namespace and replication config (#2640)
* feat(s3): bucket replication configuration round-trip
PUT/GET/DELETE ?replication store the replication configuration verbatim
(validated for a Role and at least one Rule with a Destination/Bucket)
instead of falling through to CreateBucket. Storage-only fidelity — floci
performs no actual replication. Split from a cross-service commit; the IAM
password-policy and CloudFormation SSM-parameter changes ship separately.
* fix(s3): resolve buckets cross-account under a global bucket namespace
S3 bucket names are globally unique in AWS: a bucket lives in one account but is
legitimately reachable cross-account. floci's per-account isolation broke LZA,
which has member accounts read/write a management-owned shared assets bucket and
runs cross-account custom resources (e.g. Custom::S3PutBucketReplication) whose
Lambda calls back under a different account context than the bucket's owner.
Add an opt-in globalBucketNamespace mode (default off, preserving isolation):
bucket/object existence RESOLUTION spans every account's partition while LISTING
stays owner-scoped. Reads route through resolveBucket/resolveObject; bucket-config
MUTATIONS route through a new owner-aware mutateBucket helper that resolves the
owning account via AccountAwareStorageBackend.findAnyAccountEntry and writes back
to the owner's partition (putForAccount) rather than forking a phantom bucket into
the caller's partition. Applied to put/deleteBucketReplication — the path LZA's
Logging stage exercises cross-account.
* test(s3): guard getObject against torn reads under concurrent overwrite
LZA's Bootstrap stage fans out ~15 CodeBuild actions that redundantly re-upload
the same artifact keys (Source.zip/Config.zip) while other builds concurrently
download them. A non-atomic truncate-then-write would let a reader observe an
empty/partial object — which surfaced as an empty src-Config secondary source and
ENOENT: global-config.yaml. Add a stress test (4 writers / 4 readers) asserting
getObject never returns a torn view of a constant-size key.
* docs(s3): document the global bucket namespace flag
Describe FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE in s3.md, the
multi-account isolation exception, and the environment-variable reference.
* feat(s3): account-level Block Public Access (s3control PublicAccessBlock)
Add account-scoped PUT/GET/DELETE PublicAccessBlock to the s3control
controller, keyed by the x-amz-account-id header and stored separately
from the bucket-level configuration. LZA's Custom::PutPublicAccessBlock
custom resource calls this account-level op while building the
LoggingStack; without a route the resource reported FAILED and the
stack rolled back (NoStack on CDK readback).
(cherry picked from commit a1cdf186ac7909647350ced455c4e0ba5d2d26a0)
* fix(s3): persist account-level Block Public Access
The account-level (s3control) PublicAccessBlock configuration was held in a
plain ConcurrentHashMap, bypassing StorageFactory while every other piece of
S3 state goes through it. Block Public Access is a security control, and LZA's
Custom::PutPublicAccessBlock runs once per governed account during the
LoggingStack deploy — it does not re-run on a resumed pipeline. A restart
therefore dropped the control silently and every governed account started
reporting NoSuchPublicAccessBlockConfiguration.
Move it to a StorageFactory-backed store (s3-account-public-access-block.json)
addressed through the explicit *ForAccount overloads, so the account comes from
the validated x-amz-account-id header and globalBucketNamespace never widens it.
The s3 descriptor already declares storageKey/storageMode, so no catalog change
is needed and PersistentPathValidator now covers this state.
clear() no longer wipes the config: like the bucket and object stores, its
lifecycle belongs to StorageFactory.clearAll().
* fix(s3): check x-amz-account-id against the caller on Block Public Access
The account-level PublicAccessBlock operations took the account solely from the
x-amz-account-id header, which was only checked for being non-blank. Any caller
could read, overwrite or delete any account's Block Public Access configuration
by setting one header — and Block Public Access is a security control.
AWS s3control answers AccessDenied when the header does not name the caller's
own account: there a cross-account call carries credentials assumed into the
target account, so header and caller always agree. Compare the header against
the caller's resolved account and return the same AWS-shaped AccessDenied (403)
on a mismatch, resolving the caller exactly as AccountAwareStorageBackend does
so the check and the storage partition can never disagree.
One exception is kept deliberately: the configured default (management) account
may act on any account, because Floci's launched Lambdas run on placeholder
credentials that resolve to the management account instead of assuming a role in
the target account. Without it LZA's Custom::PutPublicAccessBlock — the reason
these operations exist — would be denied for every governed account. This is the
same allowance S3Service.mutateBucket already makes for
Custom::S3PutBucketReplication.
Enforcement is scoped to the three PublicAccessBlock routes; the tag routes on
this controller accept and ignore the header as before.
* docs(s3): state the global bucket namespace trade-off explicitly
No behaviour change. The flag widens bucket resolution across accounts, which
reads as an account-isolation violation to a reviewer working from a checklist.
Say the intent in place, on the config option and in the S3 guide: S3 bucket
names are globally unique in AWS, a bucket lives in one owning account, and
cross-account access is a policy decision — so a hard per-account partition
models a state AWS cannot reach and fails legitimate cross-account calls with
NoSuchBucket. Record what it costs too: with the flag on, only IAM and bucket
policy stand between a caller and another account's object. Mutations still
write back to the owning account and listing stays owner-scoped, and the flag
is off by default.
* fix(s3): keep the account-aware bucket replication over the upstream #2519 duplicate
Upstream landed its own Put/Get/DeleteBucketReplication (
|
||
|
|
c90c5adfcb |
feat(lambda): code-signing endpoints and account settings (#2646)
* feat(lambda): GetAccountSettings with usage-derived account limits Adds the Lambda GetAccountSettings operation. AccountUsage (total code size and function count) is derived from the caller's stored $LATEST functions in the region; AccountLimit reports the configured regional concurrency limit and its unreserved share after per-function reserved concurrency. * fix(lambda): widen the default Runtime API port pool to 12000-12499 One Runtime API port is held for the lifetime of each running Lambda container, so the width of the range is a hard ceiling on concurrent Lambda executions. The old default of 9200-9299 gave 100, which a multi-account AWS Landing Zone Accelerator deployment exhausts: it fans out several custom-resource Lambdas per account and can want well over a hundred at once. Exhaustion did not announce itself as a capacity limit either. The custom resource reported FAILED and CloudFormation rolled the stack back, so an operator saw an apparently unrelated CloudFormation error with no hint that a port pool was the cause. 12000 rather than a widened 9200 because the old range's tail collides with ports floci and its sidecars already use: 9200 is OpenSearch's own REST port, 9400-9499 is the OpenSearch host-binding pool, 9092 is Kafka and 9644 Redpanda's admin port. Both application.yml and the @WithDefault annotation are updated. application.yml is a config source, not a set of defaults, so a value set there wins over the annotation; changing only the annotation would have been a silent no-op (issue #2225). The new test asserts the two agree, so they cannot drift apart again. Refs #2206 * fix(lambda): make the Runtime API port-pool exhaustion error self-describing The old message did not name the pool, its width, or the property that widens it. It also rarely reaches an operator directly: the Lambda failure surfaces as a custom resource reporting FAILED and CloudFormation rolling the stack back, so this text is buried in floci's own log alongside a CloudFormation error that looks unrelated. The message now carries its own diagnosis — which pool ran dry, how many ports it had, that one port is held per running container so this is the concurrent-execution ceiling, and the two properties that widen it. Previously the only way to learn those knobs existed was to find this class in the source. Refs #2206 * feat(lambda): add ListFunctionsByCodeSigningConfig Net-new endpoint, GET /2020-04-22/code-signing-configs/{arn}/functions, always returns an empty FunctionArns list since this codebase has no CodeSigningConfig management (no Create/PutFunctionCodeSigningConfig), so no function can ever actually have one attached. Implemented as its own controller class with its own class-level @Path("/2020-04-22") rather than folding it into the existing LambdaCodeSigningController (/2020-06-30): a JAX-RS class-level @Path is load-bearing for route-matching priority, and stripping it to share one class across two API-version prefixes causes both endpoints to fall through to a more general catch-all route elsewhere in the app. * fix(lambda): scope code storage, publish-version counters, and S3 sync-reload to the owning account CodeStore resolved extracted code to baseDir/<functionName> with no account segment, so two accounts' same-named functions in one region shared a single on-disk directory and overwrote each other's package -- while codeObjectKey already wrote the same package to an account-prefixed S3 key. Cross-account invoke resolves a function by the ARN's own account, so a collision here silently serves one account's code under the other's ARN. The PublishVersion counter was keyed region+"::"+functionName and the delete path removed that same unscoped key; both now key on the owning account, via the shared ownerAccount() helper the S3 key already used. onS3ObjectUpdated runs on the CDI event thread with no RequestContext, so its ambient scan only ever saw the default account's partition and its save wrote back into that partition. It now lists across every account (keeping the region and $LATEST filters) and saves into the function's own account. listAll(), whose only caller is the startup concurrency rehydration, is broadened the same way so a restart no longer drops non-default accounts' reserved concurrency. Recovered from 613db7bd1, re-derived onto upstream's current shape: CodeStore's methods are re-signed rather than overloaded (the unscoped forms had no remaining consumer), and the sync-reload uses a new region-filtered listAllAccounts() instead of widening listAll() at that call site. * fix(lambda): carry persisted version counters across the account-scoped key change The counter map is persisted precisely so a restart cannot re-issue a version number that already names a snapshot. Re-keying it on the owning account made every pre-existing entry unreachable, so the next PublishVersion on an upgraded deployment would have started again at 1 and overwritten the live :1 snapshot. The counter now adopts and clears the pre-account key on a miss, and deleting a function clears both forms. Also covers the widened listAll(): the reserved-concurrency pool is per region and shared across accounts, so the startup rehydration that feeds it has to see every account or a restart silently frees capacity that steady-state PutFunctionConcurrency had already accounted for. * fix(lambda): validate CodeSigningConfigArn on ListFunctionsByCodeSigningConfig The handler took @PathParam("codeSigningConfigArn") and never read it, so any input — including "not-an-arn" — got a 200 with an empty FunctionArns array. It also dropped the modeled Marker/MaxItems query parameters. Botocore models InvalidParameterValueException (400) and ResourceNotFoundException (404) for this operation, and carries a pattern on the CodeSigningConfigArn shape: arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}((-gov)|(-iso(b?)))?-[a-z]+-\d{1} :\d{12}:code-signing-config:csc-[a-z0-9]{17} (max 200 chars). That pattern is now applied verbatim, whole-string. The 404 for a well-formed ARN is a derivation, not an observation against real AWS: ResourceNotFoundException is modeled for this operation, the only resource the path parameter can name is a code-signing config, and Floci implements no CreateCodeSigningConfig / PutFunctionCodeSigningConfig — therefore every well-formed ARN necessarily names a config that does not exist. The previous always-empty 200 asserted the opposite (config exists, has no functions), which is the stronger and false claim. Validation order matches AWS: ARN shape, then MaxItems range (botocore MaxListItems: min 1, max 10000), then resource resolution — so a bad MaxItems is reported as such instead of being masked by the not-found. Marker is accepted and stateless: the result set is always empty, so no NextMarker is ever emitted. The pre-existing test asserted the 200-empty behaviour using an ARN whose csc- suffix was 9 characters, which the model's pattern rejects; it is replaced by six cases covering the two error classes and both MaxItems bounds. docs/services/lambda.md's two "always empty" claims are corrected to match. * docs(lambda): derive the operation count from the routed operations The branch adds two operations (GetAccountSettings and ListFunctionsByCodeSigningConfig) but bumped docs/services/index.md by one, 30 -> 31. Rather than hand-correcting to 32, the count was re-derived from the routes, because 30 could not be reconstructed from anything in the tree. index.md's own preamble states the rule for REST services: "the count reflects distinct AWS SDK operations, collapsing routes where one JAX-RS handler fans out via query-string or header markers". Counting JAX-RS methods across the Lambda controllers on upstream/main gives: LambdaController 24 LambdaConcurrencyController 3 LambdaEventInvokeController 5 LambdaLayerController 5 LambdaTagController 3 LambdaUrlController 4 -- 44 Two collapses applied. LambdaCodeSigningController's /2020-06-30 route and LambdaController's /2015-03-31 route are the same SDK operation (GetFunctionCodeSigningConfig) and count once. LambdaUrlInvocationController (5) and the lambda-package ApiGatewayController (5) are data-plane proxies with {proxy: .*} catch-alls, not Lambda SDK operations, so they are excluded. 44 + GetAccountSettings + ListFunctionsByCodeSigningConfig = 46. Corroboration that 44 is the real base and 30 is drift: docs/services/lambda.md's Supported Operations table lists 34 rows on upstream/main and omits exactly the 5 layer and 5 event-invoke operations — 34 + 10 = 44. Those 10 missing table rows are pre-existing and left alone here; only the count is in scope. * fix(lambda): match the current CodeSigningConfigArn pattern for isolated partitions The inlined regex predated the model's (eusc-)? prefix and widened -iso(b?) alternation, so a well-formed ARN in aws-iso-e/iso-f or the European sovereign cloud was rejected as malformed instead of reaching the modeled 404. * fix(lambda): validate FunctionName length, Role ARN, and Handler on config paths botocore models FunctionName up to 256 chars with dots allowed in the name segment; LambdaArnUtils rejected dots and never bounded length. Also close the gap where UpdateFunctionConfiguration accepted a malformed Role ARN or a whitespace-containing/oversized Handler and stored it verbatim. * fix(lambda): close leaked directory-listing streams and block dot-segment traversal in CodeStore Files.walk/Files.list returned streams that were never closed, leaking file descriptors and making delete() flaky on platforms that refuse to remove an open file. Separately, sanitizeName replaced disallowed characters but let a segment consisting entirely of dots (".", "..") pass through untouched, so an account or function name of exactly ".." resolved outside baseDir via Path.resolve instead of being rejected. * fix(lambda): reclaim pre-account-scoped code directories on delete and update A function created before code storage was account-scoped left its extracted code at <codePath>/<functionName>. DeleteFunction only ever targeted the new <codePath>/<accountId>/<functionName> path, and UpdateFunctionCode re-extracted to the new path without touching the old one, so the legacy directory (and its disk usage) lingered indefinitely after either operation. CodeStore now also clears the legacy path on delete, and re-extraction reclaims it on success. * fix(lambda): reject an explicit null Handler on UpdateFunctionConfiguration validateHandler treated null as "clear the handler", matching how Description is handled, but null is not a string at all -- and unlike Description, Handler names the file AWS invokes. A request with "Handler": null silently cleared it instead of failing with a 400, which would have broken every subsequent invocation of the function instead of the one bad request that caused it. * fix(lambda): do not reclaim a legacy code directory another account's function still uses The pre-account-scoped layout gave every account's same-named function the exact same on-disk directory. CodeStore.delete() and code re-extraction both reclaimed that legacy directory unconditionally once a function migrated to the account-scoped path, so a delete or code update in one account could destroy the legacy directory while another account's never-migrated $LATEST still served invocations from it -- its next cold start would then fail with a missing code directory. CodeStore.delete() no longer touches the legacy path at all; only LambdaService calls deleteLegacy() explicitly, after checking every account's $LATEST functions (via the existing cross-account listAllAccounts) for one still pointing its codeLocalPath at that directory. * fix(lambda): check published versions, not just $LATEST, before reclaiming a legacy code directory publishVersion snapshots codeLocalPath verbatim (required so a version-qualified invoke doesn't launch a container with no code, #1987), so a version published while $LATEST was still on the pre-account-scoped legacy path keeps that directory alive on its own after $LATEST migrates. The unused-check only scanned $LATEST records via listAllAccounts(region), so a later delete or code update reclaimed the directory out from under that published version's own future invokes. Switched to functionStore.listAll(), which has no $LATEST or region filter, matching the fact that the legacy path itself carries neither. * fix(lambda): close a publish-vs-legacy-cleanup race on the code directory publishVersion read codeLocalPath and persisted a snapshot of it with no synchronization against extractZipCodeBytes's/deleteFunction's decision to reclaim the pre-account-scoped legacy code directory (added in |
||
|
|
7188b3ec9d |
feat(iam): enforce SCPs and populate aws:PrincipalArn during policy evaluation (#2637)
* feat(iam): enforce service control policies during policy evaluation
Service control policies from the caller's organization now gate IAM
policy evaluation. CallerContext carries an optional list of SCP levels
(root, each OU on the account's path, then the account); the evaluator
requires an explicit allow and no explicit deny at every level before
identity policies are consulted. SCPs never grant permissions on their
own.
The ceiling applies to evaluate() only. IamEnforcementFilter is the
single producer of SCP levels, so simulatePrincipalPolicy and the
AppSync GraphQL IAM-auth path (IamAuthValidator) evaluate without one.
Both are explicit non-goals rather than oversights: giving them a
ceiling would require IAM to resolve the principal's organization,
which is the dependency ScpProvider exists to avoid. The coarse AppSync
request is still bounded by the filter ahead of the resource; only the
field-level check runs outside it.
The new ScpProvider interface keeps the dependency direction clean:
OrganizationsService implements it and IamEnforcementFilter resolves it
lazily via Instance, so IAM never depends on Organizations while
Organizations keeps using IamService for role provisioning.
Enforcement is doubly opt-in — FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED
plus FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED — and the
management account is exempt, matching AWS.
* fix(iam): apply service control policies to the account-root principal
floci's account-root principal is a bare 12-digit account-id access key
(LocalStack multi-account convention). IamService.resolveCallerContext
returns null for it, so IamEnforcementFilter took the unknown-key bypass
and returned before SCP levels were ever consulted. Effect: a
DenyLeaveOrganization SCP attached to a workload OU did not stop a member
account from leaving — SCPs never applied to floci's primary
multi-account principal, unlike the AWS account root which is fully
bounded by SCPs.
Fix: when the caller has no registered identity but the account actually
has an effective SCP ceiling and the access key is the account root
(akid == accountId), synthesize an implicit full-access identity
(ROOT_ALLOW_ALL) and evaluate it against the SCP levels. Accounts with no
effective SCPs, and unknown AKIA keys, keep the historical bypass.
Strictly more enforcement, gated behind two opt-in flags
(iam.enforcement-enabled + organizations.scp-enforcement-enabled, both
default off), so the LZA campaign and existing bare-account behavior are
unaffected.
Known flag-flip caveats (both are correct SCP semantics, documented here
for operators enabling enforcement):
- A level that carries SCPs but no FullAWSAccess denies everything for
the account root, since scpAllows requires an explicit allow at each
non-empty level. Auto-attached FullAWSAccess covers the normal path.
- Condition-scoped guardrails keyed on aws:PrincipalArn (e.g. a
DenyRootUser "Deny * when aws:PrincipalArn like *:root") are inert:
IamConditionContextResolver never populates aws:PrincipalArn, so a
plain StringLike on that absent key fails the condition block and the
statement does not apply. A regression test locks this in.
Tests: unit coverage in IamEnforcementFilterTest (bare-account deny,
non-denied allow proven via arnBuilder invocation, and the realistic
two-statement workload-guardrails doc) plus an end-to-end
ScpEnforcementLeaveOrganizationIntegrationTest driving the Organizations
control plane over HTTP.
* feat(iam): populate aws:PrincipalArn for real identities in policy conditions
IamEnforcementFilter built the condition context only from
IamConditionContextResolver, which populates s3:prefix/delimiter/max-keys
and nothing else. aws:PrincipalArn was therefore never set, so every
policy condition keyed on it was inert across all policy layers (SCPs,
identity, session, permissions boundary): a principal-scoped Deny never
fired and a principal-scoped Allow never matched.
Fix: after resolving the condition context, look up the caller's ARN via
IamService.resolveCallerArn(akid) and, when present, set aws:PrincipalArn.
The lookup returns the user ARN for IAM-user access keys and the
assumed-role ARN for STS sessions, and Optional.empty() for the bare
account-id key (floci's account root) and unknown keys. So the key is
populated for real, identifiable principals and stays absent for the
account root — which is exactly why a DenyRootUser guardrail keyed on
aws:PrincipalArn continues not to fire against the account root, per the
account-root SCP change in the preceding commit.
Effect is bidirectional and applies to every policy layer that
evaluate() consults: a principal-scoped Deny can now deny, and a
principal-scoped Allow can now grant. Both remain gated behind the two
opt-in enforcement flags (iam.enforcement-enabled +
organizations.scp-enforcement-enabled, both default off).
IamEnforcementFilter is the sole caller of the condition-aware
IamPolicyEvaluator.evaluate overload and the sole user of
IamConditionContextResolver, so there is no second evaluation path where
the key would be absent and the same policy would behave differently.
Known caveat (pre-existing, surfaced here for operators): resolveCallerArn
hardcodes the assumed-role session name as "floci-session", so
aws:PrincipalArn for assumed-role callers will not match a condition that
pins a specific session name. This matches what STS GetCallerIdentity
already reports.
Tests: two conditional cases in IamEnforcementFilterTest exercise both
directions against a real IamPolicyEvaluator — a principal-scoped SCP
Deny that fires for an IAM user, and an identity-policy Allow gated on an
IAM-user principal that grants access. Both were confirmed RED with the
population disabled.
* docs(iam,organizations): document account-root SCP handling and condition keys
Clarify how SCP enforcement treats the bare account-id key (subject to the
SCP chain as the account root, but carrying no identity policy), the
condition keys floci populates (s3:prefix/delimiter/max-keys,
aws:PrincipalArn), and the absent-key rule that keeps aws:PrincipalArn
guardrails inert against the account root.
* feat(iam): organization support ops for LZA bootstrap
Add ListOrganizationsFeatures and the root-credentials-management and
root-sessions enable/disable pairs, backed by OrganizationRootFeatures.
LZA custom resources call these during the Prepare/Accounts stages
(EnableAllFeatures), alongside CreateServiceLinkedRole for the Access
Analyzer role, which the emulator already implements — the tests here
cover the service-linked role names those stages depend on.
* fix(iam): register OrganizationRootFeatures for reflection
PersistedModelReflectionTest asserts every type reachable from persisted
storage carries @RegisterForReflection -- without it, native-image
persistence breaks on restart. OrganizationRootFeatures was added in
e60e8abd (organization support ops) without the annotation, so the test
has been red since.
Adds @RegisterForReflection plus @JsonIgnoreProperties(ignoreUnknown =
true), matching the convention of every sibling model in the package
(InstanceProfile, IamPolicy, IamGroup).
* feat(iam): tag and untag instance profiles
Adds a tags map to InstanceProfile and wires TagInstanceProfile /
UntagInstanceProfile through the query handler, with an integration test
covering the tag round trip.
* feat(iam): add UpdateGroup
Net-new operation modeled on the existing updateUser: rename and/or
change a group's path, with the ARN and stored users moving with it.
Same EntityAlreadyExists/NoSuchEntity exception shape as updateUser.
* docs(iam): document SCP enforcement where it is implemented
The Organizations page described SCP participation in policy evaluation and
linked to iam.md#service-control-policies-scps and iam.md#bypass-rules, neither
of which existed anywhere. The behaviour belongs to the IAM enforcement layer —
IamEnforcementFilter resolves the chain via effectiveScpLevels — so document it
there, including the account-root and bypass cases, and restore the
cross-reference now that both anchors resolve.
* fix: use canonical IAM service-linked role names
* feat(iam): seed AWS Backup service-role managed policies
LZA's OperationsStack attaches AWSBackupServiceRolePolicyForBackup and
AWSBackupServiceRolePolicyForRestores to its backup service roles; without
catalog entries AttachRolePolicy fails with NoSuchEntity and the stack
rolls back.
* feat(iam): seed AWS Backup S3 service-role managed policies
LZA's OperationsStack backup role also references
AWSBackupServiceRolePolicyForS3Backup / ForS3Restore, which live at the
root path in real AWS rather than /service-role/. Without them the role
create fails with NoSuchEntity and the stack rolls back.
* fix(iam): deny when a service control policy fails to parse
The SCP ceiling skipped any document it could not parse and evaluated
whatever else the level held. Since FullAWSAccess is attached to every
target, a level almost always carries it alongside the customer's
guardrail: a malformed guardrail dropped out, FullAWSAccess supplied the
required explicit allow, and the restriction vanished with only a WARN
line to show for it. A security control must not fail open.
parseAll now reports whether any document failed, and a level holding an
unparseable document denies. Only SCP evaluation reads that signal —
identity, resource, session and boundary policies keep skipping bad
documents as before.
* perf(organizations): scan the policy store once per SCP resolution
effectiveScpLevels called policiesIn(organization) inside the loop over
the account's ancestry, and policiesIn scans every account's policy
store. A root -> OU -> account chain therefore did three full scans on
an authenticated request path. Hoist the scan above the loop and keep
the per-node target filter inside it.
Also record why the SCP levels are resolved before resolveCallerContext
in IamEnforcementFilter: the account-root branch needs to know whether a
ceiling exists before it can choose between enforcing and bypassing.
* test(organizations): cover each reason effectiveScpLevels returns null
The management-account exemption, the account-outside-any-organization
case, and the SCP-policy-type-disabled case were only asserted as three
lines inside the walk-the-chain test, where a name never says what broke
and an earlier failure hides them. Give each its own test, and assert a
member account does get a ceiling in the same setup so the exemption
cases cannot pass for the trivial reason that no SCPs exist at all.
* fix(iam): never reissue deleted policy version ids
CreatePolicyVersion derived the next version id from the version count,
so deleting a non-default version and creating a new one silently
rewrote the highest surviving version. AWS ids are monotonic; derive
the next id from the highest existing one and cap on the live count.
* fix(iam): resolve principal policies in the account the ARN names
collectUserPolicies, collectRolePolicies, resolveUserBoundaryDocument
and resolveRoleBoundaryDocument stripped a bare name out of the given
principal ARN and looked it up in ambient request-context storage. When
two accounts each hold a same-named user or role, presenting account
A's ARN resolved whichever account the request happened to run as — a
cross-account authorization bypass in either direction, and one that
also silently applied the wrong permissions boundary.
Each lookup now scopes to the account segment of the ARN it was given,
via the existing findRole(accountId, roleName) and a new symmetric
findUser(accountId, userName). resolvePrincipalContext passes the full
ARN to the user-side helpers instead of pre-stripping it to a name.
Callers that legitimately have no ARN — resolveCallerContext, reached
from a long-term access key — still resolve through the ambient account,
so account-routed access keys keep working.
* fix(iam): enforce the modeled password-policy bounds and instance-profile tag limits
UpdateAccountPasswordPolicy stored whatever numbers arrived, so a policy with
MinimumPasswordLength outside 6-128, MaxPasswordAge outside 1-1095 or
PasswordReusePrevention outside 1-24 persisted and was read straight back by
GetAccountPasswordPolicy as if AWS had accepted it. Reject with ValidationError,
the code the service already raises for shape-constraint failures.
TagInstanceProfile merged the tag map with no cardinality check and
UntagInstanceProfile accepted an unbounded TagKeys list, though both shapes are
max 50. Tagging past the quota now raises LimitExceeded, matching the other
per-resource quota guards; an over-long TagKeys request raises ValidationError.
* fix(iam): check the instance-profile tag list shape before resolving the profile
Separates the two constraints the previous commit conflated: a request carrying
more than 50 tags fails the tagListType shape and is now rejected with
ValidationError before the profile lookup, matching untagInstanceProfile's order
and AWS's; exceeding the 50-tag per-resource quota across requests stays
LimitExceeded.
* fix(iam): validate GroupName/NewPath and InstanceProfileName shape before mutation
UpdateGroup read GroupName and NewPath with getParam and passed them straight
into IamService.updateGroup with no pattern/length check, and TagInstanceProfile
did the same for InstanceProfileName before reaching IamService.tagInstanceProfile.
botocore's iam/2010-05-08 model constrains groupNameType/instanceProfileNameType
to [\w+=,.@-]{1,128} and pathType to 512 chars matching a bare slash or a
slash-delimited run of !-~; a malformed value previously surfaced as
NoSuchEntity/200 instead of the ValidationError AWS returns.
* fix(iam): never reissue a policy version id after deleting the highest surviving version
CreatePolicyVersion derived the next id from the max of the currently-live version keys, so
deleting the highest-numbered surviving version (as opposed to an older one) and creating a
new one silently reissued the deleted id — e.g. deleting v5 while v4 survives makes the next
version v5 again, violating IAM's monotonic version-id contract. IamPolicy now tracks a
persisted next-version high-water mark, taken as the max of itself and the live-key floor so a
policy rehydrated from before this field existed is never regressed below what it already has
on disk.
* fix(iam): defensively copy InstanceProfile tags and reject a null map
setTags assigned the incoming map directly and allowed null. A persisted "tags": null on
rehydration, or a caller mutating the map it passed in after the call, could NPE at
new LinkedHashMap<>(profile.getTags()) in tagInstanceProfile or silently mutate the profile's
stored tags out from under it. Now defensively copies into a fresh ConcurrentHashMap, or an
empty one for null, matching how getTags()/setTags() are used elsewhere on this model.
* fix(iam): validate UpdateGroup's NewGroupName and keep member policies resolving across a rename
NewGroupName reached storage with no pattern/length check (the same groupNameType gap already
closed on GroupName/NewPath), and UntagInstanceProfile's InstanceProfileName had the same gap
UpdateGroup's tag-sibling TagInstanceProfile already closed. Also: renaming a group rekeyed
only the group record, leaving each member's own groupNames list pointing at the deleted old
name, so ListGroupsForUser dropped the renamed group and collectUserPolicies silently stopped
resolving its inline/attached policies for those members. updateGroup now updates every
member's groupNames symmetrically with addUserToGroup/removeUserFromGroup.
* fix(iam): guard against reissuing a version id deleted before nextVersionNumber existed
nextVersionNumber previously defaulted to 2 in its field initializer, so a policy persisted by a
pre-migration Floci version rehydrated with the same value a genuinely fresh policy would have,
regardless of how many versions it actually held historically. If such a policy's then-highest
version had been deleted (e.g. v1-v4 live after a pre-migration DeletePolicyVersion("v5")), the
live-key floor alone could not reveal that v5 was already used, and CreatePolicyVersion reissued
it. The field is now left null (unset) unless a policy explicitly sets it, so Jackson leaves a
legacy record's value null instead of masquerading as fresh; CreatePolicyVersion treats null as
"true history unknown" and jumps the counter past the live-key max by 5 (a policy can never hold
more than 5 concurrent versions, so no more than 5 stacked deletions could sit above the live max
between two persists).
* fix(iam): populate aws:PrincipalArn as the account root for the synthesized root principal
Maintainer review on #2637 (pgermosen): SCPs already treat floci's bare account-id key as the
account root (enforced), but aws:PrincipalArn was left absent for it, so a common DenyRootUser
guardrail keyed on aws:PrincipalArn (StringLike arn:aws:iam::*:root) could never fire against it
even though the same principal is otherwise bounded as root — an internal inconsistency between
the two forms of root enforcement. IamEnforcementFilter now populates aws:PrincipalArn as
arn:aws:iam::<account>:root right where the root identity is synthesized, matching AWS's own
root ARN shape. Inverts the IamEnforcementFilterTest that pinned the old inert behavior (a
DenyRootUser guardrail now correctly denies the account root's other actions too, not just the
one an accompanying statement explicitly targets) and adds a direct assertion that the exact
root ARN is what's populated. Docs updated to match.
|
||
|
|
715bab68e7 |
feat(networkfirewall): emulate AWS Network Firewall (#2580)
* feat: emulate AWS Network Firewall
* docs: register Network Firewall service
* feat(networkfirewall): add AssociateFirewallPolicy
Sets FirewallPolicyArn on the stored firewall, validating that both the
firewall and the policy exist. Round-trip covered by an integration test
(create -> associate -> describe shows the new policy ARN).
FirewallPolicyChangeProtection is not enforced; documented as a limitation.
* docs(networkfirewall): register the generated action table
* docs(networkfirewall): correct the service matrix protocol and action count
The Network Firewall row claimed JSON 1.1 with 25 actions; the service speaks
x-amz-json-1.0 and the generated action table lists 27.
* test(networkfirewall): assert list membership instead of positional indexes
hasSize(1) and [0] assertions coupled these tests to JUnit's method order and
to being the only resource in the store.
* fix(networkfirewall): declare the storage key and mode in the service catalog
The service persists four backends through StorageFactory, but its descriptor
left storageKey and storageMode null, so it was skipped by PersistentPathValidator
and by per-service storage configuration.
* fix(networkfirewall): reject DeleteFirewall when delete protection is enabled
AWS raises InvalidOperationException rather than deleting a protected firewall;
the emulator deleted it regardless of the flag it had already stored.
* fix(networkfirewall): give the subnet and AZ association ops real semantics
All four routed through updateFirewall, which copies request fields onto the
stored firewall wholesale. That ignored SubnetChangeProtection and
AvailabilityZoneChangeProtection, and a Disassociate call left the mappings it
was meant to remove in place. Associate now adds deduplicated mappings,
Disassociate removes the named ones, and either is rejected with
InvalidOperationException while the matching change protection is set.
DescribeFirewall only synthesises endpoints for a firewall created without
SubnetMappings, so draining every subnet now reports no sync states.
* fix(networkfirewall): name the resource kind in ResourceAlreadyExistsException
createNamed passed the response wrapper field, so a duplicate create reported
"RuleGroupResponse already exists" instead of "RuleGroup already exists".
* fix(networkfirewall): validate association requests before touching the firewall
mappingsOf() creates the mappings array on the live stored node, so it ran
before the request array was validated: a rejected DisassociateSubnets on a
firewall created without SubnetMappings left an empty array behind and
permanently suppressed the synthetic sync states in DescribeFirewall.
* fix(networkfirewall): name the resource kind in ResourceNotFoundException
describeNamed passed the response wrapper field as the kind, so a miss reported
"RuleGroupResponse not found". Same defect as the create path; the now-unused
responseField parameter goes with it.
* fix(networkfirewall): return the deleted firewall and its status from DeleteFirewall
AWS responds with {Firewall, FirewallStatus}; the emulator returned only the ARN
and name, so an SDK client parsed an empty response. The handler already had the
region in scope, so no controller change was needed.
* fix(networkfirewall): enforce modeled enums on rule group Type and logging config
Three modeled enums were read and stored without being checked.
CreateRuleGroup/UpdateRuleGroup Type: the model enumerates STATELESS, STATEFUL
and STATEFUL_DOMAIN. The prefix choice was a two-way branch, so every unmodelled
value (including a lowercase "stateful") silently fell through to the
stateful-rulegroup ARN and was persisted as a rule group AWS would have
rejected. The branch keeps its meaning deliberately: only STATELESS gets the
stateless prefix, and both stateful variants share stateful-rulegroup, matching
AWS. A test pins STATEFUL_DOMAIN to that prefix so the mapping is no longer
implicit.
UpdateLoggingConfiguration LogType (ALERT/FLOW/TLS) and LogDestinationType
(S3/CloudWatchLogs/KinesisDataFirehose): the LoggingConfiguration is stored
verbatim, so an unmodelled or wrongly-cased value was persisted and echoed back
by DescribeLoggingConfiguration. Enforced case-sensitively, as the model spells
them and as LZA's network-firewall construct sends them.
Rejections use InvalidRequestException, which both operations list.
* fix(networkfirewall): validate association requests before mutating stored mappings
mappingsOf handed back the live stored array (or installed one), so a
request with a valid mapping followed by an invalid one mutated the
firewall before the rejection. The mappings are now a detached copy,
validated in full, and attached only when storeAndRespond commits.
* fix(networkfirewall): whitelist mutable fields on the shared UpdateFirewall* path
The generic update loop copied every raw request field onto the stored
firewall, so an UpdateFirewallDescription request carrying SubnetMappings
or AvailabilityZoneMappings persisted them without the change-protection
checks the Associate/Disassociate ops enforce. The loop now copies only
the union of fields the six UpdateFirewall* operations actually model
(Description, the four protection flags, EnabledAnalysisTypes), matching
AWS dropping unmodeled request members.
* fix(networkfirewall): scope UpdateFirewall* to the invoked op's own field
The shared updateFirewall path copied any field present in the raw
request that appeared in the union of all UpdateFirewall* mutable
fields, regardless of which specific action was invoked. A plain
UpdateFirewallDescription request could therefore smuggle
DeleteProtection (or any other operation's field) past its own
dedicated operation and change-protection checks.
Each UpdateFirewall* operation models exactly one mutable field
(botocore 2020-11-12); replace the shared whitelist with a per-action
field map so a request only ever mutates the field its own action
models.
* fix(networkfirewall): default DeleteProtection/SubnetChangeProtection/FirewallPolicyChangeProtection to true
botocore's network-firewall 2020-11-12 model documents CreateFirewall as
initializing these three flags to TRUE when the caller omits them;
AvailabilityZoneChangeProtection is the lone exception, documented as
defaulting to FALSE (already correct). Floci defaulted all four to false,
so the enforcement code in firewallForChange/deleteFirewall was correct
but unreachable in the common case of an SDK/Terraform caller that omits
the flags entirely.
RED-first: createFirewall_withoutProtectionFlags_defaultsToProtected
failed against the old defaults (DeleteProtection false, expected true).
Existing tests that relied on the old false default to exercise
mutation paths now pass explicit false for the flags they don't intend
to test, matching how a real caller opts out of protection.
NetworkFirewallIntegrationTest: 27/27 green.
* fix(networkfirewall): flatten UpdateFirewall* response to the modelled shape
All six UpdateFirewall* operations shared updateFirewall(), which returned
firewallResponse()'s nested {Firewall, FirewallStatus} envelope -- the
CreateFirewall/DescribeFirewall shape. botocore 2020-11-12 models each
UpdateFirewall*Response as a flat {FirewallArn, FirewallName, <field>,
UpdateToken}, confirmed for all six ops (UpdateFirewallDescription,
UpdateFirewallDeleteProtection, UpdateSubnetChangeProtection,
UpdateFirewallPolicyChangeProtection, UpdateAvailabilityZoneChangeProtection,
UpdateFirewallAnalysisSettings). A typed SDK client got null back from every
modelled accessor.
RED-first: updateFirewallDeleteProtection_returnsTheFlatModelledShape failed
(FirewallArn/DeleteProtection/UpdateToken were all null at the top level;
present one level down inside Firewall). CreateFirewall/DescribeFirewall
still use firewallResponse() and are unaffected -- only the six Update*
callers changed. NetworkFirewallIntegrationTest: 28/28 green.
* fix(networkfirewall): omit optional update fields instead of echoing null
UpdateFirewallDescription and UpdateFirewallAnalysisSettings read the response
member back with path(), so a firewall created without Description or
EnabledAnalysisTypes serialised the resulting MissingNode as an explicit null.
Both members are optional on these ops (botocore 2020-11-12 marks no required
members on either), so the response now omits what was never set.
* docs: correct service count to 79 after the #2579 merge
The upstream/main merge (
|
||
|
|
f912c3b717 |
feat(servicequotas,ram): add Service Quotas and AWS RAM resource sharing (#2579)
* feat(servicequotas,ram): add Service Quotas and RAM sharing stub
Two Landing Zone Accelerator pipeline prerequisites:
- servicequotas: ListServiceQuotas/GetServiceQuota (+ AWS-default
variants) over JSON 1.1 with curated real quota codes for codebuild
and lambda, deterministic generated quotas for other services, and
offset-token pagination
- ram: EnableSharingWithAwsOrganization returning {returnValue: true}
* feat(ram): model resource shares with the reads LZA's TGW share flow needs
RamController previously registered only /enablesharingwithawsorganization;
every other restJson1 RAM path fell through to S3's /{bucket} template route
and returned an XML error the LZA Lambdas' JSON parser choked on
(SyntaxError: Unexpected token '<'). Adds CreateResourceShare,
GetResourceShares (SELF vs OTHER-ACCOUNTS visibility incl. org/OU
principals), GetResourceShareInvitations (always empty — organization
sharing auto-accepts, matching real AWS), and ListResources with RAM
resource-type derivation.
* fix(ram): show every non-owned share to OTHER-ACCOUNTS callers
Launched-container credentials resolve to the emulator default account,
so LZA's Custom::GetResourceShare Lambda never matches an account-ID
principal check for the account it actually runs in. Principal-based
visibility hid IPAM pool shares from the accepting NetworkVpcStack while
org-ARN shares (TGW) passed, failing Network_VPCs. The Lambda filters
client-side by owningAccountId + name, so returning all non-owned shares
is safe.
* feat(servicequotas): add RequestServiceQuotaIncrease
Persists the requested increase and returns a RequestedServiceQuotaChange
the subsequent Get/List operations can read back. Limitations documented in
docs/services/servicequotas.md.
* fix(config): restore EmrServerless config body lost in rebase
The rebase onto upstream/main collided where both upstream and this branch
declare a new service config interface sharing a trailing body; the
EmrServerless interface was left open, so the file did not parse.
* fix(ram): persist resource shares
* feat(ram): add principal associations and resource-share lifecycle
* fix(test): conform RAM storage test doubles to upstream StorageFactory API
e9826026 introduced SharedStorageFactory overriding StorageFactory.create with
the pre-upstream return type StorageBackend<String,V>; upstream now returns
AccountAwareStorageBackend<V>. Matches the template used by upstream's own
CodeBuildServicePersistenceTest.
* fix(ram): restrict resource-share mutations to the owning account
Every mutating RAM operation resolved the share ARN with a global
all-accounts scan, so any caller holding an ARN could rename, retag,
associate resources into, or delete another account's resource share.
Thread the caller's account into the mutation paths and resolve the
share only within it; a non-owner now gets the same
UnknownResourceException an unknown ARN gets, matching AWS, which
resolves share ARNs inside the caller's account. Read visibility under
OTHER-ACCOUNTS is unchanged.
* fix(ram): return 400 SerializationException for a malformed request body
An unparseable body left readTree throwing UncheckedIOException, which
escaped the controller and surfaced as a 500 InternalFailure. Reject it
with the modeled restJson1 client error instead.
* fix(config): restore the bedrock-agent-core-control enabled flag
A rebase left the key with a null body in both the main and test
application.yml, silently dropping the service's enabled flag.
* docs(servicequotas): fix the docs path in the consumer test javadoc
* docs: correct the service count and the Service Quotas and RAM matrix rows
docs/index.md still claimed 75 services and listed RAM under JSON 1.1;
the canonical count in docs/services/index.md is 78 and RAM speaks
restJson1. Bring the Service Quotas row up to its five handled actions
and the RAM row up to its twelve REST operations.
* docs(tooling): acknowledge the RAM controller in the docs registry
RAM's action table is hand-written and carries a method-and-path column
the generator does not emit, so register it as a deferred handler rather
than a rest-mode source.
* test(ram): cover owner mutation over HTTP and pin the non-owner error message
The ownership checks were asserted only against the service; nothing
exercised the caller account the controller now threads through, so a
mismatch between the identity stamped at create time and the one
resolved at delete time would have gone unnoticed. Select the existing
SELF assertion by share name, since the store is shared across the
class.
* docs(ram): generate the action table from the controller
The RAM table was hand-written and only acknowledged in the docs
registry, so the drift sentinel could never fire on it. Fold the method
and path into each description the way the FIS REST controller's doc
does, add the generator markers, and register the controller as a
rest-mode source. Also record that mutations are owner-only.
* fix(ram): enforce the modeled resourceOwner enum on the share read paths
GetResourceShares, ListPrincipals and ListResources all read resourceOwner and
fed it to a two-way visibility fork: "SELF" meant owned shares, and literally
anything else meant OTHER-ACCOUNTS. The model enumerates exactly SELF and
OTHER-ACCOUNTS, so a caller who sent "self" or "OTHER_ACCOUNTS" was silently
handed the inverse of what they asked for rather than the InvalidParameterException
AWS returns — an error all three operations list.
Validated at the three entry points rather than inside the per-share visibility
check, so the rejection does not depend on the store being non-empty.
* test(ram): cover the resourceOwner enum rejection on the HTTP path
The service-level test proved the check; this pins the wire behaviour LZA
actually exercises. RamController substitutes "SELF" via asText("SELF") only for
an absent or null resourceOwner, so a present-but-unmodelled value — including a
non-string that Jackson coerces — must still reach the service and surface as a
400 InvalidParameterException on all three read routes. The absent case is
asserted to still return 200, so the default is not silently changed.
* fix(ram): stop exposing the contents of a deleted resource share
ListResources and ListPrincipals reported a deleted share's resources
as AVAILABLE to non-owning consumers. Both now skip DELETED shares,
while GetResourceShares keeps returning the share with DELETED status,
matching the retention window real RAM applies.
* fix(ram): reject a malformed GetResourceShareInvitations body
The endpoint ignores its body semantically, but malformed JSON is a
client error: it now goes through readTree and answers the modeled 400
SerializationException instead of 200 with an empty list.
* fix(ram): reject mutations on DELETED resource shares
A deleted share stays readable via GetResourceShares for the retention
window, but real RAM treats it as terminal: update, associate,
disassociate, tag, untag, and a second delete all raise
UnknownResourceException. findOwnedShare now filters DELETED so every
mutation path resolves a deleted share the same as an unknown ARN.
* fix(ram): apply the GetResourceShares filters and advance lastUpdatedTime
Four response-fidelity gaps from the maintainer review, interleaved in
the same two files:
GetResourceShares read only resourceOwner, so name, resourceShareArns
and resourceShareStatus were silently dropped and a caller narrowing by
share name got every visible share back. All three are applied now, and
an unmodelled resourceShareStatus is rejected with
InvalidParameterException the way resourceOwner already is.
lastUpdatedTime never advanced: ResourceShare had no such field and
creationTime was echoed in its place, on the share node, on the
association rows, and on ListPrincipals. The field now exists and is
stamped in putForOwner, the single seam every create and mutation
already passes through. State written before the field existed reads
back with creationTime, which is correct for a share never mutated
since.
Shares also report the modeled featureSet (STANDARD — floci has no path
to produce a policy-derived share), and DeleteResourceShare echoes the
clientToken the caller sent, both of which the model carries.
* docs(ram): record the filter support and the unrouted-operation behavior
* fix(ram): require resourceOwner on the share read paths
GetResourceShares, ListPrincipals and ListResources all substituted
SELF for a missing resourceOwner, which the model marks required. That
answered a question the caller never asked, and answered it with the
caller's own shares rather than an error. All three now pass a missing
or null value to the validator that already rejected unmodelled ones,
so it surfaces as InvalidParameterException.
* docs(ram): name GetResourceShareAssociations in the fall-through note
Per review, the unrouted-operation note is more useful if it names the
operation Terraform's association resources read on every refresh, and
says the symptom is an S3 NoSuchBucket XML body rather than a
credentials problem.
* fix(ram): reject trailing tokens after a valid JSON body
Jackson's default readTree stops at the first complete value, so a body
like "{} not-json" parsed as an empty object and the request executed
instead of returning the modeled 400 SerializationException. Read with
FAIL_ON_TRAILING_TOKENS, the convention the JSON 1.0/1.1 controllers,
FIS, Signin and EventBridge already follow.
* fix(servicequotas): validate the ServiceCode shape
ServiceCode was only checked for emptiness. Because an unknown code
deliberately generates a quota catalog, that meant a caller typoing
"!!!" got three invented quotas back instead of an error. Validate
against the modeled [a-zA-Z][a-zA-Z0-9-]{1,63} and 63-character cap;
unknown-but-well-formed codes keep generating as before.
|
||
|
|
d3871e1f25 |
feat(resourceexplorer2): add AWS Resource Explorer 2 with cross-service resource discovery (#2485)
* feat(resourceexplorer2): Add AWS Resource Explorer 2 with cross-service resource discovery Resource Explorer 2 lets AWS SDK clients discover resources across S3, RDS, DynamoDB, ElastiCache, and OpenSearch through a single query interface — the same way real AWS Resource Explorer aggregates resources from multiple services. Architecture: a ResourceProvider CDI interface in core/resource/ decouples Resource Explorer from individual services. Each service implements the interface to expose its resources. Resource Explorer discovers all providers via CDI Instance<ResourceProvider> and queries them live on every request — no intermediate store, no eventual consistency. New services become discoverable by implementing the interface; Resource Explorer never imports service packages directly. Query parsing: hand-written character-by-character tokenizer that implements the full Resource Explorer filter syntax — all 10 filter attributes (accountid, application, id, region, resourcetype, resourcetype.supports, service, tag, tag.key, tag.value), comma-OR within filters, negation (-), wildcard suffix (*), quoted strings, backslash escaping, and free-form text keywords. ListResources rejects free-form text (filter-only mode); Search accepts both. Tokens are classified by splitting on the first unescaped colon and looking the prefix up against the known attributes, matching the documented grammar. API surface: 20 REST JSON endpoints covering ListResources, Search, ListSupportedResourceTypes, full Index CRUD (CreateIndex always creates LOCAL — promote via UpdateIndexType, matching real AWS), full View CRUD with Scope and FilterString, BatchGetView with Errors for missing ARNs, default view association, and pagination with NextToken on all list operations. Tag operations use the existing SharedTagsController + TagHandler infrastructure. A default AGGREGATOR index and default view with tags included are auto-provisioned on startup so ListResources works without setup. AWS behavioral fidelity (matched against the API reference, not guessed): ListResources/Search with no view and no regional default return UnauthorizedException (401), not 404; the default view is scoped per region; CreateView requires a unique, regex-valid ViewName (ConflictException 409 / ValidationException 400) and only accepts "tags" as an included property; promoting a second aggregator index returns ConflictException; ListResources suppresses NextToken at MaxResults=1000; Search/ListResources cap results at the first 1000 matches; QueryString is required (empty string allowed) and MaxResults is range-validated. Pagination offsets are clamped so a stale NextToken against a shrunk live result set returns an empty page instead of a 500. All response JSON uses PascalCase field names built via Jackson ObjectNode (never valueToTree on domain models) to match the AWS SDK wire format exactly. Verified by decompiling every SDK model class with javap and comparing field-by-field, then running 16 read-only SDK tests against production resource-explorer-2 in us-east-1. ElastiCache ReplicationGroup gains arn and region fields so Resource Explorer can discover it. RDS resources get tags via ResourceGroupsTaggingService (the cross-service tagging API) since floci's RDS service doesn't implement AddTagsToResource. Indexes and views are persisted (hybrid storage) in production; tests pin the service to in-memory storage so runs stay isolated and idempotent. Testing: - 50 query parser unit tests covering the full grammar - 20 filter evaluation unit tests against synthetic resources - 9 pagination unit tests for the offset clamp and 1000-result cap - 73 integration tests (@QuarkusTest + RestAssured), grouped with @Nested by behavior class: conditional/stateful response fields, data provenance across services, edge/boundary pagination, cross-service data consistency, filter semantics, and AWS API fidelity (401 no-default-view, conflict on duplicate view name and second aggregator, view-name and included-property validation) - 28 SDK compatibility tests using real AWS SDK v2 ResourceExplorer2Client, asserting every field the SDK model exposes. Dual-mode: run against floci or real AWS via FLOCI_TARGET=aws (mutating tests skipped against real AWS). * feat(lambda): expose functions to Resource Explorer 2 Implement ResourceProvider so Lambda functions surface via the Resource Explorer 2 ListResources/Search APIs and lambda appears in ListSupportedResourceTypes. Iterates $LATEST versions only so published versions don't produce duplicate function entries. * feat(sns): expose topics to Resource Explorer 2 * feat(kms): expose keys to Resource Explorer 2 * feat(sqs): expose queues to Resource Explorer 2 Queue ARNs aren't persisted on the model; reconstruct them from the region (recovered from the storage key) plus the queue name via regionResolver.buildArn. * feat(ecr): expose repositories to Resource Explorer 2 * feat(stepfunctions): expose state machines to Resource Explorer 2 * feat(msk): expose clusters to Resource Explorer 2 * feat(pipes): expose pipes to Resource Explorer 2 * feat(acm): expose certificates to Resource Explorer 2 * feat(cognito): expose user pools to Resource Explorer 2 * feat(iam): expose users and roles to Resource Explorer 2 IAM is a global service: its ARNs carry no region, and Resource Explorer reports global resources with the region "global" (not an empty string), matching real AWS. Emit two resource types, iam:user and iam:role. * test(resourceexplorer2): parameterize per-service ListResources coverage The ten single-service resource tests were byte-for-byte identical except for the service name and resource type — the same service-filter/assert-no-foreign-service/assert-type-present shape copied ten times. Fold them into one @ParameterizedTest whose CsvSource carries the (service, resourceType) pairs, so adding a service is one row instead of a new @Nested class. IAM stays separate: it reports the global region and two resource types, which the shared shape can't express. * feat(amazonmq): expose brokers to Resource Explorer 2 Amazon MQ arrived on main after this branch was cut. Implement ResourceProvider so brokers surface via Search/ListResources and mq appears in ListSupportedResourceTypes, matching the other services already wired into Resource Explorer. Brokers carry an ARN and tags, so the mapping is the same shape as the rest: one mq:broker resource per stored broker. * feat(lightsail): expose resources to Resource Explorer 2 Lightsail landed upstream (#1583) after this branch began and models taggable, ARN-bearing resources (instances, disks, static IPs, key pairs) that AWS Resource Explorer indexes. Without a ResourceProvider its resources were invisible to Search/ListResources, unlike every other resource-owning service on this branch. LightsailService now implements ResourceProvider: getResources() maps each stored resource node to an ExplorerResource, deriving region and account from the ARN and resourceType as lightsail:<Type>; getSupportedResourceTypes() advertises the four stored types (static IPs flagged non-taggable, matching AWS). Coverage: a focused unit test asserts the node->ExplorerResource mapping (arn, type, region, account, tags) without Quarkus, plus the parameterized RE2 integration test seeds a Lightsail instance and disk and asserts both surface via ListResources. * feat(rum): expose app monitors to Resource Explorer 2 CloudWatch RUM (added upstream in #1797) owns taggable, ARN-addressable app monitors, so it fits the ResourceProvider extension point the rest of this branch uses to surface resources to Resource Explorer 2 Search, ListResources, and ListSupportedResourceTypes. RUM is the first RE2 provider whose API model carries neither an ARN nor a region (GetAppMonitor returns neither), so getResources() reconstructs the ARN: the region comes from the storage key, and the owning account is captured at creation time on the AppMonitor. That owner account is @JsonIgnore'd so it never leaks into the RUM API body and is not persisted; getResources() falls back to the default account for monitors reloaded from disk. Resolving the account at creation rather than at query time is what keeps a monitor's identity stable — an earlier draft read the account from the request context inside getResources(), which stamped every resource with the account of whoever called ListResources instead of its true owner. Injecting RegionResolver into RumService (threaded through the existing unit tests) and adding RegionResolver.getDefaultAccountId() support this. Adds RumResourceProviderTest, including a regression test proving the owner account is the creator's, not the querying caller's, plus a RumServiceTest assertion that the owner account never appears in the serialized API body. Extends ResourceExplorer2IntegrationTest to seed an app monitor and assert rum:appmonitor surfaces via ListResources and ListSupportedResourceTypes. * feat(resourceexplorer2): complete the API surface and close the AWS gaps Follow-up to the Resource Explorer 2 branch, addressing the gaps found reviewing it against the AWS API reference and search-syntax documentation. Wire-level corrections: - MaxResults ceilings are now per-operation, as AWS models them: 1000 for Search/ListResources/ListSupportedResourceTypes, 100 for indexes, 50 for views, 10 for member indexes. ListSupportedResourceTypes previously rejected page sizes AWS accepts, and ListViews accepted ones it rejects. - ListViews is scoped to the calling Region. AWS returns "the views available in the AWS Region in which you call this operation"; every Region's views were being listed. - Free-form keywords are OR'd rather than AND'd, which is how AWS reads them. The remaining deviation — AWS ranks a non-matching resource lower instead of excluding it — is documented rather than emulated, since a keyword-only search returning the whole account is not a useful local answer. - A tag filter against a view whose IncludedProperties omit `tags` is rejected with a ValidationException, as AWS documents for tag: / tag.key: / tag.value: / application:, instead of being evaluated on data the view may not expose. - Backslash escaping is honoured throughout the query grammar: escapes now survive tokenization and are resolved only where the character's meaning is decided, so `\-`, `\:`, `\,` and `\*` are literal text and a quoted phrase neutralises every operator inside it. - application: matches the application name as well as the resource-group ARN; resourcetype.supports:tags consults the provider's declared tag support instead of passing everything through; free-form keywords match tag keys and values. The remaining 12 operations are implemented, taking the service to all 32: the multi-Region setup lifecycle (CreateResourceExplorerSetup, DeleteResourceExplorerSetup, GetResourceExplorerSetup) provisions real indexes and views and records each Region's outcome independently, so one Region's failure is reported through its ErrorDetails rather than abandoning the task. The organization and trusted-service surfaces answer with the wire-accurate empty result, since floci models neither. Eleven more services expose their resources: EC2 (instances, VPCs, subnets, security groups, volumes, internet and NAT gateways, route tables), CloudFormation, CloudWatch Logs, EventBridge, Secrets Manager, SSM, ECS, EKS, Kinesis, Firehose, and ELB v2 — thirty providers in total. API Gateway and Route 53 stay out: RestApi carries no Region and Route53Service resolves no account id, so each needs a field added to an unrelated service first. Also documents the service, which a new service requires: docs/services/ resource-explorer.md with the generated action table, the deviations above, and the routing note, plus the mkdocs nav, README, and environment-variable entries. Seven existing tests asserted on the emulator's total resource count, which thirty providers push past Search's 1000-result cap; they are scoped to a bounded slice so their arithmetic stays meaningful. 24 tests added for the new behaviour. * fix(rum): keep a monitor's owning account across updates UpdateAppMonitor rebuilds the AppMonitor from its current state and never carried ownerAccountId over, so an update silently reassigned the monitor to whichever account next called ListResources. Resource Explorer then reported a wrong ARN and OwningAccountId for any monitor not owned by that caller. getResources' fallback for monitors reloaded from disk — where the transient owner account did not survive — was the configured default account. monitorStore.keys() is already scoped to the calling account by the account-aware backend, so a monitor reachable there is owned by that caller by construction; the caller's account is the correct fallback. Also addresses review findings on the Resource Explorer branch: braces in the compatibility test's cleanup, a synchronized override in the Lightsail provider test's storage stub, and four unread locals in the integration test. * chore: drop the stray local-dev Dockerfile docker/Dockerfile.localdev was carried in with the Resource Explorer work but is unrelated to it: nothing in the repo references it, and its header points at a CI pipeline and dev cluster that do not exist in this org. * fix(resourceexplorer2): order paginated results before slicing NextToken is a bare offset, but the list it indexes into is rebuilt on every call by iterating Instance<ResourceProvider> and StorageBackend.scan, neither of which promises an order. Offset pagination is only well defined over a stable order: page through Search or ListResources with MaxResults smaller than the result set and the second page indexes into a differently arranged list, silently dropping or repeating resources. Sort on a unique key before every paginate call: ARN for resources and indexes, the view ARN for ListViews, the resource type for ListSupportedResourceTypes. The regression test drives a provider that reshuffles its resources on each call, which is what an unordered map-backed store is free to do; without the sort a 25-resource set pages down to 16 distinct ARNs. This also makes ResourceProvider#getResources()'s "ordering is not significant" contract true rather than merely permitted. * docs: add the Resource Explorer row to the service matrix The downmerge picks up #2465's service-matrix gate, which fails `make docs-check` for any service registered in ResolvedServiceCatalog without a row in docs/services/index.md — resource-explorer-2 was one. The descriptor's external key carries the API version suffix while the page is resource-explorer.md, so it also needs an alias entry, the same way apigatewayv2 and cognito-idp do. * test(resourceexplorer2): scope the tag-provenance lookup to the caller's Region dynamoDbTagResourceUpdatesResourceExplorer took Resources[0] from an unfiltered ListResources and tagged it. ListResources spans every Region the view covers while DynamoDB TagResource resolves the table in the request's Region, so the ARN it picked only worked as long as the first result happened to be local. Deterministic ARN ordering makes that assumption fail reliably instead of by luck: the first table is now eu-west-2's and TagResource reports it as not found. Filter on region:us-east-1, the same way the region-scoping tests in this class already do. --------- Co-authored-by: Marius Volkhart <marius@volkhart.com> Co-authored-by: Hector Ventura <hectorvent@gmail.com> |
||
|
|
943b4c1b45 |
feat(efs): add Elastic File System (file systems, mount targets, access points) (#2371)
* chore(efs): initialize service structure * feat: implement EFS service models for file system and mount target management * feat(efs): implement EFS metadata service emulator This introduces support for the AWS Elastic File System (EFS) service, handling the control plane operations across the 2015-02-01 REST API. - Scaffolded and generated EFS DTO models with Jackson PascalCase mapping Created EfsService with StorageBackend capabilities for File Systems, Mount Targets, Access Points, and Policies Created EfsController for all mapped REST-JSON routes under /2015-02-01 Registered EFS in the global EmulatorConfig and ResolvedServiceCatalog Added comprehensive EfsIntegrationTest verifying end-to-end API lifecycle Created EFS service documentation in docs/services/efs.md * feat(efs): implement EFS metadata service emulator This introduces support for the AWS Elastic File System (EFS) service, handling the control plane operations across the 2015-02-01 REST API. - Scaffolded and generated EFS DTO models with Jackson PascalCase mapping - Created EfsService with StorageBackend capabilities for File Systems, Mount Targets, Access Points, and Policies - Created EfsController for all mapped REST-JSON routes under /2015-02-01 - Registered EFS in the global EmulatorConfig and ResolvedServiceCatalog - Added comprehensive EfsIntegrationTest verifying end-to-end API lifecycle - Created EFS service documentation in docs/services/efs.md * fix(efs): address code review comments - Fixed describe listings to be appropriately region-scoped - Ensured idempotency token caching for AccessPoint and FileSystem creations - Altered creation timestamps to use standard epoch seconds * fix(efs): register models for reflection to satisfy native-image requirements * fix(efs): resolve remaining review comments and add documentation - Prevented file system deletion when mount targets exist - Cleaned up policies and access points upon file system deletion - Validated parent file system exists during Access Point creation - Added proper logging for tolerated exceptions during mount target deletion - Created missing documentation page docs/services/efs.md * fix(efs): prevent deletion races by locking on file system ID Wraps all state-mutating operations on file systems and their dependent resources in synchronized blocks keyed by the file system ID. This guarantees that CreateMountTarget, CreateAccessPoint, and similar operations cannot race with DeleteFileSystem, satisfying the Greptile review for P1 Deletion races dependent creation. * fix(efs): resolve additional concurrency bugs identified by Greptile - Prevents duplicate access point creation when concurrent requests reuse the same ClientToken across different file systems by adding a dedicated token lock. - Prevents resurrection of deleted mount targets by wrapping modifyMountTargetSecurityGroups and deleteMountTarget in target-specific locks. * fix(efs): enforce idempotent parameter matching for access points * fix(efs): enforce parameter matching for idempotent creation requests - Compares all parameters in CreateFileSystem (PerformanceMode, ThroughputMode, Encrypted, KmsKeyId, ProvisionedThroughputInMibps) when CreationToken matches - Compares all parameters in CreateAccessPoint (FileSystemId, PosixUser, RootDirectory) when ClientToken matches - Throws IdempotentParameterMismatch if parameters differ on a retried token, satisfying Greptile bot review * fix(efs): enforce idempotent parameter matching for nested access point fields - Compares PosixUser.SecondaryGids - Compares RootDirectory.CreationInfo (OwnerUid, OwnerGid, Permissions) - Throws IdempotentParameterMismatch if nested parameters differ on a retried token, satisfying Greptile bot review * fix(efs): enforce idempotent parameter matching for default field omission and tags - Treats null PerformanceMode as 'generalPurpose' for equality checks - Treats null ThroughputMode as 'bursting' for equality checks - Treats null Encrypted as false for equality checks - Strictly compares tag lists in both CreateFileSystem and CreateAccessPoint - Throws IdempotentParameterMismatch if these differ on a retried token, satisfying Greptile bot review * fix(efs): override equals and hashCode on Tag model to enable correct idempotency comparison - Resolves issue where identical tag values on retries were evaluated as mismatched due to object identity comparison - Satisfies Greptile bot review for Tag idempotency checks * fix(efs): enforce idempotent parameter matching for AvailabilityZoneName and Backup settings - Persists AvailabilityZoneName (and derived ID) on the FileSystem during creation if supplied - Implicitly creates an ENABLED/DISABLED BackupPolicy during CreateFileSystem to match AWS default behavior - Compares AvailabilityZoneName on retry - Evaluates Backup request flag against stored BackupPolicy status - Satisfies final Greptile bot review for missing idempotency parameters * fix(efs): evaluate creation-time backup configuration rather than current mutable policy during retries - Adds originalBackupParameter to FileSystem model to immutably capture the configuration at creation time - Refactors idempotency check to evaluate this stored value rather than querying the potentially modified live BackupPolicy - Addresses Greptile P1 defect where PutBackupPolicy broke CreateFileSystem retries * fix(efs): resolve backup retry snapshot persistence across emulator restarts - Replaces @JsonIgnore FileSystem property with a dedicated originalBackupStore - Ensures the original backup parameter is properly persisted and reloaded from disk - Maintains AWS API contract fidelity while preventing IdempotentParameterMismatch on restarts * fix(config): resolve EmrServerless and EFS configuration syntax * fix(efs): prevent stale mount targets by deleting them inside the file system lock * fix(efs): correct file-system policy endpoint path to singular /policy * fix(efs): apply query string filters correctly for describe operations * fix: align EFS emulator with AWS specifications - Fix idempotency matching logic for CreateFileSystem and CreateAccessPoint - Implement modern TagResource, UntagResource, and ListTagsForResource APIs - Dynamically resolve regions and ARNs via RegionResolver - Detect mount target subnet conflicts and dynamically resolve AZs - Remove unused obsolete EFS model classes - Ensure UpdateFileSystem returns 202 Accepted status code * docs: generate EFS action table from controller Resolves 'make docs-check' failure by injecting the floci:actions sentinel markers so the automated docs tool can maintain the supported actions list. * fix: align EFS emulator with AWS specifications - Fix idempotency matching logic for CreateFileSystem and CreateAccessPoint - Implement modern TagResource, UntagResource, and ListTagsForResource APIs - Dynamically resolve regions and ARNs via RegionResolver - Detect mount target subnet conflicts and dynamically resolve AZs - Remove unused obsolete EFS model classes - Ensure UpdateFileSystem returns 202 Accepted status code * docs: generate EFS action table from controller Resolves 'make docs-check' failure by injecting the floci:actions sentinel markers so the automated docs tool can maintain the supported actions list. * fix: prevent stale count on mount target deletion failure Removes the generic catch block in deleteMountTarget so that an unexpected exception during the file system update causes the entire operation to fail, leaving the mount target intact instead of silently deleting it and causing an inconsistent parent count. * fix: store original creation requests to prevent false idempotency conflicts When a file system or access point is updated or retagged, its mutable state changes. Retries using the original creation token were incorrectly compared against this mutated state, causing IdempotentParameterMismatch conflicts. This commit introduces dedicated storage backends to retain the original CreateFileSystemRequest and CreateAccessPointRequest, ensuring that idempotent retries correctly compare their parameters against the original request rather than the current mutated state. * fix: store original creation requests to prevent false idempotency conflicts When a file system or access point is updated or retagged, its mutable state changes. Retries using the original creation token were incorrectly compared against this mutated state, causing IdempotentParameterMismatch conflicts. This commit introduces dedicated storage backends to retain the original CreateFileSystemRequest and CreateAccessPointRequest, ensuring that idempotent retries correctly compare their parameters against the original request rather than the current mutated state. * refactor: remove unused idempotent parameter stores in EFS Dropping originalFileSystemRequestStore, originalAccessPointRequestStore, and originalBackupStore, as parameter matching is no longer performed by the EFS emulator. These stores were persistent and written to on every create but never read, unnecessarily keeping state files around. * fix(efs): resolve compliance issues and reviewer feedback - Populate AccessPointDescription.Name from tags during create and describe - Return 404 FileSystemNotFound for unknown IDs or CreationTokens in DescribeFileSystems - Implement Marker/MaxItems pagination for DescribeTags - Refactor AZ-ID generation to match exact AWS shapes (e.g. usw2-az1) - Clear ProvisionedThroughputInMibps on transition to elastic/bursting mode - Reject update requests setting ProvisionedThroughputInMibps on non-provisioned filesystems - Add trailing newline to ThroughputMode.java - Expand integration tests for ThroughputMode transitions --------- Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in> |
||
|
|
824701481c |
feat(core): label emulated resource containers with io.floci.* identity (#2497)
* feat(core): add io.floci.* resource-identity labels Introduces ContainerStorageHelper.resourceIdentityLabels(service, resourceId, accountId, region), so a container manager can tag its spawned container with the emulated resource's identity. Additive to the existing floci/floci_emulator/floci_namespace labels. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(rds): label RDS containers with resource identity RDS backing containers now carry io.floci.service=rds, io.floci.resource-id=<instanceId>, io.floci.account, and io.floci.region so a spawned container can be mapped back to the DBInstanceIdentifier it emulates without empirical docker exec probing. Account/region reuse the same ARN parsing already done for log-stream routing; extracted into resolveRuntimeIdentity so both call sites share one source of truth. Closes #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(docdb): label DocDB containers with resource identity DocDB backing containers now carry io.floci.service=docdb and io.floci.resource-id=<clusterId> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(elasticache): label ElastiCache Redis/Valkey containers with resource identity Backing containers now carry io.floci.service=elasticache and io.floci.resource-id=<groupId> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(elasticache): label ElastiCache Memcached containers with resource identity Backing containers now carry io.floci.service=elasticache and io.floci.resource-id=<clusterId> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(memorydb): label MemoryDB containers with resource identity Backing containers now carry io.floci.service=memorydb and io.floci.resource-id=<clusterName> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(neptune): label Neptune containers with resource identity Backing containers now carry io.floci.service=neptune and io.floci.resource-id=<clusterId> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(msk): label MSK containers with resource identity Redpanda backing containers now carry io.floci.service=msk and io.floci.resource-id=<clusterName> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(opensearch): label OpenSearch containers with resource identity Backing containers now carry io.floci.service=opensearch and io.floci.resource-id=<domainName> alongside account/region. RegionResolver is now injected into OpenSearchDomainManager. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(ecs): label ECS task containers with resource identity Backing containers now carry io.floci.service=ecs and io.floci.resource-id=<taskId> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(eks): label EKS k3s containers with resource identity Backing containers now carry io.floci.service=eks and io.floci.resource-id=<clusterName> alongside account/region. RegionResolver is now injected into EksClusterManager. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(amazonmq): label AmazonMQ containers with resource identity RabbitMQ backing containers now carry io.floci.service=amazonmq and io.floci.resource-id=<brokerId> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(mwaa): label MWAA containers with resource identity Both the Postgres metadata container and the Airflow container now carry io.floci.service=mwaa and io.floci.resource-id=<environmentName> alongside account/region. RegionResolver is now injected into MwaaEnvironmentManager. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(kinesisanalytics): label Flink containers with resource identity Both the JobManager and TaskManager containers now carry io.floci.service=kinesisanalytics and io.floci.resource-id=<applicationName> alongside account/region. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(batch): label Batch job containers with resource identity Job containers now carry io.floci.service=batch and io.floci.resource-id=<jobId>, using the job's own account/region (already carried on BatchJob) rather than RegionResolver. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(codebuild): label CodeBuild job containers with resource identity Build containers now carry io.floci.service=codebuild and io.floci.resource-id=<buildId> alongside account/region. No new unit test: the container-spawn call site lives inside the private multi-phase runBuild() method, entangled with real filesystem and source-download side effects with no existing seam for unit testing in isolation (CodeBuild's only coverage today is the QuarkusTest-based CodeBuildIntegrationTest, which would need a real Docker daemon and a full build run to assert container labels). Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(lambda): label function containers with resource identity Lambda containers now carry io.floci.service=lambda and io.floci.resource-id=<functionName>, reusing the existing ARN-based region resolution and adding the equivalent account lookup. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(ec2): label EC2 instance containers with resource identity Backing containers now carry io.floci.service=ec2 and io.floci.resource-id=<instanceId>, using the already-passed region parameter and a new RegionResolver dependency for the account id. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * feat(ecr): label the shared registry container with resource identity The registry:2 container carries io.floci.service=ecr with no resource-id, since it is a shared singleton, not a per-resource container. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * docs(core): document io.floci.* resource-identity labels Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * style(tests): use imports instead of inline FQCN in resource-identity label tests Cleans up the Batch, EKS, and OpenSearch label tests added earlier in this branch, which used fully-qualified names inline instead of imports. Relates to #1818 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * fix(kinesisanalytics): restore Mockito import and awsEnv param in Flink label test Silently dropped by the rebase's clean auto-merge; the test no longer compiled without them. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * docs(core): note ECR keeps every identity label except resource-id EcrRegistryManager still passes account/region for the shared registry container; only resourceId is omitted. Docs previously said the opposite. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * test(elasticache): log swallowed IOException in label test cleanup Matches the pattern already used in the DocDB/Neptune/MemoryDB label tests. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> --------- Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
b243504b48 |
docs(bedrockagentcore): document the AgentCore services (#2436)
* docs(bedrockagentcore): register AgentCore in the service matrix, env-var reference, and README * docs(readme): restore FIS to the architecture diagram lost in the main merge --------- Signed-off-by: kk <kannanpoem1984@gmail.com> |
||
|
|
04d120fdd5 |
feat(fis): add AWS FIS support (#2435)
* feat(fis): add AWS FIS support * refactor: add typed FIS persistence models * ci(fis): retrigger timed-out build * fix(fis): reject trailing JSON request bodies |
||
|
|
bc13801121 |
feat(lambda): support kubernetes as the lambda runner (#1941)
* feat(lambda): support kubernetes as the lambda runner * fix(lambda): keep the port reserved when a failed launch cannot confirm pod deletion * fix(lambda): carry the owning account in the layer Content.Location URL The URL is fetched unsigned. Without an X-Amz-Credential query the account filter falls back to the default account, so a layer published under another account resolves the wrong bucket namespace and 404s. Mirror the credential query the kubernetes executor already appends to its download URLs. * chore(build): raise the surefire heap to 6g The suite outgrew the 4g default heap of 16g CI runners. At OOM a full GC reclaims almost nothing, so the live set is real. The heap dump shows 192 surviving QuarkusClassLoader instances, each pinned test app keeping its own copy of the Jandex index. This PR widens the classpath with the kubernetes client, which made each pinned copy heavier and tipped CI over the edge. Verified locally that the full suite passes with 6g and fails with 4g. Unpinning the leaked classloaders remains follow-up work on main. |
||
|
|
f8b07a78ff | feat(lambda): add the ability to name and label lambda containers, code volumes (#2409) | ||
|
|
02898cf5e2 |
fix(iam): route long-term access keys to owning accounts (#2319)
* feat(storage): expose account ownership when scanning resources * fix(storage): validate account prefixes when scanning * fix(iam): resolve long-term access key accounts * test(iam): cover long-term access key account routing * docs(auth): clarify account-routing trust model |
||
|
|
bfda938f72 |
feat(firehose): honor BufferingHints with time and size based flush (#2314)
* feat(firehose): honor BufferingHints with time and size based flush Buffers now flush when the stream's BufferingHints.SizeInMBs is reached or when IntervalInSeconds has elapsed since the first buffered record, replacing the hardcoded 5-record count trigger that matched neither AWS nor LocalStack. A single-thread daemon flusher ticks every floci.services.firehose.tick-interval-seconds (default 10). Buffers are drained on ShutdownDelayInitiatedEvent so pending records reach S3 before EmulatorLifecycle persists storage to disk. DeleteDeliveryStream keeps discarding pending records, matching real AWS (verified empirically: 3 records buffered under a 300s/5MB hint never reached the bucket after deletion). Fixes #1886 * feat(firehose): add opt-in flush-record-count trigger Emulator-only volume trigger complementing BufferingHints: setting floci.services.firehose.flush-record-count to N flushes a stream's buffer as soon as it holds N records. Disabled by default (0) so out-of-the-box delivery matches real AWS; 1 gives LocalStack-style record-at-a-time delivery for interactive local dev, where stream definitions mirror production intervals and waiting for IntervalInSeconds is impractical. Covers the use case of #1852. Co-Authored-By: yoshinori-aono-om <yoshinori.aono@omiai.inc> * test(firehose): cover size and interval flush triggers at the wire level The size trigger delivers inline on the writing request, and the interval trigger runs through the real background flusher started on StartupEvent — previously only verified manually. The test-scope Clock is the frozen MutableClock alternative, so the interval test advances it explicitly instead of sleeping through real time. * fix(firehose): clamp the flush tick interval and mirror config keys in application.yml A zero or negative floci.services.firehose.tick-interval-seconds reached scheduleAtFixedRate unchanged, which throws IllegalArgumentException from the StartupEvent observer and aborts startup. Clamp it to a 1s minimum, the same guard RdsDataService applies to its cleanup interval. Also list tick-interval-seconds and flush-record-count under the firehose service in the main and test application.yml, matching how other tunable service settings are surfaced there. * test(firehose): wait for buffered delivery in DataLake and SES compatibility tests DataLakeTest relied on the removed 5-record flush: with buffered delivery its Athena query ran before anything reached S3, failing with NoSuchBucket on floci-firehose-results (caught by the compatibility CI job). Both tests now set explicit BufferingHints and poll for the delivered object first. A 5s interval keeps the wait short — floci does not enforce AWS's 60s server-side minimum and the SDK does no client-side range validation. --------- Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com> |
||
|
|
9e7cdad29a | fix(rds): preserve configured database images (#2035) | ||
|
|
c48c062117 |
fix(docker): fall back to Windows named pipe when docker-host is at its unix-socket default (#2030)
Floci defaults docker-host to unix:///var/run/docker.sock, which has no equivalent on native Windows. Since this hardcoded default always overrides docker-java's own OS-aware detection, every Docker-backed operation failed at container-start time on Windows with a low-level socket error — including Lambda-invoked CloudFormation custom resources such as CDK's Custom::S3BucketNotifications. When docker-host is still unmodified and DOCKER_HOST isn't set, fall back to Docker Desktop's named pipe (npipe:////./pipe/docker_engine) on Windows, mirroring what docker-java already does correctly on its own. Linux/macOS behavior is unchanged. An explicit docker-host or DOCKER_HOST always takes priority over the fallback. Verified end-to-end: a CDK-shaped stack (S3 bucket + Lambda + Custom::S3BucketNotifications) went from CREATE_FAILED to CREATE_COMPLETE after this fix. Fixes #2006. |
||
|
|
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>
|
||
|
|
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. |
||
|
|
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.
|
||
|
|
42d94c62ee |
ci: add reusable JVM and native image publishing (#1936)
* ci: add reusable image publishing Provide a workflow_call contract that builds native amd64 and arm64 artifacts and publishes native and compat multi-architecture images for an exact caller-selected source revision. Keep registry authority in the caller and return immutable digest references plus provenance for downstream tests. * fix(docker): use glibc in JVM development image Use an Ubuntu-based Java 25 runtime so the JVM image can host glibc-linked integrations while preserving the existing entrypoint, tooling, and architecture behavior. * ci: publish JVM images by default * fix(ci): harden reusable image builds * docs(ci): clarify image registry input * fix(docker): locate the installed AWS CLI * fix(ci): tag images by build time and revision |
||
|
|
86134e8c7f |
docs(cloudwatch): document Logs Insights subset and missing Logs actions (#2044)
docs/services/cloudwatch.md listed 14 of the 24 actions that CloudWatchLogsHandler dispatches. The handler is on the deferred_handlers allowlist in tools/docs/services.yaml, so the table is maintained by hand and had drifted as actions were added. Most notably Logs Insights (StartQuery / GetQueryResults / StopQuery, added in 1.5.31) was undocumented, leaving no way to discover which parts of the query language are implemented. Add the 10 missing actions and a Logs Insights section covering the supported commands, the field syntax, and how each kind of unsupported input degrades: a dropped filter stage returns every row, a >= or <= comparison is mis-parsed into a field name and returns none, a missing projected field becomes an empty string, and an unrecognised sort direction falls back to ascending. Also note the PutSubscriptionFilter and GetDataProtectionPolicy simplifications, document FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS in both the service page and the central environment-variable list, correct the MAX_EVENTS_PER_QUERY description, and add a start-query example. |
||
|
|
836c162136 |
fix(core): stop unknown-service REST requests falling through to S3 (#1967)
* fix(core): stop unknown-service REST requests falling through to S3 REST requests whose SigV4 credential scope names a service Floci does not implement matched no JAX-RS resource and fell through to S3's path-style wildcard routes, surfacing as misleading NoSuchBucket XML and triggering SDK retry storms. Reject them with UnknownOperationException instead. The guard fires only on positive identification: a parseable SigV4 scope naming a service absent from the catalog. Unsigned, presigned, Bearer/Basic and SigV4a requests are untouched. Also declares the EKS read-only sub-resource lists the emulator does not model (ListAccessEntries, ListAddons, ListIdentityProviderConfigs, ListPodIdentityAssociations) as explicit routes, so they outrank the S3 catch-all and answer with each operation's model-exact empty result key, or ResourceNotFoundException for a missing cluster. Closes #1754 * fix(iam): normalise signing-scope aliases before IAM enforcement S3 accepts requests signed under the s3express scope, but IAM action rules, resource ARNs and condition keys are all keyed by the canonical signing name. An alias therefore resolved to no action, which IamEnforcementFilter treats as ALLOW, so policy-protected S3 operations were reachable without a policy check. Resolve the scope through the catalog before enforcement runs. Only aliases are rewritten: a service whose external key is not itself one of its credential scopes (CloudWatch Logs signs as logs) is left unchanged, as is any scope the catalog does not know. Also documents why SigV4a stays outside the unknown-service guard — its credential omits the region segment, so SigV4CredentialScope does not match it — and pins that with a test, since widening the pattern would silently start rejecting SigV4a traffic. Refs #1754 * fix(iot): declare the iot-jobs-data signing scope so its routes stay reachable The IoT Jobs Data Plane (GetPendingJobExecutions, DescribeJobExecution, StartNextPendingJobExecution, UpdateJobExecution) signs under iot-jobs-data while IotController serves its /things/{thing}/jobs routes. The scope was not in the catalog, so the unknown-service guard rejected requests to routes Floci does implement. The Go, Java and Python SDK compat suites all caught it on GetPendingJobExecutions. Audited the other sibling signing names for the same failure mode: ssmmessages, eks-auth, ecr-public, cognito-identity and aoss have no Floci routes, so rejecting those stays correct. Refs #1754 * fix(iam): scope alias normalisation to an explicit table Deriving the canonical scope from the descriptor's external key was wrong: the external key is a routing key, not an IAM namespace. SES routes under email and Bedrock Runtime under bedrock-runtime while their IAM namespaces are ses: and bedrock:, so ses, sesv2 and bedrock were rewritten onto prefixes AWS never issues. Every action would then resolve to null and enforcement would be skipped for those services — the same bypass the s3express fix closed. Replace the derivation with an explicit alias table holding the one case that genuinely shares a namespace, s3express -> s3, and sweep every scope the catalog declares in the test so any future rewrite has to be deliberate. Refs #1754 * fix(core): make the unknown-service guard configurable and verify scope coverage The guard is only as good as the catalog's scope list, and the iot-jobs-data miss showed the list can be wrong. Two changes so that is recoverable and detectable rather than a hard 404 nobody can work around. Gate the rejection behind floci.protocols.reject-unknown-service-scope, matching the other two abort paths in AwsProtocolClaimFilter, which are both already gated. It defaults to true so #1754 stays fixed out of the box; turning it off restores the previous fall-through for anyone blocked by a scope Floci has not enumerated yet. Add CredentialScopeCoverageTest, which walks botocore's models and fails when Floci routes most of a service's operations without declaring the name that service signs with. Removing iot-jobs-data from the catalog makes it fail with 'iot-jobs-data=2/3 routes served'. Thresholds are conservative because small services share generic templates, so it is a tripwire rather than a proof, and it skips where the gitignored botocore checkout is absent (CI runners). Refs #1754 * fix(iam): resolve the iot-jobs-data signing scope to the iot namespace Admitting iot-jobs-data to the catalog let the IoT Jobs Data Plane reach its routes, but IAM enforcement still saw the raw scope. Its policy actions live under iot: (iot:DescribeJobExecution and peers in the Service Authorization Reference), so the scope belongs in the alias table next to s3express. No behaviour change today: IamActionRegistry carries no iot rules at all, so every IoT request resolves to no action and is allowed through regardless. This makes the mapping correct ahead of those rules existing, rather than leaving a scope that would silently escape them. Refs #1754 |
||
|
|
45ed00ebc7 |
feat(ecs): apply EFS access point POSIX ownership to shared local volumes (#1686)
* feat(ecs): apply EFS access point POSIX ownership to shared local volumes #1569 materialises an ECS task's efsVolumeConfiguration volume as a shared local Docker named volume (floci-efs-<fileSystemId>). Docker creates a named volume root:root 0755, so a task whose image runs as a non-root USER — as containers mounting an EFS access point typically do — cannot create files on it and fails with EACCES. Real EFS initialises an access point's root directory per RootDirectory.CreationInfo {OwnerUid, OwnerGid, Permissions} and applies the access point's PosixUser to all I/O regardless of the process uid. This change emulates that mechanism for the shared local volume, driven by generic config: - New floci.storage.efs.* block (owner-uid, owner-gid, root-permissions, setgid, init-image, mount-user, mount-group-add). Every value is empty/false by default, so a shared volume behaves exactly as before (a plain named volume, no ownership change) unless explicitly configured. - ContainerLifecycleManager.ensureSharedVolume(...) ensures the volume then, if ownership is configured, chowns/chmods the mount root once (run-once guard; optional setgid so subdirectories inherit the owner gid) inside a short-lived helper container. - ContainerSpec/ContainerBuilder gain withUser/withGroupAdd; wired into createContainerCmd.withUser and HostConfig.withGroupAdd. - EcsContainerManager initialises the EFS volume root via ensureSharedVolume before mounting it. Unit tests cover the no-op default (no helper container, no image pull), the one-off chown/chmod/setgid helper with the run-once guard, the builder round-trip, and the EcsContainerManager wiring. * fix(ecs): apply configured EFS PosixUser to containers mounting a shared volume Wire the previously-inert floci.storage.efs.mount-user / mount-group-add config into the ECS container spec: a container mounting an EFS-backed shared volume now runs under the configured uid[:gid] and adds the supplementary group, emulating the access point's PosixUser squashing. Without this a non-root image USER could not write a volume owned by owner-uid/owner-gid. Also add the floci.storage.efs.* section to application.yml (the source of truth for effective defaults) and correct the root-permissions Javadoc, which implied leaving it empty always skips volume init even when owner/setgid are set. * docs: regenerate action tables |
||
|
|
073e653d35 |
fix(docker): isolate managed resource containers (#1703)
* fix(docker): namespace managed resource containers * fix(rds): avoid containerized host path creation * fix(docker): isolate child container names * fix(opensearch): preserve legacy domain container names |
||
|
|
f490bbefad |
feat(rds): add mock mode to create clusters and instances without Docker (#1655)
* feat(rds): add mock mode to create clusters/instances without Docker Floci backs RDS clusters and instances with real Docker containers and an auth proxy. In CI or environments without access to the Docker socket, CreateDBCluster/CreateDBInstance fail, so the resources never reach an available state. Add FLOCI_SERVICES_RDS_MOCK (default false), mirroring the existing mock mode of EC2/EKS/ECS/OpenSearch/MSK. When enabled, cluster and instance creation skip the container and proxy and are registered as AVAILABLE immediately with a localhost endpoint; delete and runtime restoration likewise skip all Docker calls. Non-mock behavior is unchanged. * fix(rds): make rebootDbInstance mock-aware In mock mode, reboot skipped the container restart (guarded by a null containerId) but still started a real TCP auth proxy, breaking the no-container/no-proxy invariant. Gate the container restart and proxy start on !mock so a mock reboot only flips status back to AVAILABLE. * fix(rds): give mock resources unique ports and gate delete proxy stop Address PR review: mock mode hardcoded proxyBasePort for every cluster and instance, collapsing all endpoints onto localhost:7001 and leaving usedPorts unreserved. Allocate a unique proxy port even in mock mode (still skipping the container and auth proxy), and preserve/reserve the persisted port on restore instead of resetting it. Also gate proxyManager.stopProxy on !mock in the delete paths, matching the reboot path. Add tests for standalone-instance deletion in mock mode and for distinct mock endpoint ports. * fix(rds): skip Docker volume name for mock cluster members and document mode switching Review feedback from #1655: - Cluster member instances created in mock mode no longer persist a volume name fabricated from the cluster's null volume id, which a later non-mock restore could try to reference. - Document RDS mock mode on the service page, including that switching FLOCI_SERVICES_RDS_MOCK over persisted state is best-effort in both directions, matching the other mock-capable services. |
||
|
|
38bf55d323 |
feat(core): claim wire protocols reactively per Smithy selection guide (#1712)
* feat(core): claim wire protocols reactively per Smithy selection guide AWS services will adopt additional wire protocols without advance notice starting April 2026, so the protocol must be identified per request rather than assumed per service. Adds a ProtocolClaimer that claims each request from its non-payload signals (Smithy-Protocol header, content type, X-Amz-Target, method, path) in Smithy precision order, exposed to downstream filters by a pre-matching claim filter and consumed by the service-enablement filter in place of its duplicated sniffing. Also fixes smithy-rpc-v2 path routing: the service segment AWS SDKs send is the target prefix (Kinesis_20131202, DynamoDB_20120810, ...), not the SDK serviceId, so rpcv2 service names are now derived from the catalog's target prefixes and the path-based CBOR dispatcher gains the missing Kinesis case. Opt-in strict mode (FLOCI_PROTOCOLS_STRICT_CLAIMING) rejects RPC-signaled requests that no supported protocol claims, including the recognized but unimplemented rpc-v2-json. Default wire behavior is unchanged. Refs #156 * fix(core): scope Smithy-Protocol content-type normalization to rpcv2 paths The normalization filter runs before the path-rewriting filters, so rewriting Content-Type on arbitrary paths erased the signal filters like S3VirtualHostFilter use to bypass non-S3 management traffic. Only normalize POST requests whose path matches the rpcv2 shape — the only requests the rpcv2Cbor claim can succeed for. |
||
|
|
4f4e7be90e |
fix(iam): enforce STS session policies (#1636)
* test(iam): expose STS session policy S3 deny gap * fix(iam): enforce STS session policies ## Summary STS session policies were recorded on temporary credentials but IAM enforcement evaluated only the caller's identity policies. As a result, an assumed role with broad role permissions could still perform an action even when the inline `AssumeRole` session policy should have denied or narrowed it. This changes enforcement to evaluate the full caller context, including identity policies, session policies, and permission boundaries. It also keeps temporary-credential lookup account-independent so assumed-role sessions can be resolved after account routing moves the request into the role account, and it uses the resolved request account when building resource ARNs for policy evaluation. ## Type of change - [x] Bug fix (`fix:`) ## AWS Compatibility Incorrect behavior: STS `AssumeRole` accepted the standard inline `Policy` parameter, but later requests signed with those temporary credentials did not have that session policy applied by IAM enforcement. The fix matches AWS policy evaluation semantics: explicit denies in session policies participate in the deny pass, and a present session policy must also explicitly allow the request for the role's permissions to be effective. This preserves the existing Floci bypass behavior for unknown local credentials and the `test` root credential. ## What changed - `IamEnforcementFilter` resolves a `CallerContext` and evaluates the complete IAM context instead of identity-policy documents only. - `IamService` resolves STS sessions across account namespaces for caller context, caller ARN, account routing, and temporary secret lookup. - Enforcement resource ARN construction uses the request account already resolved by `AccountContextFilter`, so assumed-role credentials evaluate account-scoped resources against the role account. - IAM and multi-account docs now describe session-policy intersection and temporary-credential resolution accurately. - Java SDK compatibility coverage now checks that an assumed-role session policy deny overrides a role allow. ## Checklist - [x] `./mvnw test` passes locally - attempted; only failures were unrelated LambdaReactiveSyncIntegrationTest container startup Broken pipe errors - [x] Selected Java SDK compatibility tests pass locally - in `compatibility-tests/sdk-test-java`: `mvn -q -Dtest=IamEnforcementTest,IamTest,StsTest,S3Test test` - [x] New or updated integration test added - [x] Commit messages follow Conventional Commits * fix(iam): tighten cross-account session lookup |
||
|
|
fef03c6b0f |
fix(ec2): align AMI guest and launch template parity (#1597)
* fix(ec2): preserve launch template instance profiles * fix(ec2): skip networkd wait-online in AMI guests * feat(docker): add image registry override * fix(ec2): align launch template AMI parity * fix(docker): simplify registry base config handling * fix(docker): normalize registry base once |
||
|
|
f52b9209cf |
feat(iam): route assumed-role credentials to the target account (#1549)
* feat(iam): route assumed-role credentials to the target account Assumed-role temporary credentials (ASIA… keys) collapsed to the default account: account resolution only recognised 12-digit access key IDs and had no link to the STS session store. Cross-account "assume a role in account B, then provision" flows therefore landed resources in account 000000000000 instead of B. Add a SessionAccountLookup port in core.common, implemented by IamService, mapping a temporary access key to its account — the account in the session's role (or federated-user) ARN, or the caller account captured at mint time for role-less GetSessionToken credentials. AccountContextFilter now resolves with the precedence 12-digit AKID → session lookup → default, for both the Authorization header and the presigned X-Amz-Credential parameter. STS handlers record the caller account on every minted session, and SessionCredential gains an originAccountId field. The session lookup is account-independent, since sessions are keyed by a globally unique access key. IamService is now @Startup so AWS-managed policies seed under the default account at boot. Seeding is account-namespaced and AccountContextFilter now instantiates IamService to resolve the request account, so lazy seeding would otherwise bind managed policies to whichever account made the first request. Tests: unit coverage for resolver/filter precedence and session lookup, plus an integration test proving a table created with role-B credentials materialises in account B and is invisible to account A. * perf(iam): skip session-store scan for non-ASIA access keys Account resolution runs on every request. Gating the session lookup on the ASIA temporary-credential prefix keeps the common case (e.g. the 'test' default credential) off the session-store scan, which would otherwise grow with every issued session. * chore: re-trigger CI Unrelated flaky CodeBuildTest.batchGetBuilds_eventuallySucceeds; root-cause fix in floci-io/floci#1577. |
||
|
|
398535ed55 | feat(core): add opt-in Private Network Access for CORS preflights (#1530) |