Light, fluffy, and always free - The AWS Local Emulator alternative
refactor(eks): resolve the token webhook's key and its owner in one lookup (#5055)
Robin Baeckman60c368e939a8
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.javaindex 1438807a8f..93376e3c7c 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java@@ -55,7 +55,8 @@ class EksTokenValidator {this.clock = clock;}- record VerifiedToken(String accessKeyId, String region) {}+ /** {@code keyAccountId} owns a long-term key, from the lookup that verified it; null for a temporary key. */+ record VerifiedToken(String accessKeyId, String region, String keyAccountId) {}boolean validate(String token, String clusterName) {return verify(token, clusterName).isPresent();@@ -84,10 +85,11 @@ class EksTokenValidator {return Optional.empty();}- String secretKey = secretKey(scope.accessKeyId(), parameters.get("X-Amz-Security-Token"));- if (secretKey == null) {+ IamService.OwnedSecretKey key = secretKey(scope.accessKeyId(), parameters.get("X-Amz-Security-Token"));+ if (key == null) {return Optional.empty();}+ String secretKey = key.secretAccessKey();String canonicalRequest = canonicalRequest(request, parameters, clusterName);String stringToSign = ALGORITHM + "\n"@@ -99,7 +101,8 @@ class EksTokenValidator {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();+ return valid ? Optional.of(new VerifiedToken(scope.accessKeyId(), scope.region(), key.accountId()))+ : Optional.empty();} catch (Exception exception) {LOG.debugv("EKS IAM token validation rejected a malformed token: {0}", exception.getMessage());return Optional.empty();@@ -163,12 +166,11 @@ class EksTokenValidator {return !signedAt.isAfter(now.plus(MAX_FUTURE_SKEW)) && !now.isAfter(signedAt.plus(TOKEN_LIFETIME));}- private String secretKey(String accessKeyId, String sessionToken) {+ private IamService.OwnedSecretKey secretKey(String accessKeyId, String sessionToken) {if (iamService.isSeededDeployerAccessKey(accessKeyId)) {return null;}- Optional<String> secretKey = iamService.findSecretKeyInAnyAccount(accessKeyId, sessionToken);- return secretKey.orElse(null);+ return iamService.findSecretKeyInAnyAccount(accessKeyId, sessionToken).orElse(null);}private static CredentialScope parseCredentialScope(String encodedCredential) {diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.javaindex 770b4ea456..9ad4b88e8e 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java@@ -44,8 +44,8 @@ class EksWorkerAuthentication {if (IamService.isTemporaryAccessKey(token.accessKeyId())) {return Optional.empty();}- // Keys resolve from every account, and the legacy identity is system:masters.- return iam.resolveAccountId(token.accessKeyId())+ // The legacy identity is system:masters, so only a key of the cluster's own account gets it.+ return Optional.ofNullable(token.keyAccountId()).filter(owner -> owner.equals(clusterAccount(account))).flatMap(owner -> legacyIdentity());}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 34367cf258..d996de1c1d 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@@ -3212,11 +3212,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {* it. Only for callers with no account in scope that check the owner themselves, such as the* EKS token webhook: everywhere else a key from another account must stay unknown.*/- public Optional<String> findSecretKeyInAnyAccount(String accessKeyId, String sessionToken) {- return findSecretKey(accessKeyId, sessionToken)- .or(() -> activeAccessKeyInAnyAccount(accessKeyId).map(entry -> entry.value().getSecretAccessKey()));+ public Optional<OwnedSecretKey> findSecretKeyInAnyAccount(String accessKeyId, String sessionToken) {+ Optional<OwnedSecretKey> own = activeAccessKeySecret(accessKeyId)+ .map(secret -> new OwnedSecretKey(secret, accessKeys instanceof AccountAwareStorageBackend<AccessKey> aware+ ? aware.accountId() : null));+ return own+ .or(() -> currentSession(accessKeyId)+ .filter(session -> hasMatchingSessionToken(session, sessionToken))+ .map(session -> new OwnedSecretKey(session.getSecretAccessKey(), null)))+ .or(() -> activeAccessKeyInAnyAccount(accessKeyId)+ .map(entry -> new OwnedSecretKey(entry.value().getSecretAccessKey(), entry.accountId())));}+ /**+ * A secret access key with the account that owns it, so a caller that checks the owner needs no+ * second lookup. The account is null for a temporary key, whose session records its own.+ */+ public record OwnedSecretKey(String secretAccessKey, String accountId) {}+/** The active long-term key with this ID, from whichever account owns it. */private Optional<AccountAwareStorageBackend.AccountEntry<AccessKey>> activeAccessKeyInAnyAccount(String accessKeyId) {diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthenticationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthenticationTest.javaindex 58f435ecfb..3373c2baf3 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthenticationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthenticationTest.java@@ -43,7 +43,7 @@ class EksWorkerAuthenticationTest {private final IamRole role = new IamRole("AROA-original", "worker", "/path/", ROLE, "{}");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);+ private final EksTokenValidator.VerifiedToken verified = new EksTokenValidator.VerifiedToken(KEY, REGION, null);@BeforeEachvoid setup() {@@ -71,7 +71,8 @@ class EksWorkerAuthenticationTest {@Testvoid signedWorkerTokenProducesNodeIdentityWithoutAdministratorGroup() throws Exception {- when(iam.findSecretKeyInAnyAccount(KEY, "session-token")).thenReturn(Optional.of("worker-secret"));+ when(iam.findSecretKeyInAnyAccount(KEY, "session-token"))+ .thenReturn(Optional.of(new IamService.OwnedSecretKey("worker-secret", null)));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(),@@ -90,37 +91,33 @@ class EksWorkerAuthenticationTest {@Testvoid 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());+ Optional<Map<String, Object>> user = auth.authenticate(longTermToken(ACCOUNT), "demo", ACCOUNT, REGION, CREATED.toString());assertEquals(List.of("system:masters"), user.orElseThrow().get("groups"));+ verify(iam, never()).resolveAccountId(any());}@Testvoid 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());+ assertTrue(auth.authenticate(longTermToken(OTHER_ACCOUNT), "demo", ACCOUNT, REGION, CREATED.toString()).isEmpty());}@Testvoid 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());+ assertTrue(auth.authenticate(longTermToken(null), "demo", ACCOUNT, REGION, CREATED.toString()).isEmpty());}@Testvoid 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());+ assertTrue(auth.authenticate(longTermToken(DEFAULT_ACCOUNT), "demo", null, null, null).isPresent());+ assertTrue(auth.authenticate(longTermToken(OTHER_ACCOUNT), "demo", null, null, null).isEmpty());}- private static EksTokenValidator.VerifiedToken longTermToken() {- return new EksTokenValidator.VerifiedToken(LONG_TERM_KEY, REGION);+ private static EksTokenValidator.VerifiedToken longTermToken(String keyAccountId) {+ return new EksTokenValidator.VerifiedToken(LONG_TERM_KEY, REGION, keyAccountId);}@Testdiff --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 3b1001becb..c2ddbaa17a 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@@ -1329,7 +1329,9 @@ class IamServiceTest {IamService service = iamService(false, accessKeys, new InMemoryStorage<>());- assertEquals("other-secret", service.findSecretKeyInAnyAccount(accessKey.getAccessKeyId(), null).orElseThrow());+ IamService.OwnedSecretKey found = service.findSecretKeyInAnyAccount(accessKey.getAccessKeyId(), null).orElseThrow();+ assertEquals("other-secret", found.secretAccessKey());+ assertEquals("111122223333", found.accountId());}@Test@@ -1341,10 +1343,58 @@ class IamServiceTest {IamService service = iamService(false, accessKeys, new InMemoryStorage<>());- assertEquals("own-secret", service.findSecretKeyInAnyAccount(accessKey.getAccessKeyId(), null).orElseThrow());+ IamService.OwnedSecretKey found = service.findSecretKeyInAnyAccount(accessKey.getAccessKeyId(), null).orElseThrow();+ assertEquals("own-secret", found.secretAccessKey());+ assertEquals("000000000000", found.accountId());Mockito.verify(accessKeys, Mockito.never()).scanAllAccountEntries(Mockito.any());}+ @Test+ void findSecretKeyInAnyAccountNamesTheRequestAccountAsTheOwnerOfItsOwnKey() {+ AccountAwareStorageBackend<AccessKey> accessKeys = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), null, "111122223333");+ AccessKey accessKey = new AccessKey("AKIAREQUESTACCOUNT", "request-secret", "dev");+ accessKeys.putForAccount("111122223333", accessKey.getAccessKeyId(), accessKey);++ IamService service = iamService(false, accessKeys, new InMemoryStorage<>());++ IamService.OwnedSecretKey found = service.findSecretKeyInAnyAccount(accessKey.getAccessKeyId(), null).orElseThrow();+ assertEquals("request-secret", found.secretAccessKey());+ assertEquals("111122223333", found.accountId());+ }++ @Test+ void findSecretKeyInAnyAccountPrefersTheRequestAccountsKeyOverADuplicateIdElsewhere() {+ AccountAwareStorageBackend<AccessKey> accessKeys = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), null, "111122223333");+ accessKeys.putForAccount("111122223333", "AKIADUPLICATEKEYID",+ new AccessKey("AKIADUPLICATEKEYID", "request-secret", "dev"));+ accessKeys.putForAccount("444455556666", "AKIADUPLICATEKEYID",+ new AccessKey("AKIADUPLICATEKEYID", "other-secret", "worker"));++ IamService service = iamService(false, accessKeys, new InMemoryStorage<>());++ IamService.OwnedSecretKey found = service.findSecretKeyInAnyAccount("AKIADUPLICATEKEYID", null).orElseThrow();+ assertEquals("request-secret", found.secretAccessKey());+ assertEquals("111122223333", found.accountId());+ }++ @Test+ void findSecretKeyInAnyAccountReportsTheAccountHoldingTheSecretItReturnsAmongDuplicateIds() {+ AccountAwareStorageBackend<AccessKey> accessKeys = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), null, "000000000000");+ accessKeys.putForAccount("111122223333", "AKIADUPLICATEKEYID",+ new AccessKey("AKIADUPLICATEKEYID", "secret-of-111122223333", "worker"));+ accessKeys.putForAccount("444455556666", "AKIADUPLICATEKEYID",+ new AccessKey("AKIADUPLICATEKEYID", "secret-of-444455556666", "worker"));++ IamService service = iamService(false, accessKeys, new InMemoryStorage<>());++ // Either key may be found; the account must be the one whose secret signs the request.+ IamService.OwnedSecretKey found = service.findSecretKeyInAnyAccount("AKIADUPLICATEKEYID", null).orElseThrow();+ assertEquals("secret-of-" + found.accountId(), found.secretAccessKey());+ }+@Testvoid findSecretKeyInAnyAccountOfATemporaryKeyDoesNotScanLongTermKeys() {AccountAwareStorageBackend<AccessKey> accessKeys = Mockito.spy(new AccountAwareStorageBackend<>(