Light, fluffy, and always free - The AWS Local Emulator alternative
feat(sts): dispatch GetAccessKeyInfo, the account an access key id belongs to (#6121)
Priamo Germosen4eea01741f03
diff --git a/docs/services/index.md b/docs/services/index.mdindex f5460c72b6..726755dbc9 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -24,7 +24,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 || [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane || [IAM](iam.md) | `POST /` with `Action=` param | Query | 176 |-| [STS](sts.md) | `POST /` with `Action=` param | Query | 8 |+| [STS](sts.md) | `POST /` with `Action=` param | Query | 9 || [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 || [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 90 |diff --git a/docs/services/sts.md b/docs/services/sts.mdindex da9a307a1e..783d0206ef 100644--- a/docs/services/sts.md+++ b/docs/services/sts.md@@ -14,6 +14,23 @@| `GetFederationToken` | Get temporary credentials for a federated user || `DecodeAuthorizationMessage` | Decode an encoded authorization failure message || `GetDelegatedAccessToken` | Exchange a delegation request's trade-in token for temporary credentials |+| `GetAccessKeyInfo` | Returns the account an access key ID belongs to |++## Access Key Info++`GetAccessKeyInfo` answers the account an access key ID belongs to, and nothing about the key+itself: AWS states that the operation "does not indicate the state of the access key. The key might+be active, inactive, or deleted", so an inactive key answers its account the same as an active one.+A long-term `AKIA` key resolves through the account that holds it and a temporary `ASIA` key through+the session that minted it. The ID is read against its own shape first, 16 to 128 characters of+`[\w]`, which answers `ValidationError` before any lookup.++One answer is Floci's own. The operation models no errors at all, and the reference says only that+"providing a deleted access key might return an error that the key doesn't exist", so a well-formed+ID that this emulator never issued answers `InvalidParameterValue`, the published common error+closest to that sentence. Nothing in the reference says what AWS answers for an ID it never issued,+and real access key IDs are not random the way Floci's are, so treat that one as a deviation rather+than a recorded behaviour.## Delegated Access Tokendiff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex b4d1bdc60a..92e7ff844f 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@@ -4515,16 +4515,47 @@ public class IamService implements SessionAccountLookup, ResourceProvider {*/public record OwnedSecretKey(String secretAccessKey, String accountId) {}+ /**+ * The account that owns an access key id, in whatever state the key is, which is the lookup STS+ * GetAccessKeyInfo answers from: "This operation does not indicate the state of the access key.+ * The key might be active, inactive, or deleted." {@link #resolveAccountId} is the other+ * question, the one authentication asks, and it takes only an active key and a live session.+ */+ public Optional<String> findAccountForAccessKeyId(String accessKeyId) {+ if (accessKeyId == null || accessKeyId.isBlank()) {+ return Optional.empty();+ }+ if (!isTemporaryAccessKey(accessKeyId)) {+ return accessKeyInAnyAccount(accessKeyId)+ .map(AccountAwareStorageBackend.AccountEntry::accountId);+ }+ return storedSessionAnyAccount(accessKeyId)+ .map(session -> AwsArnUtils.accountOrDefault(session.getRoleArn(), session.getOriginAccountId()))+ .filter(account -> !account.isBlank());+ }++ /** The long-term key with this id from whichever account holds it, Active or not. */+ private Optional<AccountAwareStorageBackend.AccountEntry<AccessKey>> accessKeyInAnyAccount(+ String accessKeyId) {+ return longTermKeysInAnyAccount(accessKeyId).stream().findFirst();+ }+/** The active long-term key with this ID, from whichever account owns it. */private Optional<AccountAwareStorageBackend.AccountEntry<AccessKey>> activeAccessKeyInAnyAccount(String accessKeyId) {+ return longTermKeysInAnyAccount(accessKeyId).stream()+ .filter(entry -> "Active".equals(entry.value().getStatus()))+ .findFirst();+ }++ /** Every long-term key stored under this id, across accounts, in whatever state. */+ private List<AccountAwareStorageBackend.AccountEntry<AccessKey>> longTermKeysInAnyAccount(+ String accessKeyId) {if (accessKeyId == null || isTemporaryAccessKey(accessKeyId)|| !(accessKeys instanceof AccountAwareStorageBackend<AccessKey> aware)) {- return Optional.empty();+ return List.of();}- return aware.scanAllAccountEntries(accessKeyId::equals).stream()- .filter(entry -> "Active".equals(entry.value().getStatus()))- .findFirst();+ return aware.scanAllAccountEntries(accessKeyId::equals);}private Optional<String> activeAccessKeySecret(String accessKeyId) {diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.javaindex 61238aa61a..3d0abf11f6 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.IamConditionContextResolver;import io.github.hectorvent.floci.core.common.IamEnforcementFilter;import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.SmithyValidationErrors;import io.github.hectorvent.floci.core.common.WebIdentityToken;import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;import io.github.hectorvent.floci.core.common.XmlBuilder;@@ -35,6 +36,7 @@ import java.util.List;import java.util.Map;import java.util.Optional;import java.util.concurrent.ThreadLocalRandom;+import java.util.regex.Pattern;/*** Query-protocol handler for STS (Security Token Service) actions.@@ -44,6 +46,11 @@ import java.util.concurrent.ThreadLocalRandom;@ApplicationScopedpublic class StsQueryHandler {+ /** accessKeyIdType, the only member GetAccessKeyInfo takes: 16 to 128 characters of {@code [\w]}. */+ private static final Pattern ACCESS_KEY_ID_PATTERN = Pattern.compile("[\\w]*");+ private static final int ACCESS_KEY_ID_MIN_LENGTH = 16;+ private static final int ACCESS_KEY_ID_MAX_LENGTH = 128;+private static final Logger LOG = Logger.getLogger(StsQueryHandler.class);private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";private static final String STS_AUDIENCE = "sts.amazonaws.com"; // partition-literal: web-identity audience; no source outside the commercial partition (P9)@@ -113,6 +120,7 @@ public class StsQueryHandler {return switch (action) {case "AssumeRole" -> handleAssumeRole(params);case "GetCallerIdentity" -> handleGetCallerIdentity(params);+ case "GetAccessKeyInfo" -> handleGetAccessKeyInfo(params);case "GetSessionToken" -> handleGetSessionToken(params);case "AssumeRoleWithWebIdentity" -> handleAssumeRoleWithWebIdentity(params);case "AssumeRoleWithSAML" -> handleAssumeRoleWithSAML(params);@@ -258,6 +266,70 @@ public class StsQueryHandler {return Response.ok(AwsQueryResponse.envelope("GetCallerIdentity", AwsNamespaces.STS, result)).build();}+ /**+ * The account an access key id belongs to. AWS answers one member and models no errors at all,+ * and the page is explicit that the key's state is not part of the answer: "This operation does+ * not indicate the state of the access key. The key might be active, inactive, or deleted." So+ * the lookup takes the key whatever state it is in, which is why it is not+ * {@code resolveAccountId}, the authentication path, that answers here.+ *+ * <p>A key Floci does not hold is the one answer the reference leaves open. It models no error+ * for it and says only that "providing a deleted access key might return an error that the key+ * doesn't exist", so this answers {@code InvalidParameterValue}, the published common error+ * nearest that sentence, and {@code docs/services/sts.md} records it as the deviation it is.+ */+ private Response handleGetAccessKeyInfo(MultivaluedMap<String, String> params) {+ Response validation = validateAccessKeyId(params);+ if (validation != null) {+ return validation;+ }+ String accessKeyId = getParam(params, "AccessKeyId");+ Optional<String> account = iamService.findAccountForAccessKeyId(accessKeyId);+ if (account.isEmpty()) {+ return AwsQueryResponse.error("InvalidParameterValue",+ "The access key " + accessKeyId + " does not exist.", AwsNamespaces.STS, 400);+ }+ String result = new XmlBuilder().elem("Account", account.get()).build();+ return Response.ok(AwsQueryResponse.envelope("GetAccessKeyInfo", AwsNamespaces.STS, result)).build();+ }++ /**+ * accessKeyIdType: required, 16 to 128 characters of {@code [\w]*}, which the reference+ * describes as "any upper- or lowercase letter or digit". Read before the lookup, so a+ * malformed id answers for its shape rather than for a key that could not exist.+ *+ * <p>An absent member and a present empty one are different answers: only the absent one is+ * "Member must not be null", where {@code AccessKeyId=} is a value that fails the minimum. That+ * is what IAM answers for an empty {@code RoleName} on this same wire.+ *+ * <p>The member is named the way AWS names it in a constraint message, lower camel case, and+ * the offending value is quoted beside it, which is what the one recorded rendering Floci+ * follows elsewhere does: {@link IamService} reads {@code roleName} that way, and so does this+ * handler's own {@code DurationSeconds} check. The older STS operations name the parameter as+ * written instead, which is a drift of its own rather than something to copy here.+ */+ private Response validateAccessKeyId(MultivaluedMap<String, String> params) {+ String accessKeyId = params.getFirst("AccessKeyId");+ String constraint;+ if (accessKeyId == null) {+ constraint = "Member must not be null";+ } else if (accessKeyId.length() < ACCESS_KEY_ID_MIN_LENGTH) {+ constraint = "Member must have length greater than or equal to " + ACCESS_KEY_ID_MIN_LENGTH;+ } else if (accessKeyId.length() > ACCESS_KEY_ID_MAX_LENGTH) {+ constraint = "Member must have length less than or equal to " + ACCESS_KEY_ID_MAX_LENGTH;+ } else if (!ACCESS_KEY_ID_PATTERN.matcher(accessKeyId).matches()) {+ constraint = "Member must satisfy regular expression pattern: "+ + ACCESS_KEY_ID_PATTERN.pattern();+ } else {+ return null;+ }+ String value = accessKeyId == null ? "null" : "'" + accessKeyId + "'";+ return AwsQueryResponse.error("ValidationError",+ SmithyValidationErrors.message(List.of("Value " + value+ + " at 'accessKeyId' failed to satisfy constraint: " + constraint)),+ AwsNamespaces.STS, 400);+ }+private Response handleGetSessionToken(MultivaluedMap<String, String> params) {if (IamService.isTemporaryAccessKey(callerAccessKeyId())) {return AwsQueryResponse.error("AccessDenied", "Cannot call GetSessionToken with session credentials",diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsAccessKeyInfoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsAccessKeyInfoIntegrationTest.javanew file mode 100644index 0000000000..39b8436366--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsAccessKeyInfoIntegrationTest.java@@ -0,0 +1,142 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.testing.PartitionCleanup;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.RegisterExtension;++import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.startsWith;++/**+ * {@code GetAccessKeyInfo} over the wire.+ *+ * <p>The operation answers one member, the account an access key id belongs to, and models no+ * errors at all. Its one explicit behaviour is what it does not do: "this operation does not+ * indicate the state of the access key. The key might be active, inactive, or deleted", so an+ * inactive key still answers its account. A key Floci does not hold is the answer the reference+ * leaves open, and {@code docs/services/sts.md} carries that deviation.+ */+@QuarkusTest+class StsAccessKeyInfoIntegrationTest {++ private static final String ACCOUNT = "000000000941";+ private static final String REGION = "us-east-1";+ private static final String RESULT = "GetAccessKeyInfoResponse.GetAccessKeyInfoResult";++ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();++ @Test+ void aLongTermKeyAnswersTheAccountThatHoldsIt() {+ String userName = user("holder");+ String accessKeyId = accessKeyFor(userName);++ sts("GetAccessKeyInfo", Map.of("AccessKeyId", accessKeyId)).statusCode(200)+ .body(RESULT + ".Account", equalTo(ACCOUNT));+ }++ @Test+ void anInactiveKeyStillAnswersItsAccount() {+ // "This operation does not indicate the state of the access key. The key might be active,+ // inactive, or deleted", so the status is not a reason to refuse.+ String userName = user("inactive");+ String accessKeyId = accessKeyFor(userName);++ iam("UpdateAccessKey", Map.of("UserName", userName, "AccessKeyId", accessKeyId,+ "Status", "Inactive")).statusCode(200);++ sts("GetAccessKeyInfo", Map.of("AccessKeyId", accessKeyId)).statusCode(200)+ .body(RESULT + ".Account", equalTo(ACCOUNT));+ }++ @Test+ void aSessionKeyAnswersTheAccountItsSessionBelongsTo() {+ // "Access key IDs beginning with ASIA are temporary credentials that are created using+ // STS operations", and they resolve through the session rather than the key store.+ String sessionKeyId = sts("GetSessionToken", Map.of()).statusCode(200)+ .body("GetSessionTokenResponse.GetSessionTokenResult.Credentials.AccessKeyId",+ startsWith("ASIA"))+ .extract().path("GetSessionTokenResponse.GetSessionTokenResult.Credentials.AccessKeyId");++ sts("GetAccessKeyInfo", Map.of("AccessKeyId", sessionKeyId)).statusCode(200)+ .body(RESULT + ".Account", equalTo(ACCOUNT));+ }++ @Test+ void anIdOutsideTheShapeIsReadBeforeAnyLookup() {+ sts("GetAccessKeyInfo", Map.of("AccessKeyId", "AKIASHORT")).statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message",+ equalTo("1 validation error detected: Value 'AKIASHORT' at 'accessKeyId' "+ + "failed to satisfy constraint: Member must have length greater "+ + "than or equal to 16"));++ sts("GetAccessKeyInfo", Map.of("AccessKeyId", "AKIA-NOT-A-VALID-KEY-ID")).statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message",+ containsString("Member must satisfy regular expression pattern"));++ // A member sent empty is a value that fails the minimum, where an absent one is the+ // refusal that names it null, which is the pair IAM already answers for RoleName here.+ sts("GetAccessKeyInfo", Map.of("AccessKeyId", "")).statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message",+ equalTo("1 validation error detected: Value '' at 'accessKeyId' failed to "+ + "satisfy constraint: Member must have length greater than or "+ + "equal to 16"));++ sts("GetAccessKeyInfo", Map.of()).statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))+ .body("ErrorResponse.Error.Message",+ containsString("Value null at 'accessKeyId'"));+ }++ @Test+ void aWellFormedKeyNobodyHoldsIsRefused() {+ sts("GetAccessKeyInfo", Map.of("AccessKeyId", "AKIAABSENTKEY0000000")).statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"));+ }++ private String user(String label) {+ String userName = "access-key-info-" + label;+ iam("CreateUser", Map.of("UserName", userName)).statusCode(200);+ cleanup.register(() -> iam("DeleteUser", Map.of("UserName", userName)).statusCode(200));+ return userName;+ }++ private String accessKeyFor(String userName) {+ String accessKeyId = iam("CreateAccessKey", Map.of("UserName", userName)).statusCode(200)+ .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");+ cleanup.register(() -> iam("DeleteAccessKey",+ Map.of("UserName", userName, "AccessKeyId", accessKeyId)).statusCode(200));+ return accessKeyId;+ }++ private static ValidatableResponse iam(String action, Map<String, String> params) {+ return call(action, "iam", "2010-05-08", params);+ }++ private static ValidatableResponse sts(String action, Map<String, String> params) {+ return call(action, "sts", "2011-06-15", params);+ }++ private static ValidatableResponse call(String action, String service, String version,+ Map<String, String> params) {+ RequestSpecification spec = given()+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT+ + "/20261019/" + REGION + "/" + service + "/aws4_request, "+ + "SignedHeaders=host, Signature=abc")+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", action)+ .formParam("Version", version);+ params.forEach(spec::formParam);+ return spec.when().post("/").then();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.javaindex 98035c1392..a6f51f17a3 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java@@ -514,6 +514,102 @@ class StsQueryHandlerTest {PartitionMatrix.assertGlobalArnIn(partitionCase, arn);}+ @Test+ void getAccessKeyInfoAnswersTheAccountThatHoldsTheKey() {+ IamService service = mock(IamService.class);+ when(service.findAccountForAccessKeyId("AKIAIOSFODNN7EXAMPLE"))+ .thenReturn(Optional.of("111122223333"));+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("AccessKeyId", "AKIAIOSFODNN7EXAMPLE");++ Response response = newHandler(service, new RegionResolver(REGION, "000000000000"))+ .handle("GetAccessKeyInfo", params);++ assertEquals(200, response.getStatus());+ String body = (String) response.getEntity();+ assertTrue(body.contains("<GetAccessKeyInfoResponse"), body);+ assertTrue(body.contains("<Account>111122223333</Account>"), body);+ // The lookup is the state-independent one, not the authentication path.+ verify(service).findAccountForAccessKeyId("AKIAIOSFODNN7EXAMPLE");+ verify(service, never()).resolveAccountId(anyString());+ }++ @Test+ void getAccessKeyInfoRefusesAKeyNobodyHolds() {+ // The operation models no error at all, and the page says only that a deleted key "might+ // return an error that the key doesn't exist", so this is the published common error+ // nearest that sentence rather than a reading.+ IamService service = mock(IamService.class);+ when(service.findAccountForAccessKeyId(anyString())).thenReturn(Optional.empty());+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("AccessKeyId", "AKIAABSENTKEY0000000");++ Response response = newHandler(service, new RegionResolver(REGION, "000000000000"))+ .handle("GetAccessKeyInfo", params);++ assertEquals(400, response.getStatus());+ assertTrue(response.getEntity().toString().contains("<Code>InvalidParameterValue</Code>"));+ }++ @ParameterizedTest+ @CsvSource({+ "-, Value null at 'accessKeyId' failed to satisfy constraint: Member must not be null",+ "AKIATOOSHORT, Value 'AKIATOOSHORT' at 'accessKeyId' failed to satisfy constraint: "+ + "Member must have length greater than or equal to 16",+ "AKIA-NOT-A-VALID-KEY-ID, Member must satisfy regular expression pattern",+ })+ void getAccessKeyInfoReadsTheIdsShapeBeforeAnyLookup(String accessKeyId, String expected) {+ IamService service = mock(IamService.class);+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ if (!"-".equals(accessKeyId)) {+ params.add("AccessKeyId", accessKeyId);+ }++ Response response = newHandler(service, new RegionResolver(REGION, "000000000000"))+ .handle("GetAccessKeyInfo", params);++ assertEquals(400, response.getStatus());+ // The Query error body escapes the apostrophes the message quotes the member with.+ String body = ((String) response.getEntity()).replace("'", "'");+ assertTrue(body.contains("<Code>ValidationError</Code>"), body);+ assertTrue(body.contains(expected), body);+ verifyNoInteractions(service);+ }++ @ParameterizedTest+ @ValueSource(strings = {"", " "})+ void getAccessKeyInfoReadsAPresentBlankIdAsAValue(String accessKeyId) {+ // Present and empty is a value, not an absence: it fails the minimum and is quoted in the+ // message, which is what IAM answers for an empty RoleName over this same wire.+ IamService service = mock(IamService.class);+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("AccessKeyId", accessKeyId);++ Response response = newHandler(service, new RegionResolver(REGION, "000000000000"))+ .handle("GetAccessKeyInfo", params);++ assertEquals(400, response.getStatus());+ String body = ((String) response.getEntity()).replace("'", "'");+ assertTrue(body.contains("Value '" + accessKeyId + "' at 'accessKeyId' failed to satisfy "+ + "constraint: Member must have length greater than or equal to 16"), body);+ verifyNoInteractions(service);+ }++ @Test+ void getAccessKeyInfoRefusesAnIdPastTheMaximum() {+ IamService service = mock(IamService.class);+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("AccessKeyId", "A".repeat(129));++ Response response = newHandler(service, new RegionResolver(REGION, "000000000000"))+ .handle("GetAccessKeyInfo", params);++ assertEquals(400, response.getStatus());+ assertTrue(response.getEntity().toString()+ .contains("Member must have length less than or equal to 128"));+ verifyNoInteractions(service);+ }+@ParameterizedTest@MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")void getFederationTokenMintsTheFederatedUserArnInTheDeploymentsPartition(PartitionCase partitionCase) {