* fix(eks): accept a role ARN from another partition the way STS does
An account keeps one IAM namespace whichever partition a request is for
(partitions.md, Known gaps). STS AssumeRole already resolved a role ARN
from another partition to the account's role, while EKS Pod Identity and
add-ons required the cluster's partition and an exact stored-ARN match.
Move the STS role-ARN matcher to IamService.roleArnMatches and use it for
the Pod Identity roleArn and the add-on role ARNs; targetRoleArn accepts
any well-formed partition. The Pod Identity session names the stored
role's ARN, as an STS session does. The EKS model sets no pattern on
roleArn or targetRoleArn.
* fix(eks): keep a role recreated under another path out of a pod identity session
The credentials endpoint finds the association's role by name only. Since
the session started naming the stored role's ARN, a role deleted and
recreated under another path gave the session its ARN and role id through
the old association. The found role now has to match the association's
role ARN the way roleArnMatches does everywhere else; one that does not is
treated as absent, as before this branch.
The association test also checks that a rejected role update leaves the
stored role ARN as it was.
* fix(eks): refuse pod identity credentials when the association's role is gone
EKS Auth assumes the association's role through STS, so a role that no
longer exists gets no credentials. The endpoint still issued them, and
since enforcement loads a session's policies by role name, a pod whose
role was recreated under another path ran with the replacement's policies.
A role that is missing, or that does not match the association's role ARN,
is now a 400 AccessDeniedException and no session is registered.
The k3s registries.yaml listed the default account across the regions of
the deployment's partition, so a cluster in another account, or in a region
of another partition served by the same process, could not pull from
Floci's ECR through its own repository hostnames.
Build the mirror from the cluster's account (then the default account)
across every region of the cluster's partition. A commercial cluster in
the default account gets the same file as before.
ECR built repositoryUri, the GetAuthorizationToken proxyEndpoint and
the Lambda and ECS image rewrites from floci.port, the port Floci
listens on inside its own container. The Docker daemon performs login,
push and pull, and reaches Floci through the host port that container
publishes. When Floci ran as docker run -p 54321:4566, every advertised
address named port 4566 on the host, where nothing answers, so docker
login, CDK container asset publishing and ECS or Lambda image pulls
failed.
EcrRegistryManager now has advertisedPort(): the host port Floci's
container publishes for floci.port, read through the existing
CurrentContainerNetworkResolver.resolvePublishedPort as RDS does for
its proxy endpoint, or floci.port when Floci is not in a container or
the port is not published. repositoryUri (hostname and path style,
plain and TLS URI mode), proxyEndpoint and rewriteImageUri all use it.
The EKS registry mirror keys must match the URIs pods name, so they
use the same advertised port. The mirror endpoint stays Floci's
in-network address on floci.port.
The resolver now caches every published-port answer, "not published"
and a failed inspect included, as it already caches the network: a
running container's port bindings cannot change, and an inspect that
fails fails the same way next time. ECR requests therefore do not
inspect the container each time.
Support joining real EC2 instances to an EKS cluster as Kubernetes nodes.
Inspect instance user data during RunInstances for bootstrap scripts or
nodeadm YAML targeting an EKS cluster, recording pending joins and
reconciling node registration asynchronously via the readiness poller.
Ensure RunInstances returns without blocking on kubectl or shared locks,
and guard storage mutations under the deletion lock so deleted clusters
cannot be resurrected. Scope restoration tracking per account.
Support AL2023 MIME multipart nodeadm configurations, and share the
in-use IP check and cursor loop between subnet and subnetless launches.
Update node metadata derivation to match AWS conventions, using instance
private DNS names for node names and aws:///<az>/<instance-id> for
provider IDs, with topology and instance-type labels.
* feat(eks): apply nodegroup labels, taints and capacity type to the node
* fix(eks): address review feedback on nodegroup metadata injection
* fix(docs): sync IAM operation count in service matrix
* fix(eks): use single string literals without concatenation in log messages
* chore(eks): resolve phantom nodegroup review finding
* docs(eks): document CAPACITY_BLOCK capacity type for nodegroups
* feat(eks): stop shipping a default storage class in clusters
* test(eks): verify coredns rollout status and preserve cluster storage on restore
* test(eks): assert storage class absence after coredns rollout completes
* docs(eks): clarify stock storage class and provisioner behavior
The EKS token webhook looked long-term keys up through findSecretKey,
which is account-scoped. k3s calls the webhook with no account routing,
so it saw only the default account's keys. A correctly signed
`aws eks get-token` from a user in any other account was rejected:
kubectl reported "the server has asked for the client to provide
credentials".
The webhook now uses a new IamService.findSecretKeyInAnyAccount. It
tries the request's account first and scans the other accounts only on
a miss. Inactive keys are still refused, and temporary (ASIA) keys never
reach the scan. findSecretKey itself stays account-scoped: the
ElastiCache, MemoryDB and RDS IAM-auth proxies verify through it and do
not compare the key's account with the cluster's.
Because a long-term key can now reach the webhook from any account, the
legacy identity (system:masters) is limited to long-term keys owned by the
cluster's account, or by the default account on unscoped webhook paths
that predate per-account clusters. This also tightens one existing case:
a default-account key used to get system:masters on clusters of every
account, and now gets it only on the default account's clusters.
Session credentials without an instance ID still map to the legacy
identity on any cluster; that predates this change and is left alone.
Co-authored-by: Robin Baeckman <27041454+RobinBaeckman@users.noreply.github.com>
* feat(eks): name cluster nodes after their EC2 instance
* fix(eks): prune legacy hostname nodes on finalize and test container recreation
* fix(eks): preserve active nodes when pruning legacy cluster nodes
* fix(eks): delimit jsonpath node records with newline outside condition range
* fix(eks): name nodes using EC2 private DNS name format and align synthetic instance
* fix(eks): implement DnsRecordSource to resolve node private DNS names
* fix(eks): prevent VPC forwarding rules from bypassing node private DNS resolution
* fix(eks): scope node DNS system rules to matching VPC only
* feat(eks): support per-cluster kubelet and API server arguments
* fix(eks): prevent security group leak and reject authorization-mode override
* refactor(eks): classify authorization-mode as refused argument
* fix(eks): strip modifier suffixes before collision validation
* feat(eks): bound cluster node capacity and reserve kubelet resources
* fix(eks): use the large managed node pod cap
* fix(eks): preserve node capacity through restart failures and restores
* fix(eks): retain restored node until capacity replacement starts
* fix(eks): let concurrent node groups share user data execution
* fix(eks): finalize first node group after bootstrap
* fix(eks): retain restored replacement when backup cleanup fails
* fix(eks): stop live node before retrying backup cleanup
* ci: retry transient mqtt port collision
* fix(eks): preserve cluster API port during node capacity change
* test(docker): verify exec attach stream closes on timeout
* fix(eks): keep capacity backup names outside cluster namespace
Program static kernel routes in EKS cluster containers from emulated
VPC route tables associated with the cluster subnets or VPC.
- Implement route table resolution for cluster VPC and subnets
- Resolve EC2 instance and network interface targets to reachable IPs
- Generate idempotent routing shell commands using ip route
- Attach cluster containers to the VPC bridge network when present
- Notify active clusters on route table modifications via VpcRouteTableListener
- Add configuration flag floci.services.eks.vpc-route-programming
- Add unit and Docker integration tests for route programming
Implement DnsRecordSource SPI via Route53DnsRecordSource to decouple Route 53 resolution from EmbeddedDnsServer. Add DnsLookupHelper in core.common.dns for external IPv4 resolution via upstream forwarders with system fallback, shared by Route53DnsRecordSource for CNAME and ALIAS chasing. Discover private hosted zones via Route53Service and support in-zone chasing, built-in Floci suffixes, and EC2 internal names. Authoritatively resolve A records within private zones to prevent upstream query leakage. Wire EKS cluster containers to embedded DNS via specBuilder.withEmbeddedDns().
* feat(ec2): expose synthesized cluster node instances to the EC2 service
* fix(ec2): enforce account isolation and tag persistence for cluster node instances
* fix(ec2): scope findInstanceById to caller account for external instances
Scope findInstanceById to the caller account when falling back to
external instances instead of matching across all accounts. Thread
the account identifier into SSM direct command execution, ELBv2 target
resolution, and classic ELB health checking so external cluster nodes
remain strictly account-isolated across all instance lookup paths.
* fix(ssm,eks): update test stubs for account-scoped direct execution and harden cluster provider
Validate node group launchTemplate specifications against EC2 during
CreateNodegroup. Reject requests where neither or both of id and name
are supplied, or where the referenced launch template or version does
not resolve in EC2, with InvalidParameterException (400). Resolve
launch templates and construct nodegroup ARNs using the cluster's region
rather than the default region.
* feat(eks): serve pod identity credentials on 169.254.170.23
* fix(eks): safely handle cluster arn and initialize test cluster in pod identity integration test
* test(eks): configure fixed test port for pod identity docker integration test
* fix(eks): isolate pod routing and restore webhook timeout
* feat(eks): inject pod identity credentials through a mutating webhook
Each real-mode cluster gets a MutatingWebhookConfiguration in its k3s
server manifests directory, scoped to pod CREATE and pointing at a
per-cluster, per-account Floci endpoint. On a pod create Floci looks up
an association matching the pod's namespace and service account name
and, when the eks-pod-identity-agent addon is installed, returns a
JSONPatch carrying the projected token volume, the mount and the two
container credentials environment variables, the same shape real EKS
injects. A pod that matches nothing is admitted unchanged.
The webhook carries failurePolicy: Ignore and every path through the
admission handler admits the pod, including a malformed review and an
internal error, so it can never block a pod from being created.
Kubernetes only accepts an https webhook URL with a caBundle it trusts,
so registration needs floci.tls.enabled; with TLS off the cluster starts
with a warning and pods are not mutated. A failed registration logs and
leaves the cluster running.
Nothing answers http://169.254.170.23/v1/credentials yet, so an injected
pod still cannot obtain credentials.
* fix(eks): default the pod identity webhook off until the credential endpoint exists
Injecting AWS_CONTAINER_CREDENTIALS_FULL_URI sends the SDK down the
container credentials path, and nothing answers that URI yet, so a
workload that was picking up credentials earlier in the chain loses
them. On by default that is a regression for anyone already recording
associations, in exchange for a capability that cannot work. Turning it
off also takes the per-cluster warning off a default install.
The webhook timeout drops from the Kubernetes default of 10 seconds to
3. Floci is a local process, so a healthy call takes milliseconds and
the timeout only runs down when Floci is unreachable, which every pod
creation in the cluster pays for.
CreateNodeGroupRequest modelled 14 of the 19 documented CreateNodegroup body
members. The other five were discarded by @JsonIgnoreProperties during
deserialization, so DescribeNodegroup omitted them and OpenTofu saw a node group
with no launch template where one was declared. Adding a launch template to a
node group that lacks one is ForceNew in the AWS provider schema, so every plan
destroyed and recreated the node group.
The five are added to the request as Object and copied onto the stored node
group, matching the generic JSON passthrough convention Nodegroup already
records for recursive sub-structures. warmPoolConfig was also missing from
Nodegroup itself and is added there too.
They are recorded as metadata only. Launch template user data is not executed.
Pods running without hostNetwork: true run in isolated network namespaces
managed by the CNI plugin (e.g. flannel in k3s). When pods send requests
to link-local addresses such as IMDS (169.254.169.254:80), the packets reach
the host node network namespace where CNI portmap installed
-A PREROUTING -m addrtype --dst-type LOCAL -j CNI-HOSTPORT-DNAT.
Because 169.254.169.254 is assigned to lo, the kernel evaluates its addrtype
as LOCAL, causing non-host-network pods to misroute or drop link-local traffic
if an ingress controller binds the same port.
This introduces EksPodNetworkRouting and an opt-in configuration setting
floci.services.eks.imds-pod-network (defaulting to false to preserve default
pod network isolation). When enabled alongside floci.services.eks.imds,
DNAT iptables rules are programmed in a dedicated FLOCI-LINK-LOCAL chain
inserted at rule 1 of PREROUTING. Requests originating from the cluster pod CIDR
targeting configured link-local endpoints (such as IMDS at 169.254.169.254:80,
and extensible for Pod Identity at 169.254.170.23:80) are explicitly DNATed
to the node's loopback listener, preempting CNI-HOSTPORT-DNAT without
conflicting with CNI portmap or flannel routing.
LinkLocalEndpoint strictly validates IPv4 literal format to reject non-IPs
or malformed strings. Rules are idempotent and degrade gracefully if iptables
configuration fails, ensuring cluster startup is never aborted.
Support standard AWS EKS Kubernetes versions (1.28 and above) with strict
1.xx validation format, mapped to stable k3s images when requested. Fall
back to default-image (with 1.29 cluster version metadata) when no version
is specified. Support service IPv4 CIDR validation (RFC 1918 containment,
/12 to /24 prefix, non-overlapping with VPC CIDR) with automatic fallback
to alternative CIDR, and preserve standard k3s pod CIDR to avoid collisions
with Docker networks.
* fix(eks): populate clusterSecurityGroupId on cluster responses
Real AWS EKS automatically provisions a cluster security group and
returns its identifier in resourcesVpcConfig.clusterSecurityGroupId
on CreateCluster and DescribeCluster responses.
- Create a security group in Ec2Service with the pattern
eks-cluster-sg-<cluster-name>-<suffix> using 8 hex characters.
- Set standard AWS description and tags (Name, kubernetes.io/cluster/<cluster-name>,
and aws:eks:cluster-name).
- Set clusterSecurityGroupId to empty string when cluster has no VPC.
- Delete the cluster security group on DeleteCluster, tolerating
InvalidGroup.NotFound for idempotency.
- Backfill cluster security groups for pre-existing clusters on startup.
* fix(eks): address cluster security group review feedback
* fix(eks): add self-referencing egress rule and cleanup on SG setup failure
* feat(eks): sign k3s service account tokens with the cluster OIDC key
In real EKS, workloads authenticate via IAM Roles for Service Accounts (IRSA) using projected tokens signed by the cluster OIDC key with audience sts.amazonaws.com. In Floci, k3s launches with default signing flags, meaning it signs in-cluster pod tokens using its own internal auto-generated key under https://kubernetes.default.svc.cluster.local. Because Floci STS verifies tokens against Floci's per-cluster OIDC key and issuer, in-cluster pod tokens cannot be verified, forcing local workloads to use static credentials instead of IRSA.
To bridge this gap, Floci now passes the cluster's per-cluster OIDC keypair and issuer to the k3s container on cluster start and restore. EksClusterManager exports the cluster keypair as restrictive PEM files (0600) into /etc/rancher/k3s/ and configures kube-apiserver with signing keys, dual issuers, and dual audiences (https://kubernetes.default.svc.cluster.local and sts.amazonaws.com). Projected pod tokens now verify cleanly against Floci STS, while internal cluster components continue operating without disruption.
* fix(eks): isolate IRSA signing key files by account and region
Persist cluster OIDC signing keypairs under dataPath/keys/<accountId>/<region>/<clusterName> instead of only clusterName. Because EKS cluster names are unique only within an account and region, same-named clusters across different accounts or regions previously shared host key files, risking key overwrite during startup or restore.
* fix(eks): create signing key files with atomic owner-only permissions
Create the signing key and public key files with PosixFilePermissions rw------- atomically on creation via Files.createFile, avoiding any brief window where private key material is readable with default umask permissions.
* fix(eks): guard webhookPath against null cluster ARN and createdAt
Safely resolve accountId, region, and createdAt with fallbacks in webhookPath when cluster fields are null, and ensure integration tests populate cluster ARN and createdAt.
* feat(eks): expose IMDS on 169.254.169.254 inside cluster containers
When applications or agents run on Kubernetes nodes or use hostNetwork: true, they expect the AWS Instance Metadata Service (IMDS) at the standard link-local address 169.254.169.254:80. In Floci, EKS k3s cluster containers lacked access to IMDS at this link-local address, preventing workloads from discovering instance identities, node IAM roles, or dynamic cluster credentials without custom endpoint overrides.
This change exposes IMDS on 169.254.169.254:80 inside EKS cluster containers when floci.services.eks.imds is enabled. It configures a background TCP relay via socat pointing to the host's EC2 metadata port, registers a synthesized EC2 node instance with the cluster's IAM role and container IP in Ec2MetadataServer, extracts reusable metadata proxy logic into Ec2MetadataProxy, and documents node network namespace reachability and hop limit handling.
* fix(eks): address review feedback on lifecycle check, default flag, and instance seed
* fix(eks): synthesize distinct node instance profile and import CompletableFuture
* test(eks): enable IMDS profile and provide curl in docker test fixture
Route Docker Distribution traffic through Floci so repository mutability applies to manifest writes. Keep legacy registry storage reachable while moving public ECR endpoints to the guarded listener.
* fix(sts): return ExpiredTokenException for an expired web identity token
AssumeRoleWithWebIdentity mapped every WebIdentityTokenVerifier failure to
InvalidIdentityToken, so an expired but otherwise valid IRSA token got the
same wire error as a bad signature or wrong issuer. Real STS reports the
expiry case as ExpiredTokenException so callers can refresh and retry.
Fixes#3205
* test(eks): inject EksOidcService through the test constructor
* feat(eks): support IRSA with a real OIDC issuer and JWT validation
Every EKS cluster now gets an OIDC identity provider, so the full IRSA flow
works end to end without mocked or hardcoded tokens.
CreateCluster generates an RSA-2048 keypair and an AWS-shaped issuer URL,
returned by DescribeCluster as identity.oidc.issuer. The issuer is a faithful
string for building trust policies but is never dereferenced: STS resolves the
signing key in-process via a new OidcIssuerKeyLookup port, declared in
core.common so services.iam does not depend on services.eks.
Key material lives in storage separate from the Cluster model. Cluster is
serialized straight onto the DescribeCluster wire response, so a private key
carried there would leak; @JsonIgnore would instead lose it across restarts and
break tokens minted earlier.
sts:AssumeRoleWithWebIdentity previously accepted any non-blank token and
returned a hardcoded subject. It now verifies, but only for issuers Floci hosts:
- RS256 signature against the cluster's public key
- iss matches the issuer exactly
- aud contains sts.amazonaws.com
- exp / nbf, with 60s of clock-skew tolerance
- the role's trust policy, via a new WebIdentityTrustPolicyEvaluator matching
Principal.Federated and the Condition block
The response now carries the token's real claims in
SubjectFromWebIdentityToken, Provider, and Audience. Bad tokens return
InvalidIdentityToken (400); a trust policy that does not permit the subject
returns AccessDenied (403) — a check the web-identity path was missing entirely.
Tokens from an issuer Floci does not host stay permissive, since Floci cannot
verify a third-party signature. Existing behaviour is therefore unchanged and no
configuration flag is required.
WebIdentityTrustPolicyEvaluator is a sibling of AssumeRolePolicyEvaluator rather
than an extension of it: that evaluator serves sts:AssumeRole, hardcodes that
action, reads only Principal.AWS, and ignores conditions. Condition values are
compared with exact, case-sensitive equality instead of the existing
globMatches, which lowercases both operands — case-folding an OIDC subject would
silently admit a different service account.
Because Floci has no kubelet to project a token into a pod, a local-dev harness
can mint one via POST _floci/eks/clusters/{name}/oidc-token and write it to the
file named by AWS_WEB_IDENTITY_TOKEN_FILE. Signing stays server-side so the
private key never leaves Floci. OIDC discovery and JWKS routes are served under
the same _floci namespace, for fidelity rather than because anything fetches
them; the AWS-shaped issuer path is not resolvable by Floci's embedded DNS and
would collide with S3's path-style catch-all.
Adds 51 tests: unit coverage for the verifier, the trust-policy evaluator, and
the OIDC service, plus an end-to-end integration test covering the mint ->
assume -> credentials path and its negative cases (wrong service account,
tampered signature, wrong audience, expired, alg:none).
* fix(iam): close two web-identity validation gaps and backfill cluster OIDC state
Three defects found in review of the IRSA change.
An unsigned "header.payload." token bypassed validation entirely. verify()
split with a -1 limit so a trailing empty segment was preserved, but
parseClaims() — which backs peekIssuer() — did not. Java drops trailing empty
strings by default, so such a token split into two parts, its issuer went unseen,
and STS classified it as an opaque third-party token: signature, claim, and
trust-policy checks were all skipped and credentials were issued for a JWT that
was never signed. Both split sites now pass -1.
StringLike and StringNotLike on an OIDC condition key folded case. They
delegated to IamPolicyEvaluator.globMatches, which lowercases both operands, so
a trust policy scoped to one service account or namespace would admit another
differing only in case — the exact hazard the StringEquals branch was written to
avoid. Adds a case-sensitive glob and uses it for both operators. Action matching
still uses globMatches, which is correctly case-insensitive.
Clusters persisted before this feature never gained an issuer or key, so after an
upgrade DescribeCluster reported no identity.oidc.issuer, minting returned 400,
and the JWKS routes 404'd until the cluster was recreated. EksService now
backfills on startup, and re-runs ensureKey for clusters that already have an
issuer so a restart cannot leave a known issuer without its signing key.
Each fix has a regression test confirmed to fail without it.
* fix(eks): keep IRSA OIDC state scoped to the cluster's owning account
The startup backfill read clusters across every account via scanAllAccounts() but
wrote them back with the request-scoped put(), which resolves to the default
account outside a request context. A cluster owned by any other account kept its
issuer-less record while a duplicate appeared under the default account, leaving
DescribeCluster and the IRSA endpoints broken for the owner. The backfill now
takes the account from the cluster record and writes with putForAccount, per the
pattern StorageFactory documents for work running outside a request.
The same root cause affected key lookup more seriously. findVerificationKey used
the account-scoped scan(), so an issuer owned by a non-default account went
unresolved — and an unresolved issuer is treated as a third-party provider, so
STS accepted the token with no signature, claim, or trust-policy check at all.
It now scans every account, which is correct regardless: an issuer URL is
globally unique, and the account calling AssumeRoleWithWebIdentity need not be
the one that owns the cluster.
deleteKey and findKeyByCluster stay account-scoped; both are only reached from
request-scoped paths (DeleteCluster and the JWKS route), where the caller's
account is the right scope.
Both fixes have a regression test confirmed to fail without them.
k3s containerd could not reach the emulated ECR registry: repository
URIs embed localhost plus the host-published port, which resolves to the
k3s container itself, and containerd requires a registries.yaml entry
before it will speak plain HTTP to a registry.
New clusters now get a generated /etc/rancher/k3s/registries.yaml,
injected through the Docker API before the container starts, that
mirrors every repository hostname the emulator can mint (the default
account across the region catalog, plus the path-style form) to the
registry container's in-network endpoint. Public registries are never
matched, and any failure skips the mirror without aborting cluster
creation. Opt out with FLOCI_SERVICES_EKS_ECR_REGISTRY_MIRROR=false.
Closes#1761
In real mode `aws eks create-cluster` brought up a k3s container that was
unreachable from the host and rejected every request with 401. This makes the
native AWS workflow work end to end (`aws eks update-kubeconfig` + `kubectl`).
- describe-cluster returns a host-reachable endpoint (https://localhost:<hostPort>),
configurable via endpoint-mode (host|network), default host
- token-authentication webhook (POST /_floci/eks/token-webhook) validates the
`aws eks get-token` bearer token and maps it to system:masters; pins the
apiserver to the v1 TokenReview API and echoes the request apiVersion
- webhook kubeconfig is injected into k3s via the Docker API (create -> copy ->
start), so it works in native and Docker-in-Docker with no host-path config
- k3s network falls back to the global docker-network, then auto-detected
Closes#1118
* docs: update Docker image references to floci/floci
* docs: keep README Docker Hub badges pointing to hectorvent/floci
The hectorvent/floci image has accumulated pull and size metrics; switch
the badges to floci/floci once the new image has comparable numbers.