mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(eks): authenticate EC2 workers through access entries (#3805)
This commit is contained in:
1 parent
459e2bbe7a
commit
6b389c33eb
16 files changed
+464
-34
No files matched your search
@@ -95,6 +95,7 @@ final class Ec2InstanceCredentials {
|
||||
SessionCredential session = new SessionCredential(accessKey, randomString(30), randomString(48),
|
||||
role.getArn(), now.plusSeconds(3600), null, account);
|
||||
session.setEc2InstanceId(instance.getInstanceId());
|
||||
session.setEc2RoleId(role.getRoleId());
|
||||
iam.registerEc2InstanceSession(session);
|
||||
history.add(new Issued(session, role.getRoleId(), instance.getIamInstanceProfileArn()));
|
||||
return Optional.of(session);
|
||||
|
||||
@@ -4632,6 +4632,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
return kp;
|
||||
}
|
||||
|
||||
public Optional<Instance> findInstanceForAccount(String accountId, String region, String instanceId) {
|
||||
return instances instanceof AccountAwareStorageBackend<Instance> aware
|
||||
? aware.getForAccount(accountId, key(region, instanceId)) : instances.get(key(region, instanceId));
|
||||
}
|
||||
|
||||
public Instance findInstanceById(String instanceId) {
|
||||
return instances.scan(k -> true).stream()
|
||||
.filter(i -> instanceId.equals(i.getInstanceId()))
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.eks.model.AccessEntry;
|
||||
@@ -22,6 +23,7 @@ import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Access-entry management metadata; Kubernetes authorization is handled separately. */
|
||||
@@ -132,6 +134,15 @@ public class EksAccessEntryService {
|
||||
return entry;
|
||||
}
|
||||
|
||||
synchronized Optional<AccessEntry> workerEntry(Cluster cluster, String accountId, String principal, String roleId) {
|
||||
requireApiAccess(cluster);
|
||||
String key = prefix(cluster) + principal;
|
||||
Optional<StoredEntry> stored = entries instanceof AccountAwareStorageBackend<StoredEntry> aware
|
||||
? aware.getForAccount(accountId, key) : entries.get(key);
|
||||
return stored.filter(value -> roleId != null && roleId.equals(value.principalId()))
|
||||
.map(StoredEntry::entry).filter(entry -> "EC2_LINUX".equals(entry.type()));
|
||||
}
|
||||
|
||||
public synchronized AccessEntry describe(Cluster cluster, String principal) {
|
||||
requireApiAccess(cluster);
|
||||
return entries.get(prefix(cluster) + principal).map(StoredEntry::entry)
|
||||
|
||||
@@ -210,14 +210,14 @@ 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 and mapped to their Kubernetes identity. The k3s API server POSTs a TokenReview to Floci's
|
||||
// _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());
|
||||
webhookLocalFile = writeWebhookKubeconfig(cluster);
|
||||
if (webhookLocalFile != null) {
|
||||
specBuilder.withHostDockerInternalOnLinux();
|
||||
serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-config-file="
|
||||
@@ -567,12 +567,14 @@ public class EksClusterManager {
|
||||
* written (in which case the caller skips the webhook so cluster creation still succeeds). The
|
||||
* file is later streamed into the container via the Docker API, so no host path is involved.
|
||||
*/
|
||||
private String writeWebhookKubeconfig(String clusterName) {
|
||||
private String writeWebhookKubeconfig(Cluster cluster) {
|
||||
String clusterName = cluster.getName();
|
||||
Path localFile = Paths.get(config.services().eks().dataPath(), "webhook", clusterName, WEBHOOK_CONFIG_FILE)
|
||||
.toAbsolutePath().normalize();
|
||||
try {
|
||||
Files.createDirectories(localFile.getParent());
|
||||
Files.writeString(localFile, buildWebhookKubeconfig(webhookUrl(clusterName)));
|
||||
Files.writeString(localFile, buildWebhookKubeconfig("http://" + dockerHostResolver.resolve() + ":"
|
||||
+ config.port() + webhookPath(cluster)));
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("EKS token-webhook disabled for cluster {0}: could not write kubeconfig: {1}",
|
||||
clusterName, e.getMessage());
|
||||
@@ -697,6 +699,11 @@ public class EksClusterManager {
|
||||
return "http://" + dockerHostResolver.resolve() + ":" + config.port() + webhookPath(clusterName);
|
||||
}
|
||||
|
||||
static String webhookPath(Cluster cluster) {
|
||||
return webhookPath(cluster.getName()) + "?accountId=" + cluster.getAccountId()
|
||||
+ "®ion=" + cluster.getArn().split(":", 6)[3] + "&createdAt=" + cluster.getCreatedAt();
|
||||
}
|
||||
|
||||
static String webhookPath(String clusterName) {
|
||||
return "/_floci/eks/clusters/" + clusterName + "/token-webhook";
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -302,6 +303,11 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
cluster.setEndpoint("https://localhost:" + config.services().eks().apiServerBasePort());
|
||||
}
|
||||
|
||||
public Optional<Cluster> findAuthenticationCluster(String accountId, String name) {
|
||||
return storage instanceof AccountAwareStorageBackend<Cluster> aware
|
||||
? aware.getForAccount(accountId, name) : storage.get(name);
|
||||
}
|
||||
|
||||
public Cluster describeCluster(String name) {
|
||||
return storage.get(name)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
|
||||
@@ -54,32 +54,38 @@ class EksTokenValidator {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
record VerifiedToken(String accessKeyId, String region) {}
|
||||
|
||||
boolean validate(String token, String clusterName) {
|
||||
return verify(token, clusterName).isPresent();
|
||||
}
|
||||
|
||||
Optional<VerifiedToken> verify(String token, String clusterName) {
|
||||
if (token == null || clusterName == null || clusterName.isBlank() || token.length() > MAX_TOKEN_LENGTH) {
|
||||
return false;
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
try {
|
||||
URI request = parseToken(token);
|
||||
if (request == null) {
|
||||
return false;
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Map<String, String> parameters = parseQuery(request.getRawQuery());
|
||||
if (!hasExpectedRequestShape(request, parameters)) {
|
||||
return false;
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
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;
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
String secretKey = secretKey(scope.accessKeyId(), parameters.get("X-Amz-Security-Token"));
|
||||
if (secretKey == null) {
|
||||
return false;
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
String canonicalRequest = canonicalRequest(request, parameters, clusterName);
|
||||
@@ -89,12 +95,13 @@ class EksTokenValidator {
|
||||
+ sha256Hex(canonicalRequest);
|
||||
String expectedSignature = hexEncode(hmacSha256(
|
||||
deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service()), stringToSign));
|
||||
return MessageDigest.isEqual(
|
||||
boolean valid = MessageDigest.isEqual(
|
||||
expectedSignature.getBytes(StandardCharsets.UTF_8),
|
||||
parameters.get("X-Amz-Signature").getBytes(StandardCharsets.UTF_8));
|
||||
return valid ? Optional.of(new VerifiedToken(scope.accessKeyId(), scope.region())) : Optional.empty();
|
||||
} catch (Exception exception) {
|
||||
LOG.debugv("EKS IAM token validation rejected a malformed token: {0}", exception.getMessage());
|
||||
return false;
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+15
-12
@@ -7,12 +7,13 @@ import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Kubernetes token-authentication webhook for k3s-backed EKS clusters.
|
||||
@@ -20,8 +21,8 @@ import java.util.Map;
|
||||
* <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 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.
|
||||
* the request signature, expiration, and signed cluster ID before resolving worker access entries.
|
||||
* Non-worker credentials retain the legacy cluster-admin compatibility behavior.
|
||||
*
|
||||
* <p>This is Floci plumbing under the {@code _floci/...} namespace, not an AWS API.
|
||||
*/
|
||||
@@ -33,34 +34,36 @@ public class EksTokenWebhookController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksTokenWebhookController.class);
|
||||
private final EksTokenValidator tokenValidator;
|
||||
private final EksWorkerAuthentication authentication;
|
||||
|
||||
@Inject
|
||||
public EksTokenWebhookController(EksTokenValidator tokenValidator) {
|
||||
public EksTokenWebhookController(EksTokenValidator tokenValidator, EksWorkerAuthentication authentication) {
|
||||
this.tokenValidator = tokenValidator;
|
||||
this.authentication = authentication;
|
||||
}
|
||||
|
||||
@POST
|
||||
public Response review(@PathParam("clusterName") String clusterName, Map<String, Object> tokenReview) {
|
||||
public Response review(@PathParam("clusterName") String clusterName, @QueryParam("accountId") String accountId,
|
||||
@QueryParam("region") String region, @QueryParam("createdAt") String createdAt,
|
||||
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 = tokenValidator.validate(token, clusterName);
|
||||
Optional<Map<String, Object>> user = tokenValidator.verify(token, clusterName)
|
||||
.flatMap(verified -> authentication.authenticate(verified, clusterName, accountId, region, createdAt));
|
||||
|
||||
if (authenticated) {
|
||||
LOG.debugv("EKS token-webhook: authenticated aws-iam token for cluster {0} as cluster-admin",
|
||||
if (user.isPresent()) {
|
||||
LOG.debugv("EKS token-webhook: authenticated aws-iam token for cluster {0}",
|
||||
clusterName);
|
||||
return Response.ok(Map.of(
|
||||
"apiVersion", apiVersion,
|
||||
"kind", "TokenReview",
|
||||
"status", Map.of(
|
||||
"authenticated", true,
|
||||
"user", Map.of(
|
||||
"username", "floci:aws-iam",
|
||||
"uid", "floci-aws-iam",
|
||||
"groups", List.of("system:masters"))))).build();
|
||||
"user", user.get()))).build();
|
||||
}
|
||||
|
||||
LOG.debugv("EKS token-webhook: rejected aws-iam token for cluster {0}", clusterName);
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.eks.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.IamService.EksSessionIdentity;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Maps verified instance credentials to node identities using server-owned EC2 metadata. */
|
||||
@ApplicationScoped
|
||||
class EksWorkerAuthentication {
|
||||
private final IamService iam;
|
||||
private final EksService eks;
|
||||
private final Ec2Service ec2;
|
||||
private final EksAccessEntryService entries;
|
||||
|
||||
@Inject
|
||||
EksWorkerAuthentication(IamService iam, EksService eks, Ec2Service ec2, EksAccessEntryService entries) {
|
||||
this.iam = iam;
|
||||
this.eks = eks;
|
||||
this.ec2 = ec2;
|
||||
this.entries = entries;
|
||||
}
|
||||
|
||||
Optional<Map<String, Object>> authenticate(EksTokenValidator.VerifiedToken token, String name,
|
||||
String account, String region, String createdAt) {
|
||||
Optional<EksSessionIdentity> session = iam.findEksSessionIdentity(token.accessKeyId());
|
||||
// Keep the existing non-worker compatibility path. Expired/revoked temporary sessions
|
||||
// must never fall through to it after signature validation.
|
||||
if (session.isEmpty()) {
|
||||
return IamService.isTemporaryAccessKey(token.accessKeyId()) ? Optional.empty() : legacyIdentity();
|
||||
}
|
||||
EksSessionIdentity identity = session.get();
|
||||
if (identity.instanceId() == null) {
|
||||
return legacyIdentity();
|
||||
}
|
||||
if (account == null || region == null || createdAt == null || !account.equals(identity.accountId())
|
||||
|| !region.equals(token.region()) || identity.roleArn() == null || identity.roleId() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<Cluster> cluster = eks.findAuthenticationCluster(account, name)
|
||||
.filter(value -> value.getArn() != null && value.getArn().equals(
|
||||
"arn:aws:eks:" + region + ":" + account + ":cluster/" + name))
|
||||
.filter(value -> createdAt.equals(String.valueOf(value.getCreatedAt())));
|
||||
if (cluster.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String roleName = identity.roleArn().substring(identity.roleArn().lastIndexOf('/') + 1);
|
||||
Optional<IamRole> role = iam.findRole(account, roleName)
|
||||
.filter(value -> identity.roleArn().equals(value.getArn()) && identity.roleId().equals(value.getRoleId()));
|
||||
if (role.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
if (entries.workerEntry(cluster.get(), account, identity.roleArn(), identity.roleId()).isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
} catch (AwsException rejected) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<Instance> instance = ec2.findInstanceForAccount(account, region, identity.instanceId())
|
||||
.filter(value -> value.getState() != null && "running".equals(value.getState().getName()))
|
||||
.filter(value -> region.equals(value.getRegion()))
|
||||
.filter(value -> profileMatches(value, account, roleName));
|
||||
if (instance.isEmpty() || instance.get().getPrivateDnsName() == null
|
||||
|| instance.get().getPrivateDnsName().isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(Map.of("username", "system:node:" + instance.get().getPrivateDnsName(),
|
||||
"uid", account + ":" + identity.roleId() + ":" + identity.instanceId(),
|
||||
"groups", List.of("system:bootstrappers", "system:nodes")));
|
||||
}
|
||||
|
||||
private boolean profileMatches(Instance instance, String account, String roleName) {
|
||||
String arn = instance.getIamInstanceProfileArn();
|
||||
if (arn == null || !arn.startsWith("arn:aws:iam::" + account + ":instance-profile/")) {
|
||||
return false;
|
||||
}
|
||||
return iam.findInstanceProfile(account, arn.substring(arn.lastIndexOf('/') + 1))
|
||||
.filter(profile -> arn.equals(profile.getArn()))
|
||||
.filter(profile -> List.of(roleName).equals(profile.getRoleNames())).isPresent();
|
||||
}
|
||||
|
||||
private static Optional<Map<String, Object>> legacyIdentity() {
|
||||
return Optional.of(Map.of("username", "floci:aws-iam", "uid", "floci-aws-iam",
|
||||
"groups", List.of("system:masters")));
|
||||
}
|
||||
}
|
||||
@@ -1883,6 +1883,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
.map(AccessKey::getSecretAccessKey);
|
||||
}
|
||||
|
||||
public record EksSessionIdentity(String accountId, String roleArn, String roleId, String instanceId) {}
|
||||
|
||||
/** Returns only identity metadata, never the session secret or token. */
|
||||
public Optional<EksSessionIdentity> findEksSessionIdentity(String accessKeyId) {
|
||||
return currentSession(accessKeyId).map(session -> new EksSessionIdentity(
|
||||
session.getOriginAccountId(), session.getRoleArn(), session.getEc2RoleId(), session.getEc2InstanceId()));
|
||||
}
|
||||
|
||||
private Optional<SessionCredential> currentSession(String accessKeyId) {
|
||||
return findSessionAnyAccount(accessKeyId)
|
||||
.filter(session -> session.getExpiration() == null || Instant.now().isBefore(session.getExpiration()));
|
||||
|
||||
@@ -24,6 +24,7 @@ public class SessionCredential {
|
||||
/** True when this session belongs to a Floci-launched Lambda container. */
|
||||
private boolean lambdaExecutionRole;
|
||||
private String ec2InstanceId;
|
||||
private String ec2RoleId;
|
||||
|
||||
public SessionCredential() {}
|
||||
|
||||
@@ -92,6 +93,9 @@ public class SessionCredential {
|
||||
public String getOriginAccountId() { return originAccountId; }
|
||||
public void setOriginAccountId(String originAccountId) { this.originAccountId = originAccountId; }
|
||||
|
||||
public String getEc2RoleId() { return ec2RoleId; }
|
||||
public void setEc2RoleId(String ec2RoleId) { this.ec2RoleId = ec2RoleId; }
|
||||
|
||||
public String getEc2InstanceId() { return ec2InstanceId; }
|
||||
public void setEc2InstanceId(String ec2InstanceId) { this.ec2InstanceId = ec2InstanceId; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user