fix(eks): resolve the token webhook's access keys from any account (#5003)

The EKS token webhook looked long-term keys up through findSecretKey,
which is account-scoped. k3s calls the webhook with no account routing,
so it saw only the default account's keys. A correctly signed
`aws eks get-token` from a user in any other account was rejected:
kubectl reported "the server has asked for the client to provide
credentials".

The webhook now uses a new IamService.findSecretKeyInAnyAccount. It
tries the request's account first and scans the other accounts only on
a miss. Inactive keys are still refused, and temporary (ASIA) keys never
reach the scan. findSecretKey itself stays account-scoped: the
ElastiCache, MemoryDB and RDS IAM-auth proxies verify through it and do
not compare the key's account with the cluster's.

Because a long-term key can now reach the webhook from any account, the
legacy identity (system:masters) is limited to long-term keys owned by the
cluster's account, or by the default account on unscoped webhook paths
that predate per-account clusters. This also tightens one existing case:
a default-account key used to get system:masters on clusters of every
account, and now gets it only on the default account's clusters.

Session credentials without an instance ID still map to the legacy
identity on any cluster; that predates this change and is left alone.

Co-authored-by: Robin Baeckman <27041454+RobinBaeckman@users.noreply.github.com>
This commit is contained in:
Robin BaeckmanandRobin Baeckman authored and GitHub committed 2026-10-03 15:55:34 -05:00
1 parent f8a721ce57
commit 7822b2c396
8 files changed
+243 -17

No files matched your search

@@ -1,9 +1,11 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.config.EmulatorConfig;
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.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
@@ -13,16 +15,65 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class EksTokenWebhookControllerTest {
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 static final String DEFAULT_ACCOUNT = "000000000000";
private final IamService iamService = IamServiceTestHelper.iamServiceWithAccessKeyInAccount(
ACCESS_KEY_ID, SECRET_ACCESS_KEY, DEFAULT_ACCOUNT);
private final EmulatorConfig config = mock(EmulatorConfig.class);
private final EksTokenWebhookController controller = new EksTokenWebhookController(
new EksTokenValidator(iamService), new EksWorkerAuthentication(iamService, null, null, null));
new EksTokenValidator(iamService), new EksWorkerAuthentication(iamService, null, null, null, config));
@BeforeEach
void defaultAccount() {
when(config.defaultAccountId()).thenReturn(DEFAULT_ACCOUNT);
}
@Test
void scopedWebhookAcceptsAKeyOnlyOnAClusterOfItsOwnAccount() throws Exception {
IamService otherAccountKeys = IamServiceTestHelper.iamServiceWithAccessKeyInAccount(
ACCESS_KEY_ID, SECRET_ACCESS_KEY, "111122223333", DEFAULT_ACCOUNT);
EksTokenWebhookController scoped = new EksTokenWebhookController(new EksTokenValidator(otherAccountKeys),
new EksWorkerAuthentication(otherAccountKeys, null, null, null, config));
Response sameAccount = scoped.reviewScoped(CLUSTER_NAME, "111122223333", "us-east-1", "0",
tokenReview(validToken()));
Response otherAccount = scoped.reviewScoped(CLUSTER_NAME, "999988887777", "us-east-1", "0",
tokenReview(validToken()));
assertTrue((Boolean) status(sameAccount).get("authenticated"));
assertFalse((Boolean) status(otherAccount).get("authenticated"));
}
@Test
void defaultAccountKeyIsRejectedOnAnotherAccountsCluster() throws Exception {
Response own = controller.reviewScoped(CLUSTER_NAME, DEFAULT_ACCOUNT, "us-east-1", "0",
tokenReview(validToken()));
Response other = controller.reviewScoped(CLUSTER_NAME, "111122223333", "us-east-1", "0",
tokenReview(validToken()));
assertTrue((Boolean) status(own).get("authenticated"));
assertFalse((Boolean) status(other).get("authenticated"));
}
@Test
void webhookRejectsAnInactiveKey() throws Exception {
IamService inactive = IamServiceTestHelper.iamServiceWithAccessKeyInAccount(
ACCESS_KEY_ID, SECRET_ACCESS_KEY, DEFAULT_ACCOUNT);
inactive.updateAccessKey("test-user", ACCESS_KEY_ID, "Inactive");
EksTokenWebhookController controllerWithInactiveKey = new EksTokenWebhookController(
new EksTokenValidator(inactive), new EksWorkerAuthentication(inactive, null, null, null, config));
Response response = controllerWithInactiveKey.review(CLUSTER_NAME, null, null, null, tokenReview(validToken()));
assertFalse((Boolean) status(response).get("authenticated"));
}
@SuppressWarnings("unchecked")
private Map<String, Object> status(Response response) {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
@@ -26,6 +27,9 @@ import static org.mockito.Mockito.*;
class EksWorkerAuthenticationTest {
private static final String ACCOUNT = "123456789012";
private static final String OTHER_ACCOUNT = "111122223333";
private static final String DEFAULT_ACCOUNT = "000000000000";
private static final String LONG_TERM_KEY = "AKIAUSERKEY";
private static final String REGION = "us-east-1";
private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/path/worker";
private static final String KEY = "ASIAWORKER";
@@ -37,11 +41,13 @@ class EksWorkerAuthenticationTest {
private final Cluster cluster = new Cluster();
private final Instance instance = new Instance();
private final IamRole role = new IamRole("AROA-original", "worker", "/path/", ROLE, "{}");
private final EksWorkerAuthentication auth = new EksWorkerAuthentication(iam, eks, ec2, entries);
private final EmulatorConfig config = mock(EmulatorConfig.class);
private final EksWorkerAuthentication auth = new EksWorkerAuthentication(iam, eks, ec2, entries, config);
private final EksTokenValidator.VerifiedToken verified = new EksTokenValidator.VerifiedToken(KEY, REGION);
@BeforeEach
void setup() {
when(config.defaultAccountId()).thenReturn(DEFAULT_ACCOUNT);
cluster.setName("demo");
cluster.setArn("arn:aws:eks:" + REGION + ":" + ACCOUNT + ":cluster/demo");
cluster.setCreatedAt(CREATED);
@@ -65,7 +71,7 @@ class EksWorkerAuthenticationTest {
@Test
void signedWorkerTokenProducesNodeIdentityWithoutAdministratorGroup() throws Exception {
when(iam.findSecretKey(KEY, "session-token")).thenReturn(Optional.of("worker-secret"));
when(iam.findSecretKeyInAnyAccount(KEY, "session-token")).thenReturn(Optional.of("worker-secret"));
String token = SigV4TokenTestHelper.createEksToken("demo", KEY, "worker-secret", Instant.now(), 60, "session-token");
EksTokenWebhookController controller = new EksTokenWebhookController(new EksTokenValidator(iam), auth);
Map<?, ?> response = (Map<?, ?>) controller.review("demo", ACCOUNT, REGION, CREATED.toString(),
@@ -75,12 +81,48 @@ class EksWorkerAuthenticationTest {
Map<?, ?> user = (Map<?, ?>) status.get("user");
assertEquals("system:node:ip-10-0-0-1.ec2.internal", user.get("username"));
assertEquals(List.of("system:bootstrappers", "system:nodes"), user.get("groups"));
when(iam.findSecretKey(KEY, "session-token")).thenReturn(Optional.empty());
when(iam.findSecretKeyInAnyAccount(KEY, "session-token")).thenReturn(Optional.empty());
response = (Map<?, ?>) controller.review("demo", ACCOUNT, REGION, CREATED.toString(),
Map.of("spec", Map.of("token", token))).getEntity();
assertEquals(Map.of("authenticated", false), response.get("status"));
}
@Test
void longTermKeyOfTheClustersAccountGetsTheLegacyIdentity() {
when(iam.findEksSessionIdentity(LONG_TERM_KEY)).thenReturn(Optional.empty());
when(iam.resolveAccountId(LONG_TERM_KEY)).thenReturn(Optional.of(ACCOUNT));
Optional<Map<String, Object>> user = auth.authenticate(longTermToken(), "demo", ACCOUNT, REGION, CREATED.toString());
assertEquals(List.of("system:masters"), user.orElseThrow().get("groups"));
}
@Test
void longTermKeyOfAnotherAccountIsRejected() {
when(iam.findEksSessionIdentity(LONG_TERM_KEY)).thenReturn(Optional.empty());
when(iam.resolveAccountId(LONG_TERM_KEY)).thenReturn(Optional.of(OTHER_ACCOUNT));
assertTrue(auth.authenticate(longTermToken(), "demo", ACCOUNT, REGION, CREATED.toString()).isEmpty());
}
@Test
void longTermKeyOfNoKnownAccountIsRejected() {
when(iam.findEksSessionIdentity(LONG_TERM_KEY)).thenReturn(Optional.empty());
when(iam.resolveAccountId(LONG_TERM_KEY)).thenReturn(Optional.empty());
assertTrue(auth.authenticate(longTermToken(), "demo", ACCOUNT, REGION, CREATED.toString()).isEmpty());
}
@Test
void unscopedWebhookAdmitsOnlyTheDefaultAccountsKeys() {
// Clusters created before scoped webhook paths call it without an account.
when(iam.findEksSessionIdentity(LONG_TERM_KEY)).thenReturn(Optional.empty());
when(iam.resolveAccountId(LONG_TERM_KEY)).thenReturn(Optional.of(DEFAULT_ACCOUNT));
assertTrue(auth.authenticate(longTermToken(), "demo", null, null, null).isPresent());
when(iam.resolveAccountId(LONG_TERM_KEY)).thenReturn(Optional.of(OTHER_ACCOUNT));
assertTrue(auth.authenticate(longTermToken(), "demo", null, null, null).isEmpty());
}
private static EksTokenValidator.VerifiedToken longTermToken() {
return new EksTokenValidator.VerifiedToken(LONG_TERM_KEY, REGION);
}
@Test
void missingOrStandardEntryDoesNotFallBackToAdministrator() {
entries.delete(cluster, ROLE);
@@ -24,6 +24,7 @@ import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
@@ -1304,6 +1305,70 @@ class IamServiceTest {
assertTrue(service.resolveAccountId(accessKey.getAccessKeyId()).isEmpty());
}
@Test
void findSecretKeyDoesNotResolveAnotherAccountsKey() {
// The ElastiCache, MemoryDB and RDS IAM-auth proxies verify through findSecretKey and do
// not compare the key's account with the cluster's, so another account's key must stay unknown.
AccountAwareStorageBackend<AccessKey> accessKeys = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), null, "000000000000");
AccessKey accessKey = new AccessKey("AKIAOTHERACCOUNTKEY", "other-secret", "worker");
accessKeys.putForAccount("111122223333", accessKey.getAccessKeyId(), accessKey);
IamService service = iamService(false, accessKeys, new InMemoryStorage<>());
assertTrue(service.findSecretKey(accessKey.getAccessKeyId()).isEmpty());
assertTrue(service.findSecretKey(accessKey.getAccessKeyId(), null).isEmpty());
}
@Test
void findSecretKeyInAnyAccountResolvesLongTermKeyFromAnotherAccount() {
AccountAwareStorageBackend<AccessKey> accessKeys = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), null, "000000000000");
AccessKey accessKey = new AccessKey("AKIAOTHERACCOUNTKEY", "other-secret", "worker");
accessKeys.putForAccount("111122223333", accessKey.getAccessKeyId(), accessKey);
IamService service = iamService(false, accessKeys, new InMemoryStorage<>());
assertEquals("other-secret", service.findSecretKeyInAnyAccount(accessKey.getAccessKeyId(), null).orElseThrow());
}
@Test
void findSecretKeyInAnyAccountOfTheRequestAccountDoesNotScanOtherAccounts() {
AccountAwareStorageBackend<AccessKey> accessKeys = Mockito.spy(new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), null, "000000000000"));
AccessKey accessKey = new AccessKey("AKIAOWNACCOUNTKEY", "own-secret", "dev");
accessKeys.putForAccount("000000000000", accessKey.getAccessKeyId(), accessKey);
IamService service = iamService(false, accessKeys, new InMemoryStorage<>());
assertEquals("own-secret", service.findSecretKeyInAnyAccount(accessKey.getAccessKeyId(), null).orElseThrow());
Mockito.verify(accessKeys, Mockito.never()).scanAllAccountEntries(Mockito.any());
}
@Test
void findSecretKeyInAnyAccountOfATemporaryKeyDoesNotScanLongTermKeys() {
AccountAwareStorageBackend<AccessKey> accessKeys = Mockito.spy(new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), null, "000000000000"));
IamService service = iamService(false, accessKeys, new InMemoryStorage<>());
service.findSecretKeyInAnyAccount("ASIATEMPORARYKEY1234", "session-token");
Mockito.verify(accessKeys, Mockito.never()).scanAllAccountEntries(Mockito.any());
}
@Test
void findSecretKeyInAnyAccountIgnoresInactiveKeyInAnotherAccount() {
AccountAwareStorageBackend<AccessKey> accessKeys = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), null, "000000000000");
AccessKey accessKey = new AccessKey("AKIAOTHERINACTIVE", "other-secret", "worker");
accessKey.setStatus("Inactive");
accessKeys.putForAccount("111122223333", accessKey.getAccessKeyId(), accessKey);
IamService service = iamService(false, accessKeys, new InMemoryStorage<>());
assertTrue(service.findSecretKeyInAnyAccount(accessKey.getAccessKeyId(), null).isEmpty());
}
private static final class CountingAccountAwareSessionStorage
extends AccountAwareStorageBackend<SessionCredential> {
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.iam.IamService;
@@ -92,6 +93,42 @@ public final class IamServiceTestHelper {
}
}
/**
* Like {@link #iamServiceWithAccessKey}, but on account-aware storage, as production runs, with
* the key owned by {@code accountId}, so code that asks which account a key belongs to sees it.
*/
public static IamService iamServiceWithAccessKeyInAccount(String accessKeyId, String secretAccessKey,
String accountId) {
return iamServiceWithAccessKeyInAccount(accessKeyId, secretAccessKey, accountId, accountId);
}
/** As above, but with {@code defaultAccountId} as the account a request without one falls back to. */
public static IamService iamServiceWithAccessKeyInAccount(String accessKeyId, String secretAccessKey,
String accountId, String defaultAccountId) {
try {
Constructor<IamService> constructor = IamService.class.getDeclaredConstructor(
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
RegionResolver.class
);
constructor.setAccessible(true);
AccountAwareStorageBackend<AccessKey> accessKeys =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccountId);
accessKeys.putForAccount(accountId, accessKeyId, new AccessKey(accessKeyId, secretAccessKey, "test-user"));
return constructor.newInstance(null, null, null, null, accessKeys, null, null,
new RegionResolver("us-east-1", defaultAccountId));
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Failed to construct IamService test fixture", e);
}
}
@SuppressWarnings("unchecked")
public static IamService iamServiceWithSessionCredential(String accessKeyId, String secretAccessKey) {
return iamServiceWithSessionCredential(