diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 3c546c512a..a5a1cd3302 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -322,10 +322,12 @@ environment as a Kubernetes pod instead of a Docker container. This is designed for CI/CD clusters where privileged containers and `docker.sock` access are not allowed. Floci talks to the cluster through the standard Kubernetes API: when running inside the cluster it uses its ServiceAccount, and when running outside -it uses your local kubeconfig. Only an inline static bearer `token` or a -client-certificate/client-key credential with a PKCS#8 private key is -supported; `tokenFile`, exec, and auth-provider credential plugins -(`aws eks get-token`, gcloud, etc.) are not, and fail with a named error. +it uses your local kubeconfig. An inline static bearer `token`, a +client-certificate/client-key credential with a PKCS#8 private key, or the +`aws eks get-token --cluster-name [--region ]` exec plugin +(what `aws eks update-kubeconfig` generates) is supported. `--role-arn`, +`tokenFile`, any other exec command, and auth-provider credential plugins +(gcloud, etc.) are not, and fail with a named error. How an invocation works: diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java new file mode 100644 index 0000000000..9354f46758 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java @@ -0,0 +1,507 @@ +package io.github.hectorvent.floci.services.lambda.launcher.kubernetes; + +import com.fasterxml.jackson.databind.JsonNode; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.TreeMap; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +/** + * Mints EKS bearer tokens the way {@code aws eks get-token} does: a presigned + * {@code sts:GetCallerIdentity} URL with an {@code x-k8s-aws-id} header bound into the + * signature, base64url-encoded and prefixed with {@code k8s-aws-v1.}. This is the format + * the {@code aws-iam-authenticator} webhook that fronts EKS clusters expects; see + * https://github.com/kubernetes-sigs/aws-iam-authenticator's token generator for the reference + * implementation this mirrors: a 60-second {@code X-Amz-Expires} (STS ignores it for this + * action; real validity is a verifier-enforced 15 minutes off {@code X-Amz-Date}), refreshed + * a minute early for clock-skew slack. + * + *

Lets the kubernetes Lambda executor reach a real EKS cluster without shelling out to + * the AWS CLI or an exec-credential plugin process, keeping {@link KubernetesApiClient} + * dependency-free (see its class javadoc for why that matters). + * + *

Only {@code eks get-token --cluster-name } is recognized, as {@code aws eks + * update-kubeconfig} actually generates it: {@code get-token} need not be the first two + * arguments (a global {@code --region} always precedes it in a generated kubeconfig, and + * {@code --output json} follows), so recognition scans for that pair anywhere in the args + * list rather than requiring it at a fixed position. {@code --role}/{@code --role-arn} + * (assume-role before minting, in either the subcommand's own long form or the abbreviated + * form {@code update-kubeconfig --role-arn} actually writes) and {@code aws-iam-authenticator + * token} are not supported and are rejected explicitly rather than silently mishandled. + * + *

Credentials are resolved from {@code AWS_ACCESS_KEY_ID}/{@code AWS_SECRET_ACCESS_KEY}/ + * {@code AWS_SESSION_TOKEN}, else the {@code AWS_PROFILE} (default {@code default}) section of + * the shared credentials file ({@code AWS_SHARED_CREDENTIALS_FILE}, else {@code + * ~/.aws/credentials}). Unlike plain env-var precedence, an {@code AWS_PROFILE} the kubeconfig + * exec block's own {@code env} entries name explicitly (how {@code aws eks update-kubeconfig + * --profile

} selects one) is honored ahead of static keys that merely happen to be ambient + * in Floci's own process; only keys the exec block itself sets take precedence over that + * profile. The SSO/IMDS/container-credentials/IRSA legs of the SDK's default chain are not + * implemented. + */ +final class EksTokenMinter { + + private static final String CLUSTER_ID_HEADER = "x-k8s-aws-id"; + private static final String TOKEN_PREFIX = "k8s-aws-v1."; + /** + * The {@code X-Amz-Expires} query value, matching aws-iam-authenticator's token generator. + * STS currently ignores this value for {@code GetCallerIdentity}; the token's real validity + * is {@link #TOKEN_VALIDITY_SECONDS}, enforced by the verifying webhook off {@code X-Amz-Date} + * instead. Kept at parity with the reference implementation rather than raised, since a + * larger value here has no verified effect and isn't what real callers actually send. + */ + private static final int PRESIGN_QUERY_EXPIRES_SECONDS = 60; + /** Real token validity: aws-iam-authenticator's verifier treats every token as good for 15 minutes. */ + private static final int TOKEN_VALIDITY_SECONDS = 15 * 60; + /** Re-mint this long before the token's real validity would expire, for clock-skew slack. */ + private static final int REFRESH_MARGIN_SECONDS = 60; + private static final String EMPTY_BODY_SHA256 = + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + private static final DateTimeFormatter AMZ_DATE = + DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC); + private static final DateTimeFormatter AMZ_DATE_STAMP = + DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC); + + private EksTokenMinter() { + } + + /** + * Returns a caching token supplier if {@code exec} is a recognized {@code aws eks get-token} + * invocation, or empty if it is some other exec/auth-provider plugin this class does not + * handle. When the shape is recognized but a required piece (cluster name, region) is + * missing or unsupported ({@code --role-arn}), throws immediately rather than returning + * empty, so the caller gets a specific error instead of the generic "exec not supported" one. + */ + static Optional> tokenSupplierIfRecognized(JsonNode exec) { + if (!isAwsEksGetToken(exec)) { + return Optional.empty(); + } + var execEnv = execEnv(exec); + UnaryOperator env = name -> execEnv.getOrDefault(name, System.getenv(name)); + var args = parseArgs(exec, env); + return Optional.of(new CachingTokenSupplier(args.clusterName(), args.region(), execEnv)); + } + + /** + * Kubeconfig lets an exec plugin declare extra environment variables under {@code exec.env} + * (a list of {@code {name, value}} pairs). This is how {@code aws eks update-kubeconfig + * --profile

} propagates the profile it was run with, since the exec plugin would + * otherwise be a subprocess with no reason to inherit it. We don't spawn a subprocess, but + * we still need to honor these entries ahead of Floci's own process environment, or a + * profile-scoped kubeconfig silently resolves the wrong AWS identity. + */ + private static Map execEnv(JsonNode exec) { + var envNode = exec.path("env"); + if (!envNode.isArray()) { + return Map.of(); + } + var result = new LinkedHashMap(); + for (var entry : envNode) { + var name = entry.path("name").asText(null); + var value = entry.path("value").asText(null); + if (name != null && value != null) { + result.put(name, value); + } + } + return result; + } + + static boolean isAwsEksGetToken(JsonNode exec) { + var command = exec.path("command").asText(""); + if (command.isBlank()) { + return false; + } + var fileName = Path.of(command).getFileName(); + var commandName = fileName == null ? command : fileName.toString(); + if (!"aws".equals(commandName)) { + return false; + } + return findSubcommandIndex(exec.path("args")) >= 0; + } + + /** + * Finds {@code "eks", "get-token"} as a consecutive pair anywhere in {@code args}, not just + * at the front. {@code aws eks update-kubeconfig} always generates {@code --region + * eks get-token --cluster-name --output json}, i.e. a global option ahead of the + * subcommand (confirmed against the AWS CLI's own {@code update_kubeconfig.py}), so a + * strictly-positional check would reject every kubeconfig that tool actually produces. + */ + private static int findSubcommandIndex(JsonNode args) { + if (!args.isArray()) { + return -1; + } + for (var i = 0; i + 1 < args.size(); i++) { + if ("eks".equals(args.get(i).asText()) && "get-token".equals(args.get(i + 1).asText())) { + return i; + } + } + return -1; + } + + record ExecArgs(String clusterName, String region) { + } + + /** + * Assumes {@link #isAwsEksGetToken(JsonNode)} already returned true for {@code exec}. + * {@code env} is injected (rather than reading {@link System#getenv(String)} directly) so + * the region fallback is deterministically testable regardless of the host's own environment. + */ + static ExecArgs parseArgs(JsonNode exec, UnaryOperator env) { + var args = exec.path("args"); + var subcommandIndex = findSubcommandIndex(args); + String clusterName = null; + String region = null; + for (var i = 0; i < args.size(); i++) { + if (i == subcommandIndex || i == subcommandIndex + 1) { + continue; + } + var arg = args.get(i).asText(); + if (isRoleOption(arg)) { + throw new IllegalStateException( + "kubeconfig exec plugin 'aws eks get-token --role-arn' is not supported: the " + + "kubernetes Lambda executor only mints a token for its own resolved " + + "credentials, not an assumed role. Point --cluster-name at credentials " + + "that already have cluster access."); + } + if (("--cluster-name".equals(arg) || "--region".equals(arg)) && i + 1 < args.size()) { + var value = args.get(++i).asText(); + if ("--cluster-name".equals(arg)) { + clusterName = value; + } else { + region = value; + } + } + } + if (clusterName == null || clusterName.isBlank()) { + throw new IllegalStateException( + "kubeconfig exec plugin 'aws eks get-token' has no --cluster-name argument"); + } + if (region == null || region.isBlank()) { + region = env.apply("AWS_REGION"); + } + if (region == null || region.isBlank()) { + region = env.apply("AWS_DEFAULT_REGION"); + } + if (region == null || region.isBlank()) { + throw new IllegalStateException( + "kubeconfig exec plugin 'aws eks get-token --cluster-name " + clusterName + + "' has no region: pass --region, or set AWS_REGION/AWS_DEFAULT_REGION."); + } + return new ExecArgs(clusterName, region); + } + + /** + * {@code aws eks get-token}'s own flag is {@code --role-arn}, but {@code aws eks + * update-kubeconfig --role-arn } writes the abbreviated {@code --role} into the + * kubeconfig it generates (confirmed against the AWS CLI source). More generally, AWS CLI's + * argument parser accepts any unambiguous prefix of a long option, and {@code role-arn} is + * the only {@code get-token} option starting with "role", so {@code --role-a} and + * {@code --role-ar} are just as valid to a real invocation as {@code --role} itself. Matching + * only the one abbreviation actually seen in generated output, rather than the full prefix + * range, would leave the others free to silently mint a token with ambient or profile + * credentials instead of the requested role: a wrong-identity bug, not a merely + * unsupported-shape one. So every prefix from {@code --role} through {@code --role-arn}, + * with or without a {@code --flag=value} suffix, is rejected explicitly. + */ + private static boolean isRoleOption(String arg) { + var name = arg.split("=", 2)[0]; + return name.length() >= "--role".length() && "--role-arn".startsWith(name); + } + + private static final class CachingTokenSupplier implements Supplier { + private final String clusterName; + private final String region; + private final Map execEnv; + private String token; + private Instant expiresAt = Instant.EPOCH; + + private CachingTokenSupplier(String clusterName, String region, Map execEnv) { + this.clusterName = clusterName; + this.region = region; + this.execEnv = execEnv; + } + + @Override + public synchronized String get() { + var now = Instant.now(); + if (token == null || !now.isBefore(expiresAt.minusSeconds(REFRESH_MARGIN_SECONDS))) { + token = mint(clusterName, region, execEnv); + expiresAt = now.plusSeconds(TOKEN_VALIDITY_SECONDS); + } + return token; + } + } + + private static String mint(String clusterName, String region, Map execEnv) { + return mint(clusterName, region, resolveCredentials(execEnv, System::getenv), Clock.systemUTC()); + } + + /** Package-visible so the signing math is testable with fixed credentials, no env/file I/O. */ + static String mint(String clusterName, String region, AwsCredentials credentials) { + return mint(clusterName, region, credentials, Clock.systemUTC()); + } + + /** + * Package-visible so the signing math is testable against a fixed, independently-verifiable + * timestamp: with a real clock, X-Amz-Date changes every call, so the resulting signature + * can only ever be checked for shape, never against a hard-coded expected value. + */ + static String mint(String clusterName, String region, AwsCredentials credentials, Clock clock) { + var now = clock.instant(); + var amzDate = AMZ_DATE.format(now); + var dateStamp = AMZ_DATE_STAMP.format(now); + var host = stsHost(region); + var credentialScope = dateStamp + "/" + region + "/sts/aws4_request"; + var signedHeaders = "host;" + CLUSTER_ID_HEADER; + + var queryParams = new TreeMap(); + queryParams.put("Action", "GetCallerIdentity"); + queryParams.put("Version", "2011-06-15"); + queryParams.put("X-Amz-Algorithm", "AWS4-HMAC-SHA256"); + queryParams.put("X-Amz-Credential", credentials.accessKeyId() + "/" + credentialScope); + queryParams.put("X-Amz-Date", amzDate); + queryParams.put("X-Amz-Expires", String.valueOf(PRESIGN_QUERY_EXPIRES_SECONDS)); + queryParams.put("X-Amz-SignedHeaders", signedHeaders); + if (credentials.sessionToken() != null && !credentials.sessionToken().isBlank()) { + queryParams.put("X-Amz-Security-Token", credentials.sessionToken()); + } + + var canonicalQueryString = queryParams.entrySet().stream() + .map(e -> uriEncode(e.getKey()) + "=" + uriEncode(e.getValue())) + .collect(Collectors.joining("&")); + + // Sorted by header name ("host" < "x-k8s-aws-id"), matching X-Amz-SignedHeaders above. + var canonicalHeaders = "host:" + host + "\n" + CLUSTER_ID_HEADER + ":" + clusterName + "\n"; + var canonicalRequest = "GET\n/\n" + canonicalQueryString + "\n" + + canonicalHeaders + "\n" + signedHeaders + "\n" + EMPTY_BODY_SHA256; + + var stringToSign = "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n" + + sha256Hex(canonicalRequest); + var signingKey = deriveSigningKey(credentials.secretAccessKey(), dateStamp, region, "sts"); + var signature = hexEncode(hmacSha256(signingKey, stringToSign)); + + var url = "https://" + host + "/?" + canonicalQueryString + "&X-Amz-Signature=" + signature; + return TOKEN_PREFIX + Base64.getUrlEncoder().withoutPadding() + .encodeToString(url.getBytes(StandardCharsets.UTF_8)); + } + + record AwsCredentials(String accessKeyId, String secretAccessKey, String sessionToken) { + } + + /** Maps a region to its STS hostname, honoring the region's actual partition. */ + private static String stsHost(String region) { + return "sts." + region + "." + partitionDnsSuffix(region); + } + + /** + * Sourced from the AWS SDKs' own public partition metadata (e.g. botocore's + * {@code partitions.json}, MIT-licensed and openly published at + * https://github.com/boto/botocore/blob/develop/botocore/data/partitions.json), rather than + * assumed. Covers every partition that metadata currently defines: the commercial + * {@code aws} partition and {@code aws-us-gov} share {@code amazonaws.com} so neither needs + * a case of its own, {@code aws-cn} is the one commonly-hit split, and the classified + * ISO/ISOB/ISOE/ISOF partitions (regions matching {@code us-iso-*}, {@code us-isob-*}, + * {@code eu-isoe-*}, {@code us-isof-*}) each resolve under their own distinct domain. + */ + private static String partitionDnsSuffix(String region) { + if (region.matches("cn-\\w+-\\d+")) { + return "amazonaws.com.cn"; + } + if (region.matches("us-iso-\\w+-\\d+")) { + return "c2s.ic.gov"; + } + if (region.matches("us-isob-\\w+-\\d+")) { + return "sc2s.sgov.gov"; + } + if (region.matches("eu-isoe-\\w+-\\d+")) { + return "cloud.adc-e.uk"; + } + if (region.matches("us-isof-\\w+-\\d+")) { + return "csp.hci.ic.gov"; + } + if (region.matches("eusc-de-\\w+-\\d+")) { + return "amazonaws.eu"; + } + return "amazonaws.com"; + } + + /** + * {@code execEnv} (the kubeconfig exec block's own {@code env} entries, not merged with + * Floci's process environment) is consulted as a unit before falling back to plain env-var + * precedence. {@code aws eks update-kubeconfig --profile

} selects a profile by writing + * exactly {@code AWS_PROFILE} into exec.env, a specific instruction for this resolution; if + * static keys that merely happen to be ambient in Floci's own process were allowed to + * outrank it (as flat "env vars beat profile" precedence would normally do), a profile-scoped + * kubeconfig would silently authenticate as the wrong principal instead of failing loudly or + * using the profile it named. + */ + static AwsCredentials resolveCredentials(Map execEnv, UnaryOperator ambientEnv) { + UnaryOperator env = name -> execEnv.getOrDefault(name, ambientEnv.apply(name)); + + if (hasPairedKeys("exec.env", execEnv.get("AWS_ACCESS_KEY_ID"), execEnv.get("AWS_SECRET_ACCESS_KEY"))) { + // The session token must come from exec.env too, not the merged (execEnv-or-ambient) + // lookup: a session token is only valid for the specific access/secret key pair STS + // issued it alongside, so pairing exec.env's static keys with an unrelated session + // token that merely happens to be ambient in Floci's own process would sign with a + // key/token combination STS never issued together, and reject the request. + return new AwsCredentials(execEnv.get("AWS_ACCESS_KEY_ID"), execEnv.get("AWS_SECRET_ACCESS_KEY"), + execEnv.get("AWS_SESSION_TOKEN")); + } + if (execEnv.containsKey("AWS_PROFILE")) { + return resolveFromSharedCredentialsFile(env, execEnv.get("AWS_PROFILE")); + } + + // execEnv has neither key at this point (the check above already rejected exactly one + // being present), so these are necessarily ambient-sourced; the session token must be + // too, for the same reason as the exec.env branch above. + var accessKeyId = ambientEnv.apply("AWS_ACCESS_KEY_ID"); + var secretAccessKey = ambientEnv.apply("AWS_SECRET_ACCESS_KEY"); + if (hasPairedKeys("the environment", accessKeyId, secretAccessKey)) { + return new AwsCredentials(accessKeyId, secretAccessKey, ambientEnv.apply("AWS_SESSION_TOKEN")); + } + return resolveFromSharedCredentialsFile(env, env.apply("AWS_PROFILE")); + } + + /** + * True if both keys are present, false if both are absent, and throws if exactly one is: + * matching botocore's own env-credential provider, which raises {@code PartialCredentialsError} + * for a lone access key or secret key rather than treating it as "absent, fall through to the + * next provider." Silently falling through here (e.g. to a profile named alongside a broken + * key pair) would mint a token under a different identity than whatever the caller actually + * intended to supply. + */ + private static boolean hasPairedKeys(String source, String accessKeyId, String secretAccessKey) { + var hasAccessKeyId = accessKeyId != null && !accessKeyId.isBlank(); + var hasSecretAccessKey = secretAccessKey != null && !secretAccessKey.isBlank(); + if (hasAccessKeyId != hasSecretAccessKey) { + throw new IllegalStateException( + "Partial AWS credentials in " + source + ": " + + (hasAccessKeyId ? "AWS_ACCESS_KEY_ID is set but AWS_SECRET_ACCESS_KEY is not" + : "AWS_SECRET_ACCESS_KEY is set but AWS_ACCESS_KEY_ID is not") + + ". Set both, or neither."); + } + return hasAccessKeyId; + } + + private static AwsCredentials resolveFromSharedCredentialsFile(UnaryOperator env, String profileEnv) { + var pathValue = env.apply("AWS_SHARED_CREDENTIALS_FILE"); + var path = (pathValue != null && !pathValue.isBlank()) + ? Path.of(pathValue) + : Path.of(System.getProperty("user.home"), ".aws", "credentials"); + if (!Files.exists(path)) { + throw new IllegalStateException( + "Could not resolve AWS credentials to mint an EKS token: no AWS_ACCESS_KEY_ID/" + + "AWS_SECRET_ACCESS_KEY in the environment and no shared credentials file at " + + path + ". Set AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY, or " + + "AWS_SHARED_CREDENTIALS_FILE."); + } + var profile = (profileEnv == null || profileEnv.isBlank()) ? "default" : profileEnv; + var section = readIniSection(path, profile); + var accessKeyId = section.get("aws_access_key_id"); + var secretAccessKey = section.get("aws_secret_access_key"); + if (accessKeyId == null || secretAccessKey == null) { + throw new IllegalStateException( + "AWS credentials profile '" + profile + "' in " + path + + " has no aws_access_key_id/aws_secret_access_key"); + } + return new AwsCredentials(accessKeyId, secretAccessKey, section.get("aws_session_token")); + } + + private static Map readIniSection(Path path, String profile) { + var target = "[" + profile + "]"; + var result = new LinkedHashMap(); + try { + var inSection = false; + for (var raw : Files.readAllLines(path, StandardCharsets.UTF_8)) { + var line = raw.strip(); + if (line.isEmpty() || line.startsWith("#") || line.startsWith(";")) { + continue; + } + if (line.startsWith("[") && line.endsWith("]")) { + inSection = line.equals(target); + continue; + } + if (!inSection) { + continue; + } + var eq = line.indexOf('='); + if (eq > 0) { + result.put(line.substring(0, eq).strip(), line.substring(eq + 1).strip()); + } + } + } catch (IOException e) { + throw new IllegalStateException("Could not read AWS credentials file " + path + ": " + e.getMessage(), e); + } + if (result.isEmpty()) { + throw new IllegalStateException("AWS credentials profile '" + profile + "' not found in " + path); + } + return result; + } + + /** RFC 3986 percent-encoding, byte-wise over UTF-8, per the SigV4 spec (not {@link java.net.URLEncoder}). */ + private static String uriEncode(String input) { + var result = new StringBuilder(); + for (var b : input.getBytes(StandardCharsets.UTF_8)) { + var c = (char) (b & 0xFF); + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') + || c == '-' || c == '_' || c == '.' || c == '~') { + result.append(c); + } else { + result.append('%').append(String.format("%02X", b & 0xFF)); + } + } + return result.toString(); + } + + private static byte[] deriveSigningKey(String secretKey, String date, String region, String service) { + var kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8); + var kDate = hmacSha256(kSecret, date); + var kRegion = hmacSha256(kDate, region); + var kService = hmacSha256(kRegion, service); + return hmacSha256(kService, "aws4_request"); + } + + private static byte[] hmacSha256(byte[] key, String data) { + try { + var mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key, "HmacSHA256")); + return mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Could not compute HMAC-SHA256: " + e.getMessage(), e); + } + } + + private static String sha256Hex(String input) { + try { + var digest = MessageDigest.getInstance("SHA-256"); + return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8))); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Could not compute SHA-256: " + e.getMessage(), e); + } + } + + private static String hexEncode(byte[] bytes) { + var sb = new StringBuilder(bytes.length * 2); + for (var b : bytes) { + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesApiClient.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesApiClient.java index e55a9408ae..36b135395a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesApiClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesApiClient.java @@ -65,8 +65,10 @@ import java.util.stream.Collectors; * {@code ~/.kube/config}), current-context only, with a static bearer token or a * client-certificate/client-key credential (PKCS#8 only). {@code insecure-skip-tls-verify} * is honored (skips both chain and hostname validation, matching kubectl), which covers - * most kind/minikube configs. exec/auth-provider plugins (e.g. {@code aws eks get-token}) - * are not supported and fail with a clear error. + * most kind/minikube configs. The {@code aws eks get-token --cluster-name } exec + * plugin is also recognized and its token minted natively, see {@link EksTokenMinter}; + * any other exec command, {@code --role-arn}, or an auth-provider plugin (e.g. gcloud) + * is not supported and fails with a clear error. * */ @ApplicationScoped @@ -371,12 +373,17 @@ public class KubernetesApiClient { } var token = user.path("token").asText(null); - if (token == null && keyManagers == null) { + Supplier execTokenSupplier = user.has("exec") + ? EksTokenMinter.tokenSupplierIfRecognized(user.path("exec")).orElse(null) + : null; + if (token == null && keyManagers == null && execTokenSupplier == null) { if (user.has("exec") || user.has("auth-provider")) { throw new IllegalStateException( "kubeconfig user '" + userName + "' uses an exec or auth-provider credential " - + "plugin, which the kubernetes Lambda executor does not support. Use a " - + "static token or client-certificate/client-key credential instead."); + + "plugin the kubernetes Lambda executor does not recognize (only 'aws eks " + + "get-token --cluster-name [--region ]' is supported). Use " + + "a static token, client-certificate/client-key credential, or that exec " + + "shape instead."); } throw new IllegalStateException("kubeconfig user '" + userName + "' has no supported credential (token or client-certificate/client-key) in " + path); @@ -394,7 +401,8 @@ public class KubernetesApiClient { httpBuilder.sslParameters(sslParameters); } this.http = httpBuilder.build(); - this.tokenSupplier = token == null ? null : () -> token; + this.tokenSupplier = execTokenSupplier != null ? execTokenSupplier + : token == null ? null : () -> token; } private static Path kubeconfigPath() { diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinterTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinterTest.java new file mode 100644 index 0000000000..4ea87bb430 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinterTest.java @@ -0,0 +1,475 @@ +package io.github.hectorvent.floci.services.lambda.launcher.kubernetes; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Exercises the {@code aws eks get-token} recognition, argument parsing, and the presigned + * {@code sts:GetCallerIdentity} URL that becomes the bearer token, against fixed credentials so + * the tests are deterministic regardless of the host's own AWS environment. What can't be + * checked without a real AWS account (that STS actually accepts the signature) is left to + * manual verification against a real cluster. + */ +class EksTokenMinterTest { + + private static final EksTokenMinter.AwsCredentials CREDENTIALS = + new EksTokenMinter.AwsCredentials("AKIAEXAMPLE", "secret", null); + + @Test + void recognizesAwsEksGetToken() throws Exception { + assertThat(EksTokenMinter.isAwsEksGetToken(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster] + """))).isTrue(); + } + + @Test + void recognizesAwsFromAnAbsolutePath() throws Exception { + assertThat(EksTokenMinter.isAwsEksGetToken(execNode(""" + command: /usr/local/bin/aws + args: [eks, get-token, --cluster-name, my-cluster] + """))).isTrue(); + } + + @Test + void doesNotRecognizeOtherCommands() throws Exception { + assertThat(EksTokenMinter.isAwsEksGetToken(execNode(""" + command: gcloud + args: [container, clusters, get-credentials] + """))).isFalse(); + } + + @Test + void doesNotRecognizeAwsIamAuthenticator() throws Exception { + assertThat(EksTokenMinter.isAwsEksGetToken(execNode(""" + command: aws-iam-authenticator + args: [token, -i, my-cluster] + """))).isFalse(); + } + + @Test + void doesNotRecognizeOtherAwsSubcommands() throws Exception { + assertThat(EksTokenMinter.isAwsEksGetToken(execNode(""" + command: aws + args: [sts, get-caller-identity] + """))).isFalse(); + } + + @Test + void recognizesTheShapeAwsEksUpdateKubeconfigActuallyGenerates() throws Exception { + // Confirmed against the AWS CLI's own update_kubeconfig.py: --region always precedes + // the subcommand, and --output json always follows -- get-token is never args[0]/[1]. + assertThat(EksTokenMinter.isAwsEksGetToken(execNode(""" + command: aws + args: [--region, us-west-2, eks, get-token, --cluster-name, my-cluster, --output, json] + """))).isTrue(); + } + + @Test + void parsesClusterNameAndRegionFromTheGeneratedShape() throws Exception { + var args = EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [--region, us-west-2, eks, get-token, --cluster-name, my-cluster, --output, json] + """), name -> { + throw new AssertionError("--region is given inline, should not fall back to env"); + }); + + assertThat(args.clusterName()).isEqualTo("my-cluster"); + assertThat(args.region()).isEqualTo("us-west-2"); + } + + @Test + void parsesClusterNameAndExplicitRegion() throws Exception { + var args = EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster, --region, eu-west-1] + """), name -> { + throw new AssertionError("should not fall back to env when --region is given"); + }); + + assertThat(args.clusterName()).isEqualTo("my-cluster"); + assertThat(args.region()).isEqualTo("eu-west-1"); + } + + @Test + void fallsBackToAwsRegionEnvVar() throws Exception { + var args = EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster] + """), name -> "AWS_REGION".equals(name) ? "ap-south-1" : null); + + assertThat(args.region()).isEqualTo("ap-south-1"); + } + + @Test + void fallsBackToAwsDefaultRegionEnvVarWhenAwsRegionIsUnset() throws Exception { + var args = EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster] + """), name -> "AWS_DEFAULT_REGION".equals(name) ? "ca-central-1" : null); + + assertThat(args.region()).isEqualTo("ca-central-1"); + } + + @Test + void rejectsMissingClusterName() throws Exception { + assertThatThrownBy(() -> EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --region, us-east-1] + """), name -> null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("--cluster-name"); + } + + @Test + void rejectsRoleArn() throws Exception { + assertThatThrownBy(() -> EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster, --role-arn, arn:aws:iam::111122223333:role/x] + """), name -> null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("--role-arn"); + } + + @Test + void rejectsTheAbbreviatedRoleFlagAwsEksUpdateKubeconfigActuallyGenerates() throws Exception { + // update_kubeconfig.py writes "--role", not "--role-arn", when --role-arn was passed to + // update-kubeconfig. Missing this form would silently mint under ambient credentials + // instead of the requested role, so it must reject exactly like the long form does. + assertThatThrownBy(() -> EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [--region, us-west-2, eks, get-token, --cluster-name, my-cluster, --output, json, --role, arn:aws:iam::111122223333:role/x] + """), name -> null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("--role-arn"); + } + + @Test + void rejectsTheEqualsSignFormOfRoleArn() throws Exception { + assertThatThrownBy(() -> EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster, --role-arn=arn:aws:iam::111122223333:role/x] + """), name -> null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("--role-arn"); + } + + @Test + void rejectsTheEqualsSignFormOfTheAbbreviatedRoleFlag() throws Exception { + assertThatThrownBy(() -> EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster, --role=arn:aws:iam::111122223333:role/x] + """), name -> null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("--role-arn"); + } + + @Test + void rejectsIntermediateUnambiguousRoleArnAbbreviations() throws Exception { + // AWS CLI's argument parser accepts any unambiguous prefix of a long option, and + // role-arn is the only get-token option starting with "role", so these are just as + // valid to a real invocation as the --role form update-kubeconfig actually generates. + for (var abbreviation : new String[]{"--role-a", "--role-ar"}) { + assertThatThrownBy(() -> EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster, %s, arn:aws:iam::111122223333:role/x] + """.formatted(abbreviation)), name -> null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("--role-arn"); + } + } + + @Test + void rejectsWhenNoRegionIsResolvable() throws Exception { + assertThatThrownBy(() -> EksTokenMinter.parseArgs(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster] + """), name -> null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("region"); + } + + @Test + void mintedTokenDecodesToAWellFormedPresignedGetCallerIdentityUrl() throws Exception { + var token = EksTokenMinter.mint("my-cluster", "us-west-2", CREDENTIALS); + + assertThat(token).startsWith("k8s-aws-v1."); + var url = decode(token); + var uri = URI.create(url); + var query = parseQuery(uri); + + assertThat(uri.getScheme()).isEqualTo("https"); + assertThat(uri.getHost()).isEqualTo("sts.us-west-2.amazonaws.com"); + assertThat(query.get("Action")).isEqualTo("GetCallerIdentity"); + assertThat(query.get("Version")).isEqualTo("2011-06-15"); + assertThat(query.get("X-Amz-Algorithm")).isEqualTo("AWS4-HMAC-SHA256"); + assertThat(query.get("X-Amz-Credential")).startsWith("AKIAEXAMPLE/").endsWith("/us-west-2/sts/aws4_request"); + assertThat(query.get("X-Amz-Expires")).isEqualTo("60"); + assertThat(query.get("X-Amz-SignedHeaders")).isEqualTo("host;x-k8s-aws-id"); + assertThat(query.get("X-Amz-Signature")).matches("[0-9a-f]{64}"); + assertThat(query).doesNotContainKey("X-Amz-Security-Token"); + } + + @Test + void mintedSignatureMatchesAnIndependentlyComputedReferenceValue() throws Exception { + // Fixed inputs, cross-checked against a from-scratch Python re-implementation of the + // SigV4 spec (not ported from EksTokenMinter's own code, so it can't share a bug with + // it): canonical request -> string to sign -> HMAC-derived signing key -> signature. + // Structural assertions elsewhere only prove the token has the right shape; this proves + // the actual signature bytes are what the spec says they should be for these inputs. + var credentials = new EksTokenMinter.AwsCredentials( + "AKIAIOSFODNN7EXAMPLE", + "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", + "FQoGZXIvYXdzEXAMPLESESSIONTOKENvaluevaluevalue"); + var clock = Clock.fixed(Instant.parse("2024-01-15T12:00:00Z"), ZoneOffset.UTC); + + var token = EksTokenMinter.mint("my-cluster", "us-west-2", credentials, clock); + var query = parseQuery(URI.create(decode(token))); + + assertThat(query.get("X-Amz-Date")).isEqualTo("20240115T120000Z"); + assertThat(query.get("X-Amz-Credential")) + .isEqualTo("AKIAIOSFODNN7EXAMPLE/20240115/us-west-2/sts/aws4_request"); + assertThat(query.get("X-Amz-Signature")) + .isEqualTo("1f3eff1793d8e9b9ecf0b461c6b40f9aa3029d913ffc70a17b498c932a6c34e1"); + } + + @Test + void includesSecurityTokenWhenSessionTokenIsPresent() throws Exception { + var credentials = new EksTokenMinter.AwsCredentials("AKIAEXAMPLE", "secret", "session-token"); + var query = parseQuery(URI.create(decode(EksTokenMinter.mint("my-cluster", "us-west-2", credentials)))); + + assertThat(query.get("X-Amz-Security-Token")).isEqualTo("session-token"); + } + + @Test + void signatureIsBoundToTheClusterName() throws Exception { + var forClusterA = signatureOf(EksTokenMinter.mint("cluster-a", "us-west-2", CREDENTIALS)); + var forClusterB = signatureOf(EksTokenMinter.mint("cluster-b", "us-west-2", CREDENTIALS)); + + // The whole point of x-k8s-aws-id being a signed header: a token minted for one + // cluster must not verify against another, so the two signatures must differ. + assertThat(forClusterA).isNotEqualTo(forClusterB); + } + + @Test + void signsChinaRegionsAgainstTheChinaStsSuffix() throws Exception { + var uri = URI.create(decode(EksTokenMinter.mint("my-cluster", "cn-north-1", CREDENTIALS))); + + assertThat(uri.getHost()).isEqualTo("sts.cn-north-1.amazonaws.com.cn"); + } + + @Test + void signsGovCloudRegionsAgainstTheStandardStsSuffix() throws Exception { + var uri = URI.create(decode(EksTokenMinter.mint("my-cluster", "us-gov-west-1", CREDENTIALS))); + + assertThat(uri.getHost()).isEqualTo("sts.us-gov-west-1.amazonaws.com"); + } + + @Test + void signsIsoRegionsAgainstTheIsoStsSuffix() throws Exception { + var uri = URI.create(decode(EksTokenMinter.mint("my-cluster", "us-iso-east-1", CREDENTIALS))); + + assertThat(uri.getHost()).isEqualTo("sts.us-iso-east-1.c2s.ic.gov"); + } + + @Test + void signsIsoBRegionsAgainstTheIsoBStsSuffix() throws Exception { + var uri = URI.create(decode(EksTokenMinter.mint("my-cluster", "us-isob-east-1", CREDENTIALS))); + + assertThat(uri.getHost()).isEqualTo("sts.us-isob-east-1.sc2s.sgov.gov"); + } + + @Test + void signsIsoERegionsAgainstTheIsoEStsSuffix() throws Exception { + var uri = URI.create(decode(EksTokenMinter.mint("my-cluster", "eu-isoe-west-1", CREDENTIALS))); + + assertThat(uri.getHost()).isEqualTo("sts.eu-isoe-west-1.cloud.adc-e.uk"); + } + + @Test + void signsIsoFRegionsAgainstTheIsoFStsSuffix() throws Exception { + var uri = URI.create(decode(EksTokenMinter.mint("my-cluster", "us-isof-south-1", CREDENTIALS))); + + assertThat(uri.getHost()).isEqualTo("sts.us-isof-south-1.csp.hci.ic.gov"); + } + + @Test + void signsEuscRegionsAgainstTheEuscStsSuffix() throws Exception { + var uri = URI.create(decode(EksTokenMinter.mint("my-cluster", "eusc-de-east-1", CREDENTIALS))); + + assertThat(uri.getHost()).isEqualTo("sts.eusc-de-east-1.amazonaws.eu"); + } + + @Test + void execEnvSuppliesCredentialsAheadOfTheProcessEnvironment() throws Exception { + var supplier = EksTokenMinter.tokenSupplierIfRecognized(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster, --region, us-west-2] + env: + - name: AWS_ACCESS_KEY_ID + value: AKIAFROMEXECENV + - name: AWS_SECRET_ACCESS_KEY + value: secret-from-exec-env + """)).orElseThrow(); + + var query = parseQuery(URI.create(decode(supplier.get()))); + + // Proves exec.env, not whatever AWS_ACCESS_KEY_ID happens to be in Floci's own + // environment, drove credential resolution -- the bug aws eks update-kubeconfig + // --profile

would otherwise trip, since it threads the profile through exec.env. + assertThat(query.get("X-Amz-Credential")).startsWith("AKIAFROMEXECENV/"); + } + + @Test + void execEnvProfileTakesPrecedenceOverAmbientStaticKeys(@TempDir Path tempDir) throws Exception { + var credentialsFile = tempDir.resolve("credentials"); + Files.writeString(credentialsFile, """ + [work] + aws_access_key_id = AKIAFROMPROFILE + aws_secret_access_key = secret-from-profile + """); + Map execEnv = Map.of("AWS_PROFILE", "work"); + // Simulates static keys that merely happen to be ambient in Floci's own process, + // unrelated to this kubeconfig -- these must not win just because plain env-var + // precedence would normally put raw keys ahead of a profile. + UnaryOperator ambientEnv = name -> switch (name) { + case "AWS_ACCESS_KEY_ID" -> "AKIAAMBIENT"; + case "AWS_SECRET_ACCESS_KEY" -> "ambient-secret"; + case "AWS_SHARED_CREDENTIALS_FILE" -> credentialsFile.toString(); + default -> null; + }; + + var credentials = EksTokenMinter.resolveCredentials(execEnv, ambientEnv); + + assertThat(credentials.accessKeyId()).isEqualTo("AKIAFROMPROFILE"); + } + + @Test + void execEnvExplicitKeysStillOutrankExecEnvProfile() throws Exception { + Map execEnv = Map.of( + "AWS_PROFILE", "work", + "AWS_ACCESS_KEY_ID", "AKIAFROMEXECENV", + "AWS_SECRET_ACCESS_KEY", "secret-from-exec-env"); + + var credentials = EksTokenMinter.resolveCredentials(execEnv, name -> null); + + assertThat(credentials.accessKeyId()).isEqualTo("AKIAFROMEXECENV"); + } + + @Test + void execEnvExplicitKeysDoNotInheritAnUnrelatedAmbientSessionToken() throws Exception { + // A session token is only valid for the specific key pair STS issued it with. If + // exec.env supplies static keys but no session token, an ambient one (left over from + // some unrelated temporary credential set in Floci's own process) must not get + // attached, or the mismatched key/token combination gets rejected by STS. + Map execEnv = Map.of( + "AWS_ACCESS_KEY_ID", "AKIAFROMEXECENV", + "AWS_SECRET_ACCESS_KEY", "secret-from-exec-env"); + UnaryOperator ambientEnv = name -> "AWS_SESSION_TOKEN".equals(name) ? "unrelated-ambient-token" : null; + + var credentials = EksTokenMinter.resolveCredentials(execEnv, ambientEnv); + + assertThat(credentials.sessionToken()).isNull(); + } + + @Test + void ambientKeysDoNotInheritAnUnrelatedExecEnvSessionToken() throws Exception { + // Symmetric case: exec.env names a session token but no keys of its own (nothing real + // generates this, but the risk is the same either direction), so the keys resolved + // from the ambient environment must not pick it up either. + Map execEnv = Map.of("AWS_SESSION_TOKEN", "exec-env-only-token"); + UnaryOperator ambientEnv = name -> switch (name) { + case "AWS_ACCESS_KEY_ID" -> "AKIAAMBIENT"; + case "AWS_SECRET_ACCESS_KEY" -> "ambient-secret"; + default -> null; + }; + + var credentials = EksTokenMinter.resolveCredentials(execEnv, ambientEnv); + + assertThat(credentials.sessionToken()).isNull(); + } + + @Test + void rejectsAPartialExecEnvKeyPairRatherThanFallingThroughToTheProfile() throws Exception { + // AWS_ACCESS_KEY_ID with no AWS_SECRET_ACCESS_KEY alongside AWS_PROFILE is a broken + // config, not "no explicit keys, use the profile" -- silently falling through here + // would mint a token under a different identity than intended. + Map execEnv = Map.of( + "AWS_PROFILE", "work", + "AWS_ACCESS_KEY_ID", "AKIAFROMEXECENV"); + + assertThatThrownBy(() -> EksTokenMinter.resolveCredentials(execEnv, name -> null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("AWS_SECRET_ACCESS_KEY"); + } + + @Test + void rejectsAPartialAmbientKeyPairRatherThanFallingThroughToTheSharedCredentialsFile() throws Exception { + UnaryOperator ambientEnv = name -> "AWS_SECRET_ACCESS_KEY".equals(name) ? "ambient-secret" : null; + + assertThatThrownBy(() -> EksTokenMinter.resolveCredentials(Map.of(), ambientEnv)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("AWS_ACCESS_KEY_ID"); + } + + @Test + void execEnvSuppliesRegionFallbackAheadOfTheProcessEnvironment() throws Exception { + var supplier = EksTokenMinter.tokenSupplierIfRecognized(execNode(""" + command: aws + args: [eks, get-token, --cluster-name, my-cluster] + env: + - name: AWS_REGION + value: eu-central-1 + - name: AWS_ACCESS_KEY_ID + value: AKIAFROMEXECENV + - name: AWS_SECRET_ACCESS_KEY + value: secret-from-exec-env + """)).orElseThrow(); + + var uri = URI.create(decode(supplier.get())); + + assertThat(uri.getHost()).isEqualTo("sts.eu-central-1.amazonaws.com"); + } + + private static String signatureOf(String token) throws Exception { + return parseQuery(URI.create(decode(token))).get("X-Amz-Signature"); + } + + private static String decode(String token) { + assertThat(token).startsWith("k8s-aws-v1."); + return new String(Base64.getUrlDecoder().decode(token.substring("k8s-aws-v1.".length())), + StandardCharsets.UTF_8); + } + + private static Map parseQuery(URI uri) { + return Arrays.stream(uri.getRawQuery().split("&")) + .map(pair -> pair.split("=", 2)) + .collect(Collectors.toMap( + p -> URLDecoder.decode(p[0], StandardCharsets.UTF_8), + p -> URLDecoder.decode(p[1], StandardCharsets.UTF_8))); + } + + private static JsonNode execNode(String yaml) throws Exception { + return new ObjectMapper(new YAMLFactory()).readTree(yaml); + } +}