diff --git a/compatibility-tests/sdk-test-awscli/test/iam.bats b/compatibility-tests/sdk-test-awscli/test/iam.bats index ed95589e0e..fe8939dd84 100644 --- a/compatibility-tests/sdk-test-awscli/test/iam.bats +++ b/compatibility-tests/sdk-test-awscli/test/iam.bats @@ -5,6 +5,7 @@ setup() { load 'test_helper/common-setup' ROLE_NAME="bats-test-role-$(unique_name)" POLICY_ARN="" + ACCOUNT_ALIAS="" } teardown() { @@ -13,6 +14,10 @@ teardown() { aws_cmd iam delete-policy --policy-arn "$POLICY_ARN" >/dev/null 2>&1 || true fi aws_cmd iam delete-role --role-name "$ROLE_NAME" >/dev/null 2>&1 || true + # An account holds one alias, so a leaked one would fail every later create. + if [ -n "$ACCOUNT_ALIAS" ]; then + aws_cmd iam delete-account-alias --account-alias "$ACCOUNT_ALIAS" >/dev/null 2>&1 || true + fi } @test "IAM: create role" { @@ -179,3 +184,75 @@ create_oidc_provider() { assert_failure assert_output --partial "ValidationError" } + +@test "IAM: list account aliases is empty by default" { + run aws_cmd iam list-account-aliases + assert_success + count=$(json_get "$output" '.AccountAliases | length') + [ "$count" = "0" ] +} + +@test "IAM: create and list account alias" { + ACCOUNT_ALIAS="$(unique_name bats-alias)" + + run aws_cmd iam create-account-alias --account-alias "$ACCOUNT_ALIAS" + assert_success + + run aws_cmd iam list-account-aliases + assert_success + alias=$(json_get "$output" '.AccountAliases[0]') + [ "$alias" = "$ACCOUNT_ALIAS" ] +} + +@test "IAM: creating another account alias replaces the current one" { + ACCOUNT_ALIAS="$(unique_name bats-alias)" + aws_cmd iam create-account-alias --account-alias "$ACCOUNT_ALIAS" >/dev/null + + local replacement + replacement="$(unique_name bats-alias-two)" + run aws_cmd iam create-account-alias --account-alias "$replacement" + assert_success + ACCOUNT_ALIAS="$replacement" + + run aws_cmd iam list-account-aliases + assert_success + alias=$(json_get "$output" '.AccountAliases[0]') + [ "$alias" = "$replacement" ] +} + +@test "IAM: re-creating the alias the account already holds fails" { + ACCOUNT_ALIAS="$(unique_name bats-alias)" + aws_cmd iam create-account-alias --account-alias "$ACCOUNT_ALIAS" >/dev/null + + run aws_cmd iam create-account-alias --account-alias "$ACCOUNT_ALIAS" + assert_failure + assert_output --partial "EntityAlreadyExists" +} + +@test "IAM: deleting a mismatched account alias fails" { + ACCOUNT_ALIAS="$(unique_name bats-alias)" + aws_cmd iam create-account-alias --account-alias "$ACCOUNT_ALIAS" >/dev/null + + run aws_cmd iam delete-account-alias --account-alias "bats-alias-not-set-$$" + assert_failure + assert_output --partial "NoSuchEntity" +} + +@test "IAM: delete account alias" { + ACCOUNT_ALIAS="$(unique_name bats-alias)" + aws_cmd iam create-account-alias --account-alias "$ACCOUNT_ALIAS" >/dev/null + + run aws_cmd iam delete-account-alias --account-alias "$ACCOUNT_ALIAS" + assert_success + + run aws_cmd iam list-account-aliases + assert_success + count=$(json_get "$output" '.AccountAliases | length') + [ "$count" = "0" ] +} + +@test "IAM: malformed account alias is rejected" { + run aws_cmd iam create-account-alias --account-alias "Upper-Case" + assert_failure + assert_output --partial "ValidationError" +} diff --git a/docs/services/iam.md b/docs/services/iam.md index b5702863d9..908ab2ae58 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -130,6 +130,34 @@ | UpdateAccessKey | Updates an access key's status. | | DeleteAccessKey | Deletes an access key from a user. | +### Account Aliases + +| Action | Description | +|--------|-------------| +| ListAccountAliases | Lists the alias set for the account, or an empty list when none is set. | +| CreateAccountAlias | Sets the account alias. An account can hold only one. | +| DeleteAccountAlias | Removes the account alias. | + +An account holds one alias, and AWS enforces that by replacement rather than rejection: +`CreateAccountAlias` with a new value silently swaps the current one. `EntityAlreadyExists` means +the requested name is taken — on AWS that includes names held by other accounts, since aliases are +globally unique, but the store here is per-account so only "you already hold this one" arises. + +`DeleteAccountAlias` must name the current alias; a mismatch returns `NoSuchEntity`. Both verbs +apply the same pattern constraint, so a malformed value returns `ValidationError` on either. +Aliases are 3–63 characters of lowercase letters, digits and hyphens, may not start or end with a +hyphen, and may not contain two hyphens in a row — AWS's documented +`^[a-z0-9]([a-z0-9]|-(?!-)){1,61}[a-z0-9]$`. The `ValidationError` message is reproduced from AWS +verbatim and does not itself mention the consecutive-hyphen rule. + +Set `FLOCI_SERVICES_IAM_ACCOUNT_ALIAS` to seed an alias at startup, for callers that expect to +read one without creating it first. It seeds the **default account** only, so a caller signing +with a credential that resolves to a different account still reads an empty list. Seeding is +skipped when an alias is already stored, so under `storage.mode: persistent` a changed value has +no effect on later starts — the skip is logged at debug with both values. `/_floci/state/reset` +clears the alias without re-seeding it, as it does the optional deployer principal; the seed +returns on restart. + ### OIDC Identity Providers | Action | Description | @@ -341,6 +369,7 @@ Three deviations to be aware of: | `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_ACCOUNT_ALIAS` | _(unset)_ | Seed an account alias at startup; unset means the account has no alias | ## Examples diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index a1414c77b9..3704be00fd 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -790,6 +790,13 @@ public interface EmulatorConfig { @WithDefault("false") boolean seedDeployerPrincipal(); + + /** + * 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 + * is the AWS default. + */ + Optional accountAlias(); } interface MskServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index 0ac496826f..0e20ab2845 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -78,6 +78,11 @@ public class IamQueryHandler { case "ListOpenIDConnectProviderTags" -> handleListOpenIDConnectProviderTags(params); case "ListServerCertificates" -> handleListServerCertificates(params); + // Account Aliases + case "ListAccountAliases" -> handleListAccountAliases(params); + case "CreateAccountAlias" -> handleCreateAccountAlias(params); + case "DeleteAccountAlias" -> handleDeleteAccountAlias(params); + // Groups case "CreateGroup" -> handleCreateGroup(params); case "GetGroup" -> handleGetGroup(params); @@ -403,6 +408,29 @@ public class IamQueryHandler { return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, result)).build(); } + // ========================================================================= + // Account Aliases + // ========================================================================= + + // ListAccountAliases is paginated on the wire (IsTruncated) even though an account can only + // ever hold one alias, so the envelope carries the flag to match the AWS response shape. + private Response handleListAccountAliases(MultivaluedMap params) { + var xml = new XmlBuilder().start("AccountAliases"); + iamService.getAccountAlias().ifPresent(alias -> xml.elem("member", alias)); + xml.end("AccountAliases").elem("IsTruncated", false); + return Response.ok(AwsQueryResponse.envelope("ListAccountAliases", AwsNamespaces.IAM, xml.build())).build(); + } + + private Response handleCreateAccountAlias(MultivaluedMap params) { + iamService.createAccountAlias(getParam(params, "AccountAlias")); + return Response.ok(AwsQueryResponse.envelopeNoResult("CreateAccountAlias", AwsNamespaces.IAM)).build(); + } + + private Response handleDeleteAccountAlias(MultivaluedMap params) { + iamService.deleteAccountAlias(getParam(params, "AccountAlias")); + return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteAccountAlias", AwsNamespaces.IAM)).build(); + } + // ========================================================================= // Groups // ========================================================================= 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 09aeee1d53..3828d72818 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 @@ -56,6 +56,10 @@ public class IamService implements SessionAccountLookup { 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"; + 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 = + Pattern.compile("^[a-z0-9]([a-z0-9]|-(?!-)){1,61}[a-z0-9]$"); private static final int MAX_OIDC_CLIENT_IDS = 100; private static final int MAX_OIDC_THUMBPRINTS = 5; private static final int MAX_OIDC_URL_LENGTH = 255; @@ -79,11 +83,24 @@ public class IamService implements SessionAccountLookup { private final StorageBackend accessKeys; private final StorageBackend instanceProfiles; private final StorageBackend sessions; + /** + * Holds at most one entry per account under {@link #ACCOUNT_ALIAS_KEY} — an account alias is a + * single value, and the store is already account-namespaced, so no further keying is needed. + */ + private final StorageBackend accountAliases; + /** + * Guards the check-then-write in alias create/delete. Unlike a named resource, where two + * racing creates carry the same name and either winner is equivalent, racing alias creates + * carry different values — an unguarded race would report success to both callers while + * silently keeping only one. A single lock across accounts is enough: alias writes are rare. + */ + private final Object accountAliasLock = new Object(); private final StorageBackend oidcProviders; /** Deletion is synchronous, so an issued task id is a completed one; the value is its role. */ private final StorageBackend serviceLinkedRoleDeletions; private final RegionResolver regionResolver; private final boolean seedDeployerPrincipal; + private final String seededAccountAlias; /** * AWS-managed policies (arn:aws:iam::aws:policy/...), keyed by ARN. These are global — @@ -102,10 +119,12 @@ public class IamService implements SessionAccountLookup { storageFactory.create("iam", "iam-access-keys.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-instance-profiles.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-sessions.json", new TypeReference<>() {}), + storageFactory.create("iam", "iam-account-aliases.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-oidc-providers.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-slr-deletions.json", new TypeReference<>() {}), regionResolver, - config.services().iam().seedDeployerPrincipal() + config.services().iam().seedDeployerPrincipal(), + config.services().iam().accountAlias().orElse(null) ); } @@ -130,7 +149,8 @@ public class IamService implements SessionAccountLookup { RegionResolver regionResolver, boolean seedDeployerPrincipal) { this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions, - new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal); + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + regionResolver, seedDeployerPrincipal, null); } IamService(StorageBackend users, @@ -140,10 +160,12 @@ public class IamService implements SessionAccountLookup { StorageBackend accessKeys, StorageBackend instanceProfiles, StorageBackend sessions, + StorageBackend accountAliases, StorageBackend oidcProviders, StorageBackend serviceLinkedRoleDeletions, RegionResolver regionResolver, - boolean seedDeployerPrincipal) { + boolean seedDeployerPrincipal, + String seededAccountAlias) { this.users = users; this.groups = groups; this.roles = roles; @@ -151,10 +173,12 @@ public class IamService implements SessionAccountLookup { this.accessKeys = accessKeys; this.instanceProfiles = instanceProfiles; this.sessions = sessions; + this.accountAliases = accountAliases; this.oidcProviders = oidcProviders; this.serviceLinkedRoleDeletions = serviceLinkedRoleDeletions; this.regionResolver = regionResolver; this.seedDeployerPrincipal = seedDeployerPrincipal; + this.seededAccountAlias = seededAccountAlias; } @PostConstruct @@ -163,6 +187,7 @@ public class IamService implements SessionAccountLookup { if (seedDeployerPrincipal) { seedDefaultDeployerPrincipal(); } + seedConfiguredAccountAlias(); } private static Map buildAwsManagedPolicies() { @@ -190,6 +215,23 @@ public class IamService implements SessionAccountLookup { LOG.debugv("AWS managed policy catalog available: {0} policies", awsManagedPolicies.size()); } + private void seedConfiguredAccountAlias() { + if (seededAccountAlias == null || seededAccountAlias.isBlank()) { + return; + } + validateAccountAlias(seededAccountAlias); + Optional stored = accountAliases.get(ACCOUNT_ALIAS_KEY); + if (stored.isEmpty()) { + accountAliases.put(ACCOUNT_ALIAS_KEY, seededAccountAlias); + LOG.infov("Seeded IAM account alias: {0}", seededAccountAlias); + } else if (!stored.get().equals(seededAccountAlias)) { + // Under persistent storage the alias outlives the process, so a changed configuration + // value is ignored on later starts. Say so rather than leaving it to be puzzled out. + LOG.debugv("Configured IAM account alias {0} ignored; {1} is already stored", + seededAccountAlias, stored.get()); + } + } + private void seedDefaultDeployerPrincipal() { String adminPolicyArn = AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess"; IamUser user = users.get(DEFAULT_DEPLOYER_USER) @@ -1228,6 +1270,62 @@ public class IamService implements SessionAccountLookup { } // ========================================================================= + // Account Aliases + // ================================================================== + public Optional getAccountAlias() { + return accountAliases.get(ACCOUNT_ALIAS_KEY); + } + + /** + * An account holds one alias, and AWS enforces that by replacement rather than rejection: + * creating a free alias while another is set silently swaps it. {@code EntityAlreadyExists} + * means the requested name is taken — globally on AWS, since aliases are unique across all + * accounts. Only the "you already hold this one" case can arise here, because the store is + * namespaced per account and holds no other account's aliases. + */ + public void createAccountAlias(String alias) { + validateAccountAlias(alias); + synchronized (accountAliasLock) { + Optional existing = accountAliases.get(ACCOUNT_ALIAS_KEY); + if (existing.isPresent() && existing.get().equals(alias)) { + throw new AwsException("EntityAlreadyExists", + "The account alias " + alias + " already exists.", 409); + } + accountAliases.put(ACCOUNT_ALIAS_KEY, alias); + } + LOG.infov("Set IAM account alias: {0}", alias); + } + + /** + * AWS requires the caller to name the alias being removed and rejects a mismatch, so a stale + * value in a delete call cannot silently clear the current alias. + */ + public void deleteAccountAlias(String alias) { + // AWS applies the same pattern constraint to delete as to create, so a malformed value is + // a ValidationError rather than a miss. + validateAccountAlias(alias); + synchronized (accountAliasLock) { + String existing = accountAliases.get(ACCOUNT_ALIAS_KEY) + .orElseThrow(() -> new AwsException("NoSuchEntity", + "The account alias " + alias + " cannot be found.", 404)); + if (!existing.equals(alias)) { + throw new AwsException("NoSuchEntity", + "The account alias " + alias + " cannot be found.", 404); + } + accountAliases.delete(ACCOUNT_ALIAS_KEY); + } + LOG.infov("Deleted IAM account alias: {0}", alias); + } + + private void validateAccountAlias(String alias) { + if (alias == null || !ACCOUNT_ALIAS_PATTERN.matcher(alias).matches()) { + throw new AwsException("ValidationError", + "The specified value for accountAlias is invalid. It must be a minimum length of 3 " + + "characters and maximum length of 63 characters, contain only digits, lowercase " + + "letters, and hyphens (-), but cannot begin or end with a hyphen.", 400); + } + } + // OIDC Identity Providers // ========================================================================= diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 76ac54db97..ebadbf168a 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -234,6 +234,9 @@ floci: enabled: true enforcement-enabled: false seed-deployer-principal: false + # 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 msk: enabled: true mock: false diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamAccountAliasIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamAccountAliasIntegrationTest.java new file mode 100644 index 0000000000..87f3fec7a1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamAccountAliasIntegrationTest.java @@ -0,0 +1,202 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.AwsQueryController; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.isEmptyOrNullString; + +/** + * Integration tests for IAM account aliases via the Query Protocol, covering the full HTTP stack + * through {@link AwsQueryController} → {@link IamQueryHandler}. + * + *

Ordered: the alias is a single per-account value, so these cases share state deliberately — + * empty list, create, read back, reject a second create, reject a mismatched delete, delete. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IamAccountAliasIntegrationTest { + + private static final String ALIAS = "floci-test-alias"; + + // The Query-protocol controller resolves the target service from the credential scope, + // so every IAM call carries one. + private static final String IAM_CREDENTIAL = + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request"; + + @Test + @Order(1) + void listAccountAliasesIsEmptyBeforeAnyCreate() { + given() + .formParam("Action", "ListAccountAliases") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200) + .contentType("application/xml") + .body("ListAccountAliasesResponse.ListAccountAliasesResult.AccountAliases", isEmptyOrNullString()) + .body("ListAccountAliasesResponse.ListAccountAliasesResult.IsTruncated", equalTo("false")); + } + + @Test + @Order(2) + void createAccountAlias() { + given() + .formParam("Action", "CreateAccountAlias") + .formParam("AccountAlias", ALIAS) + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200) + .contentType("application/xml"); + } + + @Test + @Order(3) + void listAccountAliasesReturnsTheCreatedAlias() { + given() + .formParam("Action", "ListAccountAliases") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200) + .body("ListAccountAliasesResponse.ListAccountAliasesResult.AccountAliases.member", equalTo(ALIAS)) + .body("ListAccountAliasesResponse.ListAccountAliasesResult.IsTruncated", equalTo("false")); + } + + @Test + @Order(4) + void creatingAnotherAliasReplacesTheCurrentOne() { + given() + .formParam("Action", "CreateAccountAlias") + .formParam("AccountAlias", "another-alias") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .formParam("Action", "ListAccountAliases") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200) + .body("ListAccountAliasesResponse.ListAccountAliasesResult.AccountAliases.member", + equalTo("another-alias")); + + // Restore the alias the later ordered cases expect. + given() + .formParam("Action", "CreateAccountAlias") + .formParam("AccountAlias", ALIAS) + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(4) + void recreatingTheHeldAliasIsRejected() { + given() + .formParam("Action", "CreateAccountAlias") + .formParam("AccountAlias", ALIAS) + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(409) + .body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists")); + } + + @Test + @Order(5) + void deleteWithAMalformedAliasIsRejected() { + given() + .formParam("Action", "DeleteAccountAlias") + .formParam("AccountAlias", "Bad_Alias") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + @Test + @Order(5) + void deleteWithMismatchedAliasIsRejected() { + given() + .formParam("Action", "DeleteAccountAlias") + .formParam("AccountAlias", "not-the-current-alias") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @Test + @Order(6) + void deleteAccountAlias() { + given() + .formParam("Action", "DeleteAccountAlias") + .formParam("AccountAlias", ALIAS) + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .formParam("Action", "ListAccountAliases") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200) + .body("ListAccountAliasesResponse.ListAccountAliasesResult.AccountAliases", isEmptyOrNullString()); + } + + @Test + @Order(7) + void deleteWhenNoAliasIsSetIsRejected() { + given() + .formParam("Action", "DeleteAccountAlias") + .formParam("AccountAlias", ALIAS) + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @ParameterizedTest + @ValueSource(strings = {"ab", "-leading-hyphen", "trailing-hyphen-", "Upper-Case", "has_underscore"}) + @Order(8) + void malformedAliasesAreRejected(String alias) { + given() + .formParam("Action", "CreateAccountAlias") + .formParam("AccountAlias", alias) + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java index ec24a941b6..de2290d683 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java @@ -296,6 +296,56 @@ class IamConcurrencyTest { } } + /** + * Creating a free alias replaces whatever is set, so concurrent creates of different aliases + * all succeed and the last write wins — that is AWS behaviour, not a race to be prevented. + * What must hold is that the store ends on exactly one of the requested values rather than a + * torn or absent one. + */ + @Test + void concurrentAccountAliasCreatesLeaveOneRequestedValue() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(THREADS); + try { + for (int trial = 0; trial < TRIALS; trial++) { + IamService iam = newIamService(); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(N); + List winners = new CopyOnWriteArrayList<>(); + List unexpected = new CopyOnWriteArrayList<>(); + + for (int i = 0; i < N; i++) { + String alias = "alias-" + i; + pool.execute(() -> { + try { + start.await(10, TimeUnit.SECONDS); + iam.createAccountAlias(alias); + winners.add(alias); + } catch (io.github.hectorvent.floci.core.common.AwsException e) { + if (!"EntityAlreadyExists".equals(e.getErrorCode())) { + unexpected.add(e.getErrorCode()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }); + } + start.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "alias workers stalled"); + + String stored = iam.getAccountAlias().orElse(null); + if (winners.size() != N || stored == null || !winners.contains(stored) + || !unexpected.isEmpty()) { + fail("accountAlias trial " + trial + ": winners=" + winners.size() + "/" + N + + " stored=" + stored + " unexpectedErrors=" + unexpected); + } + } + } finally { + pool.shutdownNow(); + } + } + private static String[] createPolicies(IamService iam, String prefix) { String[] arns = new String[N]; for (int i = 0; i < N; i++) { diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java index 16a1b83cfb..77e63bf5b0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java @@ -292,4 +292,34 @@ class IamManagedPolicyAccountScopeTest { assertTrue(caller.identityPolicies().contains(AwsManagedPolicies.PERMISSIVE_DOCUMENT)); assertEquals(AwsManagedPolicies.PERMISSIVE_DOCUMENT, caller.boundaryPolicyDocument()); } + /** + * The alias is the only IAM entity keyed by a constant rather than a caller-supplied name, so + * every account shares one storage key and the separation rests entirely on + * AccountAwareStorageBackend prefixing. The failure mode is two-sided and quiet: one account + * would read another's alias, and would also be refused an alias it never set. + */ + @Test + void accountAliasIsScopedToTheCallingAccount() { + InMemoryStorage raw = new InMemoryStorage<>(); + IamService defaultAccount = serviceWithAliases( + new AccountAwareStorageBackend<>(raw, requestContextFor(DEFAULT_ACCT), DEFAULT_ACCT)); + IamService otherAccount = serviceWithAliases( + new AccountAwareStorageBackend<>(raw, requestContextFor(REQUEST_ACCT), DEFAULT_ACCT)); + + defaultAccount.createAccountAlias("acct-one"); + + assertTrue(otherAccount.getAccountAlias().isEmpty(), "the other account must not see it"); + otherAccount.createAccountAlias("acct-two"); + assertEquals("acct-one", defaultAccount.getAccountAlias().orElseThrow()); + assertEquals("acct-two", otherAccount.getAccountAlias().orElseThrow()); + } + + private static IamService serviceWithAliases(AccountAwareStorageBackend aliases) { + return new IamService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), + aliases, new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver("us-east-1", DEFAULT_ACCT), false, null); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamSeededAccountAliasIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamSeededAccountAliasIntegrationTest.java new file mode 100644 index 0000000000..a7ea7ff31c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamSeededAccountAliasIntegrationTest.java @@ -0,0 +1,90 @@ +package io.github.hectorvent.floci.services.iam; + +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 java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * Verifies that {@code floci.services.iam.account-alias} seeds the alias at startup, so callers + * that read an account alias find one without creating it first. + */ +@QuarkusTest +@TestProfile(IamSeededAccountAliasIntegrationTest.SeededAliasProfile.class) +class IamSeededAccountAliasIntegrationTest { + + private static final String SEEDED_ALIAS = "seeded-alias"; + + private static final String IAM_CREDENTIAL = + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request"; + + public static class SeededAliasProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.account-alias", SEEDED_ALIAS); + } + } + + @Test + void configuredAliasIsSeededAtStartup() { + given() + .formParam("Action", "ListAccountAliases") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200) + .body("ListAccountAliasesResponse.ListAccountAliasesResult.AccountAliases.member", + equalTo(SEEDED_ALIAS)); + } + + @Test + void recreatingTheSeededAliasIsRejected() { + given() + .formParam("Action", "CreateAccountAlias") + .formParam("AccountAlias", SEEDED_ALIAS) + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(409) + .body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists")); + } + + /** A seeded alias is ordinary state, so a later create replaces it like any other. */ + @Test + void creatingAnotherAliasReplacesTheSeededOne() { + given() + .formParam("Action", "CreateAccountAlias") + .formParam("AccountAlias", "replacement-alias") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .formParam("Action", "ListAccountAliases") + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200) + .body("ListAccountAliasesResponse.ListAccountAliasesResult.AccountAliases.member", + equalTo("replacement-alias")); + + given() + .formParam("Action", "CreateAccountAlias") + .formParam("AccountAlias", SEEDED_ALIAS) + .header("Authorization", IAM_CREDENTIAL) + .when() + .post("/") + .then() + .statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java index 98e5e5c254..5f93d0ae26 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java @@ -92,10 +92,12 @@ class IamServicePersistenceTest { load(dir, "iam-access-keys.json", new TypeReference>() {}), load(dir, "iam-instance-profiles.json", new TypeReference>() {}), load(dir, "iam-sessions.json", new TypeReference>() {}), + load(dir, "iam-account-aliases.json", new TypeReference>() {}), load(dir, "iam-oidc-providers.json", new TypeReference>() {}), load(dir, "iam-slr-deletions.json", new TypeReference>() {}), new RegionResolver("us-east-1", "000000000000"), - false); + false, + null); } private StorageBackend load(Path dir, String file, TypeReference> type) { 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 5987a13691..58186f4597 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 @@ -1073,4 +1073,111 @@ class IamServiceTest { assertEquals(1, remaining.size()); assertEquals("platform", remaining.get("team")); } + // ========================================================================= + // Account Aliases + // ========================================================================= + + @Test + void createAndGetAccountAlias() { + assertTrue(iamService.getAccountAlias().isEmpty()); + + iamService.createAccountAlias("my-account"); + + assertEquals("my-account", iamService.getAccountAlias().orElseThrow()); + } + + /** + * Verified against a live AWS account: creating a free alias while another is set replaces it + * rather than failing, which is how the one-alias-per-account rule is actually enforced. + */ + @Test + void createAccountAliasReplacesAnExistingOne() { + iamService.createAccountAlias("my-account"); + + iamService.createAccountAlias("other-account"); + + assertEquals("other-account", iamService.getAccountAlias().orElseThrow()); + } + + /** Re-creating the alias the account already holds is the case AWS rejects. */ + @Test + void createAccountAliasRejectsTheAliasAlreadyHeld() { + iamService.createAccountAlias("my-account"); + + AwsException ex = assertThrows(AwsException.class, + () -> iamService.createAccountAlias("my-account")); + assertEquals("EntityAlreadyExists", ex.getErrorCode()); + assertTrue(ex.getMessage().contains("my-account")); + assertEquals("my-account", iamService.getAccountAlias().orElseThrow()); + } + + @Test + void deleteAccountAliasRejectsAMalformedValue() { + iamService.createAccountAlias("my-account"); + + AwsException ex = assertThrows(AwsException.class, + () -> iamService.deleteAccountAlias("Bad_Alias")); + assertEquals("ValidationError", ex.getErrorCode()); + assertEquals("my-account", iamService.getAccountAlias().orElseThrow()); + } + + @Test + void deleteAccountAlias() { + iamService.createAccountAlias("my-account"); + + iamService.deleteAccountAlias("my-account"); + + assertTrue(iamService.getAccountAlias().isEmpty()); + } + + @Test + void deleteAccountAliasWithMismatchedNameFails() { + iamService.createAccountAlias("my-account"); + + AwsException ex = assertThrows(AwsException.class, + () -> iamService.deleteAccountAlias("some-other-alias")); + assertEquals("NoSuchEntity", ex.getErrorCode()); + assertEquals("my-account", iamService.getAccountAlias().orElseThrow()); + } + + @Test + void deleteAccountAliasWhenNoneSetFails() { + AwsException ex = assertThrows(AwsException.class, + () -> iamService.deleteAccountAlias("my-account")); + assertEquals("NoSuchEntity", ex.getErrorCode()); + } + + @Test + void malformedAccountAliasesAreRejected() { + for (String alias : List.of("ab", "-leading", "trailing-", "Upper", "under_score", "a".repeat(64))) { + AwsException ex = assertThrows(AwsException.class, + () -> iamService.createAccountAlias(alias), "expected rejection for: " + alias); + assertEquals("ValidationError", ex.getErrorCode(), "wrong code for: " + alias); + } + assertThrows(AwsException.class, () -> iamService.createAccountAlias(null)); + } + + /** + * AWS documents the pattern as {@code ^[a-z0-9]([a-z0-9]|-(?!-)){1,61}[a-z0-9]$} — consecutive + * dashes are rejected, which a plain character class would let through. + */ + @Test + void accountAliasRejectsConsecutiveDashes() { + AwsException ex = assertThrows(AwsException.class, + () -> iamService.createAccountAlias("my--account")); + assertEquals("ValidationError", ex.getErrorCode()); + assertTrue(iamService.getAccountAlias().isEmpty()); + + iamService.createAccountAlias("my-account"); + assertEquals("my-account", iamService.getAccountAlias().orElseThrow()); + } + + @Test + void accountAliasBoundaryLengthsAreAccepted() { + iamService.createAccountAlias("abc"); + iamService.deleteAccountAlias("abc"); + + iamService.createAccountAlias("a".repeat(63)); + assertEquals("a".repeat(63), iamService.getAccountAlias().orElseThrow()); + } }