Light, fluffy, and always free - The AWS Local Emulator alternative
fix(eks): validate IAM authentication tokens (#2912)
Simone Primarosa309043baf643
diff --git a/docs/services/eks.md b/docs/services/eks.mdindex e9c0ac9e5f..38f5811323 100644--- a/docs/services/eks.md+++ b/docs/services/eks.md@@ -46,7 +46,11 @@ aws eks update-kubeconfig --name my-clusterkubectl get nodes```-`aws eks update-kubeconfig` wires `aws eks get-token` into the kubeconfig as an exec credential. The bearer token it produces is validated by a **token-authentication webhook** that Floci wires into k3s: the k3s API server POSTs a Kubernetes `TokenReview` to Floci's `/_floci/eks/token-webhook` endpoint, and Floci maps the token to the `system:masters` group (bound to `cluster-admin`). No `aws-iam-authenticator` is required.+`aws eks update-kubeconfig` wires `aws eks get-token` into the kubeconfig as an exec credential. The bearer token contains a SigV4-presigned STS `GetCallerIdentity` request. Floci validates its signature and 60-second presign expiry, then verifies the signed `x-k8s-aws-id` header against the cluster-specific `/_floci/eks/clusters/<cluster-name>/token-webhook` endpoint before mapping the caller to the `system:masters` group (bound to `cluster-admin`). No `aws-iam-authenticator` is required.++Create an IAM access key before using EKS authentication. The public local-development pairs `test`/`test` and `floci`/`floci` are deliberately rejected because the webhook grants cluster-admin access.++Temporary IAM credentials must include their `AWS_SESSION_TOKEN` when signing the token.This webhook is enabled by default (`iam-auth-webhook: true`). Set it to `false` to start k3s without it (in which case `aws eks get-token` tokens are rejected with `401`).diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.javaindex 15aeff762e..ce01f4b3a7 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java@@ -138,9 +138,10 @@ public class EksClusterManager {// Wire a token-authentication webhook so `aws eks get-token` bearer tokens are validated by// Floci and mapped to cluster-admin. The k3s API server POSTs a TokenReview to Floci's- // _floci/eks/token-webhook endpoint. The kubeconfig is copied into the container via the- // Docker API after create and before start (below) — not bind-mounted — so it works the same- // natively and in Docker-in-Docker, with no host-path / host-persistent-path requirement.+ // _floci/eks/clusters/<cluster-name>/token-webhook endpoint. The kubeconfig is copied into+ // the container via the Docker API after create and before start (below), not bind-mounted,+ // so it works the same natively and in Docker-in-Docker, with no host-path /+ // host-persistent-path requirement.String webhookLocalFile = null;if (config.services().eks().iamAuthWebhook()) {webhookLocalFile = writeWebhookKubeconfig(cluster.getName());@@ -495,7 +496,7 @@ public class EksClusterManager {.toAbsolutePath().normalize();try {Files.createDirectories(localFile.getParent());- Files.writeString(localFile, buildWebhookKubeconfig(webhookUrl()));+ Files.writeString(localFile, buildWebhookKubeconfig(webhookUrl(clusterName)));} catch (IOException e) {LOG.warnv("EKS token-webhook disabled for cluster {0}: could not write kubeconfig: {1}",clusterName, e.getMessage());@@ -617,8 +618,12 @@ public class EksClusterManager {}/** The Floci token-webhook URL as reachable from inside the k3s container. */- String webhookUrl() {- return "http://" + dockerHostResolver.resolve() + ":" + config.port() + "/_floci/eks/token-webhook";+ String webhookUrl(String clusterName) {+ return "http://" + dockerHostResolver.resolve() + ":" + config.port() + webhookPath(clusterName);+ }++ static String webhookPath(String clusterName) {+ return "/_floci/eks/clusters/" + clusterName + "/token-webhook";}/**diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.javanew file mode 100644index 0000000000..e8df4806d4--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java@@ -0,0 +1,241 @@+package io.github.hectorvent.floci.services.eks;++import io.github.hectorvent.floci.services.iam.IamService;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import javax.crypto.Mac;+import javax.crypto.spec.SecretKeySpec;+import java.net.URI;+import java.net.URLDecoder;+import java.nio.charset.StandardCharsets;+import java.security.MessageDigest;+import java.time.Clock;+import java.time.Duration;+import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.util.Base64;+import java.util.Comparator;+import java.util.HashMap;+import java.util.Locale;+import java.util.Map;+import java.util.Optional;++/**+ * Validates the SigV4-presigned STS request embedded in an EKS IAM bearer token.+ */+@ApplicationScoped+class EksTokenValidator {++ private static final Logger LOG = Logger.getLogger(EksTokenValidator.class);+ private static final String TOKEN_PREFIX = "k8s-aws-v1.";+ private static final String ALGORITHM = "AWS4-HMAC-SHA256";+ private static final String EMPTY_PAYLOAD_SHA256 =+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";+ private static final String REQUIRED_SIGNED_HEADERS = "host;x-k8s-aws-id";+ private static final int MAX_PRESIGN_EXPIRY_SECONDS = 60;+ private static final int MAX_TOKEN_LENGTH = 4096;+ private static final Duration MAX_FUTURE_SKEW = Duration.ofMinutes(5);+ private static final DateTimeFormatter DATETIME_FORMAT =+ DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);++ private final IamService iamService;+ private final Clock clock;++ @Inject+ EksTokenValidator(IamService iamService) {+ this(iamService, Clock.systemUTC());+ }++ EksTokenValidator(IamService iamService, Clock clock) {+ this.iamService = iamService;+ this.clock = clock;+ }++ boolean validate(String token, String clusterName) {+ if (token == null || clusterName == null || clusterName.isBlank() || token.length() > MAX_TOKEN_LENGTH) {+ return false;+ }++ try {+ URI request = parseToken(token);+ if (request == null) {+ return false;+ }++ Map<String, String> parameters = parseQuery(request.getRawQuery());+ if (!hasExpectedRequestShape(request, parameters)) {+ return false;+ }++ CredentialScope scope = parseCredentialScope(parameters.get("X-Amz-Credential"));+ Instant signedAt = Instant.from(DATETIME_FORMAT.parse(parameters.get("X-Amz-Date")));+ if (!isCurrent(signedAt, parameters.get("X-Amz-Expires"))+ || !scope.date().equals(parameters.get("X-Amz-Date").substring(0, 8))) {+ return false;+ }++ String secretKey = secretKey(scope.accessKeyId(), parameters.get("X-Amz-Security-Token"));+ if (secretKey == null) {+ return false;+ }++ String canonicalRequest = canonicalRequest(request, parameters, clusterName);+ String stringToSign = ALGORITHM + "\n"+ + parameters.get("X-Amz-Date") + "\n"+ + scope.value() + "\n"+ + sha256Hex(canonicalRequest);+ String expectedSignature = hexEncode(hmacSha256(+ deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service()), stringToSign));+ return MessageDigest.isEqual(+ expectedSignature.getBytes(StandardCharsets.UTF_8),+ parameters.get("X-Amz-Signature").getBytes(StandardCharsets.UTF_8));+ } catch (Exception exception) {+ LOG.debugv("EKS IAM token validation rejected a malformed token: {0}", exception.getMessage());+ return false;+ }+ }++ private URI parseToken(String token) {+ if (!token.startsWith(TOKEN_PREFIX)) {+ return null;+ }+ String encodedRequest = token.substring(TOKEN_PREFIX.length());+ if (encodedRequest.isBlank()) {+ return null;+ }+ String decodedRequest = new String(Base64.getUrlDecoder().decode(encodedRequest), StandardCharsets.UTF_8);+ URI request = URI.create(decodedRequest);+ if (!"http".equals(request.getScheme()) && !"https".equals(request.getScheme())) {+ return null;+ }+ if (request.getHost() == null || request.getRawAuthority() == null || request.getUserInfo() != null+ || request.getRawFragment() != null || !"/".equals(request.getRawPath())) {+ return null;+ }+ return request;+ }++ private static boolean hasExpectedRequestShape(URI request, Map<String, String> parameters) {+ return request.getRawQuery() != null+ && "GetCallerIdentity".equals(parameters.get("Action"))+ && "2011-06-15".equals(parameters.get("Version"))+ && ALGORITHM.equals(parameters.get("X-Amz-Algorithm"))+ && REQUIRED_SIGNED_HEADERS.equals(parameters.get("X-Amz-SignedHeaders"))+ && parameters.containsKey("X-Amz-Credential")+ && parameters.containsKey("X-Amz-Date")+ && parameters.containsKey("X-Amz-Expires")+ && parameters.containsKey("X-Amz-Signature");+ }++ private static Map<String, String> parseQuery(String rawQuery) {+ Map<String, String> parameters = new HashMap<>();+ for (String pair : rawQuery.split("&", -1)) {+ int delimiter = pair.indexOf('=');+ if (delimiter <= 0) {+ throw new IllegalArgumentException("query parameter has no value");+ }+ String name = decode(pair.substring(0, delimiter));+ String value = decode(pair.substring(delimiter + 1));+ if (parameters.putIfAbsent(name, value) != null) {+ throw new IllegalArgumentException("query parameter appears more than once");+ }+ }+ return parameters;+ }++ private boolean isCurrent(Instant signedAt, String expiryText) {+ int expirySeconds = Integer.parseInt(expiryText);+ if (expirySeconds <= 0 || expirySeconds > MAX_PRESIGN_EXPIRY_SECONDS) {+ return false;+ }+ Instant now = clock.instant();+ return !signedAt.isAfter(now.plus(MAX_FUTURE_SKEW)) && !now.isAfter(signedAt.plusSeconds(expirySeconds));+ }++ private String secretKey(String accessKeyId, String sessionToken) {+ if (iamService.isSeededDeployerAccessKey(accessKeyId)) {+ return null;+ }+ Optional<String> secretKey = iamService.findSecretKey(accessKeyId, sessionToken);+ return secretKey.orElse(null);+ }++ private static CredentialScope parseCredentialScope(String encodedCredential) {+ String[] parts = encodedCredential.split("/", -1);+ if (parts.length != 5 || parts[0].isBlank() || !parts[1].matches("[0-9]{8}")+ || parts[2].isBlank() || !"sts".equals(parts[3]) || !"aws4_request".equals(parts[4])) {+ throw new IllegalArgumentException("invalid credential scope");+ }+ return new CredentialScope(parts[0], parts[1], parts[2], parts[3]);+ }++ private static String canonicalRequest(URI request, Map<String, String> parameters, String clusterName) {+ String canonicalQuery = parameters.entrySet().stream()+ .filter(parameter -> !"X-Amz-Signature".equals(parameter.getKey()))+ .map(parameter -> awsEncode(parameter.getKey()) + "=" + awsEncode(parameter.getValue()))+ .sorted(Comparator.naturalOrder())+ .reduce((left, right) -> left + "&" + right)+ .orElse("");+ String authority = request.getRawAuthority().toLowerCase(Locale.ROOT);+ return "GET\n/\n"+ + canonicalQuery + "\n"+ + "host:" + authority + "\n"+ + "x-k8s-aws-id:" + clusterName + "\n\n"+ + REQUIRED_SIGNED_HEADERS + "\n"+ + EMPTY_PAYLOAD_SHA256;+ }++ private static String decode(String value) {+ return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8);+ }++ private static String awsEncode(String value) {+ StringBuilder encoded = new StringBuilder();+ for (byte valueByte : value.getBytes(StandardCharsets.UTF_8)) {+ int unsigned = Byte.toUnsignedInt(valueByte);+ if ((unsigned >= 'A' && unsigned <= 'Z') || (unsigned >= 'a' && unsigned <= 'z')+ || (unsigned >= '0' && unsigned <= '9') || unsigned == '-' || unsigned == '_'+ || unsigned == '.' || unsigned == '~') {+ encoded.append((char) unsigned);+ } else {+ encoded.append('%').append(String.format("%02X", unsigned));+ }+ }+ return encoded.toString();+ }++ private static byte[] deriveSigningKey(String secretKey, String date, String region, String service)+ throws Exception {+ byte[] dateKey = hmacSha256(("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8), date);+ byte[] regionKey = hmacSha256(dateKey, region);+ byte[] serviceKey = hmacSha256(regionKey, service);+ return hmacSha256(serviceKey, "aws4_request");+ }++ private static byte[] hmacSha256(byte[] key, String data) throws Exception {+ Mac mac = Mac.getInstance("HmacSHA256");+ mac.init(new SecretKeySpec(key, "HmacSHA256"));+ return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));+ }++ private static String sha256Hex(String input) throws Exception {+ return hexEncode(MessageDigest.getInstance("SHA-256").digest(input.getBytes(StandardCharsets.UTF_8)));+ }++ private static String hexEncode(byte[] bytes) {+ StringBuilder encoded = new StringBuilder(bytes.length * 2);+ for (byte value : bytes) {+ encoded.append(String.format("%02x", value));+ }+ return encoded.toString();+ }++ private record CredentialScope(String accessKeyId, String date, String region, String service) {+ private String value() {+ return date + "/" + region + "/" + service + "/aws4_request";+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.javaindex b970d24902..13c1d9d2ee 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookController.java@@ -1,9 +1,11 @@package io.github.hectorvent.floci.services.eks;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;@@ -16,35 +18,40 @@ import java.util.Map;* Kubernetes token-authentication webhook for k3s-backed EKS clusters.** <p>The k3s API server is configured (see {@code EksClusterManager}) to POST a- * {@code TokenReview} here whenever it receives a bearer token it does not recognise — notably the- * {@code k8s-aws-v1.<presigned-sts-url>} token produced by {@code aws eks get-token}. Floci accepts- * the token and maps it to the {@code system:masters} group, which is bound to {@code cluster-admin}- * by default. This is what makes the native {@code aws eks update-kubeconfig} + {@code kubectl}- * workflow authenticate against a Floci EKS cluster.+ * {@code TokenReview} here whenever it receives a bearer token it does not recognise, notably the+ * {@code k8s-aws-v1.<presigned-sts-url>} token produced by {@code aws eks get-token}. Floci validates+ * the request signature, expiration, and signed cluster ID before mapping the token to the+ * {@code system:masters} group, which is bound to {@code cluster-admin} by default.** <p>This is Floci plumbing under the {@code _floci/...} namespace, not an AWS API.*/@ApplicationScoped-@Path("_floci/eks/token-webhook")+@Path("_floci/eks/clusters/{clusterName}/token-webhook")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public class EksTokenWebhookController {private static final Logger LOG = Logger.getLogger(EksTokenWebhookController.class);- private static final String EKS_TOKEN_PREFIX = "k8s-aws-v1.";+ private final EksTokenValidator tokenValidator;++ @Inject+ public EksTokenWebhookController(EksTokenValidator tokenValidator) {+ this.tokenValidator = tokenValidator;+ }@POST- public Response review(Map<String, Object> tokenReview) {+ public Response review(@PathParam("clusterName") String clusterName, Map<String, Object> tokenReview) {// The response apiVersion MUST match the request's (the kube-apiserver sends v1beta1 by// default and cannot convert a v1 response back). Echo whatever the apiserver sent.String apiVersion = tokenReview != null && tokenReview.get("apiVersion") instanceof String v? v : "authentication.k8s.io/v1";String token = extractToken(tokenReview);- boolean authenticated = token != null && token.startsWith(EKS_TOKEN_PREFIX);+ boolean authenticated = tokenValidator.validate(token, clusterName);if (authenticated) {- LOG.debug("EKS token-webhook: authenticated aws-iam token as cluster-admin");+ LOG.debugv("EKS token-webhook: authenticated aws-iam token for cluster {0} as cluster-admin",+ clusterName);return Response.ok(Map.of("apiVersion", apiVersion,"kind", "TokenReview",@@ -56,7 +63,7 @@ public class EksTokenWebhookController {"groups", List.of("system:masters"))))).build();}- LOG.debug("EKS token-webhook: rejecting unrecognised token");+ LOG.debugv("EKS token-webhook: rejected aws-iam token for cluster {0}", clusterName);return Response.ok(Map.of("apiVersion", apiVersion,"kind", "TokenReview",diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex c135769d18..54ea0aa2d1 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -31,6 +31,8 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;+import java.nio.charset.StandardCharsets;+import java.security.MessageDigest;import java.time.Instant;import java.util.Optional;import java.util.Set;@@ -1810,12 +1812,42 @@ public class IamService implements SessionAccountLookup, ResourceProvider {// Internal helpers// =========================================================================+ /** Returns the secret for an active access key or an unexpired temporary session. */public Optional<String> findSecretKey(String accessKeyId) {- Optional<String> fromAccessKey = accessKeys.get(accessKeyId).map(AccessKey::getSecretAccessKey);- if (fromAccessKey.isPresent()) {- return fromAccessKey;+ return activeAccessKeySecret(accessKeyId)+ .or(() -> currentSession(accessKeyId).map(SessionCredential::getSecretAccessKey));+ }++ /** Returns a temporary session secret only when the issued session token also matches. */+ public Optional<String> findSecretKey(String accessKeyId, String sessionToken) {+ return activeAccessKeySecret(accessKeyId).or(() -> currentSession(accessKeyId)+ .filter(session -> hasMatchingSessionToken(session, sessionToken))+ .map(SessionCredential::getSecretAccessKey));+ }++ /** Whether an access key ID identifies Floci's documented public deployer credential. */+ public boolean isSeededDeployerAccessKey(String accessKeyId) {+ return DEFAULT_DEPLOYER_ACCESS_KEY_ID.equals(accessKeyId);+ }++ private Optional<String> activeAccessKeySecret(String accessKeyId) {+ return accessKeys.get(accessKeyId)+ .filter(accessKey -> "Active".equals(accessKey.getStatus()))+ .map(AccessKey::getSecretAccessKey);+ }++ private Optional<SessionCredential> currentSession(String accessKeyId) {+ return findSessionAnyAccount(accessKeyId)+ .filter(session -> session.getExpiration() == null || Instant.now().isBefore(session.getExpiration()));+ }++ private static boolean hasMatchingSessionToken(SessionCredential session, String sessionToken) {+ if (sessionToken == null || session.getSessionToken() == null) {+ return false;}- return findSessionAnyAccount(accessKeyId).map(SessionCredential::getSecretAccessKey);+ return MessageDigest.isEqual(+ session.getSessionToken().getBytes(StandardCharsets.UTF_8),+ sessionToken.getBytes(StandardCharsets.UTF_8));}public Optional<AccessKey> findAccessKey(String accessKeyId) {@@ -1864,8 +1896,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {*/public void registerSession(String sessionAccessKeyId, String secretAccessKey, String roleArn,java.time.Instant expiration, String sessionPolicyDocument) {+ registerSession(sessionAccessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument);+ }++ /** Stores a temporary credential including the session token required for authentication. */+ public void registerSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,+ String roleArn, java.time.Instant expiration, String sessionPolicyDocument) {sessions.put(sessionAccessKeyId,- new SessionCredential(sessionAccessKeyId, secretAccessKey, roleArn, expiration, sessionPolicyDocument));+ new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn,+ expiration, sessionPolicyDocument));}/**@@ -1876,8 +1915,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {public void registerSession(String sessionAccessKeyId, String secretAccessKey, String roleArn,java.time.Instant expiration, String sessionPolicyDocument,String originAccountId) {+ registerSession(sessionAccessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument,+ originAccountId);+ }++ /** Stores a temporary credential and its origin account. */+ public void registerSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,+ String roleArn, java.time.Instant expiration, String sessionPolicyDocument,+ String originAccountId) {sessions.put(sessionAccessKeyId,- new SessionCredential(sessionAccessKeyId, secretAccessKey, roleArn, expiration,+ new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, expiration,sessionPolicyDocument, originAccountId));}@@ -1885,11 +1932,20 @@ public class IamService implements SessionAccountLookup, ResourceProvider {public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey,String roleArn, java.time.Instant expiration,String sessionPolicyDocument) {+ registerSessionForAccount(accountId, sessionAccessKeyId, secretAccessKey, null, roleArn, expiration,+ sessionPolicyDocument);+ }++ /** Stores a temporary credential in an explicit account namespace. */+ public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey,+ String sessionToken, String roleArn, java.time.Instant expiration,+ String sessionPolicyDocument) {if (accountId == null || accountId.isBlank()) {throw new IllegalArgumentException("Session account ID must not be blank");}SessionCredential session = new SessionCredential(- sessionAccessKeyId, secretAccessKey, roleArn, expiration, sessionPolicyDocument, accountId);+ sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, expiration, sessionPolicyDocument,+ accountId);if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {aware.putForAccount(accountId, sessionAccessKeyId, session);} else {@@ -1903,11 +1959,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {*/public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId,String secretAccessKey, String roleArn) {+ registerLambdaExecutionRoleSession(accountId, sessionAccessKeyId, secretAccessKey, null, roleArn);+ }++ /** Stores a non-expiring Lambda execution-role session with its session token. */+ public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId,+ String secretAccessKey, String sessionToken, String roleArn) {if (accountId == null || accountId.isBlank()) {throw new IllegalArgumentException("Lambda function account ID must not be blank");}SessionCredential session = new SessionCredential(- sessionAccessKeyId, secretAccessKey, roleArn, null, null, accountId);+ sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, null, null, accountId);session.setLambdaExecutionRole(true);if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {aware.putForAccount(accountId, sessionAccessKeyId, session);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.javaindex e4abe1a726..6d8fd608c1 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@@ -116,7 +116,8 @@ public class StsQueryHandler {// IAM token validation can find the temporary secret key, and account routing can map// these temporary credentials to the assumed role's account.String sessionPolicy = getParam(params, "Policy");- iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId);+ iamService.registerSession(+ accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId);String result = new XmlBuilder().raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))@@ -178,7 +179,8 @@ public class StsQueryHandler {String result = credentialsXml(accessKeyId, secretKey, sessionToken, expiration);// No role ARN — route these credentials back to the caller's account.- iamService.registerSession(accessKeyId, secretKey, null, expiration, null, regionResolver.getAccountId());+ iamService.registerSession(+ accessKeyId, secretKey, sessionToken, null, expiration, null, regionResolver.getAccountId());return Response.ok(AwsQueryResponse.envelope("GetSessionToken", AwsNamespaces.STS, result)).build();}@@ -220,7 +222,8 @@ public class StsQueryHandler {String subject = verified != null ? verified.subject() : "web-identity-subject";String sessionPolicy = getParam(params, "Policy");- iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId);+ iamService.registerSession(+ accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId);String result = new XmlBuilder().raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))@@ -342,7 +345,7 @@ public class StsQueryHandler {String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;- iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, null, callerAccountId);+ iamService.registerSession(accessKeyId, secretKey, sessionToken, roleArn, expiration, null, callerAccountId);String result = new XmlBuilder().raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))@@ -379,7 +382,8 @@ public class StsQueryHandler {String sessionPolicy = getParam(params, "Policy");// Register federation token so enforcement can scope its policies via session policy.// The federated-user ARN already carries the caller's account, so reuse it as the origin.- iamService.registerSession(accessKeyId, secretKey, federatedUserArn, expiration, sessionPolicy, accountId);+ iamService.registerSession(+ accessKeyId, secretKey, sessionToken, federatedUserArn, expiration, sessionPolicy, accountId);String result = new XmlBuilder().raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.javaindex 887b60a61d..e1f92a748a 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java@@ -11,6 +11,7 @@ public class SessionCredential {private String accessKeyId;private String secretAccessKey;+ private String sessionToken;private String roleArn;private Instant expiration;/** Inline session policy passed to AssumeRole/GetFederationToken — further restricts role policies. */@@ -40,8 +41,14 @@ public class SessionCredential {public SessionCredential(String accessKeyId, String secretAccessKey, String roleArn, Instant expiration,String sessionPolicyDocument) {+ this(accessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument);+ }++ public SessionCredential(String accessKeyId, String secretAccessKey, String sessionToken, String roleArn,+ Instant expiration, String sessionPolicyDocument) {this.accessKeyId = accessKeyId;this.secretAccessKey = secretAccessKey;+ this.sessionToken = sessionToken;this.roleArn = roleArn;this.expiration = expiration;this.sessionPolicyDocument = sessionPolicyDocument;@@ -49,8 +56,14 @@ public class SessionCredential {public SessionCredential(String accessKeyId, String secretAccessKey, String roleArn, Instant expiration,String sessionPolicyDocument, String originAccountId) {+ this(accessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument, originAccountId);+ }++ public SessionCredential(String accessKeyId, String secretAccessKey, String sessionToken, String roleArn,+ Instant expiration, String sessionPolicyDocument, String originAccountId) {this.accessKeyId = accessKeyId;this.secretAccessKey = secretAccessKey;+ this.sessionToken = sessionToken;this.roleArn = roleArn;this.expiration = expiration;this.sessionPolicyDocument = sessionPolicyDocument;@@ -63,6 +76,9 @@ public class SessionCredential {public String getSecretAccessKey() { return secretAccessKey; }public void setSecretAccessKey(String secretAccessKey) { this.secretAccessKey = secretAccessKey; }+ public String getSessionToken() { return sessionToken; }+ public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; }+public String getRoleArn() { return roleArn; }public void setRoleArn(String roleArn) { this.roleArn = roleArn; }diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.javaindex 6fa803c45b..4a69fdd8ef 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.java@@ -83,7 +83,8 @@ public class LambdaExecutionRoleCredentials {random(SECRET_CHARACTERS, 40),random(SECRET_CHARACTERS, 200));iamService.registerLambdaExecutionRoleSession(- functionAccountId, credentials.accessKeyId(), credentials.secretAccessKey(), roleArn);+ functionAccountId, credentials.accessKeyId(), credentials.secretAccessKey(),+ credentials.sessionToken(), roleArn);return Optional.of(credentials);}diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.javaindex c0c7d98160..a820abe3ee 100644--- a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java+++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java@@ -253,7 +253,7 @@ public class SigninService {Instant expiration = issuedAt.plusSeconds(ACCESS_TOKEN_TTL_SECONDS);String principalArn = "arn:aws:iam::" + accountId + ":root";iamService.registerSessionForAccount(- accountId, accessKeyId, secretAccessKey, principalArn, expiration, null);+ accountId, accessKeyId, secretAccessKey, sessionToken, principalArn, expiration, null);SessionCreds accessToken = new SessionCreds(accessKeyId, secretAccessKey, sessionToken);String idToken = includeIdToken ? idToken(principalArn, accountId, clientId, issuedAt) : null;diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex d9959d6875..bcd6070cb4 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -470,7 +470,7 @@ floci:data-path: ./data/ekskeep-running-on-shutdown: falseendpoint-mode: host # host = https://localhost:<hostPort> (host-reachable); network = container DNS name- iam-auth-webhook: true # wire a token-auth webhook into k3s so `aws eks get-token` works+ iam-auth-webhook: true # validate `aws eks get-token` SigV4 tokens through a k3s webhookecr-registry-mirror: true # inject a registries.yaml so pods can pull images pushed to Floci ECRdisable-cni: false # start k3s without its bundled flannel/kube-proxy so a real CNI (e.g. Cilium) can take overmwaa:diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.javaindex 15194b6785..65937c02af 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java@@ -42,9 +42,14 @@ import static org.mockito.Mockito.when;class EksClusterManagerTest {+ @Test+ void webhookPathBindsAuthenticationToOneCluster() {+ assertEquals("/_floci/eks/clusters/demo/token-webhook", EksClusterManager.webhookPath("demo"));+ }+@Testvoid webhookKubeconfigEmbedsServerUrl() {- String url = "http://host.docker.internal:4566/_floci/eks/token-webhook";+ String url = "http://host.docker.internal:4566/_floci/eks/clusters/demo/token-webhook";String yaml = EksClusterManager.buildWebhookKubeconfig(url);assertTrue(yaml.contains("kind: Config"), "should be a kubeconfig");@@ -55,7 +60,7 @@ class EksClusterManagerTest {@Testvoid webhookKubeconfigUsesContainerNetworkAddress() {- String url = "http://172.18.0.5:4566/_floci/eks/token-webhook";+ String url = "http://172.18.0.5:4566/_floci/eks/clusters/demo/token-webhook";String yaml = EksClusterManager.buildWebhookKubeconfig(url);assertTrue(yaml.contains("server: " + url));}diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenValidatorTest.javanew file mode 100644index 0000000000..6cf3ee2ba2--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenValidatorTest.java@@ -0,0 +1,205 @@+package io.github.hectorvent.floci.services.eks;++import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.testutil.IamServiceTestHelper;+import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;+import org.junit.jupiter.api.Test;++import java.nio.charset.StandardCharsets;+import java.time.Clock;+import java.time.Instant;+import java.time.ZoneOffset;+import java.util.Base64;++import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++class EksTokenValidatorTest {++ private static final String CLUSTER_NAME = "demo";+ private static final String ACCESS_KEY_ID = "AKIDEKSTEST";+ private static final String SECRET_ACCESS_KEY = "eks-secret-key";++ @Test+ void validateAcceptsSignedGetCallerIdentityRequest() throws Exception {+ EksTokenValidator validator = validator();+ String token = token(CLUSTER_NAME, Instant.now(), 60);++ assertTrue(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsThePublicLocalCredentialPair() throws Exception {+ EksTokenValidator validator = validator();+ String token = SigV4TokenTestHelper.createEksToken(CLUSTER_NAME, "test", "test", Instant.now(), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsThePublicSeededDeployerCredential() throws Exception {+ String accessKeyId = "floci";+ String secretAccessKey = "floci";+ IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey(accessKeyId, secretAccessKey);+ EksTokenValidator validator = new EksTokenValidator(iamService);+ String token = SigV4TokenTestHelper.createEksToken(+ CLUSTER_NAME, accessKeyId, secretAccessKey, Instant.now(), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsTamperedSignature() throws Exception {+ EksTokenValidator validator = validator();+ String token = replaceDecodedToken(token(CLUSTER_NAME, Instant.now(), 60),+ "Action=GetCallerIdentity", "Action=GetFederationToken");++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsExpiredToken() throws Exception {+ EksTokenValidator validator = validator();+ String token = token(CLUSTER_NAME, Instant.now().minusSeconds(61), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsTokenWithAStretchedExpiry() throws Exception {+ EksTokenValidator validator = validator();+ String token = token(CLUSTER_NAME, Instant.now(), 61);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsTokenSignedTooFarInTheFuture() throws Exception {+ Instant now = Instant.parse("2026-09-01T22:00:00Z");+ EksTokenValidator validator = validator(Clock.fixed(now, ZoneOffset.UTC));+ String token = token(CLUSTER_NAME, now.plusSeconds(301), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsTokenBoundToAnotherCluster() throws Exception {+ EksTokenValidator validator = validator();+ String token = token("other-cluster", Instant.now(), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsUnknownCredentials() throws Exception {+ EksTokenValidator validator = validator();+ String token = SigV4TokenTestHelper.createEksToken(+ CLUSTER_NAME, "AKIDUNKNOWN", "unknown-secret", Instant.now(), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsInactiveAccessKeys() throws Exception {+ IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey(ACCESS_KEY_ID, SECRET_ACCESS_KEY);+ iamService.findAccessKey(ACCESS_KEY_ID).orElseThrow().setStatus("Inactive");+ EksTokenValidator validator = new EksTokenValidator(iamService);+ String token = token(CLUSTER_NAME, Instant.now(), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsExpiredTemporaryCredentials() throws Exception {+ String accessKeyId = "ASIAEXPIREDTOKEN";+ String secretAccessKey = "expired-session-secret";+ IamService iamService = IamServiceTestHelper.iamServiceWithSessionCredential(+ accessKeyId, secretAccessKey, Instant.now().minusSeconds(1));+ EksTokenValidator validator = new EksTokenValidator(iamService);+ String token = SigV4TokenTestHelper.createEksToken(+ CLUSTER_NAME, accessKeyId, secretAccessKey, Instant.now(), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateAcceptsTemporaryCredentialsWithTheirSessionToken() throws Exception {+ String accessKeyId = "ASIAVALIDSESSION";+ String secretAccessKey = "valid-session-secret";+ String sessionToken = "valid-session-token";+ IamService iamService = IamServiceTestHelper.iamServiceWithSessionCredential(+ accessKeyId, secretAccessKey, sessionToken, Instant.now().plusSeconds(60));+ EksTokenValidator validator = new EksTokenValidator(iamService);+ String token = SigV4TokenTestHelper.createEksToken(+ CLUSTER_NAME, accessKeyId, secretAccessKey, Instant.now(), 60, sessionToken);++ assertTrue(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsLegacyTemporaryCredentialsWithoutAPersistedSessionToken() throws Exception {+ String accessKeyId = "ASIALEGACYMISSING";+ String secretAccessKey = "legacy-missing-secret";+ IamService iamService = IamServiceTestHelper.iamServiceWithSessionCredential(+ accessKeyId, secretAccessKey, null, Instant.now().plusSeconds(60));+ EksTokenValidator validator = new EksTokenValidator(iamService);+ String token = SigV4TokenTestHelper.createEksToken(+ CLUSTER_NAME, accessKeyId, secretAccessKey, Instant.now(), 60, "legacy-session-token");++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsTemporaryCredentialsWithoutTheirSessionToken() throws Exception {+ String accessKeyId = "ASIAMISSINGTOKEN";+ String secretAccessKey = "missing-session-secret";+ IamService iamService = IamServiceTestHelper.iamServiceWithSessionCredential(+ accessKeyId, secretAccessKey, "session-token", Instant.now().plusSeconds(60));+ EksTokenValidator validator = new EksTokenValidator(iamService);+ String token = SigV4TokenTestHelper.createEksToken(+ CLUSTER_NAME, accessKeyId, secretAccessKey, Instant.now(), 60);++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsTemporaryCredentialsWithAnotherSessionToken() throws Exception {+ String accessKeyId = "ASIAMISMATCHTOKEN";+ String secretAccessKey = "mismatch-session-secret";+ IamService iamService = IamServiceTestHelper.iamServiceWithSessionCredential(+ accessKeyId, secretAccessKey, "expected-session-token", Instant.now().plusSeconds(60));+ EksTokenValidator validator = new EksTokenValidator(iamService);+ String token = SigV4TokenTestHelper.createEksToken(+ CLUSTER_NAME, accessKeyId, secretAccessKey, Instant.now(), 60, "another-session-token");++ assertFalse(validator.validate(token, CLUSTER_NAME));+ }++ @Test+ void validateRejectsMalformedToken() {+ assertFalse(validator().validate("k8s-aws-v1.not-a-presigned-sts-request", CLUSTER_NAME));+ }++ private EksTokenValidator validator() {+ return validator(Clock.systemUTC());+ }++ private EksTokenValidator validator(Clock clock) {+ IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey(ACCESS_KEY_ID, SECRET_ACCESS_KEY);+ return new EksTokenValidator(iamService, clock);+ }++ private String token(String clusterName, Instant timestamp, int expirySeconds) throws Exception {+ return SigV4TokenTestHelper.createEksToken(+ clusterName, ACCESS_KEY_ID, SECRET_ACCESS_KEY, timestamp, expirySeconds);+ }++ private static String replaceDecodedToken(String token, String target, String replacement) {+ String prefix = "k8s-aws-v1.";+ String encodedRequest = token.substring(prefix.length());+ String request = new String(Base64.getUrlDecoder().decode(encodedRequest), StandardCharsets.UTF_8);+ String tamperedRequest = request.replace(target, replacement);+ return prefix + Base64.getUrlEncoder().withoutPadding()+ .encodeToString(tamperedRequest.getBytes(StandardCharsets.UTF_8));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.javaindex 4f24af366e..f595111718 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java@@ -1,8 +1,12 @@package io.github.hectorvent.floci.services.eks;+import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.testutil.IamServiceTestHelper;+import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;import jakarta.ws.rs.core.Response;import org.junit.jupiter.api.Test;+import java.time.Instant;import java.util.List;import java.util.Map;@@ -12,7 +16,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue;class EksTokenWebhookControllerTest {- private final EksTokenWebhookController controller = new EksTokenWebhookController();+ private static final String CLUSTER_NAME = "demo";+ private static final String ACCESS_KEY_ID = "AKIDEKSTEST";+ private static final String SECRET_ACCESS_KEY = "eks-secret-key";+ private final IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey(+ ACCESS_KEY_ID, SECRET_ACCESS_KEY);+ private final EksTokenWebhookController controller = new EksTokenWebhookController(+ new EksTokenValidator(iamService));@SuppressWarnings("unchecked")private Map<String, Object> status(Response response) {@@ -29,8 +39,8 @@ class EksTokenWebhookControllerTest {@Test@SuppressWarnings("unchecked")- void awsIamTokenAuthenticatesAsClusterAdmin() {- Response response = controller.review(tokenReview("k8s-aws-v1.aHR0cHM6Ly9zdHM..."));+ void awsIamTokenAuthenticatesAsClusterAdmin() throws Exception {+ Response response = controller.review(CLUSTER_NAME, tokenReview(validToken()));Map<String, Object> status = status(response);assertEquals(Boolean.TRUE, status.get("authenticated"));@@ -41,20 +51,20 @@ class EksTokenWebhookControllerTest {@Testvoid unrecognisedTokenIsRejected() {- Response response = controller.review(tokenReview("some-random-bearer-token"));+ Response response = controller.review(CLUSTER_NAME, tokenReview("some-random-bearer-token"));assertEquals(Boolean.FALSE, status(response).get("authenticated"));}@Testvoid emptyOrMalformedReviewIsRejected() {- assertFalse((Boolean) status(controller.review(Map.of())).get("authenticated"));- assertFalse((Boolean) status(controller.review(+ assertFalse((Boolean) status(controller.review(CLUSTER_NAME, Map.of())).get("authenticated"));+ assertFalse((Boolean) status(controller.review(CLUSTER_NAME,Map.of("spec", Map.of()))).get("authenticated"));}@Test- void responseIsAlwaysAWellFormedTokenReview() {- Response response = controller.review(tokenReview("k8s-aws-v1.abc"));+ void responseIsAlwaysAWellFormedTokenReview() throws Exception {+ Response response = controller.review(CLUSTER_NAME, tokenReview(validToken()));Map<?, ?> body = (Map<?, ?>) response.getEntity();assertEquals("authentication.k8s.io/v1", body.get("apiVersion"));assertEquals("TokenReview", body.get("kind"));@@ -62,17 +72,32 @@ class EksTokenWebhookControllerTest {}@Test- void responseEchoesRequestApiVersion() {+ void responseEchoesRequestApiVersion() throws Exception {// The kube-apiserver defaults to the v1beta1 webhook API and cannot convert a v1- // response back to v1beta1 — the response apiVersion MUST match the request's.+ // response back to v1beta1, so the response apiVersion MUST match the request's.Map<String, Object> v1beta1Review = Map.of("apiVersion", "authentication.k8s.io/v1beta1","kind", "TokenReview",- "spec", Map.of("token", "k8s-aws-v1.abc"));+ "spec", Map.of("token", validToken()));- Response response = controller.review(v1beta1Review);+ Response response = controller.review(CLUSTER_NAME, v1beta1Review);Map<?, ?> body = (Map<?, ?>) response.getEntity();assertEquals("authentication.k8s.io/v1beta1", body.get("apiVersion"));assertEquals(Boolean.TRUE, status(response).get("authenticated"));}++ @Test+ void tokenBoundToAnotherClusterIsRejected() throws Exception {+ String token = SigV4TokenTestHelper.createEksToken(+ "other-cluster", ACCESS_KEY_ID, SECRET_ACCESS_KEY, Instant.now(), 60);++ Response response = controller.review(CLUSTER_NAME, tokenReview(token));++ assertEquals(Boolean.FALSE, status(response).get("authenticated"));+ }++ private String validToken() throws Exception {+ return SigV4TokenTestHelper.createEksToken(+ CLUSTER_NAME, ACCESS_KEY_ID, SECRET_ACCESS_KEY, Instant.now(), 60);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.javaindex 9ea37bbc4e..62653bdc7d 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java@@ -16,12 +16,16 @@ import io.github.hectorvent.floci.services.iam.model.SessionCredential;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;+import java.io.IOException;+import java.nio.file.Files;import java.nio.file.Path;+import java.time.Instant;import java.util.List;import java.util.Map;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;/*** IAM state is persisted through StorageFactory, so it must survive a restart. This builds an@@ -84,6 +88,26 @@ class IamServicePersistenceTest {assertEquals("LambdaExec", restarted.getRole("LambdaExec").getRoleName());}+ @Test+ void legacySessionWithoutStoredTokenCannotAuthenticate(@TempDir Path dir) throws IOException {+ String accessKeyId = "ASIALEGACYPERSISTED";+ String secretAccessKey = "legacy-persisted-secret";+ Files.writeString(dir.resolve("iam-sessions.json"), """+ {+ "%s": {+ "accessKeyId": "%s",+ "secretAccessKey": "%s",+ "expiration": "%s"+ }+ }+ """.formatted(+ accessKeyId, accessKeyId, secretAccessKey, Instant.now().plusSeconds(60)));++ IamService restarted = newService(dir);++ assertTrue(restarted.findSecretKey(accessKeyId, "legacy-session-token").isEmpty());+ }+private IamService newService(Path dir) {return new IamService(load(dir, "iam-users.json", new TypeReference<Map<String, IamUser>>() {}),diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.javaindex e947d782e9..077ddeede8 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java@@ -623,6 +623,24 @@ class IamServiceTest {assertNull(iamService.resolveCallerPolicies("ASIAIOSFODNN7EXAMPLE"));}+ @Test+ void findSecretKeyRequiresTheTemporaryCredentialSessionToken() {+ String accessKeyId = "ASIASESSIONTOKENMATCH";+ iamService.registerSession(+ accessKeyId,+ "temporary-secret",+ "session-token",+ null,+ Instant.now().plusSeconds(3600),+ null+ );++ assertEquals("temporary-secret", iamService.findSecretKey(accessKeyId, "session-token").orElseThrow());+ assertTrue(iamService.findSecretKey(accessKeyId).isPresent());+ assertTrue(iamService.findSecretKey(accessKeyId, "wrong-token").isEmpty());+ assertTrue(iamService.findSecretKey(accessKeyId, null).isEmpty());+ }+// =========================================================================// Session account routing (SessionAccountLookup)// =========================================================================diff --git a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.javaindex 325585f244..f372c4d74e 100644--- a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java@@ -71,6 +71,7 @@ class SigninServiceTest {assertEquals(900, tokens.expiresIn());verify(iam).registerSessionForAccount(eq(ACCOUNT_A), eq(tokens.accessToken().accessKeyId()),eq(tokens.accessToken().secretAccessKey()),+ eq(tokens.accessToken().sessionToken()),eq("arn:aws:iam::" + ACCOUNT_A + ":root"), any(), isNull());assertTokenValidation(() -> exchangeCode(code, VERIFIER));}@@ -251,7 +252,7 @@ class SigninServiceTest {assertEquals(900, result.expiresIn());}verify(iam, times(2)).registerSessionForAccount(eq(ACCOUNT_A), anyString(), anyString(),- anyString(), any(), isNull());+ anyString(), anyString(), any(), isNull());} finally {executor.shutdownNow();}@@ -347,7 +348,7 @@ class SigninServiceTest {assertTrue(allowIssuance.await(5, TimeUnit.SECONDS));return null;}).when(iam).registerSessionForAccount(anyString(), anyString(), anyString(),- anyString(), any(), isNull());+ anyString(), anyString(), any(), isNull());ExecutorService executor = Executors.newFixedThreadPool(2);try {@@ -378,9 +379,9 @@ class SigninServiceTest {TokenResult rotated = refresh(initial.refreshToken());assertNotEquals(initial.refreshToken(), rotated.refreshToken());verify(iam, times(2)).registerSessionForAccount(eq(ACCOUNT_A), anyString(), anyString(),- eq("arn:aws:iam::" + ACCOUNT_A + ":root"), any(), isNull());+ anyString(), eq("arn:aws:iam::" + ACCOUNT_A + ":root"), any(), isNull());verify(iam, never()).registerSessionForAccount(eq(ACCOUNT_B), anyString(), anyString(),- anyString(), any(), isNull());+ anyString(), anyString(), any(), isNull());}private TokenResult issueInitialTokens() throws Exception {diff --git a/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java b/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.javaindex c28db0aae5..bdef283985 100644--- a/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java+++ b/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java@@ -49,6 +49,19 @@ public final class IamServiceTestHelper {@SuppressWarnings("unchecked")public static IamService iamServiceWithSessionCredential(String accessKeyId, String secretAccessKey) {+ return iamServiceWithSessionCredential(+ accessKeyId, secretAccessKey, "session-token", Instant.now().plusSeconds(3600));+ }++ @SuppressWarnings("unchecked")+ public static IamService iamServiceWithSessionCredential(+ String accessKeyId, String secretAccessKey, Instant expiration) {+ return iamServiceWithSessionCredential(accessKeyId, secretAccessKey, "session-token", expiration);+ }++ @SuppressWarnings("unchecked")+ public static IamService iamServiceWithSessionCredential(+ String accessKeyId, String secretAccessKey, String sessionToken, Instant expiration) {try {Constructor<IamService> constructor = IamService.class.getDeclaredConstructor(StorageBackend.class,@@ -63,8 +76,8 @@ public final class IamServiceTestHelper {constructor.setAccessible(true);InMemoryStorage<String, SessionCredential> sessions = new InMemoryStorage<>();- SessionCredential cred = new SessionCredential(accessKeyId, secretAccessKey, null,- Instant.now().plusSeconds(3600), null);+ SessionCredential cred = new SessionCredential(+ accessKeyId, secretAccessKey, sessionToken, null, expiration, null);sessions.put(accessKeyId, cred);return constructor.newInstance(diff --git a/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.java b/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.javaindex d650847936..ef5330e4b7 100644--- a/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.java+++ b/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.java@@ -9,6 +9,7 @@ import java.time.Instant;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;import java.util.ArrayList;+import java.util.Base64;import java.util.Comparator;import java.util.LinkedHashMap;import java.util.List;@@ -33,8 +34,8 @@ public final class SigV4TokenTestHelper {Map<String, String> params = new LinkedHashMap<>();params.put("Action", "connect");params.put("User", user);- return signToken(clusterId, null, clusterId, accessKeyId, secretKey, "us-east-1",- "elasticache", timestamp, expiresSeconds, params);+ return signToken(clusterId, null, accessKeyId, secretKey, "us-east-1",+ "elasticache", timestamp, expiresSeconds, params, Map.of("host", clusterId));}public static String createElastiCacheTokenWithoutUser(@@ -46,8 +47,8 @@ public final class SigV4TokenTestHelper {) throws Exception {Map<String, String> params = new LinkedHashMap<>();params.put("Action", "connect");- return signToken(clusterId, null, clusterId, accessKeyId, secretKey, "us-east-1",- "elasticache", timestamp, expiresSeconds, params);+ return signToken(clusterId, null, accessKeyId, secretKey, "us-east-1",+ "elasticache", timestamp, expiresSeconds, params, Map.of("host", clusterId));}public static String createRdsToken(@@ -62,31 +63,68 @@ public final class SigV4TokenTestHelper {Map<String, String> params = new LinkedHashMap<>();params.put("Action", "connect");params.put("DBUser", dbUser);- return signToken(host, port, host + ":" + port, accessKeyId, secretKey, "us-east-1",- "rds-db", timestamp, expiresSeconds, params);+ return signToken(host, port, accessKeyId, secretKey, "us-east-1",+ "rds-db", timestamp, expiresSeconds, params, Map.of("host", host + ":" + port));+ }++ public static String createEksToken(+ String clusterName,+ String accessKeyId,+ String secretKey,+ Instant timestamp,+ int expiresSeconds+ ) throws Exception {+ return createEksToken(clusterName, accessKeyId, secretKey, timestamp, expiresSeconds, null);+ }++ public static String createEksToken(+ String clusterName,+ String accessKeyId,+ String secretKey,+ Instant timestamp,+ int expiresSeconds,+ String sessionToken+ ) throws Exception {+ String host = "sts.us-east-1.amazonaws.com";+ Map<String, String> params = new LinkedHashMap<>();+ params.put("Action", "GetCallerIdentity");+ params.put("Version", "2011-06-15");+ if (sessionToken != null) {+ params.put("X-Amz-Security-Token", sessionToken);+ }+ String url = "https://" + signToken(host, null, accessKeyId, secretKey, "us-east-1", "sts",+ timestamp, expiresSeconds, params,+ Map.of("host", host, "x-k8s-aws-id", clusterName));+ return "k8s-aws-v1." + Base64.getUrlEncoder().withoutPadding()+ .encodeToString(url.getBytes(StandardCharsets.UTF_8));}private static String signToken(String host,Integer port,- String canonicalHostHeader,String accessKeyId,String secretKey,String region,String service,Instant timestamp,int expiresSeconds,- Map<String, String> params+ Map<String, String> params,+ Map<String, String> signedHeaders) throws Exception {- String date = DateTimeFormatter.BASIC_ISO_DATE.withZone(ZoneOffset.UTC).format(timestamp);+ String date = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC).format(timestamp);String dateTime = DATETIME_FMT.format(timestamp);String credentialScope = date + "/" + region + "/" + service + "/aws4_request";Map<String, String> queryParams = new LinkedHashMap<>(params);+ queryParams.put("X-Amz-Algorithm", "AWS4-HMAC-SHA256");queryParams.put("X-Amz-Credential", accessKeyId + "/" + credentialScope);queryParams.put("X-Amz-Date", dateTime);queryParams.put("X-Amz-Expires", Integer.toString(expiresSeconds));- queryParams.put("X-Amz-SignedHeaders", "host");+ String signedHeaderNames = signedHeaders.keySet().stream()+ .sorted()+ .reduce((left, right) -> left + ";" + right)+ .orElseThrow();+ queryParams.put("X-Amz-SignedHeaders", signedHeaderNames);List<String> encodedPairs = new ArrayList<>();for (Map.Entry<String, String> entry : queryParams.entrySet()) {@@ -98,10 +136,14 @@ public final class SigV4TokenTestHelper {.reduce((a, b) -> a + "&" + b).orElse("");+ String canonicalHeaders = signedHeaders.entrySet().stream()+ .sorted(Map.Entry.comparingByKey())+ .map(entry -> entry.getKey() + ":" + entry.getValue() + "\n")+ .reduce("", String::concat);String canonicalRequest = "GET\n/\n"+ canonicalQuery + "\n"- + "host:" + canonicalHostHeader + "\n\n"- + "host\n"+ + canonicalHeaders + "\n"+ + signedHeaderNames + "\n"+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";String stringToSign = "AWS4-HMAC-SHA256\n"