From 7822b2c396b1e7df4958d46ff8e1aa0bce07bd14 Mon Sep 17 00:00:00 2001 From: Robin Baeckman Date: Sat, 3 Oct 2026 22:55:34 +0200 Subject: [PATCH] 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> --- docs/services/eks.md | 2 +- .../floci/services/eks/EksTokenValidator.java | 2 +- .../services/eks/EksWorkerAuthentication.java | 19 +++++- .../floci/services/iam/IamService.java | 30 +++++++-- .../eks/EksTokenWebhookControllerTest.java | 57 +++++++++++++++- .../eks/EksWorkerAuthenticationTest.java | 48 +++++++++++++- .../floci/services/iam/IamServiceTest.java | 65 +++++++++++++++++++ .../floci/testutil/IamServiceTestHelper.java | 37 +++++++++++ 8 files changed, 243 insertions(+), 17 deletions(-) diff --git a/docs/services/eks.md b/docs/services/eks.md index 61a3261855..d6bbf4f217 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -377,7 +377,7 @@ aws eks update-kubeconfig --name my-cluster kubectl get nodes ``` -`aws eks update-kubeconfig` wires `aws eks get-token` into the kubeconfig as an exec credential. The bearer token contains a SigV4-presigned STS `GetCallerIdentity` request. Floci validates its signature and 15-minute token lifetime matching `aws-iam-authenticator` rather than the presigned expiry, then verifies the signed `x-k8s-aws-id` header against the cluster-specific `/_floci/eks/clusters//token-webhook` endpoint before resolving the caller identity. Instance-profile sessions require an EC2_LINUX access entry as described above; non-worker callers retain the `system:masters` mapping (bound to `cluster-admin`). No `aws-iam-authenticator` is required. +`aws eks update-kubeconfig` wires `aws eks get-token` into the kubeconfig as an exec credential. The bearer token contains a SigV4-presigned STS `GetCallerIdentity` request. Floci validates its signature and 15-minute token lifetime matching `aws-iam-authenticator` rather than the presigned expiry, then verifies the signed `x-k8s-aws-id` header against the cluster-specific `/_floci/eks/clusters//token-webhook` endpoint before resolving the caller identity. Instance-profile sessions require an EC2_LINUX access entry as described above; non-worker callers retain the `system:masters` mapping (bound to `cluster-admin`). A long-term access key gets it only on clusters of its own account, so a default-account key is refused on another account's cluster; on the older unscoped webhook path only the default account's keys get it. No `aws-iam-authenticator` is required. Create an IAM access key before using EKS authentication. The public local-development pairs `test`/`test` and `floci`/`floci` are deliberately rejected because the webhook grants cluster-admin access. 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.java index b9346412dd..1438807a8f 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 @@ -167,7 +167,7 @@ class EksTokenValidator { if (iamService.isSeededDeployerAccessKey(accessKeyId)) { return null; } - Optional secretKey = iamService.findSecretKey(accessKeyId, sessionToken); + Optional secretKey = iamService.findSecretKeyInAnyAccount(accessKeyId, sessionToken); return secretKey.orElse(null); } 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.java index 1be3b66db9..770b4ea456 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 @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.eks; +import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.ec2.Ec2Service; @@ -22,13 +23,16 @@ class EksWorkerAuthentication { private final EksService eks; private final Ec2Service ec2; private final EksAccessEntryService entries; + private final EmulatorConfig config; @Inject - EksWorkerAuthentication(IamService iam, EksService eks, Ec2Service ec2, EksAccessEntryService entries) { + EksWorkerAuthentication(IamService iam, EksService eks, Ec2Service ec2, EksAccessEntryService entries, + EmulatorConfig config) { this.iam = iam; this.eks = eks; this.ec2 = ec2; this.entries = entries; + this.config = config; } Optional> authenticate(EksTokenValidator.VerifiedToken token, String name, @@ -37,7 +41,13 @@ class EksWorkerAuthentication { // 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(); + 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()) + .filter(owner -> owner.equals(clusterAccount(account))) + .flatMap(owner -> legacyIdentity()); } EksSessionIdentity identity = session.get(); if (identity.instanceId() == null) { @@ -94,6 +104,11 @@ class EksWorkerAuthentication { .filter(profile -> List.of(roleName).equals(profile.getRoleNames())).isPresent(); } + /** Unscoped webhook paths predate per-account clusters, so they serve the default account. */ + private String clusterAccount(String account) { + return account != null ? account : config.defaultAccountId(); + } + private static Optional> legacyIdentity() { return Optional.of(Map.of("username", "floci:aws-iam", "uid", "floci-aws-iam", "groups", List.of("system:masters"))); 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.java index a5875b1d35..02ff57f3de 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 @@ -2947,6 +2947,28 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return DEFAULT_DEPLOYER_ACCESS_KEY_ID.equals(accessKeyId); } + /** + * Like {@link #findSecretKey(String, String)}, but finds a long-term key whichever account owns + * 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 findSecretKeyInAnyAccount(String accessKeyId, String sessionToken) { + return findSecretKey(accessKeyId, sessionToken) + .or(() -> activeAccessKeyInAnyAccount(accessKeyId).map(entry -> entry.value().getSecretAccessKey())); + } + + /** The active long-term key with this ID, from whichever account owns it. */ + private Optional> activeAccessKeyInAnyAccount( + String accessKeyId) { + if (accessKeyId == null || isTemporaryAccessKey(accessKeyId) + || !(accessKeys instanceof AccountAwareStorageBackend aware)) { + return Optional.empty(); + } + return aware.scanAllAccountEntries(accessKeyId::equals).stream() + .filter(entry -> "Active".equals(entry.value().getStatus())) + .findFirst(); + } + private Optional activeAccessKeySecret(String accessKeyId) { return accessKeys.get(accessKeyId) .filter(accessKey -> "Active".equals(accessKey.getStatus())) @@ -3258,13 +3280,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { @Override public Optional resolveAccountId(String accessKeyId) { if (!isTemporaryAccessKey(accessKeyId)) { - if (accessKeyId == null || !(accessKeys instanceof AccountAwareStorageBackend aware)) { - return Optional.empty(); - } - return aware.scanAllAccountEntries(accessKeyId::equals).stream() - .filter(entry -> "Active".equals(entry.value().getStatus())) - .map(AccountAwareStorageBackend.AccountEntry::accountId) - .findFirst(); + return activeAccessKeyInAnyAccount(accessKeyId).map(AccountAwareStorageBackend.AccountEntry::accountId); } Optional sessionOpt = findSessionAnyAccount(accessKeyId); if (sessionOpt.isEmpty()) { diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java index 78726d38b8..2cbb4955ea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenWebhookControllerTest.java @@ -1,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 status(Response response) { 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.java index f1576019cd..58f435ecfb 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 @@ -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> 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java index 69073f685a..f527fbb291 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 @@ -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 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 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 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 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 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 { diff --git a/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java b/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java index d023c59244..18425f332a 100644 --- a/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java +++ b/src/test/java/io/github/hectorvent/floci/testutil/IamServiceTestHelper.java @@ -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 constructor = IamService.class.getDeclaredConstructor( + StorageBackend.class, + StorageBackend.class, + StorageBackend.class, + StorageBackend.class, + StorageBackend.class, + StorageBackend.class, + StorageBackend.class, + RegionResolver.class + ); + constructor.setAccessible(true); + + AccountAwareStorageBackend 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(