diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamAccountPropertiesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamAccountPropertiesTest.java new file mode 100644 index 0000000000..803cf65d35 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamAccountPropertiesTest.java @@ -0,0 +1,156 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +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 software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.DisableOutboundWebIdentityFederationRequest; +import software.amazon.awssdk.services.iam.model.EnableOutboundWebIdentityFederationRequest; +import software.amazon.awssdk.services.iam.model.FeatureDisabledException; +import software.amazon.awssdk.services.iam.model.FeatureEnabledException; +import software.amazon.awssdk.services.iam.model.GetAccountPropertiesRequest; +import software.amazon.awssdk.services.iam.model.GetAccountPropertiesResponse; +import software.amazon.awssdk.services.iam.model.GetOutboundWebIdentityFederationInfoRequest; +import software.amazon.awssdk.services.iam.model.GetOutboundWebIdentityFederationInfoResponse; +import software.amazon.awssdk.services.iam.model.GlobalEndpointTokenVersion; +import software.amazon.awssdk.services.iam.model.PutAccountPropertiesRequest; +import software.amazon.awssdk.services.iam.model.SetSecurityTokenServicePreferencesRequest; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * The account property and outbound federation operations driven through the AWS SDK rather than + * hand-written requests. + * + *

This is the check the handcrafted XML assertions cannot make: the SDK parses the response + * against its own model, so a mis-named element or a map serialised in the wrong shape fails here + * even though the raw XML looked right. The {@code Properties} map is the interesting one, since it + * travels as {@code Properties.entry.N.key} and {@code Properties.entry.N.value} in both + * directions. + * + *

It also pins the error codes: the SDK maps {@code FeatureEnabled} and {@code FeatureDisabled} + * onto typed exceptions, so emitting the wrong code would arrive as a plain {@code IamException}. + */ +@DisplayName("IAM Account Properties and Outbound Federation") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IamAccountPropertiesTest { + + private static final String NAMESPACE = "SdkTestNs"; + + private static IamClient iam() { + return TestFixtures.iamClient(); + } + + @Test + @Order(1) + @DisplayName("PutAccountProperties and GetAccountProperties round-trip the map") + void propertiesRoundTrip() { + Map properties = new LinkedHashMap<>(); + properties.put(NAMESPACE + "/Enabled", "true"); + properties.put(NAMESPACE + "/Mode", "strict"); + + iam().putAccountProperties(PutAccountPropertiesRequest.builder() + .properties(properties) + .build()); + + GetAccountPropertiesResponse response = iam().getAccountProperties( + GetAccountPropertiesRequest.builder().build()); + + assertThat(response.hasProperties()).isTrue(); + assertThat(response.properties()) + .containsEntry(NAMESPACE + "/Enabled", "true") + .containsEntry(NAMESPACE + "/Mode", "strict"); + } + + @Test + @Order(2) + @DisplayName("All keys in one request must share a namespace") + void mixedNamespacesAreRejected() { + Map properties = new LinkedHashMap<>(); + properties.put(NAMESPACE + "/Alpha", "1"); + properties.put("OtherSdkNs/Beta", "2"); + + assertThatThrownBy(() -> iam().putAccountProperties(PutAccountPropertiesRequest.builder() + .properties(properties) + .build())) + .hasMessageContaining("same namespace"); + } + + @Test + @Order(3) + @DisplayName("SetSecurityTokenServicePreferences takes the version as a typed enum") + void setTokenVersion() { + iam().setSecurityTokenServicePreferences( + SetSecurityTokenServicePreferencesRequest.builder() + .globalEndpointTokenVersion(GlobalEndpointTokenVersion.V2_TOKEN) + .build()); + + // No getter for it in the API, so the assertion is that the SDK round-tripped the enum + // without the service rejecting it. + iam().setSecurityTokenServicePreferences( + SetSecurityTokenServicePreferencesRequest.builder() + .globalEndpointTokenVersion(GlobalEndpointTokenVersion.V1_TOKEN) + .build()); + } + + /** + * The whole switch in one test, because it is one account-level flag and separate tests would + * race each other. The asymmetry is the point: enabling twice is FeatureEnabled, disabling + * twice is FeatureDisabled. + */ + @Test + @Order(4) + @DisplayName("Outbound federation refuses both redundant directions, with typed errors") + void federationSwitch() { + IamClient client = iam(); + // Start from a known state, however an earlier run left it. + try { + client.disableOutboundWebIdentityFederation( + DisableOutboundWebIdentityFederationRequest.builder().build()); + } catch (FeatureDisabledException expected) { + // already disabled, which is the state this test wants + } + + assertThatThrownBy(() -> client.getOutboundWebIdentityFederationInfo( + GetOutboundWebIdentityFederationInfoRequest.builder().build())) + .isInstanceOf(FeatureDisabledException.class); + + String issuer = client.enableOutboundWebIdentityFederation( + EnableOutboundWebIdentityFederationRequest.builder().build()) + .issuerIdentifier(); + assertThat(issuer) + .as("the issuer is a per-account host under tokens.sts.global") + .matches("https://[0-9a-f-]{36}\\.tokens\\.sts\\.global\\..+"); + + assertThatThrownBy(() -> client.enableOutboundWebIdentityFederation( + EnableOutboundWebIdentityFederationRequest.builder().build())) + .isInstanceOf(FeatureEnabledException.class); + + GetOutboundWebIdentityFederationInfoResponse info = + client.getOutboundWebIdentityFederationInfo( + GetOutboundWebIdentityFederationInfoRequest.builder().build()); + assertThat(info.issuerIdentifier()).isEqualTo(issuer); + assertThat(info.jwtVendingEnabled()).isTrue(); + + client.disableOutboundWebIdentityFederation( + DisableOutboundWebIdentityFederationRequest.builder().build()); + assertThatThrownBy(() -> client.disableOutboundWebIdentityFederation( + DisableOutboundWebIdentityFederationRequest.builder().build())) + .isInstanceOf(FeatureDisabledException.class); + + // Re-enabling returns the same issuer: a relying party has pinned it. + String reissued = client.enableOutboundWebIdentityFederation( + EnableOutboundWebIdentityFederationRequest.builder().build()) + .issuerIdentifier(); + assertThat(reissued).isEqualTo(issuer); + + client.disableOutboundWebIdentityFederation( + DisableOutboundWebIdentityFederationRequest.builder().build()); + } +} diff --git a/docs/services/iam.md b/docs/services/iam.md index f276e9d24f..4f017efbdd 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -531,6 +531,52 @@ ready. `GenerateCredentialReport`'s `State`/`Description` for the no-report-exis own documented example response (`STARTED` / "No report exists. Starting a new report generation task"); the wording for the report-expired case is Floci's own, since AWS does not document it. +### Account Properties and Outbound Federation + +| Action | Description | +|--------|-------------| +| GetAccountProperties | Returns the account's properties as a `Namespace/PropertyName` to value map. | +| PutAccountProperties | Sets account properties, all of which must share one namespace. | +| SetSecurityTokenServicePreferences | Sets the account's global endpoint token version, `v1Token` or `v2Token`. | +| EnableOutboundWebIdentityFederation | Turns on outbound web identity federation and returns the account's issuer URL. | +| DisableOutboundWebIdentityFederation | Turns it off. | +| GetOutboundWebIdentityFederationInfo | Returns the issuer URL and whether JWT vending is on. | + +A property key is `Namespace/PropertyName` with exactly one forward slash and neither a leading nor +a trailing one, 1 to 50 characters matching `^[A-Za-z][A-Za-z0-9/_-]*$`, and a value of 1 to 1024. +**Every key in one `PutAccountProperties` request must belong to the same namespace**, which AWS +states directly, so a request mixing namespaces is rejected whole rather than partly applied. Role +Manager is the only namespace AWS names, and any well-formed key is accepted rather than only that +one, since an allowlist of one would refuse keys AWS takes. + +**Enabling federation twice is an error, and so is disabling it twice**, which is the asymmetry +worth noticing: `EnableOutboundWebIdentityFederation` answers `FeatureEnabled` with status 409, +while `DisableOutboundWebIdentityFederation` answers `FeatureDisabled` with status **404**. AWS +documents both, including the message wording. `GetOutboundWebIdentityFederationInfo` answers +`FeatureDisabled` too when the feature is off, reusing the disable operation's own text, so a getter +reports that the feature cannot be disabled twice. That reads oddly and is matched rather than +improved. + +The issuer URL is `https://.tokens.sts.global.`, which the API Reference +shows as `https://a1d2b0fd-1177-4468-9351-2fEXAMPLE723.tokens.sts.global.api.aws`. The suffix comes +from the request's partition rather than the literal, since `api.aws` is only the commercial +partition's. It is minted once per account and kept across a disable, so re-enabling returns the +same URL. AWS does not document which way that goes; the reasoning is that a relying party +verifying tokens will have pinned the URL, so regenerating it would break verification silently. + +Two things the feature references are not modeled. The issuer URL is documented as hosting OIDC +discovery endpoints at `/.well-known/openid-configuration` and `/.well-known/jwks.json`, and the +operation's description points at a `GetWebIdentityToken` API for obtaining JWTs. Neither is served +here: these six are the management operations only. `JwtVendingEnabled` is therefore reported as +true whenever the feature is enabled, which is the only reading available, since nothing in the API +toggles it separately. + +`SetSecurityTokenServicePreferences` stores the version, and `GetAccountSummary` reports it as +`GlobalEndpointTokenVersion`, which the operation's own description requires. What does not follow +it is STS itself: Floci does not vary its token format by account preference, so the setting is +observable in the summary rather than in a token. `v1Token` is reported as the default for an account +that has never set one. + ### Organizations Root Access | Action | Description | diff --git a/docs/services/index.md b/docs/services/index.md index bbd98874c8..52d5a11d14 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -22,7 +22,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 | | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 79 | | [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane | -| [IAM](iam.md) | `POST /` with `Action=` param | Query | 158 | +| [IAM](iam.md) | `POST /` with `Action=` param | Query | 164 | | [STS](sts.md) | `POST /` with `Action=` param | Query | 7 | | [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 | | [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 779675ca6e..a9717a0fcc 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -119,6 +119,9 @@ public class AwsQueryController { "CreateVirtualMFADevice", "DeleteVirtualMFADevice", "ListVirtualMFADevices", "EnableMFADevice", "DeactivateMFADevice", "ResyncMFADevice", "ListMFADevices", "TagMFADevice", "UntagMFADevice", "ListMFADeviceTags", + "GetAccountProperties", "PutAccountProperties", + "SetSecurityTokenServicePreferences", "EnableOutboundWebIdentityFederation", + "DisableOutboundWebIdentityFederation", "GetOutboundWebIdentityFederationInfo", "CreateServiceSpecificCredential", "ListServiceSpecificCredentials", "UpdateServiceSpecificCredential", "ResetServiceSpecificCredential", "DeleteServiceSpecificCredential", 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 dad337f7ba..aaad4419a5 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 @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.iam.model.IamUser; import io.github.hectorvent.floci.services.iam.model.InstanceProfile; import io.github.hectorvent.floci.services.iam.model.LoginProfile; import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider; +import io.github.hectorvent.floci.services.iam.model.OutboundWebIdentityFederation; import io.github.hectorvent.floci.services.iam.model.PolicyVersion; import io.github.hectorvent.floci.services.iam.model.SAMLProvider; import io.github.hectorvent.floci.services.iam.model.ServerCertificate; @@ -205,6 +206,16 @@ public class IamQueryHandler { case "ListPolicies" -> handleListPolicies(params); case "ListEntitiesForPolicy" -> handleListEntitiesForPolicy(params); case "GetAccountSummary" -> handleGetAccountSummary(params); + case "GetAccountProperties" -> handleGetAccountProperties(params); + case "PutAccountProperties" -> handlePutAccountProperties(params); + case "SetSecurityTokenServicePreferences" -> + handleSetSecurityTokenServicePreferences(params); + case "EnableOutboundWebIdentityFederation" -> + handleEnableOutboundWebIdentityFederation(params); + case "DisableOutboundWebIdentityFederation" -> + handleDisableOutboundWebIdentityFederation(params); + case "GetOutboundWebIdentityFederationInfo" -> + handleGetOutboundWebIdentityFederationInfo(params); case "GetAccountAuthorizationDetails" -> handleGetAccountAuthorizationDetails(params); case "GenerateCredentialReport" -> handleGenerateCredentialReport(params); case "GetCredentialReport" -> handleGetCredentialReport(params); @@ -1432,6 +1443,69 @@ public class IamQueryHandler { return Response.ok(AwsQueryResponse.envelope("GetAccountSummary", AwsNamespaces.IAM, xml.build())).build(); } + private Response handleGetAccountProperties(MultivaluedMap params) { + XmlBuilder xml = new XmlBuilder().start("Properties"); + for (Map.Entry entry : iamService.getAccountProperties().entrySet()) { + xml.start("entry").elem("key", entry.getKey()) + .elem("value", entry.getValue()).end("entry"); + } + xml.end("Properties"); + return Response.ok(AwsQueryResponse.envelope("GetAccountProperties", + AwsNamespaces.IAM, xml.build())).build(); + } + + /** + * The Properties map arrives as {@code Properties.entry.N.key} and + * {@code Properties.entry.N.value}, which is how the API Reference spells the member. + */ + private Response handlePutAccountProperties(MultivaluedMap params) { + Map properties = new LinkedHashMap<>(); + for (int i = 1; ; i++) { + String key = getParam(params, "Properties.entry." + i + ".key"); + if (key == null) { + break; + } + properties.put(key, getParam(params, "Properties.entry." + i + ".value")); + } + iamService.putAccountProperties(properties); + return Response.ok(AwsQueryResponse.envelopeNoResult("PutAccountProperties", + AwsNamespaces.IAM)).build(); + } + + private Response handleSetSecurityTokenServicePreferences( + MultivaluedMap params) { + iamService.setSecurityTokenServicePreferences( + requireParam(params, "GlobalEndpointTokenVersion")); + return Response.ok(AwsQueryResponse.envelopeNoResult("SetSecurityTokenServicePreferences", + AwsNamespaces.IAM)).build(); + } + + private Response handleEnableOutboundWebIdentityFederation( + MultivaluedMap params) { + XmlBuilder xml = new XmlBuilder() + .elem("IssuerIdentifier", iamService.enableOutboundWebIdentityFederation()); + return Response.ok(AwsQueryResponse.envelope("EnableOutboundWebIdentityFederation", + AwsNamespaces.IAM, xml.build())).build(); + } + + private Response handleDisableOutboundWebIdentityFederation( + MultivaluedMap params) { + iamService.disableOutboundWebIdentityFederation(); + return Response.ok(AwsQueryResponse.envelopeNoResult( + "DisableOutboundWebIdentityFederation", AwsNamespaces.IAM)).build(); + } + + private Response handleGetOutboundWebIdentityFederationInfo( + MultivaluedMap params) { + OutboundWebIdentityFederation state = iamService.getOutboundWebIdentityFederationInfo(); + XmlBuilder xml = new XmlBuilder() + .elem("IssuerIdentifier", state.getIssuerIdentifier()) + // Vending is on whenever the feature is: nothing in the API toggles it apart. + .elem("JwtVendingEnabled", true); + return Response.ok(AwsQueryResponse.envelope("GetOutboundWebIdentityFederationInfo", + AwsNamespaces.IAM, xml.build())).build(); + } + private Response handleGenerateCredentialReport(MultivaluedMap params) { IamService.CredentialReportGeneration generation = iamService.generateCredentialReport(); // State before Description: GenerateCredentialReportResponse's member order in the 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 e05a10f563..a39d91e555 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 @@ -9,7 +9,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsPartition; import io.github.hectorvent.floci.core.common.AwsPartitions; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.CertificateMaterialException; import io.github.hectorvent.floci.core.common.Pem; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -37,6 +39,7 @@ import io.github.hectorvent.floci.services.iam.model.InstanceProfile; import io.github.hectorvent.floci.services.iam.model.LoginProfile; import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider; import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures; +import io.github.hectorvent.floci.services.iam.model.OutboundWebIdentityFederation; import io.github.hectorvent.floci.services.iam.model.PolicyVersion; import io.github.hectorvent.floci.services.iam.model.ServerCertificate; import io.github.hectorvent.floci.services.iam.model.ServiceSpecificCredential; @@ -121,6 +124,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final int MAX_OIDC_THUMBPRINTS = 5; private static final int MAX_OIDC_URL_LENGTH = 255; private static final String ACCOUNT_PASSWORD_POLICY_KEY = "account-password-policy"; + private static final String STS_PREFERENCES_KEY = "sts-preferences"; + private static final String OUTBOUND_FEDERATION_KEY = "outbound-web-identity-federation"; + /** accountPropertiesMapType's key: 1 to 50 of this, and a value of 1 to 1024. */ + private static final Pattern ACCOUNT_PROPERTY_KEY_PATTERN = + Pattern.compile("^[A-Za-z][A-Za-z0-9/_-]*$"); + private static final int MAX_ACCOUNT_PROPERTY_KEY_LENGTH = 50; + private static final int MAX_ACCOUNT_PROPERTY_VALUE_LENGTH = 1024; + /** globalEndpointTokenVersion's only two values. */ + private static final Set GLOBAL_ENDPOINT_TOKEN_VERSIONS = Set.of("v1Token", "v2Token"); /** AWS-documented bounds for the account password policy's numeric fields. */ private static final int MIN_PASSWORD_LENGTH_FLOOR = 6; private static final int MIN_PASSWORD_LENGTH_CEILING = 128; @@ -297,6 +309,36 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * single-value-per-account shape as {@link #accountAliases}. */ private final StorageBackend passwordPolicies; + /** + * One entry per account property, keyed by the property key AWS defines + * ({@code Namespace/PropertyName}). Keyed per property rather than one entry holding a map, + * because PutAccountProperties sets a subset while GetAccountProperties returns all of them, + * which a key-per-entry store does without a read-modify-write. + */ + private final StorageBackend accountProperties; + /** + * Guards the batch in PutAccountProperties. A request carries several keys and AWS models + * ConcurrentModification for it, so the keys land together rather than interleaved with + * another request's. + */ + private final Object accountPropertiesLock = new Object(); + /** + * Holds at most one entry per account under {@link #STS_PREFERENCES_KEY}, the value being the + * global endpoint token version. Same single-value-per-account shape as + * {@link #accountAliases}. + */ + private final StorageBackend stsPreferences; + /** + * Holds at most one entry per account under {@link #OUTBOUND_FEDERATION_KEY}, present once the + * feature has ever been enabled. + */ + private final StorageBackend outboundFederation; + /** + * Guards the check-then-act in enable and disable. Both answer an error when the feature is + * already in the state asked for, so two racing enables must not both mint an issuer and both + * report success. + */ + private final Object outboundFederationLock = new Object(); private final StorageBackend loginProfiles; private final StorageBackend oidcProviders; /** Deletion is synchronous, so an issued task id is a completed one; the value is its role. */ @@ -368,6 +410,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { storageFactory.create("iam", "iam-signing-certificates.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-ssh-public-keys.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-service-specific-credentials.json", new TypeReference<>() {}), + storageFactory.create("iam", "iam-account-properties.json", new TypeReference<>() {}), + storageFactory.create("iam", "iam-sts-preferences.json", new TypeReference<>() {}), + storageFactory.create("iam", "iam-outbound-federation.json", new TypeReference<>() {}), regionResolver, config.services().iam().seedDeployerPrincipal(), config.services().iam().accountAlias().orElse(null) @@ -401,6 +446,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null); } @@ -426,6 +472,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, seededAccountAlias); } @@ -449,6 +496,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null); } @@ -471,6 +519,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { StorageBackend signingCertificates, StorageBackend sshPublicKeys, StorageBackend serviceCredentials, + StorageBackend accountProperties, + StorageBackend stsPreferences, + StorageBackend outboundFederation, RegionResolver regionResolver, boolean seedDeployerPrincipal, String seededAccountAlias) { @@ -493,6 +544,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { this.signingCertificates = signingCertificates; this.sshPublicKeys = sshPublicKeys; this.serviceCredentials = serviceCredentials; + this.accountProperties = accountProperties; + this.stsPreferences = stsPreferences; + this.outboundFederation = outboundFederation; this.regionResolver = regionResolver; this.seedDeployerPrincipal = seedDeployerPrincipal; this.seededAccountAlias = seededAccountAlias; @@ -1461,8 +1515,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider { summary.put("AccountPasswordPresent", 0L); // The STS global endpoint (and so the v1/v2 token choice it reports) exists only where // the partition publishes one: aws today. Elsewhere AWS has no such entry to report. + // + // The value follows SetSecurityTokenServicePreferences, whose own description says the + // version it sets "is reported in the GlobalEndpointTokenVersion entry of the response of + // the GetAccountSummary operation". Reporting a constant would leave a caller that set + // v2Token reading back 1. if (AwsPartitions.byId(regionResolver.getPartition()).hasGlobalSts()) { - summary.put("GlobalEndpointTokenVersion", 1L); + summary.put("GlobalEndpointTokenVersion", + "v2Token".equals(getGlobalEndpointTokenVersion()) ? 2L : 1L); } return summary; } @@ -2227,6 +2287,176 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } } + // Account properties and outbound web identity federation + // ========================================================================= + + /** Every account property, as GetAccountProperties returns them. */ + public Map getAccountProperties() { + Map properties = new LinkedHashMap<>(); + for (String key : accountProperties.keys()) { + accountProperties.get(key).ifPresent(value -> properties.put(key, value)); + } + return properties; + } + + /** + * Sets account properties, all of which must be in one namespace. + * + *

The key is {@code Namespace/PropertyName}: AWS requires exactly one {@code /}, forbids a + * leading or trailing one, and states that "all keys must belong to the same namespace". A + * request mixing namespaces is rejected whole rather than partly applied. + */ + public void putAccountProperties(Map properties) { + if (properties == null || properties.isEmpty()) { + throw new AwsException("ValidationError", + "Value null at 'properties' failed to satisfy constraint: Member must not be " + + "null", 400); + } + String namespace = null; + for (Map.Entry entry : properties.entrySet()) { + String keyNamespace = validateAccountPropertyKey(entry.getKey()); + validateAccountPropertyValue(entry.getKey(), entry.getValue()); + if (namespace == null) { + namespace = keyNamespace; + } else if (!namespace.equals(keyNamespace)) { + throw new AwsException("InvalidInput", + "All property keys must belong to the same namespace, but the request " + + "names both " + namespace + " and " + keyNamespace + ".", 400); + } + } + synchronized (accountPropertiesLock) { + for (Map.Entry entry : properties.entrySet()) { + accountProperties.put(entry.getKey(), entry.getValue()); + } + } + LOG.infov("Set {0} account property/properties in namespace {1}", + properties.size(), namespace); + } + + /** The namespace half of the key, having checked the whole key against the model. */ + private String validateAccountPropertyKey(String key) { + if (key == null || key.isEmpty() || key.length() > MAX_ACCOUNT_PROPERTY_KEY_LENGTH + || !ACCOUNT_PROPERTY_KEY_PATTERN.matcher(key).matches()) { + throw new AwsException("InvalidInput", + "Value '" + key + "' at 'properties' failed to satisfy constraint: Map keys " + + "must satisfy constraint: [Member must have length less than or " + + "equal to " + MAX_ACCOUNT_PROPERTY_KEY_LENGTH + ", Member must " + + "satisfy regular expression pattern: " + + ACCOUNT_PROPERTY_KEY_PATTERN.pattern() + "]", 400); + } + int separator = key.indexOf('/'); + if (separator <= 0 || separator != key.lastIndexOf('/') || separator == key.length() - 1) { + throw new AwsException("InvalidInput", + "Value '" + key + "' at 'properties' failed to satisfy constraint: a key is " + + "Namespace/PropertyName, with exactly one forward slash and neither " + + "a leading nor a trailing one.", 400); + } + return key.substring(0, separator); + } + + private void validateAccountPropertyValue(String key, String value) { + if (value == null || value.isEmpty() + || value.length() > MAX_ACCOUNT_PROPERTY_VALUE_LENGTH) { + throw new AwsException("InvalidInput", + "Value at 'properties." + key + "' failed to satisfy constraint: Member must " + + "have length between 1 and " + MAX_ACCOUNT_PROPERTY_VALUE_LENGTH, + 400); + } + } + + /** The account's global endpoint token version, {@code v1Token} or {@code v2Token}. */ + public void setSecurityTokenServicePreferences(String globalEndpointTokenVersion) { + if (globalEndpointTokenVersion == null + || !GLOBAL_ENDPOINT_TOKEN_VERSIONS.contains(globalEndpointTokenVersion)) { + throw new AwsException("ValidationError", + "Value '" + globalEndpointTokenVersion + "' at 'globalEndpointTokenVersion' " + + "failed to satisfy constraint: Member must satisfy enum value set: [" + + String.join(", ", GLOBAL_ENDPOINT_TOKEN_VERSIONS) + "]", 400); + } + stsPreferences.put(STS_PREFERENCES_KEY, globalEndpointTokenVersion); + LOG.infov("Set the global endpoint token version to {0}", globalEndpointTokenVersion); + } + + /** The stored token version, which AWS defaults to {@code v1Token} for an existing account. */ + public String getGlobalEndpointTokenVersion() { + return stsPreferences.get(STS_PREFERENCES_KEY).orElse("v1Token"); + } + + /** + * Turns on outbound web identity federation and returns the account's issuer URL. Enabling an + * already-enabled account is {@code FeatureEnabled}, which AWS states directly: "You cannot + * enable the feature multiple times." + * + *

The issuer is minted once and kept across a disable, so re-enabling returns the same URL. + * See {@link OutboundWebIdentityFederation} for why. + */ + public String enableOutboundWebIdentityFederation() { + synchronized (outboundFederationLock) { + OutboundWebIdentityFederation state = + outboundFederation.get(OUTBOUND_FEDERATION_KEY).orElse(null); + if (state != null && state.isEnabled()) { + throw new AwsException("FeatureEnabled", + "Outbound identity federation is already enabled for your AWS account. " + + "You cannot enable the feature multiple times.", 409); + } + if (state == null) { + state = new OutboundWebIdentityFederation(); + state.setIssuerIdentifier(mintIssuerIdentifier()); + } + state.setEnabled(true); + outboundFederation.put(OUTBOUND_FEDERATION_KEY, state); + LOG.infov("Enabled outbound web identity federation with issuer {0}", + state.getIssuerIdentifier()); + return state.getIssuerIdentifier(); + } + } + + /** Turns it off. Disabling an already-disabled account is {@code FeatureDisabled}. */ + public void disableOutboundWebIdentityFederation() { + synchronized (outboundFederationLock) { + OutboundWebIdentityFederation state = enabledOutboundFederation(); + state.setEnabled(false); + outboundFederation.put(OUTBOUND_FEDERATION_KEY, state); + LOG.info("Disabled outbound web identity federation"); + } + } + + /** The issuer URL and whether JWT vending is on, which it is while the feature is enabled. */ + public OutboundWebIdentityFederation getOutboundWebIdentityFederationInfo() { + synchronized (outboundFederationLock) { + return enabledOutboundFederation(); + } + } + + /** + * The federation state, or {@code FeatureDisabled} when the feature is off. AWS answers the + * getter with the disable operation's own wording, so a getter reports that the feature cannot + * be disabled twice. Matched rather than improved. + */ + private OutboundWebIdentityFederation enabledOutboundFederation() { + OutboundWebIdentityFederation state = + outboundFederation.get(OUTBOUND_FEDERATION_KEY).orElse(null); + if (state == null || !state.isEnabled()) { + throw new AwsException("FeatureDisabled", + "Outbound identity federation is already disabled for your AWS account. You " + + "cannot disable the feature multiple times", 404); + } + return state; + } + + /** + * The issuer URL AWS mints for an account: a per-account host under + * {@code tokens.sts.global.}, which the API Reference shows as + * {@code https://.tokens.sts.global.api.aws}. The suffix comes from the request's + * partition rather than the literal, since {@code api.aws} is only the commercial one. + */ + private String mintIssuerIdentifier() { + String suffix = AwsPartitions.find(regionResolver.getPartition()) + .map(AwsPartition::dualStackDnsSuffix) + .orElseGet(() -> AwsRegions.dnsSuffixFor(regionResolver.getDefaultRegion())); + return "https://" + UUID.randomUUID() + ".tokens.sts.global." + suffix; + } + // Server certificates // ========================================================================= diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/OutboundWebIdentityFederation.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/OutboundWebIdentityFederation.java new file mode 100644 index 0000000000..6e63740e41 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/OutboundWebIdentityFederation.java @@ -0,0 +1,31 @@ +package io.github.hectorvent.floci.services.iam.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The account's outbound web identity federation state: whether the feature is on, and the issuer + * URL minted for the account. + * + *

One of these exists per account once the feature has ever been enabled, and {@code enabled} + * then toggles. The entry outliving a disable is deliberate: AWS describes the issuer as "a unique + * issuer URL for your AWS account", and a relying party verifying tokens will have pinned it, so + * re-enabling mints nothing new. AWS does not document which way that goes, so this is a choice + * rather than an observed behaviour. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class OutboundWebIdentityFederation { + + private String issuerIdentifier; + private boolean enabled; + + public OutboundWebIdentityFederation() {} + + public String getIssuerIdentifier() { return issuerIdentifier; } + public void setIssuerIdentifier(String issuerIdentifier) { + this.issuerIdentifier = issuerIdentifier; + } + public boolean isEnabled() { return enabled; } + public void setEnabled(boolean enabled) { this.enabled = enabled; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesIntegrationTest.java new file mode 100644 index 0000000000..8e2dfda14e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesIntegrationTest.java @@ -0,0 +1,228 @@ +package io.github.hectorvent.floci.services.iam; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * The account property and outbound federation operations over the wire. + * + *

These are account-level singletons, so the tests share one account and are written not to + * depend on each other's properties: each uses its own namespace. + */ +@QuarkusTest +class AccountPropertiesIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request"; + + private static RequestSpecification iam(String action) { + return given().header("Authorization", IAM_AUTH).formParam("Action", action); + } + + private static String namespace() { + return "Ns" + Long.toString(System.nanoTime(), 36).replace("-", ""); + } + + private static final String PROPERTIES = + "GetAccountPropertiesResponse.GetAccountPropertiesResult.Properties."; + + @Test + void propertiesRoundTripThroughPutAndGet() { + String ns = namespace(); + + iam("PutAccountProperties") + .formParam("Properties.entry.1.key", ns + "/RoleManagerEnabled") + .formParam("Properties.entry.1.value", "true") + .formParam("Properties.entry.2.key", ns + "/Mode") + .formParam("Properties.entry.2.value", "strict") + .when().post("/").then().statusCode(200); + + iam("GetAccountProperties").when().post("/").then().statusCode(200) + .body(containsString(ns + "/RoleManagerEnabled")) + .body(containsString(ns + "/Mode")) + .body(containsString("strict")); + } + + /** "All keys must belong to the same namespace." */ + @Test + void mixingNamespacesInOneRequestIsRejected() { + String first = namespace(); + String second = namespace(); + + iam("PutAccountProperties") + .formParam("Properties.entry.1.key", first + "/Alpha") + .formParam("Properties.entry.1.value", "1") + .formParam("Properties.entry.2.key", second + "/Beta") + .formParam("Properties.entry.2.value", "2") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidInput")) + .body(containsString("same namespace")); + + // Rejected whole, not partly applied: neither key was written. + iam("GetAccountProperties").when().post("/").then().statusCode(200) + .body(not(containsString(first + "/Alpha"))) + .body(not(containsString(second + "/Beta"))); + } + + /** The key is Namespace/PropertyName: exactly one slash, not at either end. */ + @Test + void aMalformedKeyIsRejected() { + for (String key : List.of("NoSlash", "/LeadingSlash", "Trailing/", "Two/Slashes/Here", + "1StartsWithADigit", "Has Space/Prop", "Ns/Prop!")) { + iam("PutAccountProperties") + .formParam("Properties.entry.1.key", key) + .formParam("Properties.entry.1.value", "x") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidInput")); + } + } + + @Test + void aKeyOrValueOutsideItsLengthBoundsIsRejected() { + String ns = namespace(); + // keyLength is 1 to 50. + iam("PutAccountProperties") + .formParam("Properties.entry.1.key", ns + "/" + "P".repeat(60)) + .formParam("Properties.entry.1.value", "x") + .when().post("/").then().statusCode(400).body(containsString("InvalidInput")); + + // valueLength is 1 to 1024. + iam("PutAccountProperties") + .formParam("Properties.entry.1.key", ns + "/TooLongValue") + .formParam("Properties.entry.1.value", "v".repeat(1025)) + .when().post("/").then().statusCode(400).body(containsString("InvalidInput")); + + // And the top of the range is accepted, so the bound is not off by one. + iam("PutAccountProperties") + .formParam("Properties.entry.1.key", ns + "/AtTheLimit") + .formParam("Properties.entry.1.value", "v".repeat(1024)) + .when().post("/").then().statusCode(200); + } + + @Test + void anAbsentPropertiesMapIsRejected() { + iam("PutAccountProperties").when().post("/").then().statusCode(400) + .body(containsString("ValidationError")); + } + + @Test + void theTokenVersionTakesOnlyTheTwoDocumentedValues() { + for (String version : List.of("v1Token", "v2Token")) { + iam("SetSecurityTokenServicePreferences") + .formParam("GlobalEndpointTokenVersion", version) + .when().post("/").then().statusCode(200); + } + + for (String version : List.of("v3Token", "V1Token", "")) { + iam("SetSecurityTokenServicePreferences") + .formParam("GlobalEndpointTokenVersion", version) + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")); + } + + iam("SetSecurityTokenServicePreferences").when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("globalEndpointTokenVersion")); + } + + /** + * The version set here is what GetAccountSummary reports, which the operation's own + * description requires: the version "is reported in the GlobalEndpointTokenVersion entry of + * the response of the GetAccountSummary operation". Reporting a constant leaves a caller that + * set v2Token reading back 1. + */ + @Test + void theTokenVersionIsWhatTheAccountSummaryReports() { + String key = "GetAccountSummaryResponse.GetAccountSummaryResult.SummaryMap.entry" + + ".find { it.key == 'GlobalEndpointTokenVersion' }.value"; + + iam("SetSecurityTokenServicePreferences") + .formParam("GlobalEndpointTokenVersion", "v2Token") + .when().post("/").then().statusCode(200); + iam("GetAccountSummary").when().post("/").then().statusCode(200) + .body(key, equalTo("2")); + + iam("SetSecurityTokenServicePreferences") + .formParam("GlobalEndpointTokenVersion", "v1Token") + .when().post("/").then().statusCode(200); + iam("GetAccountSummary").when().post("/").then().statusCode(200) + .body(key, equalTo("1")); + } + + /** + * The federation lifecycle, in one test because it is one account-level switch: the order of + * enable and disable is the behaviour under test and separate tests would race each other. + * + *

The asymmetry is the interesting part: enabling twice is 409, disabling twice is 404. + */ + @Test + void theFederationSwitchRefusesBothRedundantDirections() { + String enabled = "EnableOutboundWebIdentityFederationResponse" + + ".EnableOutboundWebIdentityFederationResult.IssuerIdentifier"; + String info = "GetOutboundWebIdentityFederationInfoResponse" + + ".GetOutboundWebIdentityFederationInfoResult."; + + // Start from a known state: disabled, however earlier runs left it. + iam("DisableOutboundWebIdentityFederation").when().post("/"); + + iam("GetOutboundWebIdentityFederationInfo").when().post("/").then().statusCode(404) + .body(containsString("FeatureDisabled")); + + String issuer = iam("EnableOutboundWebIdentityFederation") + .when().post("/").then().statusCode(200) + // https://.tokens.sts.global., api.aws in this partition. + .body(enabled, matchesPattern( + "https://[0-9a-f-]{36}\\.tokens\\.sts\\.global\\.api\\.aws")) + .extract().path(enabled); + assertNotNull(issuer); + + iam("EnableOutboundWebIdentityFederation").when().post("/").then().statusCode(409) + .body(containsString("FeatureEnabled")) + .body(containsString("cannot enable the feature multiple times")); + + iam("GetOutboundWebIdentityFederationInfo").when().post("/").then().statusCode(200) + .body(info + "IssuerIdentifier", equalTo(issuer)) + .body(info + "JwtVendingEnabled", equalTo("true")); + + iam("DisableOutboundWebIdentityFederation").when().post("/").then().statusCode(200); + iam("DisableOutboundWebIdentityFederation").when().post("/").then().statusCode(404) + .body(containsString("FeatureDisabled")) + .body(containsString("cannot disable the feature multiple times")); + + // Re-enabling returns the same issuer: a relying party has pinned it. + String reissued = iam("EnableOutboundWebIdentityFederation") + .when().post("/").then().statusCode(200).extract().path(enabled); + assertEquals(issuer, reissued, "the issuer is minted once per account"); + + iam("DisableOutboundWebIdentityFederation").when().post("/").then().statusCode(200); + } + + /** + * Without an Authorization header the Query controller infers the service from the action name + * alone, so these have to be in its IAM set or they fall through to SQS. + */ + @Test + void theActionsRouteToIamWithNoAuthHeader() { + for (String action : List.of("GetAccountProperties", "PutAccountProperties", + "SetSecurityTokenServicePreferences", "EnableOutboundWebIdentityFederation", + "DisableOutboundWebIdentityFederation", + "GetOutboundWebIdentityFederationInfo")) { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("Version", "2010-05-08") + .when().post("/").then() + .body(containsString("iam.amazonaws.com/doc/2010-05-08")); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesStateTest.java new file mode 100644 index 0000000000..18e1e9ebf7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/AccountPropertiesStateTest.java @@ -0,0 +1,242 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.PersistentStorage; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.services.iam.model.OutboundWebIdentityFederation; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * What the wire tests cannot reach for the account-level singletons: that they survive a restart, + * that one account cannot see another's, and that two racing enables cannot both succeed. + */ +class AccountPropertiesStateTest { + + private static final String ACCOUNT_A = "000000000000"; + private static final String ACCOUNT_B = "111111111111"; + + @SuppressWarnings("unchecked") + private static Instance requestContextFor(AtomicReference accountId) { + RequestContext rc = mock(RequestContext.class); + when(rc.getAccountId()).thenAnswer(invocation -> accountId.get()); + Instance inst = mock(Instance.class); + when(inst.get()).thenReturn(rc); + return inst; + } + + private static IamService newService( + StorageBackend accountProperties, + StorageBackend stsPreferences, + StorageBackend federation, + String defaultAccount) { + return new IamService( + 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 InMemoryStorage<>(), + new InMemoryStorage<>(), + accountProperties, stsPreferences, federation, + new RegionResolver("us-east-1", defaultAccount), false, null); + } + + private static IamService inMemory(String defaultAccount) { + return newService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), defaultAccount); + } + + /** + * All three singletons survive a restart. The issuer matters most: a relying party has pinned + * it, so losing it on restart would break verification with no way to notice from the API. + */ + @Test + void thePropertiesTheTokenVersionAndTheIssuerSurviveARestart(@TempDir Path dir) { + Path propertiesFile = dir.resolve("iam-account-properties.json"); + Path stsFile = dir.resolve("iam-sts-preferences.json"); + Path federationFile = dir.resolve("iam-outbound-federation.json"); + + PersistentStorage properties = + new PersistentStorage<>(propertiesFile, new TypeReference<>() {}); + PersistentStorage sts = + new PersistentStorage<>(stsFile, new TypeReference<>() {}); + PersistentStorage federation = + new PersistentStorage<>(federationFile, new TypeReference<>() {}); + properties.load(); + sts.load(); + federation.load(); + + IamService before = newService(properties, sts, federation, ACCOUNT_A); + before.putAccountProperties(Map.of("RoleManager/Enabled", "true")); + before.setSecurityTokenServicePreferences("v2Token"); + String issuer = before.enableOutboundWebIdentityFederation(); + + PersistentStorage properties2 = + new PersistentStorage<>(propertiesFile, new TypeReference<>() {}); + PersistentStorage sts2 = + new PersistentStorage<>(stsFile, new TypeReference<>() {}); + PersistentStorage federation2 = + new PersistentStorage<>(federationFile, new TypeReference<>() {}); + properties2.load(); + sts2.load(); + federation2.load(); + IamService after = newService(properties2, sts2, federation2, ACCOUNT_A); + + assertEquals(Map.of("RoleManager/Enabled", "true"), after.getAccountProperties()); + assertEquals("v2Token", after.getGlobalEndpointTokenVersion()); + assertEquals(issuer, + after.getOutboundWebIdentityFederationInfo().getIssuerIdentifier()); + assertTrue(after.getOutboundWebIdentityFederationInfo().isEnabled()); + } + + @Test + void oneAccountCannotSeeAnothersProperties() { + AtomicReference account = new AtomicReference<>(ACCOUNT_A); + Instance context = requestContextFor(account); + AccountAwareStorageBackend properties = new AccountAwareStorageBackend<>( + new InMemoryStorage<>(), context, ACCOUNT_A); + AccountAwareStorageBackend sts = new AccountAwareStorageBackend<>( + new InMemoryStorage<>(), context, ACCOUNT_A); + AccountAwareStorageBackend federation = + new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, ACCOUNT_A); + + IamService inA = newService(properties, sts, federation, ACCOUNT_A); + IamService inB = newService(properties, sts, federation, ACCOUNT_B); + + inA.putAccountProperties(Map.of("RoleManager/Mode", "a")); + inA.setSecurityTokenServicePreferences("v2Token"); + String issuerA = inA.enableOutboundWebIdentityFederation(); + + account.set(ACCOUNT_B); + assertTrue(inB.getAccountProperties().isEmpty(), "B must not see A's properties"); + assertEquals("v1Token", inB.getGlobalEndpointTokenVersion(), + "B falls back to the default rather than reading A's preference"); + assertThrows(AwsException.class, inB::getOutboundWebIdentityFederationInfo, + "B's federation is off, whatever A did"); + + // And B enabling mints its own issuer rather than inheriting A's. + String issuerB = inB.enableOutboundWebIdentityFederation(); + assertNotEquals(issuerA, issuerB); + + account.set(ACCOUNT_A); + assertEquals(Map.of("RoleManager/Mode", "a"), inA.getAccountProperties()); + assertEquals(issuerA, + inA.getOutboundWebIdentityFederationInfo().getIssuerIdentifier()); + } + + /** + * Enabling is a check-then-act on one switch, so two racing enables must not both mint an + * issuer and both report success. Asserted by counting the winners, because an invariant + * phrased as "the stored issuer is one of the two" passes with the lock removed too. + */ + @Test + void racingEnablesProduceOneWinner() throws Exception { + for (int trial = 0; trial < 60; trial++) { + IamService service = inMemory(ACCOUNT_A); + int attempts = 8; + ExecutorService pool = Executors.newFixedThreadPool(attempts); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger enabled = new AtomicInteger(); + try { + for (int i = 0; i < attempts; i++) { + pool.submit(() -> { + start.await(); + try { + service.enableOutboundWebIdentityFederation(); + enabled.incrementAndGet(); + } catch (AwsException expected) { + // FeatureEnabled for the losers, which is the point. + } + return null; + }); + } + start.countDown(); + pool.shutdown(); + assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish"); + } finally { + pool.shutdownNow(); + } + assertEquals(1, enabled.get(), + "trial " + trial + ": exactly one enable should have succeeded"); + } + } + + /** The issuer is minted once: a disable and re-enable returns the same URL. */ + @Test + void theIssuerIsStableAcrossADisableAndReEnable() { + IamService service = inMemory(ACCOUNT_A); + String first = service.enableOutboundWebIdentityFederation(); + service.disableOutboundWebIdentityFederation(); + assertThrows(AwsException.class, service::getOutboundWebIdentityFederationInfo); + assertEquals(first, service.enableOutboundWebIdentityFederation()); + } + + private static IamService inRegion(String region) { + return new IamService( + 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 InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver(region, ACCOUNT_A), false, null); + } + + /** + * The issuer host comes from the request's partition rather than the commercial literal the + * API Reference's example happens to show. This is the test the mistake would survive + * otherwise: hardcoding {@code api.aws} passes everything else. + */ + @Test + void theIssuerHostFollowsThePartition() { + String commercial = inRegion("us-east-1").enableOutboundWebIdentityFederation(); + String chinese = inRegion("cn-north-1").enableOutboundWebIdentityFederation(); + + assertTrue(commercial.endsWith(".tokens.sts.global.api.aws"), commercial); + assertTrue(chinese.startsWith("https://"), chinese); + assertNotEquals(commercial.substring(commercial.indexOf(".tokens")), + chinese.substring(chinese.indexOf(".tokens")), + "the suffix must differ between partitions, but China gave " + chinese); + } + + /** A request mixing namespaces is rejected whole, so nothing from it is written. */ + @Test + void aMixedNamespaceRequestWritesNothing() { + IamService service = inMemory(ACCOUNT_A); + service.putAccountProperties(Map.of("RoleManager/Kept", "yes")); + + Map mixed = new LinkedHashMap<>(); + mixed.put("RoleManager/A", "1"); + mixed.put("Other/B", "2"); + assertThrows(AwsException.class, () -> service.putAccountProperties(mixed)); + + assertEquals(Map.of("RoleManager/Kept", "yes"), service.getAccountProperties(), + "neither key of the rejected request may have landed"); + } +} 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 e3abbee350..33ebb3cd3d 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 @@ -234,6 +234,7 @@ class IamServicePersistenceTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), false, null); } 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 250408cc1c..25aacdf231 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 @@ -2641,6 +2641,7 @@ class IamServiceTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), false, null); AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport); @@ -2662,6 +2663,7 @@ class IamServiceTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), false, null); IamService.CredentialReportGeneration generation = withExpiredReport.generateCredentialReport(); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java index 22168f7a21..fe834cab17 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java @@ -83,6 +83,7 @@ class ServerCertificateStateTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", defaultAccount), false, null); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialStateTest.java index 606b5f7594..c00d3db98e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialStateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialStateTest.java @@ -70,6 +70,7 @@ class ServiceSpecificCredentialStateTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), credentials, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", defaultAccount), false, null); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java index 86059fbb25..d4f1002a6d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java @@ -73,6 +73,7 @@ class SigningCertificateStateTest { certificates, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", defaultAccount), false, null); } @@ -90,6 +91,7 @@ class SigningCertificateStateTest { certificates, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", defaultAccount), false, null); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyStateTest.java index 758a0d2797..900363f9a8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyStateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyStateTest.java @@ -76,6 +76,7 @@ class SshPublicKeyStateTest { new InMemoryStorage<>(), new InMemoryStorage<>(), keys, new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", defaultAccount), false, null); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java index aedc8494b1..0e30196f2b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java @@ -54,6 +54,7 @@ class VirtualMfaAccountScopeTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", ACCOUNT_A), false, null); VirtualMfaDevice device = service.createVirtualMfaDevice("shared-name", "/", Map.of()); @@ -95,6 +96,7 @@ class VirtualMfaAccountScopeTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", ACCOUNT_A), false, null); VirtualMfaDevice inA = service.createVirtualMfaDevice("same-name", "/", Map.of()); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java index 9ea92267c6..912b9341ab 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java @@ -41,6 +41,7 @@ class VirtualMfaConcurrencyTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("eu-central-1", "000000000000"), false, null); }