mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(iam): support account aliases (#2103)
* feat(iam): support account aliases Implement ListAccountAliases, CreateAccountAlias and DeleteAccountAlias. An account holds at most one alias: creating a second returns EntityAlreadyExists, and deleting requires the current alias by name so a stale value cannot silently clear it. FLOCI_SERVICES_IAM_ACCOUNT_ALIAS seeds an alias at startup for callers that expect to read one without creating it first. Closes #2101 * fix(iam): make account alias create and delete atomic Concurrent CreateAccountAlias calls could all pass the emptiness check and write, reporting success to every caller while keeping only one value. Unlike a named resource, where racing creates carry the same name and either winner is equivalent, racing alias creates carry different values, so a loser is told their alias was set when another is stored. Guard the check-then-write on both create and delete, and cover it with a concurrency trial asserting exactly one winner. Also track the alias created by the bats delete case in ACCOUNT_ALIAS so teardown clears it if the test fails midway. * fix(iam): match verified AWS account alias semantics and unbreak the test fixture IamServiceTestHelper resolves the package-private IamService constructor reflectively against a hardcoded parameter list, so the extra storage backend broke it at run time with no compile-time signal. Every test using that fixture errored, and one of them hangs on a socket read rather than failing, which is what exhausted the CI job. Extend both lookups to the new arity. Checking the error message against a live AWS account showed the operation itself was modelled wrongly: CreateAccountAlias does not reject a second alias, it replaces the current one. EntityAlreadyExists means the requested name is taken, which for a single-account store is only the alias already held. Create now replaces and rejects just that case, which also makes the message name the alias the caller asked for. DeleteAccountAlias applies the same pattern constraint as create, so a malformed value is a ValidationError. Concurrent creates therefore all succeed with last-write-wins; the trial now asserts the store settles on one of the requested values. Seeding logs when it skips because an alias is already stored, which is otherwise invisible under persistent storage. * fix(test): repair iam.bats after the merge fused test bodies Resolving the merge by keeping both sides concatenated the OIDC and account alias cases as text, which left the create_oidc_provider helper nested inside an alias test and dropped a closing brace, so bats could not parse the file and produced no report at all. Rebuild it from main plus the alias cases, with the alias tracked in setup and teardown. * test(iam): pin account alias isolation, and document the two-dash rule 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. Every integration test here signs as the same account, so that prefixing was never exercised for aliases. The new case pins it: handing both services the store unwrapped fails it. The docs still described the pre-fix constraint. They now carry the consecutive-hyphen rule and note that the ValidationError message, reproduced from AWS verbatim, does not itself mention it. --------- Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com> Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
This commit is contained in:
12 files changed
+727
-4
No files matched your search
@@ -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"
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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<String> accountAlias();
|
||||
}
|
||||
|
||||
interface MskServiceConfig {
|
||||
|
||||
@@ -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<String, String> 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<String, String> params) {
|
||||
iamService.createAccountAlias(getParam(params, "AccountAlias"));
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("CreateAccountAlias", AwsNamespaces.IAM)).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteAccountAlias(MultivaluedMap<String, String> params) {
|
||||
iamService.deleteAccountAlias(getParam(params, "AccountAlias"));
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteAccountAlias", AwsNamespaces.IAM)).build();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Groups
|
||||
// =========================================================================
|
||||
|
||||
@@ -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<String, AccessKey> accessKeys;
|
||||
private final StorageBackend<String, InstanceProfile> instanceProfiles;
|
||||
private final StorageBackend<String, SessionCredential> 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<String, String> 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<String, OpenIDConnectProvider> oidcProviders;
|
||||
/** Deletion is synchronous, so an issued task id is a completed one; the value is its role. */
|
||||
private final StorageBackend<String, String> 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<String, IamUser> users,
|
||||
@@ -140,10 +160,12 @@ public class IamService implements SessionAccountLookup {
|
||||
StorageBackend<String, AccessKey> accessKeys,
|
||||
StorageBackend<String, InstanceProfile> instanceProfiles,
|
||||
StorageBackend<String, SessionCredential> sessions,
|
||||
StorageBackend<String, String> accountAliases,
|
||||
StorageBackend<String, OpenIDConnectProvider> oidcProviders,
|
||||
StorageBackend<String, String> 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<String, IamPolicy> 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<String> 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<String> 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<String> 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
|
||||
// =========================================================================
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+202
@@ -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}.
|
||||
*
|
||||
* <p>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"));
|
||||
}
|
||||
}
|
||||
@@ -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<String> winners = new CopyOnWriteArrayList<>();
|
||||
List<String> 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++) {
|
||||
|
||||
+30
@@ -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<String, String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
+90
@@ -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<String, String> 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);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -92,10 +92,12 @@ class IamServicePersistenceTest {
|
||||
load(dir, "iam-access-keys.json", new TypeReference<Map<String, AccessKey>>() {}),
|
||||
load(dir, "iam-instance-profiles.json", new TypeReference<Map<String, InstanceProfile>>() {}),
|
||||
load(dir, "iam-sessions.json", new TypeReference<Map<String, SessionCredential>>() {}),
|
||||
load(dir, "iam-account-aliases.json", new TypeReference<Map<String, String>>() {}),
|
||||
load(dir, "iam-oidc-providers.json", new TypeReference<Map<String, OpenIDConnectProvider>>() {}),
|
||||
load(dir, "iam-slr-deletions.json", new TypeReference<Map<String, String>>() {}),
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
false);
|
||||
false,
|
||||
null);
|
||||
}
|
||||
|
||||
private <V> StorageBackend<String, V> load(Path dir, String file, TypeReference<Map<String, V>> type) {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user