From c2d285ed2f670ff170e843207300e2875bbad678 Mon Sep 17 00:00:00 2001 From: Jeremy Chapeau <113923302+jychp@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:49:52 -0800 Subject: [PATCH] feat(iam): make the seeded deployer's access key ID configurable (#8625) FLOCI_SERVICES_IAM_SEED_DEPLOYER_ACCESS_KEY_ID (floci.services.iam.seed-deployer-access-key-id) chooses the seeded deployer's access key ID. The default stays floci, so setups signing with floci / floci keep working; any other value must be 16 to 128 word characters, as IAM requires of an AccessKeyId, or startup fails naming the setting. With such an ID the deployer's key can be deactivated and deleted, and then the floci-deployer user. Under persistent storage, seeding deletes the deployer's key seeded under an earlier ID, the one signing with the public floci secret, and keeps keys made with CreateAccessKey. The EKS token webhook refuses the seeded credential by that public secret rather than by its access key ID. Closes #8624 --- .../configuration/advanced/application-yml.md | 1 + docs/configuration/environment-variables.md | 1 + docs/services/eks.md | 2 +- docs/services/iam.md | 10 ++ docs/services/sts.md | 2 +- .../io/floci/aws/config/EmulatorConfig.java | 9 ++ .../aws/services/eks/EksTokenValidator.java | 7 +- .../io/floci/aws/services/iam/IamService.java | 57 +++++++-- src/main/resources/application.yml | 1 + .../services/eks/EksTokenValidatorTest.java | 26 +++++ .../iam/IamManagedPolicyCaseTest.java | 3 +- ...eededDeployerAccessKeyIntegrationTest.java | 109 ++++++++++++++++++ .../aws/services/iam/IamServiceTest.java | 73 ++++++++++++ src/test/resources/application.yml | 1 + 14 files changed, 284 insertions(+), 18 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/iam/IamSeededDeployerAccessKeyIntegrationTest.java diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index fce02ce7c3..fd6c83973a 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -208,6 +208,7 @@ floci: enabled: true enforcement-enabled: false # Set to true to enforce IAM policies on all requests seed-deployer-principal: false # Set to true to create a local floci-deployer admin principal + seed-deployer-access-key-id: floci # Access key ID of the seeded deployer's key networkfirewall: enabled: true diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 4299b15d48..c397d3c023 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -352,6 +352,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s | `FLOCI_SERVICES_IAM_ENABLED` | `true` | Enable the IAM service | | `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` | `false` | When `true`, enforce IAM policies on API calls. Leave `false` for most local development scenarios | | `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL` | `false` | Create a local `floci-deployer` IAM user with `AdministratorAccess` and static `floci`/`floci` credentials | +| `FLOCI_SERVICES_IAM_SEED_DEPLOYER_ACCESS_KEY_ID` | `floci` | Access key ID of the seeded deployer's key: `floci`, or 16 to 128 word characters (for example `AKIA` plus 16 uppercase letters and digits) to be able to deactivate or delete it. Floci refuses to start with any other value | ### KMS diff --git a/docs/services/eks.md b/docs/services/eks.md index 264ff7c780..1dbe72997a 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -474,7 +474,7 @@ 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`). 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. +Create an IAM access key before using EKS authentication. The public local-development pair `test`/`test` and the seeded deployer's key, whose secret `floci` is public whatever access key ID it was seeded under, are deliberately rejected because the webhook grants cluster-admin access. Temporary IAM credentials must include their `AWS_SESSION_TOKEN` when signing the token. diff --git a/docs/services/iam.md b/docs/services/iam.md index 9add781560..675b2f07ca 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2279,6 +2279,15 @@ When enabled, Floci creates the `floci-deployer` user if it does not already exi Requests signed with the seeded access key return the deployer user ARN from `sts:GetCallerIdentity`. +The default access key ID, `floci`, is shorter than IAM allows: `DeleteAccessKey` and `UpdateAccessKey` take an `AccessKeyId` of 16 to 128 characters matching `[\w]+`, so the AWS SDKs and Floci refuse the default with a validation error, and `DeleteUser` then refuses the user with `DeleteConflict` while the key exists. To provision with the deployer and then retire it, set an ID in IAM's format, for example (any value other than `floci` must be in that format, or Floci refuses to start): + +```bash +FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL=true +FLOCI_SERVICES_IAM_SEED_DEPLOYER_ACCESS_KEY_ID=AKIAFLOCIDEPLOYER001 +``` + +The secret access key stays `floci`. Seeding runs at every start, so under persistent storage a retired deployer comes back on the next start unless `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL` is turned off. When the ID changes, seeding deletes the deployer's key seeded under the earlier ID, so an install that already seeded `floci` can then retire the deployer; keys created for the deployer with `CreateAccessKey` are kept. + ## IAM Enforcement Mode By default Floci accepts any credentials without enforcing IAM policies — all requests are allowed through regardless of what policies are attached to the calling identity. This preserves backward compatibility and keeps the default setup frictionless. @@ -3966,6 +3975,7 @@ of the role it was issued for, whatever region later calls are signed for. See [ | `FLOCI_SERVICES_IAM_ENABLED` | `true` | Enable or disable the service | | `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` | `false` | Enforce IAM policies on all inbound requests | | `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL` | `false` | Seed the optional `floci-deployer` user and `floci` / `floci` access key | +| `FLOCI_SERVICES_IAM_SEED_DEPLOYER_ACCESS_KEY_ID` | `floci` | Access key ID of the seeded deployer's key: `floci`, or 16 to 128 word characters, which make it deletable | | `FLOCI_SERVICES_IAM_ACCOUNT_ALIAS` | _(unset)_ | Seed an account alias at startup; unset means the account has no alias | | `FLOCI_SERVICES_IAM_PARTNER_PERMISSION_BOUNDARIES_PATH` | _(unset)_ | A JSON file of partner account id to boundary ARN to policy document, standing in for the permissions boundaries AWS registers for a delegation partner by email; unset means none is registered | diff --git a/docs/services/sts.md b/docs/services/sts.md index cca30577a3..01b90488c8 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -466,7 +466,7 @@ The response resolves both header and query-string credentials, including the qu so a presigned request reports the same caller identity. A nonblank Authorization header retains precedence over query credentials. -When `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL=true`, requests signed with the seeded `floci` access key return `arn:aws:iam::000000000000:user/floci-deployer`. Other unknown local credentials continue to return the account root ARN for backward compatibility. +When `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL=true`, requests signed with the seeded access key (`floci` unless `FLOCI_SERVICES_IAM_SEED_DEPLOYER_ACCESS_KEY_ID` sets another) return `arn:aws:iam::000000000000:user/floci-deployer`. Other unknown local credentials continue to return the account root ARN for backward compatibility. When `FLOCI_AUTH_VALIDATE_SIGNATURES=true`, the shared signature verifier checks presigned query credentials for STS operations, including `GetCallerIdentity`, `GetSessionToken`, `GetFederationToken` diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 3ea6f4f653..4ce0d4f2d2 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1775,6 +1775,15 @@ public interface EmulatorConfig { @WithDefault("false") boolean seedDeployerPrincipal(); + /** + * Access key ID of the seeded deployer's key. The default {@code floci} is shorter than + * the 16 characters IAM requires of an AccessKeyId, so DeleteAccessKey and UpdateAccessKey + * refuse it; an ID of 16 to 128 word characters lets the key be retired like any other. + * Seeding refuses to start with any other value outside that format. + */ + @WithDefault("floci") + String seedDeployerAccessKeyId(); + /** * Alias to seed for the default account at startup, so callers that read the account * alias find one without creating it first. Unset means the account has no alias, which diff --git a/src/main/java/io/floci/aws/services/eks/EksTokenValidator.java b/src/main/java/io/floci/aws/services/eks/EksTokenValidator.java index e28940e027..e2ea836339 100644 --- a/src/main/java/io/floci/aws/services/eks/EksTokenValidator.java +++ b/src/main/java/io/floci/aws/services/eks/EksTokenValidator.java @@ -171,10 +171,9 @@ class EksTokenValidator { } private IamService.OwnedSecretKey secretKey(String accessKeyId, String sessionToken) { - if (iamService.isSeededDeployerAccessKey(accessKeyId)) { - return null; - } - return iamService.findSecretKeyInAnyAccount(accessKeyId, sessionToken).orElse(null); + return iamService.findSecretKeyInAnyAccount(accessKeyId, sessionToken) + .filter(key -> !iamService.isSeededDeployerSecret(key.secretAccessKey())) + .orElse(null); } private static CredentialScope parseCredentialScope(String encodedCredential) { diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java index a9e3b8b15c..28e183c965 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -203,6 +203,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final String DEFAULT_DEPLOYER_USER = "floci-deployer"; private static final String DEFAULT_DEPLOYER_ACCESS_KEY_ID = "floci"; private static final String DEFAULT_DEPLOYER_SECRET_ACCESS_KEY = "floci"; + /** An AccessKeyId as IAM documents it: 16 to 128 characters matching {@code [\w]+}. */ + private static final Pattern ACCESS_KEY_ID_PATTERN = Pattern.compile("\\w{16,128}"); private static final String ACCOUNT_ALIAS_KEY = "account-alias"; /** As AWS documents it: no leading or trailing dash, and no two dashes in a row. */ private static final Pattern ACCOUNT_ALIAS_PATTERN = @@ -485,6 +487,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private final Map partnerPermissionBoundaries; private final Clock clock; private final boolean seedDeployerPrincipal; + private final String seededDeployerAccessKeyId; private final String seededAccountAlias; /** Guards case-insensitive IAM name uniqueness checks and their corresponding writes. */ private final Object resourceNameLock = new Object(); @@ -581,6 +584,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { storageFactory.create("iam", "iam-outbound-federation.json", new TypeReference<>() {}), regionResolver, config.services().iam().seedDeployerPrincipal(), + config.services().iam().seedDeployerAccessKeyId(), config.services().iam().accountAlias().orElse(null), PartnerPermissionBoundaries.load(config.services().iam().partnerPermissionBoundariesPath()) .documentsByArn(), @@ -712,7 +716,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { passwordPolicies, loginProfiles, oidcProviders, serviceLinkedRoleDeletions, orgRootFeatures, credentialReports, virtualMfaDevices, serverCertificates, signingCertificates, sshPublicKeys, serviceCredentials, accountProperties, stsPreferences, outboundFederation, - regionResolver, seedDeployerPrincipal, seededAccountAlias, Map.of(), Clock.systemUTC()); + regionResolver, seedDeployerPrincipal, DEFAULT_DEPLOYER_ACCESS_KEY_ID, seededAccountAlias, Map.of(), + Clock.systemUTC()); } IamService(StorageBackend users, @@ -745,7 +750,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { passwordPolicies, loginProfiles, oidcProviders, serviceLinkedRoleDeletions, orgRootFeatures, credentialReports, virtualMfaDevices, serverCertificates, signingCertificates, sshPublicKeys, serviceCredentials, accountProperties, stsPreferences, outboundFederation, - regionResolver, seedDeployerPrincipal, seededAccountAlias, Map.of(), clock); + regionResolver, seedDeployerPrincipal, DEFAULT_DEPLOYER_ACCESS_KEY_ID, seededAccountAlias, Map.of(), + clock); } /** @@ -776,6 +782,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { StorageBackend outboundFederation, RegionResolver regionResolver, boolean seedDeployerPrincipal, + String seededDeployerAccessKeyId, String seededAccountAlias, Map partnerPermissionBoundaries, Clock clock) { @@ -803,6 +810,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { this.outboundFederation = outboundFederation; this.regionResolver = regionResolver; this.seedDeployerPrincipal = seedDeployerPrincipal; + this.seededDeployerAccessKeyId = seededDeployerAccessKeyId; this.seededAccountAlias = seededAccountAlias; this.partnerPermissionBoundaries = Map.copyOf(partnerPermissionBoundaries); this.clock = clock; @@ -885,6 +893,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } private void seedDefaultDeployerPrincipal() { + // The legacy default stays accepted so setups signing with floci / floci keep working. + // Any other ID IAM would not issue is refused at startup rather than seeded as a key that + // DeleteAccessKey and UpdateAccessKey could never take. + if (!DEFAULT_DEPLOYER_ACCESS_KEY_ID.equals(seededDeployerAccessKeyId) + && (seededDeployerAccessKeyId == null + || !ACCESS_KEY_ID_PATTERN.matcher(seededDeployerAccessKeyId).matches())) { + throw new IllegalArgumentException("floci.services.iam.seed-deployer-access-key-id must be " + + DEFAULT_DEPLOYER_ACCESS_KEY_ID + " or 16 to 128 characters matching [\\w]+, as IAM " + + "requires of an access key ID: " + seededDeployerAccessKeyId); + } String adminPolicyArn = AwsManagedPolicies.arnPrefix(regionResolver.getDefaultPartition()) + "/AdministratorAccess"; IamUser user = users.get(DEFAULT_DEPLOYER_USER) @@ -900,12 +918,25 @@ public class IamService implements SessionAccountLookup, ResourceProvider { user.getAttachedPolicyArns().add(adminPolicyArn); users.put(DEFAULT_DEPLOYER_USER, user); } - if (accessKeys.get(DEFAULT_DEPLOYER_ACCESS_KEY_ID).isEmpty()) { - accessKeys.put(DEFAULT_DEPLOYER_ACCESS_KEY_ID, new AccessKey( - DEFAULT_DEPLOYER_ACCESS_KEY_ID, - DEFAULT_DEPLOYER_SECRET_ACCESS_KEY, - DEFAULT_DEPLOYER_USER)); - LOG.infov("Seeded default IAM deployer access key: {0}", DEFAULT_DEPLOYER_ACCESS_KEY_ID); + synchronized (accessKeyLock) { + // Under persistent storage a key seeded under an earlier ID outlives a change of ID. It + // signs with the same public secret, and while it exists DeleteUser refuses the user, so + // it goes. A key created for the deployer has a secret of its own and stays. + for (AccessKey earlier : userAccessKeys(DEFAULT_DEPLOYER_USER)) { + if (!earlier.getAccessKeyId().equals(seededDeployerAccessKeyId) + && DEFAULT_DEPLOYER_SECRET_ACCESS_KEY.equals(earlier.getSecretAccessKey())) { + accessKeys.delete(earlier.getAccessKeyId()); + LOG.infov("Deleted IAM deployer access key seeded under an earlier ID: {0}", + earlier.getAccessKeyId()); + } + } + if (accessKeys.get(seededDeployerAccessKeyId).isEmpty()) { + accessKeys.put(seededDeployerAccessKeyId, new AccessKey( + seededDeployerAccessKeyId, + DEFAULT_DEPLOYER_SECRET_ACCESS_KEY, + DEFAULT_DEPLOYER_USER)); + LOG.infov("Seeded default IAM deployer access key: {0}", seededDeployerAccessKeyId); + } } } @@ -5084,9 +5115,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return currentSession(accessKeyId).map(SessionCredential::getExpiration); } - /** Whether an access key ID identifies Floci's documented public deployer credential. */ - public boolean isSeededDeployerAccessKey(String accessKeyId) { - return DEFAULT_DEPLOYER_ACCESS_KEY_ID.equals(accessKeyId); + /** + * Whether a secret access key is the seeded deployer's, which Floci's documentation publishes. + * The secret is what makes that credential public, whatever ID the key was seeded under, and + * only seeding creates a key with it: CreateAccessKey generates a secret of its own. + */ + public boolean isSeededDeployerSecret(String secretAccessKey) { + return DEFAULT_DEPLOYER_SECRET_ACCESS_KEY.equals(secretAccessKey); } /** diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 64ebc6eae9..05264064cb 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -537,6 +537,7 @@ floci: enabled: true enforcement-enabled: false seed-deployer-principal: false + seed-deployer-access-key-id: floci # floci, or 16 to 128 word characters to be able to deactivate or delete the key # account-alias: "" # When set, seeds the account alias at startup so callers can read one # without creating it first. Unset means the account has no alias, # matching AWS. Example: FLOCI_SERVICES_IAM_ACCOUNT_ALIAS=my-account diff --git a/src/test/java/io/floci/aws/services/eks/EksTokenValidatorTest.java b/src/test/java/io/floci/aws/services/eks/EksTokenValidatorTest.java index 001cda2fac..00ad04422b 100644 --- a/src/test/java/io/floci/aws/services/eks/EksTokenValidatorTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksTokenValidatorTest.java @@ -49,6 +49,32 @@ class EksTokenValidatorTest { assertFalse(validator.validate(token, CLUSTER_NAME)); } + /** The deployer's secret is the public part, so its key is refused whatever ID it was seeded under. */ + @Test + void validateRejectsTheSeededDeployerCredentialUnderAConfiguredAccessKeyId() throws Exception { + String accessKeyId = "AKIAFLOCIDEPLOYER001"; + String secretAccessKey = "floci"; + IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey(accessKeyId, secretAccessKey); + EksTokenValidator validator = new EksTokenValidator(iamService); + String token = SigV4TokenTestHelper.createEksToken( + CLUSTER_NAME, accessKeyId, secretAccessKey, Instant.now(), 60); + + assertFalse(validator.validate(token, CLUSTER_NAME)); + } + + /** An access key that holds the deployer's default ID with a secret of its own is no public credential. */ + @Test + void validateAcceptsAnAccessKeyHoldingTheDeployersDefaultIdWithItsOwnSecret() throws Exception { + String accessKeyId = "floci"; + String secretAccessKey = "existing-secret"; + IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey(accessKeyId, secretAccessKey); + EksTokenValidator validator = new EksTokenValidator(iamService); + String token = SigV4TokenTestHelper.createEksToken( + CLUSTER_NAME, accessKeyId, secretAccessKey, Instant.now(), 60); + + assertTrue(validator.validate(token, CLUSTER_NAME)); + } + @Test void validateRejectsTamperedSignature() throws Exception { EksTokenValidator validator = validator(); diff --git a/src/test/java/io/floci/aws/services/iam/IamManagedPolicyCaseTest.java b/src/test/java/io/floci/aws/services/iam/IamManagedPolicyCaseTest.java index 19fe457730..fa26398adf 100644 --- a/src/test/java/io/floci/aws/services/iam/IamManagedPolicyCaseTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamManagedPolicyCaseTest.java @@ -171,7 +171,8 @@ class IamManagedPolicyCaseTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), - new RegionResolver("us-east-1", "000000000000"), false, null, boundaries, Clock.systemUTC()); + new RegionResolver("us-east-1", "000000000000"), false, "floci", null, boundaries, + Clock.systemUTC()); } @Test diff --git a/src/test/java/io/floci/aws/services/iam/IamSeededDeployerAccessKeyIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamSeededDeployerAccessKeyIntegrationTest.java new file mode 100644 index 0000000000..b3761f5e02 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamSeededDeployerAccessKeyIntegrationTest.java @@ -0,0 +1,109 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.AccessKey; +import software.amazon.awssdk.services.iam.model.AccessKeyMetadata; +import software.amazon.awssdk.services.iam.model.AttachedPolicy; +import software.amazon.awssdk.services.iam.model.IamException; +import software.amazon.awssdk.services.iam.model.NoSuchEntityException; +import software.amazon.awssdk.services.iam.model.StatusType; +import software.amazon.awssdk.services.sts.StsClient; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * The seeded deployer's access key ID is configurable, so a deployment that provisions with it can + * then retire it the way any IAM access key is retired. DeleteAccessKey and UpdateAccessKey take an + * {@code AccessKeyId} of "Minimum length of 16. Maximum length of 128." matching {@code [\w]+} + * (IAM API Reference), so the default {@code floci} is refused by the SDKs and by Floci before the + * key is looked up, and DeleteUser then refuses the user while the key exists. + */ +@QuarkusTest +@TestProfile(IamSeededDeployerAccessKeyIntegrationTest.SeededDeployer.class) +class IamSeededDeployerAccessKeyIntegrationTest { + + private static final String DEPLOYER = "floci-deployer"; + private static final String DEPLOYER_ACCESS_KEY_ID = "AKIAFLOCIDEPLOYER001"; + private static final String DEPLOYER_SECRET_ACCESS_KEY = "floci"; + private static final String ACCOUNT = "000000000000"; + private static final String ADMINISTRATOR_ACCESS = "arn:aws:iam::aws:policy/AdministratorAccess"; + + /** Signed requests under IAM enforcement, with the deployer seeded under a configured key ID. */ + public static class SeededDeployer implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.auth.validate-signatures", "true", + "floci.services.iam.enforcement-enabled", "true", + "floci.services.iam.seed-deployer-principal", "true", + "floci.services.iam.seed-deployer-access-key-id", DEPLOYER_ACCESS_KEY_ID); + } + } + + @TestHTTPResource("/") + URI endpoint; + + @Test + void theSeededKeyCanBeDeactivatedAndDeletedAndItsUserDeleted() { + String adminName = "deployer-successor-" + UUID.randomUUID().toString().substring(0, 8); + try (IamClient deployer = AwsTestClients.create(IamClient.builder(), + DEPLOYER_ACCESS_KEY_ID, DEPLOYER_SECRET_ACCESS_KEY, Region.US_EAST_1, endpoint); + StsClient deployerSts = AwsTestClients.create(StsClient.builder(), + DEPLOYER_ACCESS_KEY_ID, DEPLOYER_SECRET_ACCESS_KEY, Region.US_EAST_1, endpoint); + IamClient root = AwsTestClients.create(IamClient.builder(), "test", "test", Region.US_EAST_1, endpoint)) { + assertThat(deployerSts.getCallerIdentity().arn(), + equalTo("arn:aws:iam::" + ACCOUNT + ":user/" + DEPLOYER)); + + deployer.createUser(b -> b.userName(adminName)); + try { + deployer.attachUserPolicy(b -> b.userName(adminName).policyArn(ADMINISTRATOR_ACCESS)); + AccessKey adminKey = deployer.createAccessKey(b -> b.userName(adminName)).accessKey(); + try (IamClient admin = AwsTestClients.create(IamClient.builder(), + adminKey.accessKeyId(), adminKey.secretAccessKey(), Region.US_EAST_1, endpoint)) { + List deployerKeys = admin.listAccessKeys(b -> b.userName(DEPLOYER)) + .accessKeyMetadata().stream().map(AccessKeyMetadata::accessKeyId).toList(); + assertThat(deployerKeys, contains(DEPLOYER_ACCESS_KEY_ID)); + + admin.updateAccessKey(b -> b.userName(DEPLOYER).accessKeyId(DEPLOYER_ACCESS_KEY_ID) + .status(StatusType.INACTIVE)); + IamException refused = assertThrows(IamException.class, deployer::listUsers); + assertThat(refused.statusCode(), equalTo(403)); + + admin.deleteAccessKey(b -> b.userName(DEPLOYER).accessKeyId(DEPLOYER_ACCESS_KEY_ID)); + admin.detachUserPolicy(b -> b.userName(DEPLOYER).policyArn(ADMINISTRATOR_ACCESS)); + admin.deleteUser(b -> b.userName(DEPLOYER)); + + assertThrows(NoSuchEntityException.class, () -> admin.getUser(b -> b.userName(DEPLOYER))); + } + } finally { + deleteUser(root, adminName); + } + } + } + + /** Removes what this class attached to a user it created, then the user. */ + private static void deleteUser(IamClient root, String userName) { + for (AccessKeyMetadata key : root.listAccessKeys(b -> b.userName(userName)).accessKeyMetadata()) { + root.deleteAccessKey(b -> b.userName(userName).accessKeyId(key.accessKeyId())); + } + for (AttachedPolicy policy : root.listAttachedUserPolicies(b -> b.userName(userName)).attachedPolicies()) { + root.detachUserPolicy(b -> b.userName(userName).policyArn(policy.policyArn())); + } + root.deleteUser(b -> b.userName(userName)); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java index 1fb09c0430..6127170283 100644 --- a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java @@ -3094,6 +3094,79 @@ class IamServiceTest { assertEquals("existing-secret", iamService.findSecretKey("floci").orElseThrow()); } + /** + * Starts with the deployer seeded under an access key ID, on the stores an earlier start left + * behind, the way a restart under persistent storage does. + */ + private static IamService startSeedingDeployerAs(String accessKeyId, StorageBackend users, + StorageBackend accessKeys) { + IamService service = new IamService(users, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), accessKeys, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000"), true, accessKeyId, null, Map.of(), + Clock.systemUTC()); + service.seedDefaults(); + return service; + } + + private static List accessKeyIds(IamService service, String userName) { + return service.listAccessKeys(userName).stream().map(AccessKey::getAccessKeyId).sorted().toList(); + } + + @Test + void seedingUnderAnotherAccessKeyIdDeletesTheKeySeededUnderTheEarlierOne() { + InMemoryStorage users = new InMemoryStorage<>(); + InMemoryStorage accessKeys = new InMemoryStorage<>(); + startSeedingDeployerAs("floci", users, accessKeys); + + IamService restarted = startSeedingDeployerAs("AKIAFLOCIDEPLOYER001", users, accessKeys); + + assertEquals(List.of("AKIAFLOCIDEPLOYER001"), accessKeyIds(restarted, "floci-deployer")); + assertTrue(restarted.findSecretKey("floci").isEmpty()); + + IamService restartedAgain = startSeedingDeployerAs("AKIAFLOCIDEPLOYER002", users, accessKeys); + + assertEquals(List.of("AKIAFLOCIDEPLOYER002"), accessKeyIds(restartedAgain, "floci-deployer")); + } + + @Test + void seedingUnderAnotherAccessKeyIdKeepsTheKeysCreatedForTheDeployer() { + InMemoryStorage users = new InMemoryStorage<>(); + InMemoryStorage accessKeys = new InMemoryStorage<>(); + String created = startSeedingDeployerAs("floci", users, accessKeys) + .createAccessKey("floci-deployer").getAccessKeyId(); + + IamService restarted = startSeedingDeployerAs("AKIAFLOCIDEPLOYER001", users, accessKeys); + + assertEquals(List.of("AKIAFLOCIDEPLOYER001", created).stream().sorted().toList(), + accessKeyIds(restarted, "floci-deployer")); + } + + /** + * IAM takes an AccessKeyId of "Minimum length of 16. Maximum length of 128." matching + * {@code [\w]+} (IAM API Reference, AccessKey), so a key seeded under any other ID could never + * be deactivated or deleted. Only the legacy default is kept outside that format. + */ + @Test + void seedingRefusesAnAccessKeyIdOutsideIamsFormat() { + for (String accessKeyId : List.of("AKIAFLOCIDEPLOY", "AKIA-FLOCI-DEPLOYER", "A".repeat(129), "test")) { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> startSeedingDeployerAs(accessKeyId, new InMemoryStorage<>(), new InMemoryStorage<>())); + assertTrue(ex.getMessage().contains("floci.services.iam.seed-deployer-access-key-id"), ex.getMessage()); + } + } + + @Test + void seedingAcceptsTheDefaultAccessKeyIdAndOnesInIamsFormat() { + for (String accessKeyId : List.of("floci", "AKIAFLOCIDEPLOYE", "A".repeat(128), "AKIA_FLOCI_DEPLOYER")) { + IamService seeded = startSeedingDeployerAs(accessKeyId, new InMemoryStorage<>(), new InMemoryStorage<>()); + assertEquals(List.of(accessKeyId), accessKeyIds(seeded, "floci-deployer")); + } + } + @Test void attachManagedPolicyToRole() { iamService.seedAwsManagedPolicies(); diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index b6361f069c..3a36f836a8 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -192,6 +192,7 @@ floci: enabled: true enforcement-enabled: false seed-deployer-principal: false + seed-deployer-access-key-id: floci msk: enabled: true mock: true