diff --git a/docs/services/eks.md b/docs/services/eks.md index 2e5d5110c1..e3c82a2697 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -146,6 +146,93 @@ services: FLOCI_SERVICES_EKS_MOCK: "true" ``` +## IRSA (IAM Roles for Service Accounts) + +Every cluster gets an OIDC identity provider, so the full IRSA flow (trust policy, service-account token, `sts:AssumeRoleWithWebIdentity`) works end to end without mocked or hardcoded tokens. + +`CreateCluster` generates an RSA-2048 signing keypair and an AWS-shaped issuer URL, returned by `DescribeCluster`: + +```json +{ + "cluster": { + "name": "my-cluster", + "identity": { "oidc": { "issuer": "https://oidc.eks.us-east-1.amazonaws.com/id/3F8A…" } } + } +} +``` + +The issuer URL is a faithful string for building trust policies, but it is not fetched: Floci's STS resolves the signing key in-process. The private key is held in storage separate from the cluster model and is never returned by any API. + +### Minting a service-account token + +Real EKS has the kubelet project a token into the pod. Floci has no kubelet, so a local-dev harness requests one and writes it to the file named by `AWS_WEB_IDENTITY_TOKEN_FILE`. Signing happens server-side, so the private key never leaves Floci. + +```bash +curl -sX POST http://localhost:4566/_floci/eks/clusters/my-cluster/oidc-token \ + -H 'Content-Type: application/json' \ + -d '{"namespace":"my-namespace","serviceAccount":"my-service-account"}' +``` + +```json +{ + "token": "eyJhbGciOiJSUzI1NiIs…", + "issuer": "https://oidc.eks.us-east-1.amazonaws.com/id/3F8A…", + "subject": "system:serviceaccount:my-namespace:my-service-account", + "audience": "sts.amazonaws.com" +} +``` + +`audience` (default `sts.amazonaws.com`) and `expirySeconds` (default 24h, max 7d) are optional. +This is Floci plumbing under `_floci/…`, not an AWS API. + +### Trust policy + +Note that the OIDC provider ARN and the condition keys use the issuer with the scheme stripped `oidc.eks..amazonaws.com/id/`, which is how the AWS console, `eksctl`, and Terraform all render it. + +```json +{ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Principal": { + "Federated": "arn:aws:iam::000000000000:oidc-provider/" + }, + "Action": "sts:AssumeRoleWithWebIdentity", + "Condition": { + "StringEquals": { + ":sub": "system:serviceaccount::", + ":aud": "sts.amazonaws.com" + } + } + }] +} +``` + +### What STS validates + +When `sts:AssumeRoleWithWebIdentity` receives a token whose `iss` names an issuer Floci hosts, it enforces all of: + +- the RS256 signature, against that cluster's public key +- `iss` matches the cluster's issuer exactly +- `aud` contains `sts.amazonaws.com` +- `exp` / `nbf`, with 60s of clock-skew tolerance +- the role's trust policy: `Principal.Federated` and the `Condition` block, comparing `oidc:sub` / `oidc:aud` with exact, case-sensitive equality + +The response then carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. Failures return `InvalidIdentityToken` (400) for a bad token or `AccessDenied` (403) when the trust policy does not permit the subject. + +A token whose issuer Floci does not host is treated as opaque and accepted, since Floci cannot adjudicate a third-party provider. Validation is therefore automatic for Floci-issued tokens and requires no configuration flag. + +### OIDC discovery endpoints + +Served for fidelity and debugging, nothing in the IRSA flow dereferences them: + +| Route | Description | +|---|---| +| `GET /_floci/eks/clusters//oidc/.well-known/openid-configuration` | OIDC discovery document | +| `GET /_floci/eks/clusters//oidc/keys` | JWKS containing the cluster's public key | + +These live under `_floci/…` rather than at the AWS-shaped issuer path, which Floci's embedded DNS does not resolve and which would collide with S3's path-style routing. + ## ARN Format ``` diff --git a/docs/services/sts.md b/docs/services/sts.md index b71b42649f..f79735c0f7 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -32,12 +32,29 @@ created through IAM with a real trust policy. ### Known limitations -- **`Condition` blocks are not evaluated.** A trust policy that requires `sts:ExternalId` (the - confused-deputy guard) is matched on its principal alone, so the role is assumable without passing - `ExternalId`, and the `ExternalId` request parameter is ignored. This matches moto/LocalStack. +- **`Condition` blocks are not evaluated for `AssumeRole`.** A trust policy that requires + `sts:ExternalId` (the confused-deputy guard) is matched on its principal alone, so the role is + assumable without passing `ExternalId`, and the `ExternalId` request parameter is ignored. This + matches moto/LocalStack. Conditions *are* evaluated on the `AssumeRoleWithWebIdentity` path (see below). - **Only the trust policy is checked.** Cross-account `AssumeRole` in AWS also requires the caller's own identity policy to allow `sts:AssumeRole`; that side is not enforced. +## Web Identity Validation (IRSA) + +`AssumeRoleWithWebIdentity` validates tokens minted by an OIDC issuer Floci hosts - currently an EKS cluster's IRSA provider. This needs no configuration flag and is independent of `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED`. + +When the token's `iss` names a known Floci issuer, all of the following are enforced: + +- the RS256 signature, against the issuer's public key +- `iss` matches that issuer exactly +- `aud` contains `sts.amazonaws.com` +- `exp` / `nbf`, with 60s of clock-skew tolerance +- the role's trust policy — `Principal.Federated` plus the `Condition` block, comparing `:sub` and `:aud` with exact, **case-sensitive** equality (`StringEquals`, `StringNotEquals`, `StringLike`, and `StringNotLike` are supported) + +The response carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. A bad token returns `InvalidIdentityToken` (400); a trust policy that does not permit the subject returns `AccessDenied` (403). + +Tokens from an issuer Floci does not host are treated as opaque and accepted, since Floci cannot verify a third-party provider's signature. See [EKS](eks.md) for the full IRSA walkthrough and the token-minting endpoint. + ## Examples ```bash diff --git a/src/main/java/io/github/hectorvent/floci/core/common/OidcIssuerKeyLookup.java b/src/main/java/io/github/hectorvent/floci/core/common/OidcIssuerKeyLookup.java new file mode 100644 index 0000000000..791df7eae1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/OidcIssuerKeyLookup.java @@ -0,0 +1,24 @@ +package io.github.hectorvent.floci.core.common; + +import java.security.interfaces.RSAPublicKey; +import java.util.Optional; + +/** + * Port that maps an OIDC issuer URL to the public key that signs its tokens. + * + *

Declared in {@code core.common} so the STS handler (which lives in + * {@code services.iam}) can verify {@code sts:AssumeRoleWithWebIdentity} tokens minted for an + * EKS cluster's IRSA issuer without {@code services.iam} depending on {@code services.eks}. + * + *

An empty result means the issuer is unknown to Floci. Callers treat that as "not a + * Floci-issued token" and fall back to permissive handling rather than rejecting, so + * third-party web-identity tokens keep working. + */ +public interface OidcIssuerKeyLookup { + + /** + * Returns the RSA public key for {@code issuer}, or {@link Optional#empty()} if no + * resource known to Floci issues tokens under that issuer URL. + */ + Optional findVerificationKey(String issuer); +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityToken.java b/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityToken.java new file mode 100644 index 0000000000..08b6ff8220 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityToken.java @@ -0,0 +1,13 @@ +package io.github.hectorvent.floci.core.common; + +import java.util.List; + +/** + * The verified claims of a web-identity JWT. + * + * @param issuer the {@code iss} claim + * @param subject the {@code sub} claim. For IRSA, {@code system:serviceaccount::} + * @param audiences the {@code aud} claim, normalized to a list (JWT allows string or array) + */ +public record WebIdentityToken(String issuer, String subject, List audiences) { +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifier.java b/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifier.java new file mode 100644 index 0000000000..80b8c7fcb7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifier.java @@ -0,0 +1,190 @@ +package io.github.hectorvent.floci.core.common; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Optional; + +import org.jboss.logging.Logger; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +/** + * Verifies RS256-signed web-identity JWTs against a Floci-known OIDC issuer. + * + *

Deliberately hand-rolled rather than pulling in a JOSE library: Floci already signs Cognito + * JWTs with plain {@code java.security} primitives, and this only needs the one algorithm EKS IRSA + * uses. + * + *

Two-stage design, which is what keeps existing permissive behaviour intact. {@link #peekIssuer} + * reads the {@code iss} claim without verifying anything, so a caller can ask "is this a + * token Floci issued?" before deciding to enforce. Only when the issuer resolves to a known key does + * {@link #verify} run and reject on any failure. + */ +@ApplicationScoped +public class WebIdentityTokenVerifier { + + private static final Logger LOG = Logger.getLogger(WebIdentityTokenVerifier.class); + + /** Tolerance for clock drift between Floci and a token minted elsewhere. */ + private static final long CLOCK_SKEW_SECONDS = 60; + + private final ObjectMapper objectMapper; + + @Inject + public WebIdentityTokenVerifier(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + /** Thrown when a token claiming a Floci-known issuer fails verification. */ + public static class InvalidTokenException extends Exception { + public InvalidTokenException(String message) { + super(message); + } + } + + /** + * Reads the {@code iss} claim without verifying the signature. Returns empty when {@code token} + * is not a parseable JWT at all — the caller then treats it as an opaque third-party token. + */ + public Optional peekIssuer(String token) { + return parseClaims(token).map(claims -> claims.path("iss").asText(null)) + .filter(iss -> iss != null && !iss.isBlank()); + } + + /** + * Fully verifies {@code token}: RS256 signature against {@code publicKey}, {@code iss} equal to + * {@code expectedIssuer}, {@code aud} containing {@code requiredAudience}, and {@code exp}/ + * {@code nbf} within {@link #CLOCK_SKEW_SECONDS}. + * + *

Claim comparisons are exact and case-sensitive, matching AWS treatment of OIDC claims. + */ + public WebIdentityToken verify(String token, RSAPublicKey publicKey, String expectedIssuer, + String requiredAudience) throws InvalidTokenException { + // Limit -1 keeps trailing empty segments, so an unsigned "header.payload." token is seen as + // three parts and rejected by the algorithm check below rather than as malformed. + String[] parts = token == null ? new String[0] : token.split("\\.", -1); + if (parts.length != 3) { + throw new InvalidTokenException("The web identity token is not a well-formed JWT"); + } + + JsonNode header = decodeJson(parts[0]) + .orElseThrow(() -> new InvalidTokenException("The web identity token header is not valid JSON")); + String alg = header.path("alg").asText(""); + if (!"RS256".equals(alg)) { + throw new InvalidTokenException("Unsupported web identity token algorithm: " + + (alg.isEmpty() ? "none" : alg)); + } + + if (!signatureValid(parts[0] + "." + parts[1], parts[2], publicKey)) { + throw new InvalidTokenException("The web identity token signature is invalid"); + } + + JsonNode claims = decodeJson(parts[1]) + .orElseThrow(() -> new InvalidTokenException("The web identity token payload is not valid JSON")); + + String issuer = claims.path("iss").asText(null); + if (issuer == null || !issuer.equals(expectedIssuer)) { + throw new InvalidTokenException("The web identity token issuer does not match the " + + "OIDC provider: " + issuer); + } + + List audiences = readAudiences(claims); + if (!audiences.contains(requiredAudience)) { + throw new InvalidTokenException("The web identity token audience does not include " + + requiredAudience); + } + + verifyValidityWindow(claims); + + String subject = claims.path("sub").asText(null); + if (subject == null || subject.isBlank()) { + throw new InvalidTokenException("The web identity token has no subject claim"); + } + + return new WebIdentityToken(issuer, subject, audiences); + } + + private void verifyValidityWindow(JsonNode claims) throws InvalidTokenException { + long now = Instant.now().getEpochSecond(); + + JsonNode exp = claims.get("exp"); + if (exp == null || !exp.isNumber()) { + throw new InvalidTokenException("The web identity token has no expiration claim"); + } + if (now > exp.asLong() + CLOCK_SKEW_SECONDS) { + throw new InvalidTokenException("The web identity token has expired"); + } + + JsonNode nbf = claims.get("nbf"); + if (nbf != null && nbf.isNumber() && now + CLOCK_SKEW_SECONDS < nbf.asLong()) { + throw new InvalidTokenException("The web identity token is not yet valid"); + } + } + + private boolean signatureValid(String signingInput, String encodedSignature, RSAPublicKey publicKey) { + try { + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initVerify(publicKey); + signature.update(signingInput.getBytes(StandardCharsets.UTF_8)); + return signature.verify(Base64.getUrlDecoder().decode(encodedSignature)); + } catch (GeneralSecurityException | IllegalArgumentException e) { + // A malformed signature segment or a key/algorithm mismatch both mean "not verifiable", + // which is a rejection rather than a server fault. + LOG.debugv("Web identity token signature check failed: {0}", e.getMessage()); + return false; + } + } + + private List readAudiences(JsonNode claims) { + List audiences = new ArrayList<>(); + JsonNode aud = claims.get("aud"); + if (aud == null) { + return audiences; + } + if (aud.isTextual()) { + audiences.add(aud.asText()); + } else if (aud.isArray()) { + for (JsonNode entry : aud) { + if (entry.isTextual()) { + audiences.add(entry.asText()); + } + } + } + return audiences; + } + + private Optional parseClaims(String token) { + if (token == null || token.isBlank()) { + return Optional.empty(); + } + // Limit -1 for the same reason as verify(): without it an unsigned "header.payload." token + // splits into two parts, so its issuer would go unseen and the caller would treat a token + // that names a Floci issuer as opaque, skipping validation entirely. + String[] parts = token.split("\\.", -1); + return parts.length == 3 ? decodeJson(parts[1]) : Optional.empty(); + } + + private Optional decodeJson(String base64UrlSegment) { + try { + byte[] decoded = Base64.getUrlDecoder().decode(base64UrlSegment); + JsonNode node = objectMapper.readTree(decoded); + return node != null && node.isObject() ? Optional.of(node) : Optional.empty(); + } catch (IllegalArgumentException | IOException e) { + // Not base64url, or not JSON. Callers treat an empty result as "unparseable segment", + // which is a normal outcome when the token came from something other than Floci. + LOG.debugv("Could not decode web identity token segment: {0}", e.getMessage()); + return Optional.empty(); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java new file mode 100644 index 0000000000..663aac8b4b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java @@ -0,0 +1,265 @@ +package io.github.hectorvent.floci.services.eks; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +/** + * Owns the RSA signing material behind each EKS cluster's IRSA OIDC issuer, mints service-account + * tokens for it, and resolves issuer URLs back to a verification key for STS. + * + *

The issuer URL is AWS-shaped ({@code https://oidc.eks..amazonaws.com/id/}) and + * deliberately cosmetic: nothing dereferences it. Real IRSA has STS fetch the JWKS, but Floci's STS + * resolves the key in-process through {@link OidcIssuerKeyLookup}, so the URL only has to be a + * faithful string for trust-policy construction. + */ +@ApplicationScoped +public class EksOidcService implements OidcIssuerKeyLookup { + + private static final Logger LOG = Logger.getLogger(EksOidcService.class); + + public static final String STS_AUDIENCE = "sts.amazonaws.com"; + private static final int DEFAULT_TOKEN_LIFETIME_SECONDS = 86400; + private static final int MAX_TOKEN_LIFETIME_SECONDS = 604800; + + private final StorageBackend keyStore; + private final ObjectMapper objectMapper; + + @Inject + public EksOidcService(StorageFactory storageFactory, ObjectMapper objectMapper) { + this.keyStore = storageFactory.create("eks", "eks-oidc-keys.json", + new TypeReference>() { + }); + this.objectMapper = objectMapper; + } + + /** + * Builds the issuer URL for a newly created cluster. The random id mirrors the 32-hex-character + * identifier real EKS embeds in the issuer path. + */ + public String newIssuerUrl(String region) { + String id = UUID.randomUUID().toString().replace("-", "").toUpperCase(); + return "https://oidc.eks." + region + ".amazonaws.com/id/" + id; + } + + /** + * Generates and stores the cluster's signing keypair if absent, returning the stored material. + * Keyed by cluster name so {@code DeleteCluster} can drop it. + */ + public synchronized ClusterOidcKey ensureKey(String clusterName, String issuer) { + return ensureKey(null, clusterName, issuer); + } + + /** + * As {@link #ensureKey}, but scoped to an explicit account. Startup and other work running + * without a request context must pass the owning account from the cluster record, since the + * request-scoped store would otherwise resolve to the default account. + */ + public synchronized ClusterOidcKey ensureKeyForAccount(String accountId, String clusterName, + String issuer) { + return ensureKey(accountId, clusterName, issuer); + } + + private ClusterOidcKey ensureKey(String accountId, String clusterName, String issuer) { + Optional existing = readKey(accountId, clusterName); + if (existing.isPresent() && issuer.equals(existing.get().getIssuer())) { + return existing.get(); + } + + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + + ClusterOidcKey key = new ClusterOidcKey( + issuer, + UUID.randomUUID().toString(), + Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()), + Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); + writeKey(accountId, clusterName, key); + LOG.debugv("Generated IRSA OIDC signing key for EKS cluster {0}", clusterName); + return key; + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("Failed to generate EKS OIDC signing keypair for cluster " + + clusterName + ": RSA unavailable", e); + } + } + + private Optional readKey(String accountId, String clusterName) { + if (accountId != null && keyStore instanceof AccountAwareStorageBackend aware) { + return aware.getForAccount(accountId, clusterName); + } + return keyStore.get(clusterName); + } + + private void writeKey(String accountId, String clusterName, ClusterOidcKey key) { + if (accountId != null && keyStore instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(accountId, clusterName, key); + return; + } + keyStore.put(clusterName, key); + } + + public void deleteKey(String clusterName) { + keyStore.delete(clusterName); + } + + public Optional findKeyByCluster(String clusterName) { + return keyStore.get(clusterName); + } + + @Override + public Optional findVerificationKey(String issuer) { + if (issuer == null || issuer.isBlank()) { + return Optional.empty(); + } + // Scans every account, not just the caller's. An issuer URL is globally unique, and the + // account calling AssumeRoleWithWebIdentity need not be the one that owns the cluster. + // Account-scoped scanning would leave the key unfound, and an unfound issuer is treated as + // a third-party provider, so the token would be accepted with no validation at all. + return allKeys().stream() + .filter(key -> issuer.equals(key.getIssuer())) + .findFirst() + .map(key -> toPublicKey(key.getPublicKey())); + } + + private List allKeys() { + if (keyStore instanceof AccountAwareStorageBackend aware) { + return aware.scanAllAccounts(); + } + return keyStore.scan(k -> true); + } + + /** + * Mints an RS256-signed service-account token for {@code namespace}/{@code serviceAccount}, + * shaped like the projected token a pod would present to STS. + */ + public String mintServiceAccountToken(String clusterName, String issuer, String namespace, + String serviceAccount, String audience, Integer lifetimeSeconds) { + if (namespace == null || namespace.isBlank()) { + throw new AwsException("InvalidParameterException", "namespace is required", 400); + } + if (serviceAccount == null || serviceAccount.isBlank()) { + throw new AwsException("InvalidParameterException", "serviceAccount is required", 400); + } + int lifetime = resolveLifetime(lifetimeSeconds); + String aud = audience == null || audience.isBlank() ? STS_AUDIENCE : audience; + + ClusterOidcKey key = ensureKey(clusterName, issuer); + long now = Instant.now().getEpochSecond(); + long exp = now + lifetime; + String subject = "system:serviceaccount:" + namespace + ":" + serviceAccount; + + String header = base64Url(writeJson(buildHeader(key.getKeyId()))); + String payload = base64Url(writeJson( + buildClaims(issuer, aud, subject, namespace, serviceAccount, now, exp))); + + String signingInput = header + "." + payload; + return signingInput + "." + sign(signingInput, toPrivateKey(key.getPrivateKey())); + } + + private int resolveLifetime(Integer requested) { + if (requested == null || requested <= 0) { + return DEFAULT_TOKEN_LIFETIME_SECONDS; + } + return Math.min(requested, MAX_TOKEN_LIFETIME_SECONDS); + } + + private ObjectNode buildHeader(String keyId) { + ObjectNode header = objectMapper.createObjectNode(); + header.put("alg", "RS256"); + header.put("typ", "JWT"); + header.put("kid", keyId); + return header; + } + + private ObjectNode buildClaims(String issuer, String audience, String subject, String namespace, + String serviceAccount, long issuedAt, long expiresAt) { + ObjectNode claims = objectMapper.createObjectNode(); + claims.put("iss", issuer); + claims.putArray("aud").add(audience); + claims.put("sub", subject); + claims.put("iat", issuedAt); + claims.put("nbf", issuedAt); + claims.put("exp", expiresAt); + claims.put("jti", UUID.randomUUID().toString()); + + ObjectNode kubernetes = claims.putObject("kubernetes.io"); + kubernetes.put("namespace", namespace); + kubernetes.putObject("serviceaccount").put("name", serviceAccount); + return claims; + } + + /** + * Serializes a claim set to bytes. Jackson handles escaping, including the control characters a + * hand-rolled escape would miss and which would otherwise produce a structurally invalid token. + */ + private byte[] writeJson(ObjectNode node) { + try { + return objectMapper.writeValueAsBytes(node); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Failed to serialize EKS OIDC token claims", e); + } + } + + private String sign(String signingInput, PrivateKey privateKey) { + try { + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(privateKey); + signature.update(signingInput.getBytes(StandardCharsets.UTF_8)); + return base64Url(signature.sign()); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("EKS OIDC token signing failed", e); + } + } + + RSAPublicKey toPublicKey(String encoded) { + try { + X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(encoded)); + return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec); + } catch (GeneralSecurityException | IllegalArgumentException e) { + throw new IllegalStateException("Failed to load EKS OIDC public key", e); + } + } + + private PrivateKey toPrivateKey(String encoded) { + try { + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(encoded)); + return KeyFactory.getInstance("RSA").generatePrivate(spec); + } catch (GeneralSecurityException | IllegalArgumentException e) { + throw new IllegalStateException("Failed to load EKS OIDC private key", e); + } + } + + private static String base64Url(byte[] data) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(data); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcTokenController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcTokenController.java new file mode 100644 index 0000000000..734f3b0177 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcTokenController.java @@ -0,0 +1,93 @@ +package io.github.hectorvent.floci.services.eks; + +import java.util.LinkedHashMap; +import java.util.Map; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.eks.model.Cluster; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +/** + * Mints an IRSA service-account token signed by a cluster's OIDC key. + * + *

Real EKS has the kubelet project this token into a pod; Floci has no kubelet in the loop, so a + * local-dev harness asks for one here, writes it to the file named by + * {@code AWS_WEB_IDENTITY_TOKEN_FILE}, and the AWS SDK on the pod presents it to + * {@code sts:AssumeRoleWithWebIdentity} exactly as it would in production. + * + *

Minting server-side keeps the RSA private key inside Floci. Callers never hold signing + * material, and the claim shape stays authoritative in one place. + */ +@ApplicationScoped +@Path("_floci/eks/clusters/{name}/oidc-token") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class EksOidcTokenController { + + private final EksService eksService; + private final EksOidcService oidcService; + + @Inject + public EksOidcTokenController(EksService eksService, EksOidcService oidcService) { + this.eksService = eksService; + this.oidcService = oidcService; + } + + @POST + public Response mintToken(@PathParam("name") String clusterName, Map request) { + Cluster cluster = eksService.describeCluster(clusterName); + String issuer = cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null + ? cluster.getIdentity().getOidc().getIssuer() + : null; + if (issuer == null || issuer.isBlank()) { + throw new AwsException("InvalidParameterException", + "Cluster " + clusterName + " has no OIDC issuer", 400); + } + + Map body = request == null ? Map.of() : request; + String namespace = string(body, "namespace"); + String serviceAccount = string(body, "serviceAccount"); + String audience = string(body, "audience"); + Integer lifetime = integer(body, "expirySeconds"); + + String token = oidcService.mintServiceAccountToken( + clusterName, issuer, namespace, serviceAccount, audience, lifetime); + + Map response = new LinkedHashMap<>(); + response.put("token", token); + response.put("issuer", issuer); + response.put("subject", "system:serviceaccount:" + namespace + ":" + serviceAccount); + response.put("audience", audience == null || audience.isBlank() + ? EksOidcService.STS_AUDIENCE : audience); + return Response.ok(response).build(); + } + + private String string(Map body, String key) { + Object value = body.get(key); + return value instanceof String s && !s.isBlank() ? s : null; + } + + private Integer integer(Map body, String key) { + Object value = body.get(key); + if (value instanceof Number n) { + return n.intValue(); + } + if (value instanceof String s && !s.isBlank()) { + try { + return Integer.parseInt(s); + } catch (NumberFormatException e) { + throw new AwsException("InvalidParameterException", + key + " must be an integer", 400); + } + } + return null; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcWellKnownController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcWellKnownController.java new file mode 100644 index 0000000000..727f14f8d2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcWellKnownController.java @@ -0,0 +1,115 @@ +package io.github.hectorvent.floci.services.eks; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.eks.model.Cluster; +import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.math.BigInteger; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Serves the OIDC discovery document and JWKS for an EKS cluster's IRSA issuer. + * + *

Floci's STS resolves signing keys in-process, so nothing in the IRSA flow dereferences these + * routes — they exist for fidelity and debuggability (inspecting the key a token was signed with, + * or pointing an external verifier at Floci). + * + *

Hosted under {@code _floci/eks/...} rather than at the AWS-shaped issuer path. The issuer + * ({@code https://oidc.eks..amazonaws.com/id/}) is not resolvable by Floci's embedded + * DNS, and serving {@code /id//.well-known/...} at the root would collide with S3's path-style + * catch-all — the same hazard that forced the Cognito well-known routes to discriminate on an + * underscore. Keying by cluster name keeps the route unambiguous. + */ +@ApplicationScoped +@Path("_floci/eks/clusters/{name}/oidc") +@Produces(MediaType.APPLICATION_JSON) +public class EksOidcWellKnownController { + + private final EksService eksService; + private final EksOidcService oidcService; + private final EmulatorConfig config; + + @Inject + public EksOidcWellKnownController(EksService eksService, EksOidcService oidcService, + EmulatorConfig config) { + this.eksService = eksService; + this.oidcService = oidcService; + this.config = config; + } + + @GET + @Path(".well-known/openid-configuration") + public Response openIdConfiguration(@PathParam("name") String clusterName) { + String issuer = requireIssuer(clusterName); + + Map body = new LinkedHashMap<>(); + body.put("issuer", issuer); + body.put("jwks_uri", jwksUri(clusterName)); + body.put("authorization_endpoint", "urn:kubernetes:programmatic_authorization"); + body.put("response_types_supported", List.of("id_token")); + body.put("subject_types_supported", List.of("public")); + body.put("id_token_signing_alg_values_supported", List.of("RS256")); + body.put("claims_supported", List.of("sub", "iss", "aud", "exp", "iat")); + return Response.ok(body).build(); + } + + @GET + @Path("keys") + public Response keys(@PathParam("name") String clusterName) { + requireIssuer(clusterName); + ClusterOidcKey key = oidcService.findKeyByCluster(clusterName) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "No OIDC signing key for cluster: " + clusterName, 404)); + + var publicKey = oidcService.toPublicKey(key.getPublicKey()); + Map jwk = new LinkedHashMap<>(); + jwk.put("kty", "RSA"); + jwk.put("alg", "RS256"); + jwk.put("use", "sig"); + jwk.put("kid", key.getKeyId()); + jwk.put("n", base64UrlEncodeUnsigned(publicKey.getModulus())); + jwk.put("e", base64UrlEncodeUnsigned(publicKey.getPublicExponent())); + + return Response.ok(Map.of("keys", List.of(jwk))).build(); + } + + private String requireIssuer(String clusterName) { + Cluster cluster = eksService.describeCluster(clusterName); + String issuer = cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null + ? cluster.getIdentity().getOidc().getIssuer() + : null; + if (issuer == null || issuer.isBlank()) { + throw new AwsException("ResourceNotFoundException", + "Cluster " + clusterName + " has no OIDC issuer", 404); + } + return issuer; + } + + private String jwksUri(String clusterName) { + return config.effectiveBaseUrl() + "/_floci/eks/clusters/" + clusterName + "/oidc/keys"; + } + + /** + * Encodes an RSA parameter as an unsigned big-endian base64url value, dropping the leading zero + * byte {@link BigInteger#toByteArray()} adds for sign — JWK requires the unsigned form. + */ + private String base64UrlEncodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes.length > 1 && bytes[0] == 0) { + bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length); + } + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java index 0eb472abe8..98ac02c95e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java @@ -11,7 +11,9 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.eks.model.CertificateAuthority; import io.github.hectorvent.floci.services.eks.model.Cluster; +import io.github.hectorvent.floci.services.eks.model.ClusterIdentity; import io.github.hectorvent.floci.services.eks.model.ClusterStatus; +import io.github.hectorvent.floci.services.eks.model.OidcIdentity; import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest; import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest; import io.github.hectorvent.floci.services.eks.model.CreateNodeGroupRequest; @@ -53,11 +55,13 @@ public class EksService implements TagHandler { private final RegionResolver regionResolver; private final EksClusterManager clusterManager; private final Ec2Service ec2Service; + private final EksOidcService oidcService; private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor(); @Inject public EksService(StorageFactory storageFactory, EmulatorConfig config, - RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service) { + RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service, + EksOidcService oidcService) { this.storage = storageFactory.create("eks", "eks-clusters.json", new TypeReference>() { }); @@ -71,15 +75,55 @@ public class EksService implements TagHandler { this.regionResolver = regionResolver; this.clusterManager = clusterManager; this.ec2Service = ec2Service; + this.oidcService = oidcService; } @PostConstruct public void init() { + backfillOidcIdentities(); if (!config.services().eks().mock()) { startReadinessPoller(); } } + /** + * Gives clusters persisted before IRSA support an OIDC issuer and signing key. Without this, + * a cluster restored from {@code eks-clusters.json} would report no + * {@code identity.oidc.issuer}, and token minting and the JWKS routes would fail for it until + * it was recreated. + */ + private void backfillOidcIdentities() { + for (Cluster cluster : allClusters()) { + // Runs at startup with no request context, so the owning account must come from the + // cluster record and be passed explicitly, so the account-scoped put()/get() would + // resolve to the default account and strand a cluster owned by any other one. + String accountId = cluster.getAccountId() != null + ? cluster.getAccountId() + : regionResolver.getAccountId(); + + if (cluster.getIdentity() != null && cluster.getIdentity().getOidc() != null + && cluster.getIdentity().getOidc().getIssuer() != null) { + oidcService.ensureKeyForAccount(accountId, cluster.getName(), + cluster.getIdentity().getOidc().getIssuer()); + continue; + } + String issuer = oidcService.newIssuerUrl(config.defaultRegion()); + cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); + oidcService.ensureKeyForAccount(accountId, cluster.getName(), issuer); + putClusterForAccount(accountId, cluster); + LOG.infov("Backfilled IRSA OIDC issuer for existing EKS cluster {0} in account {1}", + cluster.getName(), accountId); + } + } + + private void putClusterForAccount(String accountId, Cluster cluster) { + if (storage instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(accountId, cluster.getName(), cluster); + return; + } + storage.put(cluster.getName(), cluster); + } + @PreDestroy public void shutdown() { poller.shutdownNow(); @@ -119,6 +163,10 @@ public class EksService implements TagHandler { cluster.setPlatformVersion("eks.1"); cluster.setCertificateAuthority(new CertificateAuthority("")); + String issuer = oidcService.newIssuerUrl(region); + cluster.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); + oidcService.ensureKey(name, issuer); + if (config.services().eks().mock()) { cluster.setStatus(ClusterStatus.ACTIVE); cluster.setEndpoint("https://localhost:" + config.services().eks().apiServerBasePort()); @@ -157,6 +205,7 @@ public class EksService implements TagHandler { clusterManager.stopCluster(cluster); } storage.delete(name); + oidcService.deleteKey(name); return cluster; } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java index 88511aa2ae..bbd77add06 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java @@ -44,6 +44,9 @@ public class Cluster { @JsonProperty("certificateAuthority") private CertificateAuthority certificateAuthority; + @JsonProperty("identity") + private ClusterIdentity identity; + @JsonProperty("platformVersion") private String platformVersion; @@ -94,6 +97,9 @@ public class Cluster { public CertificateAuthority getCertificateAuthority() { return certificateAuthority; } public void setCertificateAuthority(CertificateAuthority certificateAuthority) { this.certificateAuthority = certificateAuthority; } + public ClusterIdentity getIdentity() { return identity; } + public void setIdentity(ClusterIdentity identity) { this.identity = identity; } + public String getPlatformVersion() { return platformVersion; } public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterIdentity.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterIdentity.java new file mode 100644 index 0000000000..d8bbd1206b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterIdentity.java @@ -0,0 +1,22 @@ +package io.github.hectorvent.floci.services.eks.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ClusterIdentity { + + @JsonProperty("oidc") + private OidcIdentity oidc; + + public ClusterIdentity() {} + + public ClusterIdentity(OidcIdentity oidc) { + this.oidc = oidc; + } + + public OidcIdentity getOidc() { return oidc; } + public void setOidc(OidcIdentity oidc) { this.oidc = oidc; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterOidcKey.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterOidcKey.java new file mode 100644 index 0000000000..8c75800954 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterOidcKey.java @@ -0,0 +1,52 @@ +package io.github.hectorvent.floci.services.eks.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * RSA signing material backing an EKS cluster's IRSA OIDC issuer. + * + *

Held in a storage backend separate from {@link Cluster} on purpose: {@code Cluster} is + * serialized straight onto the {@code DescribeCluster} wire response, so a private key carried + * on that model would leak to any caller. Keeping the key here lets it persist across restarts + * (a token minted before a restart must still verify afterwards) without ever being reachable + * from an AWS API response. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ClusterOidcKey { + + @JsonProperty("issuer") + private String issuer; + + @JsonProperty("keyId") + private String keyId; + + @JsonProperty("publicKey") + private String publicKey; + + @JsonProperty("privateKey") + private String privateKey; + + public ClusterOidcKey() {} + + public ClusterOidcKey(String issuer, String keyId, String publicKey, String privateKey) { + this.issuer = issuer; + this.keyId = keyId; + this.publicKey = publicKey; + this.privateKey = privateKey; + } + + public String getIssuer() { return issuer; } + public void setIssuer(String issuer) { this.issuer = issuer; } + + public String getKeyId() { return keyId; } + public void setKeyId(String keyId) { this.keyId = keyId; } + + public String getPublicKey() { return publicKey; } + public void setPublicKey(String publicKey) { this.publicKey = publicKey; } + + public String getPrivateKey() { return privateKey; } + public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/OidcIdentity.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/OidcIdentity.java new file mode 100644 index 0000000000..cffea6c262 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/OidcIdentity.java @@ -0,0 +1,22 @@ +package io.github.hectorvent.floci.services.eks.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class OidcIdentity { + + @JsonProperty("issuer") + private String issuer; + + public OidcIdentity() {} + + public OidcIdentity(String issuer) { + this.issuer = issuer; + } + + public String getIssuer() { return issuer; } + public void setIssuer(String issuer) { this.issuer = issuer; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java index e39dcb9846..e4abe1a726 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java @@ -6,7 +6,10 @@ import io.github.hectorvent.floci.core.common.AwsNamespaces; import io.github.hectorvent.floci.core.common.AwsQueryController; import io.github.hectorvent.floci.core.common.AwsQueryResponse; import io.github.hectorvent.floci.core.common.AccountResolver; +import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.WebIdentityToken; +import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier; import io.github.hectorvent.floci.core.common.XmlBuilder; import io.github.hectorvent.floci.services.iam.model.IamRole; import jakarta.enterprise.context.ApplicationScoped; @@ -17,8 +20,11 @@ import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; +import java.security.interfaces.RSAPublicKey; import java.time.Instant; import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; @@ -32,24 +38,34 @@ public class StsQueryHandler { private static final Logger LOG = Logger.getLogger(StsQueryHandler.class); private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final String STS_AUDIENCE = "sts.amazonaws.com"; private final IamService iamService; private final AccountResolver accountResolver; private final RegionResolver regionResolver; private final EmulatorConfig config; private final AssumeRolePolicyEvaluator trustPolicyEvaluator; + private final WebIdentityTrustPolicyEvaluator webIdentityTrustEvaluator; + private final WebIdentityTokenVerifier tokenVerifier; + private final OidcIssuerKeyLookup oidcIssuerKeys; @Context HttpHeaders headers; @Inject public StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver, - EmulatorConfig config, AssumeRolePolicyEvaluator trustPolicyEvaluator) { + EmulatorConfig config, AssumeRolePolicyEvaluator trustPolicyEvaluator, + WebIdentityTrustPolicyEvaluator webIdentityTrustEvaluator, + WebIdentityTokenVerifier tokenVerifier, + OidcIssuerKeyLookup oidcIssuerKeys) { this.iamService = iamService; this.accountResolver = accountResolver; this.regionResolver = regionResolver; this.config = config; this.trustPolicyEvaluator = trustPolicyEvaluator; + this.webIdentityTrustEvaluator = webIdentityTrustEvaluator; + this.tokenVerifier = tokenVerifier; + this.oidcIssuerKeys = oidcIssuerKeys; } public Response handle(String action, MultivaluedMap params) { @@ -174,19 +190,34 @@ public class StsQueryHandler { String roleArn = getParam(params, "RoleArn"); String sessionName = getParam(params, "RoleSessionName"); String providerId = getParam(params, "ProviderId"); + String webIdentityToken = getParam(params, "WebIdentityToken"); int durationSeconds = getIntParam(params, "DurationSeconds", 3600); + String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole"; + String callerAccountId = regionResolver.getAccountId(); + String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId); + + // Only tokens naming an issuer Floci itself hosts (an EKS cluster's IRSA OIDC provider) are + // verifiable, so only those are enforced. An opaque or third-party token keeps the historical + // permissive behaviour rather than failing a workflow Floci cannot adjudicate. + WebIdentityOutcome outcome = verifyWebIdentityToken(webIdentityToken, roleName, accountId, roleArn); + if (outcome.denial() != null) { + return outcome.denial(); + } + VerifiedWebIdentity verified = outcome.verified(); + String accessKeyId = "ASIA" + randomId(16); String secretKey = randomSecret(40); String sessionToken = randomSecret(200); Instant expiration = Instant.now().plusSeconds(durationSeconds); - String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole"; - String callerAccountId = regionResolver.getAccountId(); - String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId); String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString(); String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName; - String provider = providerId != null && !providerId.isBlank() ? providerId : "accounts.google.com"; + + String provider = verified != null ? verified.issuer() + : (providerId != null && !providerId.isBlank() ? providerId : "accounts.google.com"); + String audience = verified != null ? verified.audience() : "sts.amazonaws.com"; + String subject = verified != null ? verified.subject() : "web-identity-subject"; String sessionPolicy = getParam(params, "Policy"); iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId); @@ -199,12 +230,98 @@ public class StsQueryHandler { .end("AssumedRoleUser") .elem("PackedPolicySize", "0") .elem("Provider", provider) - .elem("Audience", "sts.amazonaws.com") - .elem("SubjectFromWebIdentityToken", "web-identity-subject") + .elem("Audience", audience) + .elem("SubjectFromWebIdentityToken", subject) .build(); return Response.ok(AwsQueryResponse.envelope("AssumeRoleWithWebIdentity", AwsNamespaces.STS, result)).build(); } + /** The claims of a token Floci issued and verified, used to fill the response accurately. */ + private record VerifiedWebIdentity(String issuer, String subject, String audience) {} + + /** + * The result of inspecting a web identity token: at most one field is non-null. Both null means + * the issuer is unknown to Floci, so the token is treated as opaque and accepted. + */ + private record WebIdentityOutcome(VerifiedWebIdentity verified, Response denial) { + + static WebIdentityOutcome unverifiable() { + return new WebIdentityOutcome(null, null); + } + + static WebIdentityOutcome allow(VerifiedWebIdentity verified) { + return new WebIdentityOutcome(verified, null); + } + + static WebIdentityOutcome deny(Response denial) { + return new WebIdentityOutcome(null, denial); + } + } + + /** + * Inspects {@code token} and decides whether it may assume {@code roleArn}. Returns an outcome + * carrying the verified claims, a denial response, or neither when the token's issuer is not one + * Floci hosts (preserving the historical permissive behaviour for third-party providers). + */ + private WebIdentityOutcome verifyWebIdentityToken(String token, String roleName, String roleAccountId, + String roleArn) { + Optional issuer = tokenVerifier.peekIssuer(token); + if (issuer.isEmpty()) { + return WebIdentityOutcome.unverifiable(); + } + Optional key = oidcIssuerKeys.findVerificationKey(issuer.get()); + if (key.isEmpty()) { + return WebIdentityOutcome.unverifiable(); + } + + WebIdentityToken claims; + try { + claims = tokenVerifier.verify(token, key.get(), issuer.get(), STS_AUDIENCE); + } catch (WebIdentityTokenVerifier.InvalidTokenException e) { + LOG.debugv("Rejecting web identity token for role {0}: {1}", roleArn, e.getMessage()); + return WebIdentityOutcome.deny(AwsQueryResponse.error("InvalidIdentityToken", + e.getMessage(), AwsNamespaces.STS, 400)); + } + + Optional role = iamService.findRole(roleAccountId, roleName); + if (role.isEmpty()) { + return WebIdentityOutcome.deny(accessDenied(roleArn)); + } + + String issuerKeyPrefix = stripScheme(issuer.get()); + String oidcProviderArn = AwsArnUtils.Arn.of("iam", "", roleAccountId, + "oidc-provider/" + issuerKeyPrefix).toString(); + Map> conditionClaims = Map.of( + "sub", List.of(claims.subject()), + "aud", claims.audiences()); + + if (!webIdentityTrustEvaluator.allows(role.get().getAssumeRolePolicyDocument(), + oidcProviderArn, issuerKeyPrefix, conditionClaims)) { + LOG.debugv("Trust policy on role {0} denies web identity subject {1}", + roleArn, claims.subject()); + return WebIdentityOutcome.deny(accessDenied(roleArn)); + } + + // verify() already required the audience list to contain STS_AUDIENCE. + return WebIdentityOutcome.allow( + new VerifiedWebIdentity(claims.issuer(), claims.subject(), STS_AUDIENCE)); + } + + private Response accessDenied(String roleArn) { + return AwsQueryResponse.error("AccessDenied", + "Not authorized to perform sts:AssumeRoleWithWebIdentity on resource: " + roleArn, + AwsNamespaces.STS, 403); + } + + /** + * Strips the URL scheme from an issuer. IAM renders an OIDC provider ARN and its condition keys + * from the host-and-path form ({@code oidc.eks..amazonaws.com/id/}), not the full URL. + */ + private static String stripScheme(String issuer) { + int schemeEnd = issuer.indexOf("://"); + return schemeEnd < 0 ? issuer : issuer.substring(schemeEnd + 3); + } + private Response handleAssumeRoleWithSAML(MultivaluedMap params) { Response validation = validateRequired(params, "RoleArn", "PrincipalArn", "SAMLAssertion"); if (validation != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/WebIdentityTrustPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/WebIdentityTrustPolicyEvaluator.java new file mode 100644 index 0000000000..2c656c9fd2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/WebIdentityTrustPolicyEvaluator.java @@ -0,0 +1,301 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.List; +import java.util.Map; + +/** + * Evaluates a role's trust policy for {@code sts:AssumeRoleWithWebIdentity}, matching the + * {@code Federated} principal and the {@code Condition} block that pins an OIDC subject and + * audience. + * + *

Separate from {@link AssumeRolePolicyEvaluator} on purpose. That evaluator serves the + * {@code sts:AssumeRole} path, hardcodes that action, reads only {@code Principal.AWS}, and ignores + * conditions — widening it would risk regressing a path that already works. The two are + * complementary: this one only ever considers federated principals. + * + *

Condition values are compared with exact, case-sensitive equality rather than + * {@link IamPolicyEvaluator#globMatches} (which lowercases both operands). An OIDC subject like + * {@code system:serviceaccount:apps:My-Account} must not match a policy naming {@code my-account}: + * case-folding here would silently grant a different service account. + */ +@ApplicationScoped +public class WebIdentityTrustPolicyEvaluator { + + private static final Logger LOG = Logger.getLogger(WebIdentityTrustPolicyEvaluator.class); + private static final String WEB_IDENTITY_ACTION = "sts:assumerolewithwebidentity"; + + private final ObjectMapper objectMapper; + + @Inject + public WebIdentityTrustPolicyEvaluator(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + /** + * Returns true if {@code trustPolicyDocument} allows a web-identity token from + * {@code oidcProviderArn} with the given claim context to assume the role. + * + *

{@code claims} holds the OIDC condition context keyed without the provider + * prefix — {@code sub}, {@code aud} — which this evaluator resolves against policy keys of the + * form {@code :sub}. An explicit {@code Deny} wins over any + * {@code Allow}, per AWS precedence. + */ + public boolean allows(String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix, + Map> claims) { + if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) { + return false; + } + JsonNode statements; + try { + statements = objectMapper.readTree(trustPolicyDocument).path("Statement"); + } catch (JsonProcessingException e) { + LOG.warnv("Failed to parse web-identity trust policy: {0}", e.getMessage()); + return false; + } + + boolean allow = false; + if (statements.isArray()) { + for (JsonNode stmt : statements) { + switch (evaluate(stmt, oidcProviderArn, issuerKeyPrefix, claims)) { + case DENY -> { return false; } + case ALLOW -> allow = true; + case NO_MATCH -> { } + } + } + return allow; + } + if (statements.isObject()) { + return evaluate(statements, oidcProviderArn, issuerKeyPrefix, claims) == Match.ALLOW; + } + return false; + } + + private enum Match { ALLOW, DENY, NO_MATCH } + + private Match evaluate(JsonNode stmt, String oidcProviderArn, String issuerKeyPrefix, + Map> claims) { + if (!actionApplies(stmt)) { + return Match.NO_MATCH; + } + if (!matchesFederatedPrincipal(stmt.get("Principal"), oidcProviderArn)) { + return Match.NO_MATCH; + } + if (!conditionsSatisfied(stmt.get("Condition"), issuerKeyPrefix, claims)) { + return Match.NO_MATCH; + } + return "Deny".equalsIgnoreCase(stmt.path("Effect").asText("Allow")) ? Match.DENY : Match.ALLOW; + } + + /** + * True when the statement's action element covers {@code sts:AssumeRoleWithWebIdentity}. Action + * names are case-insensitive in AWS policy documents, and wildcards are honoured. + */ + private boolean actionApplies(JsonNode stmt) { + JsonNode action = stmt.get("Action"); + if (action != null) { + return matchesAction(action); + } + JsonNode notAction = stmt.get("NotAction"); + if (notAction != null) { + return !matchesAction(notAction); + } + return false; + } + + private boolean matchesAction(JsonNode actionNode) { + if (actionNode.isTextual()) { + return IamPolicyEvaluator.globMatches(actionNode.asText(), WEB_IDENTITY_ACTION); + } + if (actionNode.isArray()) { + for (JsonNode entry : actionNode) { + if (entry.isTextual() + && IamPolicyEvaluator.globMatches(entry.asText(), WEB_IDENTITY_ACTION)) { + return true; + } + } + } + return false; + } + + /** + * Matches {@code Principal.Federated} against the OIDC provider ARN. Only the federated + * principal type can match a web-identity caller — an {@code AWS} principal never does. + */ + private boolean matchesFederatedPrincipal(JsonNode principalNode, String oidcProviderArn) { + if (principalNode == null || oidcProviderArn == null) { + return false; + } + if (principalNode.isTextual()) { + return "*".equals(principalNode.asText()); + } + if (!principalNode.isObject()) { + return false; + } + JsonNode federated = principalNode.get("Federated"); + if (federated == null) { + return false; + } + if (federated.isTextual()) { + return federatedMatches(federated.asText(), oidcProviderArn); + } + if (federated.isArray()) { + for (JsonNode entry : federated) { + if (entry.isTextual() && federatedMatches(entry.asText(), oidcProviderArn)) { + return true; + } + } + } + return false; + } + + private boolean federatedMatches(String declared, String oidcProviderArn) { + return "*".equals(declared) || declared.equals(oidcProviderArn); + } + + /** + * Evaluates the condition block. Every operator block and every key within it must be satisfied + * (AWS ANDs them). Only the string operators meaningful for OIDC claims are handled; a condition + * using anything else does not match, which fails closed. + */ + private boolean conditionsSatisfied(JsonNode conditionNode, String issuerKeyPrefix, + Map> claims) { + if (conditionNode == null || conditionNode.isNull()) { + // No condition constraints — the federated principal alone is enough. + return true; + } + if (!conditionNode.isObject()) { + return false; + } + + var operators = conditionNode.fields(); + while (operators.hasNext()) { + var operatorEntry = operators.next(); + String operator = operatorEntry.getKey(); + JsonNode keys = operatorEntry.getValue(); + if (!keys.isObject()) { + return false; + } + var keyIterator = keys.fields(); + while (keyIterator.hasNext()) { + var keyEntry = keyIterator.next(); + if (!keySatisfied(operator, keyEntry.getKey(), keyEntry.getValue(), + issuerKeyPrefix, claims)) { + return false; + } + } + } + return true; + } + + private boolean keySatisfied(String operator, String conditionKey, JsonNode expected, + String issuerKeyPrefix, Map> claims) { + List actual = resolveClaim(conditionKey, issuerKeyPrefix, claims); + List expectedValues = textValues(expected); + if (expectedValues.isEmpty()) { + return false; + } + + return switch (operator) { + case "StringEquals" -> actual.stream().anyMatch(expectedValues::contains); + case "StringNotEquals" -> actual.stream().noneMatch(expectedValues::contains); + case "StringLike" -> actual.stream().anyMatch( + a -> expectedValues.stream().anyMatch(e -> globMatchesCaseSensitive(e, a))); + case "StringNotLike" -> actual.stream().noneMatch( + a -> expectedValues.stream().anyMatch(e -> globMatchesCaseSensitive(e, a))); + default -> { + LOG.debugv("Unsupported web-identity trust policy condition operator: {0}", operator); + yield false; + } + }; + } + + /** + * Glob matching over {@code *} and {@code ?} that preserves case, unlike + * {@link IamPolicyEvaluator#globMatches} which lowercases both operands. A {@code StringLike} + * constraint on {@code oidc:sub} must not admit a service account differing only in case, so it + * needs the same case sensitivity as the {@code StringEquals} branch above. + */ + static boolean globMatchesCaseSensitive(String pattern, String value) { + if (pattern == null || value == null) { + return false; + } + return globMatchesHelper(pattern, value, 0, 0); + } + + private static boolean globMatchesHelper(String pattern, String value, int pi, int vi) { + while (pi < pattern.length()) { + char p = pattern.charAt(pi); + if (p == '*') { + // Collapse consecutive stars, then try every split point for the remainder. + while (pi + 1 < pattern.length() && pattern.charAt(pi + 1) == '*') { + pi++; + } + if (pi == pattern.length() - 1) { + return true; + } + for (int i = vi; i <= value.length(); i++) { + if (globMatchesHelper(pattern, value, pi + 1, i)) { + return true; + } + } + return false; + } + if (vi >= value.length()) { + return false; + } + if (p != '?' && p != value.charAt(vi)) { + return false; + } + pi++; + vi++; + } + return vi == value.length(); + } + + /** + * Resolves a policy condition key such as + * {@code oidc.eks.us-east-1.amazonaws.com/id/ABC123:sub} to the token's claim values. The key + * prefix is the issuer with its scheme stripped, which is how the AWS console, eksctl, and + * Terraform all render it. + */ + private List resolveClaim(String conditionKey, String issuerKeyPrefix, + Map> claims) { + if (conditionKey == null) { + return List.of(); + } + int separator = conditionKey.lastIndexOf(':'); + if (separator < 0) { + return List.of(); + } + String prefix = conditionKey.substring(0, separator); + String claimName = conditionKey.substring(separator + 1); + + // The provider prefix must be this token's issuer; a condition pinned to a different + // provider must not be satisfied by our claims. + if (!prefix.equalsIgnoreCase(issuerKeyPrefix)) { + return List.of(); + } + return claims.getOrDefault(claimName.toLowerCase(), List.of()); + } + + private List textValues(JsonNode node) { + if (node.isTextual()) { + return List.of(node.asText()); + } + if (node.isArray()) { + return java.util.stream.StreamSupport + .stream(node.spliterator(), false) + .filter(JsonNode::isTextual) + .map(JsonNode::asText) + .toList(); + } + return List.of(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java b/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java new file mode 100644 index 0000000000..36aaa76eba --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java @@ -0,0 +1,226 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.eks.EksOidcService; +import com.fasterxml.jackson.core.type.TypeReference; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.util.Base64; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class WebIdentityTokenVerifierTest { + + private static final String ISSUER = + "https://oidc.eks.us-east-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789"; + private static final String CLUSTER = "irsa-test-cluster"; + + private WebIdentityTokenVerifier verifier; + private EksOidcService oidcService; + + @BeforeEach + void setUp() { + ObjectMapper objectMapper = new ObjectMapper(); + verifier = new WebIdentityTokenVerifier(objectMapper); + oidcService = new EksOidcService(new StorageFactory(null, null) { + @Override + public StorageBackend create(String serviceName, String fileName, + TypeReference> typeReference) { + return new InMemoryStorage<>(); + } + }, objectMapper); + oidcService.ensureKey(CLUSTER, ISSUER); + } + + private RSAPublicKey publicKey() { + return oidcService.findVerificationKey(ISSUER).orElseThrow(); + } + + private String mint(String namespace, String serviceAccount, String audience, Integer lifetime) { + return oidcService.mintServiceAccountToken(CLUSTER, ISSUER, namespace, serviceAccount, + audience, lifetime); + } + + private static KeyPair newKeyPair() throws GeneralSecurityException { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private static String base64Url(String value) { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(value.getBytes(StandardCharsets.UTF_8)); + } + + /** Signs an arbitrary claim set, so tests can build tokens the production mint path never would. */ + private static String signRs256(PrivateKey privateKey, String claimsJson) + throws GeneralSecurityException { + String header = base64Url("{\"alg\":\"RS256\",\"typ\":\"JWT\"}"); + String payload = base64Url(claimsJson); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(privateKey); + signature.update((header + "." + payload).getBytes(StandardCharsets.UTF_8)); + return header + "." + payload + "." + + Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign()); + } + + @Test + void verifiesFlociMintedToken() throws Exception { + String token = mint("my-namespace", "my-service-account", null, null); + + WebIdentityToken verified = verifier.verify(token, publicKey(), ISSUER, + EksOidcService.STS_AUDIENCE); + + assertEquals(ISSUER, verified.issuer()); + assertEquals("system:serviceaccount:my-namespace:my-service-account", verified.subject()); + assertTrue(verified.audiences().contains(EksOidcService.STS_AUDIENCE)); + } + + @Test + void peeksIssuerWithoutVerifying() { + String token = mint("my-namespace", "my-service-account", null, null); + assertEquals(ISSUER, verifier.peekIssuer(token).orElseThrow()); + } + + @Test + void peekIssuerReturnsEmptyForOpaqueToken() { + assertTrue(verifier.peekIssuer("dummy-token").isEmpty()); + assertTrue(verifier.peekIssuer(null).isEmpty()); + assertTrue(verifier.peekIssuer("").isEmpty()); + } + + @Test + void peekIssuerSeesTheIssuerOfAnUnsignedToken() { + // Regression guard: an unsigned "header.payload." token must not read as opaque. If its + // issuer went unseen, the caller would skip validation for a token naming a Floci issuer + // and hand out credentials for an unsigned JWT. + String header = base64Url("{\"alg\":\"none\",\"typ\":\"JWT\"}"); + String payload = base64Url("{\"iss\":\"" + ISSUER + "\"," + + "\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"]," + + "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\"," + + "\"exp\":" + (System.currentTimeMillis() / 1000 + 3600) + "}"); + + assertEquals(ISSUER, verifier.peekIssuer(header + "." + payload + ".").orElseThrow()); + } + + @Test + void rejectsTamperedPayload() { + String token = mint("my-namespace", "my-service-account", null, null); + String[] parts = token.split("\\.", -1); + // The forged payload is otherwise valid — same issuer, audience, and a future expiry — so + // only the signature check can reject it. + String forgedPayload = base64Url("{\"iss\":\"" + ISSUER + "\"," + + "\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"]," + + "\"sub\":\"system:serviceaccount:my-namespace:attacker\"," + + "\"nbf\":" + (System.currentTimeMillis() / 1000 - 60) + "," + + "\"exp\":" + (System.currentTimeMillis() / 1000 + 3600) + "}"); + String tampered = parts[0] + "." + forgedPayload + "." + parts[2]; + + WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows( + WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(tampered, publicKey(), ISSUER, EksOidcService.STS_AUDIENCE)); + assertTrue(thrown.getMessage().contains("signature"), + "expected a signature failure, got: " + thrown.getMessage()); + } + + @Test + void rejectsWrongIssuer() { + String token = mint("my-namespace", "my-service-account", null, null); + + assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(token, publicKey(), + "https://oidc.eks.us-east-1.amazonaws.com/id/OTHER", + EksOidcService.STS_AUDIENCE)); + } + + @Test + void rejectsWrongAudience() { + String token = mint("my-namespace", "my-service-account", "some.other.audience", null); + + assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(token, publicKey(), ISSUER, EksOidcService.STS_AUDIENCE)); + } + + @Test + void rejectsExpiredToken() throws Exception { + // Signed with a locally generated key so the payload can carry an arbitrary past expiry; + // the production mint path always issues a future-dated token. + KeyPair keyPair = newKeyPair(); + long expired = System.currentTimeMillis() / 1000 - 7200; + String token = signRs256(keyPair.getPrivate(), + "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"]," + + "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\"," + + "\"exp\":" + expired + "}"); + + WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows( + WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(token, (RSAPublicKey) keyPair.getPublic(), ISSUER, + EksOidcService.STS_AUDIENCE)); + assertTrue(thrown.getMessage().contains("expired")); + } + + @Test + void rejectsTokenNotYetValid() throws Exception { + KeyPair keyPair = newKeyPair(); + long now = System.currentTimeMillis() / 1000; + String token = signRs256(keyPair.getPrivate(), + "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"]," + + "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\"," + + "\"nbf\":" + (now + 7200) + ",\"exp\":" + (now + 10800) + "}"); + + WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows( + WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(token, (RSAPublicKey) keyPair.getPublic(), ISSUER, + EksOidcService.STS_AUDIENCE)); + assertTrue(thrown.getMessage().contains("not yet valid")); + } + + @Test + void rejectsKeyFromAnotherCluster() { + String otherIssuer = "https://oidc.eks.us-east-1.amazonaws.com/id/OTHERCLUSTER0000000000000000"; + oidcService.ensureKey("other-cluster", otherIssuer); + String token = mint("my-namespace", "my-service-account", null, null); + RSAPublicKey otherKey = oidcService.findVerificationKey(otherIssuer).orElseThrow(); + + assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(token, otherKey, ISSUER, EksOidcService.STS_AUDIENCE)); + } + + @Test + void rejectsMalformedToken() { + assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify("not-a-jwt", publicKey(), ISSUER, EksOidcService.STS_AUDIENCE)); + } + + @Test + void rejectsUnsignedAlgNoneToken() { + String header = base64Url("{\"alg\":\"none\",\"typ\":\"JWT\"}"); + String payload = base64Url("{\"iss\":\"" + ISSUER + "\"," + + "\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"]," + + "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\"," + + "\"exp\":" + (System.currentTimeMillis() / 1000 + 3600) + "}"); + + // The empty third segment must be preserved when splitting, so this is rejected by the + // algorithm check rather than being mistaken for a two-segment malformed token. + WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows( + WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(header + "." + payload + ".", publicKey(), ISSUER, + EksOidcService.STS_AUDIENCE)); + assertTrue(thrown.getMessage().contains("algorithm"), + "expected an algorithm rejection, got: " + thrown.getMessage()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java new file mode 100644 index 0000000000..6bd4e3066a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java @@ -0,0 +1,266 @@ +package io.github.hectorvent.floci.services.eks; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; + +/** + * Full IRSA path: create a cluster, read its OIDC issuer, create a role whose trust policy pins the + * federated OIDC provider to a service account, mint a token for that service account, and exchange + * it via {@code sts:AssumeRoleWithWebIdentity}. + * + *

Also covers the negative cases that matter — wrong service account, tampered signature, wrong + * audience — and the compatibility guarantee that an opaque third-party token is still accepted. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class EksIrsaEndToEndIntegrationTest { + + private static final String JSON = "application/json"; + private static final String FORM = "application/x-www-form-urlencoded"; + private static final String CLUSTER = "irsa-e2e-cluster"; + private static final String ROLE = "irsa-e2e-role"; + private static final String NAMESPACE = "my-namespace"; + private static final String SERVICE_ACCOUNT = "cell-e2e"; + private static final String ACCOUNT = "000000000000"; + + private static String issuer; + private static String roleArn; + + private static String issuerKeyPrefix() { + return issuer.replaceFirst("^https://", ""); + } + + @Test + @Order(1) + void createClusterAndCaptureIssuer() { + issuer = given() + .contentType(JSON) + .body("{\"name\":\"" + CLUSTER + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT + ":role/eks\"}") + .when() + .post("/clusters") + .then() + .statusCode(200) + .body("cluster.identity.oidc.issuer", notNullValue()) + .extract().path("cluster.identity.oidc.issuer"); + } + + @Test + @Order(2) + void createRoleWithFederatedTrustPolicy() { + String prefix = issuerKeyPrefix(); + String trustPolicy = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{\ + "Federated":"arn:aws:iam::%s:oidc-provider/%s"},\ + "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{\ + "%s:sub":"system:serviceaccount:%s:%s","%s:aud":"sts.amazonaws.com"}}}]}""" + .formatted(ACCOUNT, prefix, prefix, NAMESPACE, SERVICE_ACCOUNT, prefix); + + roleArn = given() + .contentType(FORM) + .formParam("Action", "CreateRole") + .formParam("Version", "2010-05-08") + .formParam("RoleName", ROLE) + .formParam("AssumeRolePolicyDocument", trustPolicy) + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn"); + } + + private String mintToken(String namespace, String serviceAccount, String audience) { + StringBuilder body = new StringBuilder("{\"namespace\":\"" + namespace + + "\",\"serviceAccount\":\"" + serviceAccount + "\""); + if (audience != null) { + body.append(",\"audience\":\"").append(audience).append("\""); + } + body.append("}"); + + return given() + .contentType(JSON) + .body(body.toString()) + .when() + .post("/_floci/eks/clusters/" + CLUSTER + "/oidc-token") + .then() + .statusCode(200) + .body("token", notNullValue()) + .extract().path("token"); + } + + private Response assumeRole(String token) { + return given() + .contentType(FORM) + .formParam("Action", "AssumeRoleWithWebIdentity") + .formParam("Version", "2011-06-15") + .formParam("RoleArn", roleArn) + .formParam("RoleSessionName", "irsa-e2e-session") + .formParam("WebIdentityToken", token) + .when() + .post("/"); + } + + @Test + @Order(3) + void mintedTokenAssumesRoleAndReturnsRealClaims() { + String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, null); + + assumeRole(token) + .then() + .statusCode(200) + .body(containsString("ASIA")) + .body(containsString("")) + .body(containsString("")) + // Real claims from the token, not the old hardcoded placeholders. + .body(containsString("system:serviceaccount:" + + NAMESPACE + ":" + SERVICE_ACCOUNT + "")) + .body(containsString("" + issuer + "")) + .body(containsString("sts.amazonaws.com")); + } + + @Test + @Order(4) + void deniesTokenForDifferentServiceAccount() { + String token = mintToken(NAMESPACE, "not-the-trusted-sa", null); + + assumeRole(token) + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + } + + @Test + @Order(5) + void rejectsTamperedSignature() { + String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, null); + String[] parts = token.split("\\.", -1); + // Flip a character mid-signature. The final base64 character of a 256-byte RSA signature + // carries only a few significant bits, so mutating it can decode to identical bytes and + // still verify; a middle character always changes the signature. + int middle = parts[2].length() / 2; + char original = parts[2].charAt(middle); + String flipped = parts[2].substring(0, middle) + + (original == 'A' ? 'B' : 'A') + + parts[2].substring(middle + 1); + + assumeRole(parts[0] + "." + parts[1] + "." + flipped) + .then() + .statusCode(400) + .body(containsString("InvalidIdentityToken")); + } + + @Test + @Order(6) + void rejectsWrongAudience() { + String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, "some.other.audience"); + + assumeRole(token) + .then() + .statusCode(400) + .body(containsString("InvalidIdentityToken")); + } + + @Test + @Order(7) + void rejectsUnsignedTokenNamingAFlociIssuer() { + // An unsigned "header.payload." token must not slip through the opaque-token path: its + // issuer is one Floci hosts, so it has to be validated and rejected, not accepted. + String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, null); + String[] parts = token.split("\\.", -1); + + assumeRole(parts[0] + "." + parts[1] + ".") + .then() + .statusCode(400) + .body(containsString("InvalidIdentityToken")); + } + + @Test + @Order(8) + void opaqueThirdPartyTokenRemainsAccepted() { + // Compatibility guarantee: Floci cannot adjudicate an issuer it does not host, so the + // historical permissive behaviour is preserved rather than failing the call. + assumeRole("dummy-token") + .then() + .statusCode(200) + .body(containsString("ASIA")) + .body(containsString("web-identity-subject")); + } + + @Test + @Order(9) + void jwksAndDiscoveryEndpointsServeTheSigningKey() { + given() + .when() + .get("/_floci/eks/clusters/" + CLUSTER + "/oidc/.well-known/openid-configuration") + .then() + .statusCode(200) + .body("issuer", equalTo(issuer)) + .body("id_token_signing_alg_values_supported[0]", equalTo("RS256")); + + given() + .when() + .get("/_floci/eks/clusters/" + CLUSTER + "/oidc/keys") + .then() + .statusCode(200) + .body("keys[0].kty", equalTo("RSA")) + .body("keys[0].alg", equalTo("RS256")) + .body("keys[0].n", notNullValue()) + .body("keys[0].e", equalTo("AQAB")); + } + + @Test + @Order(10) + void mintRejectsMissingServiceAccount() { + given() + .contentType(JSON) + .body("{\"namespace\":\"" + NAMESPACE + "\"}") + .when() + .post("/_floci/eks/clusters/" + CLUSTER + "/oidc-token") + .then() + .statusCode(400); + } + + @Test + @Order(11) + void mintRejectsUnknownCluster() { + given() + .contentType(JSON) + .body("{\"namespace\":\"" + NAMESPACE + "\",\"serviceAccount\":\"" + SERVICE_ACCOUNT + "\"}") + .when() + .post("/_floci/eks/clusters/no-such-cluster/oidc-token") + .then() + .statusCode(404); + } + + @Test + @Order(12) + void deletingClusterDropsSigningKey() { + given().when().delete("/clusters/" + CLUSTER).then().statusCode(200); + + given() + .when() + .get("/_floci/eks/clusters/" + CLUSTER + "/oidc/keys") + .then() + .statusCode(404); + + // Cleanup runs as the last ordered step rather than in @AfterAll: Quarkus has already shut + // the test HTTP server down by then, so an @AfterAll request fails with a connection reset. + given() + .contentType(FORM) + .formParam("Action", "DeleteRole") + .formParam("Version", "2010-05-08") + .formParam("RoleName", ROLE) + .when() + .post("/") + .then() + .statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcIdentityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcIdentityIntegrationTest.java new file mode 100644 index 0000000000..9b7f7b8b56 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcIdentityIntegrationTest.java @@ -0,0 +1,121 @@ +package io.github.hectorvent.floci.services.eks; + +import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * DescribeCluster must expose {@code identity.oidc.issuer} so IRSA callers can build a trust policy + * referencing the cluster's OIDC provider, and must never expose the signing material behind it. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class EksOidcIdentityIntegrationTest { + + private static final String JSON = "application/json"; + private static final String CLUSTER = "oidc-it-cluster"; + + @Inject + EksOidcService oidcService; + + @Test + @Order(1) + void createClusterReturnsAwsShapedOidcIssuer() { + given() + .contentType(JSON) + .body("{\"name\":\"" + CLUSTER + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/eks\"}") + .when() + .post("/clusters") + .then() + .statusCode(200) + .body("cluster.identity.oidc.issuer", matchesPattern( + "https://oidc\\.eks\\.us-east-1\\.amazonaws\\.com/id/[A-F0-9]{32}")); + } + + @Test + @Order(2) + void describeClusterReturnsStableIssuer() { + String issuer = given() + .when() + .get("/clusters/" + CLUSTER) + .then() + .statusCode(200) + .body("cluster.identity.oidc.issuer", notNullValue()) + .extract().path("cluster.identity.oidc.issuer"); + + // The issuer is persisted, not regenerated per describe — a trust policy written once + // must keep matching. + given() + .when() + .get("/clusters/" + CLUSTER) + .then() + .statusCode(200) + .body("cluster.identity.oidc.issuer", equalTo(issuer)); + } + + @Test + @Order(3) + void describeClusterNeverExposesSigningMaterial() { + // Asserted against the actual stored key rather than a list of guessed field names, so this + // fails if key material is ever surfaced under any property. + ClusterOidcKey stored = oidcService.findKeyByCluster(CLUSTER).orElseThrow(); + + String body = given() + .when() + .get("/clusters/" + CLUSTER) + .then() + .statusCode(200) + .extract().asString(); + + assertFalse(body.contains(stored.getPrivateKey()), + "DescribeCluster response leaked the OIDC private key"); + assertFalse(body.contains(stored.getPublicKey()), + "DescribeCluster response leaked the OIDC public key"); + // A PKCS#8 RSA private key in base64 always begins with this prefix. + assertFalse(body.contains("MII"), "DescribeCluster response contains encoded key material"); + } + + @Test + @Order(4) + void distinctClustersGetDistinctIssuers() { + String second = CLUSTER + "-2"; + String firstIssuer = given() + .when().get("/clusters/" + CLUSTER) + .then().statusCode(200) + .extract().path("cluster.identity.oidc.issuer"); + + String secondIssuer = given() + .contentType(JSON) + .body("{\"name\":\"" + second + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/eks\"}") + .when() + .post("/clusters") + .then() + .statusCode(200) + .extract().path("cluster.identity.oidc.issuer"); + + assertNotEquals(firstIssuer, secondIssuer); + + given().when().delete("/clusters/" + second).then().statusCode(200); + } + + @Test + @Order(5) + void deleteClusterSucceeds() { + given() + .when() + .delete("/clusters/" + CLUSTER) + .then() + .statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java new file mode 100644 index 0000000000..67ecf24f5c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java @@ -0,0 +1,165 @@ +package io.github.hectorvent.floci.services.eks; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Base64; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class EksOidcServiceTest { + + private static final String ISSUER = + "https://oidc.eks.us-east-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789"; + private static final String CLUSTER = "irsa-test-cluster"; + + private EksOidcService oidcService; + + @BeforeEach + void setUp() { + oidcService = new EksOidcService(new StorageFactory(null, null) { + @Override + public StorageBackend create(String serviceName, String fileName, + TypeReference> typeReference) { + return new InMemoryStorage<>(); + } + }, new ObjectMapper()); + } + + private String decodePayload(String token) { + return new String(Base64.getUrlDecoder().decode(token.split("\\.", -1)[1])); + } + + @Test + void newIssuerUrlIsAwsShapedAndUnique() { + String first = oidcService.newIssuerUrl("us-east-1"); + String second = oidcService.newIssuerUrl("us-east-1"); + + assertTrue(first.matches("https://oidc\\.eks\\.us-east-1\\.amazonaws\\.com/id/[A-F0-9]{32}"), + "unexpected issuer shape: " + first); + assertNotEquals(first, second); + assertTrue(oidcService.newIssuerUrl("eu-west-2").contains("oidc.eks.eu-west-2.")); + } + + @Test + void ensureKeyIsIdempotentForTheSameIssuer() { + ClusterOidcKey first = oidcService.ensureKey(CLUSTER, ISSUER); + ClusterOidcKey second = oidcService.ensureKey(CLUSTER, ISSUER); + + assertEquals(first.getKeyId(), second.getKeyId()); + assertEquals(first.getPrivateKey(), second.getPrivateKey()); + } + + @Test + void ensureKeyRotatesWhenTheIssuerChanges() { + ClusterOidcKey original = oidcService.ensureKey(CLUSTER, ISSUER); + ClusterOidcKey rotated = oidcService.ensureKey(CLUSTER, + "https://oidc.eks.us-east-1.amazonaws.com/id/0000000000000000000000000000BEEF"); + + assertNotEquals(original.getPrivateKey(), rotated.getPrivateKey()); + assertTrue(oidcService.findVerificationKey(ISSUER).isEmpty()); + } + + @Test + void findVerificationKeyResolvesAcrossAccounts() { + // STS must resolve an issuer regardless of which account owns the cluster: the caller need + // not be the owner, and an unresolved issuer is treated as a third-party provider — so the + // token would be accepted with no validation at all. + StorageBackend raw = new InMemoryStorage<>(); + var accountAware = new AccountAwareStorageBackend<>(raw, null, "000000000000"); + EksOidcService service = new EksOidcService(new StorageFactory(null, null) { + @Override + @SuppressWarnings("unchecked") + public StorageBackend create(String serviceName, String fileName, + TypeReference> typeReference) { + return (StorageBackend) accountAware; + } + }, new ObjectMapper()); + + service.ensureKeyForAccount("999999999999", CLUSTER, ISSUER); + + // The lookup runs outside any request context, so it resolves to the default account. + assertTrue(service.findVerificationKey(ISSUER).isPresent()); + } + + @Test + void findVerificationKeyResolvesOnlyKnownIssuers() { + oidcService.ensureKey(CLUSTER, ISSUER); + + assertTrue(oidcService.findVerificationKey(ISSUER).isPresent()); + assertTrue(oidcService.findVerificationKey("https://accounts.google.com").isEmpty()); + assertTrue(oidcService.findVerificationKey(null).isEmpty()); + assertTrue(oidcService.findVerificationKey("").isEmpty()); + } + + @Test + void deleteKeyRemovesSigningMaterial() { + oidcService.ensureKey(CLUSTER, ISSUER); + oidcService.deleteKey(CLUSTER); + + assertTrue(oidcService.findKeyByCluster(CLUSTER).isEmpty()); + assertTrue(oidcService.findVerificationKey(ISSUER).isEmpty()); + } + + @Test + void mintedTokenCarriesKubernetesServiceAccountClaims() { + oidcService.ensureKey(CLUSTER, ISSUER); + String payload = decodePayload(oidcService.mintServiceAccountToken( + CLUSTER, ISSUER, "my-namespace", "my-service-account", null, null)); + + assertTrue(payload.contains("\"sub\":\"system:serviceaccount:my-namespace:my-service-account\"")); + assertTrue(payload.contains("\"kubernetes.io\"")); + assertTrue(payload.contains("\"namespace\":\"my-namespace\"")); + assertTrue(payload.contains("\"name\":\"my-service-account\"")); + } + + @Test + void mintRejectsMissingNamespaceOrServiceAccount() { + oidcService.ensureKey(CLUSTER, ISSUER); + + assertThrows(AwsException.class, () -> oidcService.mintServiceAccountToken( + CLUSTER, ISSUER, null, "my-service-account", null, null)); + assertThrows(AwsException.class, () -> oidcService.mintServiceAccountToken( + CLUSTER, ISSUER, " ", "my-service-account", null, null)); + assertThrows(AwsException.class, () -> oidcService.mintServiceAccountToken( + CLUSTER, ISSUER, "my-namespace", null, null, null)); + assertThrows(AwsException.class, () -> oidcService.mintServiceAccountToken( + CLUSTER, ISSUER, "my-namespace", " ", null, null)); + } + + @Test + void mintClampsLifetimeToTheMaximum() { + oidcService.ensureKey(CLUSTER, ISSUER); + long now = System.currentTimeMillis() / 1000; + + String payload = decodePayload(oidcService.mintServiceAccountToken( + CLUSTER, ISSUER, "my-namespace", "my-service-account", null, Integer.MAX_VALUE)); + + long exp = Long.parseLong(payload.replaceAll(".*\"exp\":(\\d+).*", "$1")); + assertTrue(exp <= now + 604800, "expiry was not clamped to 7 days: " + exp); + } + + @Test + void namespaceWithControlCharactersStillProducesAParseableToken() { + // Claims are serialized with Jackson, so a newline is escaped rather than breaking the JSON. + oidcService.ensureKey(CLUSTER, ISSUER); + String payload = decodePayload(oidcService.mintServiceAccountToken( + CLUSTER, ISSUER, "bad\nnamespace\"quote", "my-service-account", null, null)); + + assertFalse(payload.contains("\n"), "raw newline leaked into the JWT payload"); + assertTrue(payload.contains("\\n")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java index 58829be1ec..2d21dfd0b4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.eks; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -12,7 +13,10 @@ import io.github.hectorvent.floci.services.ec2.Ec2ImageCatalog; import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager; +import io.github.hectorvent.floci.services.eks.model.ClusterIdentity; +import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey; import io.github.hectorvent.floci.services.eks.model.ClusterStatus; +import io.github.hectorvent.floci.services.eks.model.OidcIdentity; import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest; import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest; import io.github.hectorvent.floci.services.eks.model.CreateNodeGroupRequest; @@ -24,6 +28,7 @@ import io.github.hectorvent.floci.services.eks.model.NodegroupScalingConfig; import io.github.hectorvent.floci.services.eks.model.NodegroupStatus; import io.github.hectorvent.floci.services.eks.model.ResourcesVpcConfig; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -56,7 +61,8 @@ class EksServiceTest { EksClusterManager clusterManager = null; Ec2Service ec2Service = null; RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); - eksService = new EksService(storageFactory, config, regionResolver, clusterManager, ec2Service); + eksService = new EksService(storageFactory, config, regionResolver, clusterManager, ec2Service, + new EksOidcService(storageFactory, new ObjectMapper())); } private EmulatorConfig testConfig() { @@ -181,6 +187,113 @@ class EksServiceTest { assertNotNull(cluster.getCreatedAt()); } + @Test + void createClusterAssignsOidcIssuerAndKey() { + CreateClusterRequest req = new CreateClusterRequest(); + req.setName("oidc-cluster"); + req.setRoleArn("arn:aws:iam::000000000000:role/eks-role"); + + Cluster cluster = eksService.createCluster(req); + + assertNotNull(cluster.getIdentity()); + assertNotNull(cluster.getIdentity().getOidc()); + assertTrue(cluster.getIdentity().getOidc().getIssuer() + .matches("https://oidc\\.eks\\.us-east-1\\.amazonaws\\.com/id/[A-F0-9]{32}")); + } + + @Test + void initBackfillsOidcIdentityForClustersPersistedBeforeIrsaSupport() { + // A cluster restored from storage without an identity — what an upgrade looks like — must + // gain an issuer and key on startup, or minting and the JWKS routes stay broken for it. + StorageBackend clusterStore = new InMemoryStorage<>(); + StorageBackend keyStore = new InMemoryStorage<>(); + + Cluster legacy = new Cluster(); + legacy.setName("legacy-cluster"); + legacy.setStatus(ClusterStatus.ACTIVE); + clusterStore.put("legacy-cluster", legacy); + assertNull(legacy.getIdentity()); + + EksOidcService oidcService = new EksOidcService( + fixedStorageFactory(keyStore), new ObjectMapper()); + EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(), + new RegionResolver("us-east-1", "000000000000"), null, null, oidcService); + restarted.init(); + + Cluster migrated = restarted.describeCluster("legacy-cluster"); + assertNotNull(migrated.getIdentity()); + String issuer = migrated.getIdentity().getOidc().getIssuer(); + assertTrue(issuer.matches("https://oidc\\.eks\\.us-east-1\\.amazonaws\\.com/id/[A-F0-9]{32}")); + assertTrue(oidcService.findVerificationKey(issuer).isPresent()); + } + + @Test + void initLeavesAnExistingOidcIssuerUnchanged() { + StorageBackend clusterStore = new InMemoryStorage<>(); + StorageBackend keyStore = new InMemoryStorage<>(); + + String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789"; + Cluster existing = new Cluster(); + existing.setName("existing-cluster"); + existing.setIdentity(new ClusterIdentity(new OidcIdentity(issuer))); + clusterStore.put("existing-cluster", existing); + + EksOidcService oidcService = new EksOidcService( + fixedStorageFactory(keyStore), new ObjectMapper()); + EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(), + new RegionResolver("us-east-1", "000000000000"), null, null, oidcService); + restarted.init(); + + // The issuer a trust policy was written against must survive a restart, and its key must + // be present so previously minted tokens still verify. + assertEquals(issuer, + restarted.describeCluster("existing-cluster").getIdentity().getOidc().getIssuer()); + assertTrue(oidcService.findVerificationKey(issuer).isPresent()); + } + + @Test + void initBackfillsUnderTheOwningAccountNotTheDefault() { + // Startup has no request context, so the account-scoped put() resolves to the default + // account. A cluster owned by another account must still be migrated in place, or the owner + // keeps an issuer-less record while a duplicate appears under the default account. + String otherAccount = "999999999999"; + StorageBackend rawClusters = new InMemoryStorage<>(); + StorageBackend rawKeys = new InMemoryStorage<>(); + var clusterStore = new AccountAwareStorageBackend<>(rawClusters, null, "000000000000"); + var keyStore = new AccountAwareStorageBackend<>(rawKeys, null, "000000000000"); + + Cluster legacy = new Cluster(); + legacy.setName("legacy-cluster"); + legacy.setAccountId(otherAccount); + legacy.setStatus(ClusterStatus.ACTIVE); + clusterStore.putForAccount(otherAccount, "legacy-cluster", legacy); + + EksOidcService oidcService = new EksOidcService( + fixedStorageFactory(keyStore), new ObjectMapper()); + new EksService(fixedStorageFactory(clusterStore), testConfig(), + new RegionResolver("us-east-1", "000000000000"), null, null, oidcService).init(); + + Cluster migrated = clusterStore.getForAccount(otherAccount, "legacy-cluster").orElseThrow(); + String issuer = migrated.getIdentity().getOidc().getIssuer(); + assertNotNull(issuer); + // No duplicate stranded under the default account. + assertTrue(clusterStore.getForAccount("000000000000", "legacy-cluster").isEmpty()); + // The signing key is stored under the owner too, and is still resolvable by issuer. + assertTrue(keyStore.getForAccount(otherAccount, "legacy-cluster").isPresent()); + assertTrue(oidcService.findVerificationKey(issuer).isPresent()); + } + + @SuppressWarnings("unchecked") + private StorageFactory fixedStorageFactory(StorageBackend backend) { + return new StorageFactory(null, null) { + @Override + public StorageBackend create(String serviceName, String fileName, + TypeReference> typeReference) { + return (StorageBackend) backend; + } + }; + } + @Test void createClusterDuplicateFails() { CreateClusterRequest req = new CreateClusterRequest(); @@ -202,7 +315,8 @@ class EksServiceTest { } }; RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); - EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service()); + EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service(), + new EksOidcService(storageFactory, new ObjectMapper())); ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig(); vpcConfig.setSubnetIds(List.of("subnet-1", "subnet-2")); @@ -228,7 +342,8 @@ class EksServiceTest { } }; RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); - EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service()); + EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service(), + new EksOidcService(storageFactory, new ObjectMapper())); ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig(); vpcConfig.setSubnetIds(List.of("subnet-default-a", "subnet-default-b")); @@ -261,7 +376,7 @@ class EksServiceTest { }; RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, - realEc2Service()); + realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper())); ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig(); vpcConfig.setSubnetIds(List.of("subnet-default-a", "subnet-default-b")); @@ -290,7 +405,7 @@ class EksServiceTest { }; RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000"); EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, - realEc2Service()); + realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper())); ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig(); vpcConfig.setSubnetIds(List.of("subnet-default-a")); @@ -336,7 +451,7 @@ class EksServiceTest { // The request is for eu-west-2, where that subnet does not exist. RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000"); EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, - ec2Service); + ec2Service, new EksOidcService(storageFactory, new ObjectMapper())); ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig(); vpcConfig.setSubnetIds(List.of(usEastOnlySubnet)); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/WebIdentityTrustPolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/WebIdentityTrustPolicyEvaluatorTest.java new file mode 100644 index 0000000000..3014d5b859 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/WebIdentityTrustPolicyEvaluatorTest.java @@ -0,0 +1,244 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class WebIdentityTrustPolicyEvaluatorTest { + + private static final String PREFIX = + "oidc.eks.us-east-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789"; + private static final String PROVIDER_ARN = "arn:aws:iam::000000000000:oidc-provider/" + PREFIX; + private static final String NAMESPACE = "my-namespace"; + private static final String SERVICE_ACCOUNT = "my-service-account"; + private static final String SUBJECT = "system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT; + + private final WebIdentityTrustPolicyEvaluator evaluator = + new WebIdentityTrustPolicyEvaluator(new ObjectMapper()); + + /** The canonical IRSA trust policy shape. */ + private String irsaTrustPolicy(String subject) { + return """ + { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Principal": { "Federated": "%s" }, + "Action": "sts:AssumeRoleWithWebIdentity", + "Condition": { + "StringEquals": { + "%s:sub": "%s", + "%s:aud": "sts.amazonaws.com" + } + } + }] + }""".formatted(PROVIDER_ARN, PREFIX, subject, PREFIX); + } + + private Map> claims(String subject) { + return Map.of("sub", List.of(subject), "aud", List.of("sts.amazonaws.com")); + } + + private boolean allows(String policy, Map> claims) { + return evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims); + } + + @Test + void allowsMatchingSubjectAndAudience() { + assertTrue(allows(irsaTrustPolicy(SUBJECT), claims(SUBJECT))); + } + + @Test + void deniesDifferentServiceAccount() { + assertFalse(allows(irsaTrustPolicy(SUBJECT), + claims("system:serviceaccount:my-namespace:other-service-account"))); + } + + @Test + void deniesDifferentNamespace() { + assertFalse(allows(irsaTrustPolicy(SUBJECT), + claims("system:serviceaccount:other-ns:" + SERVICE_ACCOUNT))); + } + + @Test + void subjectComparisonIsCaseSensitive() { + // globMatches lowercases both operands; OIDC subjects must not case-fold or a policy for + // "my-service-account" would admit the distinct service account "My-Service-Account". + assertFalse(allows(irsaTrustPolicy("system:serviceaccount:my-namespace:My-Service-Account"), + claims(SUBJECT))); + assertFalse(allows(irsaTrustPolicy(SUBJECT), + claims("system:serviceaccount:my-namespace:My-Service-Account"))); + } + + @Test + void deniesWrongAudience() { + Map> claims = Map.of( + "sub", List.of(SUBJECT), "aud", List.of("some.other.audience")); + assertFalse(allows(irsaTrustPolicy(SUBJECT), claims)); + } + + @Test + void deniesUnrelatedOidcProvider() { + String policy = irsaTrustPolicy(SUBJECT); + assertFalse(evaluator.allows(policy, + "arn:aws:iam::000000000000:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/OTHER", + PREFIX, claims(SUBJECT))); + } + + @Test + void deniesConditionKeyedToAnotherProvider() { + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{ + "oidc.eks.us-east-1.amazonaws.com/id/SOMEONEELSE:sub":"%s"}}}]}""" + .formatted(PROVIDER_ARN, SUBJECT); + assertFalse(allows(policy, claims(SUBJECT))); + } + + @Test + void deniesAwsPrincipalOnlyPolicy() { + String policy = """ + {"Statement":[{"Effect":"Allow", + "Principal":{"AWS":"arn:aws:iam::000000000000:root"}, + "Action":"sts:AssumeRoleWithWebIdentity"}]}"""; + assertFalse(allows(policy, claims(SUBJECT))); + } + + @Test + void deniesWrongAction() { + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRole","Condition":{"StringEquals":{"%s:sub":"%s"}}}]}""" + .formatted(PROVIDER_ARN, PREFIX, SUBJECT); + assertFalse(allows(policy, claims(SUBJECT))); + } + + @Test + void allowsWildcardAction() { + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:*","Condition":{"StringEquals":{"%s:sub":"%s"}}}]}""" + .formatted(PROVIDER_ARN, PREFIX, SUBJECT); + assertTrue(allows(policy, claims(SUBJECT))); + } + + @Test + void explicitDenyOverridesAllow() { + String policy = """ + {"Statement":[ + {"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity", + "Condition":{"StringEquals":{"%s:sub":"%s"}}}, + {"Effect":"Deny","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity"} + ]}""".formatted(PROVIDER_ARN, PREFIX, SUBJECT, PROVIDER_ARN); + assertFalse(allows(policy, claims(SUBJECT))); + } + + @Test + void allowsSubjectListContainingClaim() { + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{ + "%s:sub":["system:serviceaccount:my-namespace:other","%s"]}}}]}""" + .formatted(PROVIDER_ARN, PREFIX, SUBJECT); + assertTrue(allows(policy, claims(SUBJECT))); + } + + @Test + void allowsStringLikeWildcardSubject() { + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringLike":{ + "%s:sub":"system:serviceaccount:my-namespace:*"}}}]}""" + .formatted(PROVIDER_ARN, PREFIX); + assertTrue(allows(policy, claims(SUBJECT))); + } + + @Test + void stringLikeComparisonIsCaseSensitive() { + // StringLike must not fold case either, or a pattern scoped to one namespace would admit a + // differently-cased one. The literal part of the pattern is what matters here. + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringLike":{ + "%s:sub":"system:serviceaccount:My-Namespace:*"}}}]}""" + .formatted(PROVIDER_ARN, PREFIX); + assertFalse(allows(policy, claims(SUBJECT))); + } + + @Test + void stringNotLikeComparisonIsCaseSensitive() { + // The claim differs from the pattern only by case, so it does NOT match, so StringNotLike + // is satisfied and the statement allows. + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringNotLike":{ + "%s:sub":"system:serviceaccount:MY-NAMESPACE:*"}}}]}""" + .formatted(PROVIDER_ARN, PREFIX); + assertTrue(allows(policy, claims(SUBJECT))); + } + + @Test + void caseSensitiveGlobHandlesWildcardsAndQuestionMarks() { + assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("abc", "abc")); + assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("abc", "ABC")); + assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("a*", "abcdef")); + assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("*f", "abcdef")); + assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("a*e?", "abcdef")); + assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("**abc**", "xxabcyy")); + assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("*", "")); + assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("a?c", "ac")); + assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("abc", "abcd")); + assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive(null, "abc")); + assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("abc", null)); + } + + @Test + void allowsFederatedPrincipalWithoutConditions() { + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity"}]}""".formatted(PROVIDER_ARN); + assertTrue(allows(policy, claims(SUBJECT))); + } + + @Test + void deniesUnsupportedConditionOperator() { + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"DateGreaterThan":{ + "aws:CurrentTime":"2020-01-01T00:00:00Z"}}}]}""".formatted(PROVIDER_ARN); + assertFalse(allows(policy, claims(SUBJECT))); + } + + @Test + void deniesNullBlankOrMalformedPolicy() { + assertFalse(allows(null, claims(SUBJECT))); + assertFalse(allows("", claims(SUBJECT))); + assertFalse(allows("{not json", claims(SUBJECT))); + } + + @Test + void handlesSingleStatementObject() { + String policy = """ + {"Statement":{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{ + "%s:sub":"%s"}}}}""".formatted(PROVIDER_ARN, PREFIX, SUBJECT); + assertTrue(allows(policy, claims(SUBJECT))); + } + + @Test + void conditionKeyPrefixIsCaseInsensitive() { + // Condition *keys* are case-insensitive in AWS even though values are not. + String policy = """ + {"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"}, + "Action":"STS:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{ + "%s:SUB":"%s"}}}]}""".formatted(PROVIDER_ARN, PREFIX.toUpperCase(), SUBJECT); + assertTrue(allows(policy, claims(SUBJECT))); + } +}