Light, fluffy, and always free - The AWS Local Emulator alternative
fix(appsync): use ApiKey.id as the API key value (#2645)
武田隆志29325006bb7f
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.javaindex 96ade718ee..5e1b57152e 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java@@ -133,9 +133,9 @@ class AppSyncTest {keyId = resp.apiKey().id();assertThat(keyId).isNotBlank();assertThat(resp.apiKey().description()).isEqualTo("sdk-test-key");- // AWS SDK v2 ApiKey has no apiKey() accessor; Floci returns the da2- secret on the wire.- apiKeyValue = fetchApiKeyValue(apiId, keyId);- assertThat(apiKeyValue).startsWith("da2-");+ // As on AWS, the id is the key value sent as x-api-key.+ assertThat(keyId).matches("da2-[a-z0-9]{26}");+ apiKeyValue = keyId;}@Test@@ -1315,24 +1315,4 @@ class AppSyncTest {assertThat(location.get("column")).isNotNull();assertThat(location.get("span")).isEqualTo(-1);}-- @SuppressWarnings("unchecked")- private static String fetchApiKeyValue(String apiId, String keyId) throws Exception {- String url = TestFixtures.endpoint() + "/v1/apis/" + apiId + "/apikeys";- HttpRequest req = HttpRequest.newBuilder()- .uri(URI.create(url))- .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request")- .GET()- .build();- HttpResponse<String> resp = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());- Map<String, Object> body = mapper.readValue(resp.body(), Map.class);- List<Map<String, Object>> keys = (List<Map<String, Object>>) body.get("apiKeys");- assertThat(keys).isNotEmpty();- for (Map<String, Object> key : keys) {- if (keyId.equals(key.get("id"))) {- return String.valueOf(key.get("apiKey"));- }- }- throw new IllegalStateException("API key not listed for id " + keyId);- }}diff --git a/docs/services/appsync.md b/docs/services/appsync.mdindex 9f39b3964a..abb27e480d 100644--- a/docs/services/appsync.md+++ b/docs/services/appsync.md@@ -77,6 +77,8 @@ Floci implements the AWS AppSync Management API, providing local emulation of Gr| `DeleteApiKey` | Delete an API key || `ListApiKeys` | List all API keys for an API |+As on AWS, `ApiKey.id` is the key value itself (`da2-` followed by 26 lowercase alphanumerics) and is what clients send in the `x-api-key` header. There is no separate secret field.+### Tags| Operation | Description |@@ -219,7 +221,7 @@ Configured modes are the API default `authenticationType` plus `additionalAuthen| Mode | Emulator notes ||---|---|-| API_KEY | Lookup by key value (`da2-…`). Identity is absent (not `{}`). Default key expiry is 7 days when `expires` is omitted; stored `expires` is rounded down to the nearest hour. Create/UpdateApiKey require `expires` between 1 and 365 days from now (`ApiKeyValidityOutOfBoundsException`, 400). `deletes` is `expires` plus 60 days. |+| API_KEY | Lookup by `ApiKey.id`, which is the key value (`da2-…`). Identity is absent (not `{}`). Default key expiry is 7 days when `expires` is omitted; stored `expires` is rounded down to the nearest hour. Create/UpdateApiKey require `expires` between 1 and 365 days from now (`ApiKeyValidityOutOfBoundsException`, 400). `deletes` is `expires` plus 60 days. || AWS_IAM | Parses `Credential=` access key; no HMAC. Known keys evaluate `appsync:GraphQL`. Unknown/`test` keys are emulator ALLOW. || Cognito / OIDC | JWT payload decode only (no JWKS). OIDC as the sole mode skips the `iss` check. OIDC identity is `{sub, issuer, claims}` (no `sourceIp`). || Lambda | AppSync `isAuthorized` contract via `LambdaService.invoke` (not an API Gateway policy document). |diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.javaindex 28f7eba856..c946acfa1b 100644--- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java@@ -17,6 +17,7 @@ import jakarta.enterprise.inject.Instance;import jakarta.inject.Inject;import org.jboss.logging.Logger;+import java.security.SecureRandom;import java.time.Clock;import java.time.Duration;import java.util.*;@@ -26,6 +27,12 @@ import java.util.Base64;public class AppSyncService {private static final Logger LOG = Logger.getLogger(AppSyncService.class);+ // AWS issues API keys as "da2-" followed by 26 lowercase alphanumerics, and ApiKey.id is+ // that value: it is what clients send in the x-api-key header.+ private static final String API_KEY_PREFIX = "da2-";+ private static final String API_KEY_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";+ private static final int API_KEY_RANDOM_LENGTH = 26;+private final StorageBackend<String, GraphqlApi> apiStore;private final AccountAwareStorageBackend<String> schemaStore;private final AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore;@@ -33,6 +40,8 @@ public class AppSyncService {private final StorageBackend<String, Resolver> resolverStore;private final StorageBackend<String, FunctionConfiguration> functionStore;private final StorageBackend<String, ApiKey> apiKeyStore;+ // Instance field on purpose: a static SecureRandom would be captured in the native image heap.+ private final SecureRandom apiKeyRandom = new SecureRandom();private final StorageBackend<String, AppSyncType> typeStore;private final StorageBackend<String, DomainName> domainStore;private final StorageBackend<String, String> associationStore;@@ -585,7 +594,7 @@ public class AppSyncService {"The API key exceeded a limit.", 400);}ApiKey key = new ApiKey();- key.setId(generateShortId());+ key.setId(generateApiKeyId());key.setApiId(apiId);key.setDescription((String) request.get("description"));Object expiresValue = request.get("expires");@@ -594,8 +603,6 @@ public class AppSyncService {: parseExpires(expiresValue);applyApiKeyExpires(key, expires);- key.setApiKey("da2-" + generateShortId());-apiKeyStore.put(apiKey(apiId, key.getId()), key);return key;}@@ -615,7 +622,9 @@ public class AppSyncService {}long now = clock.instant().getEpochSecond();for (ApiKey key : apiKeyStore.scan(k -> k.startsWith(apiId + "::"))) {- if (keyValue.equals(key.getApiKey())) {+ // Keys persisted by earlier builds have a short id that was never a valid+ // x-api-key value; keep them listable and deletable but never authenticate them.+ if (key.getId() != null && key.getId().startsWith(API_KEY_PREFIX) && keyValue.equals(key.getId())) {if (key.getExpires() != null && key.getExpires() <= now) {return Optional.empty();}@@ -1095,6 +1104,14 @@ public class AppSyncService {return UUID.randomUUID().toString().replace("-", "").substring(0, 7);}+ private String generateApiKeyId() {+ StringBuilder sb = new StringBuilder(API_KEY_PREFIX);+ for (int i = 0; i < API_KEY_RANDOM_LENGTH; i++) {+ sb.append(API_KEY_ALPHABET.charAt(apiKeyRandom.nextInt(API_KEY_ALPHABET.length())));+ }+ return sb.toString();+ }+private String apiKey(String apiId, String name) {return apiId + "::" + name;}diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/ApiKey.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/ApiKey.javaindex 5140604c2f..7e6c857357 100644--- a/src/main/java/io/github/hectorvent/floci/services/appsync/model/ApiKey.java+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/ApiKey.java@@ -13,7 +13,6 @@ public class ApiKey {private Long expires;private Long deletes;private String apiId;- private String apiKey;public String getId() { return id; }public void setId(String id) { this.id = id; }@@ -29,7 +28,4 @@ public class ApiKey {public String getApiId() { return apiId; }public void setApiId(String apiId) { this.apiId = apiId; }-- public String getApiKey() { return apiKey; }- public void setApiKey(String apiKey) { this.apiKey = apiKey; }}diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.javaindex a5ac9cea92..0b8244ddef 100644--- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncAuthIntegrationTest.java@@ -265,7 +265,7 @@ class AppSyncAuthIntegrationTest {.post("/v1/apis/" + apiId + "/apikeys").then().statusCode(200)- .extract().path("apiKey.apiKey");+ .extract().path("apiKey.id");}private static void startSchema(String apiId, String definition) {diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.javaindex a6626a58ab..e7625a8a34 100644--- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java@@ -356,7 +356,7 @@ class AppSyncExecutionIntegrationTest {.post("/v1/apis/" + apiId + "/apikeys").then().statusCode(200)- .extract().path("apiKey.apiKey");+ .extract().path("apiKey.id");}private static void startSchema(String apiId, String definition) {diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.javaindex de964a1dc0..afa88dedac 100644--- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java@@ -229,8 +229,8 @@ class AppSyncIntegrationTest {.post("/v1/apis/" + apiId + "/apikeys").then().statusCode(200)- .body("apiKey.id", notNullValue())- .body("apiKey.apiKey", startsWith("da2-"))+ .body("apiKey.id", matchesPattern("da2-[a-z0-9]{26}"))+ .body("apiKey", not(hasKey("apiKey"))).body("apiKey.description", equalTo("test-key")).extract().path("apiKey.id");}diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.javaindex 0dfded5188..1ddfc69965 100644--- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java@@ -43,6 +43,7 @@ class AppSyncServiceTest {private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");private AppSyncService service;+ private AccountAwareStorageBackend<ApiKey> apiKeyStoreOverride;@BeforeEachvoid setUp() {@@ -53,7 +54,36 @@ class AppSyncServiceTest {void validateApiKeyLooksUpByValue() {GraphqlApi api = service.createGraphqlApi(Map.of("name", "a", "authenticationType", "API_KEY"), "us-east-1");ApiKey created = service.createApiKey(api.getApiId(), Map.of());- assertTrue(service.validateApiKey(api.getApiId(), created.getApiKey()).isPresent());+ assertTrue(service.validateApiKey(api.getApiId(), created.getId()).isPresent());+ }++ @Test+ void createApiKeyIdIsTheUsableKeyValue() {+ GraphqlApi api = service.createGraphqlApi(Map.of("name", "fmt", "authenticationType", "API_KEY"), "us-east-1");+ ApiKey created = service.createApiKey(api.getApiId(), Map.of());+ assertTrue(created.getId().matches("da2-[a-z0-9]{26}"), created.getId());+ assertTrue(service.validateApiKey(api.getApiId(), created.getId()).isPresent());+ assertTrue(service.validateApiKey(api.getApiId(), "da2-" + "x".repeat(26)).isEmpty());+ assertEquals(created.getId(), service.getApiKey(api.getApiId(), created.getId()).getId());+ }++ @Test+ void legacyShortApiKeyIdIsListedButNeverAuthenticates() {+ // Keys persisted by builds before ApiKey.id became the key value have a 7-character id.+ AccountAwareStorageBackend<ApiKey> keyStore = AccountAwareStorageBackend.inMemory("000000000000");+ apiKeyStoreOverride = keyStore;+ AppSyncService svc = newService(Clock.fixed(NOW, ZoneOffset.UTC));+ GraphqlApi api = svc.createGraphqlApi(Map.of("name", "legacy", "authenticationType", "API_KEY"), "us-east-1");+ ApiKey legacy = new ApiKey();+ legacy.setId("ad6c9b6");+ legacy.setApiId(api.getApiId());+ legacy.setExpires(NOW.getEpochSecond() + Duration.ofDays(7).getSeconds());+ keyStore.put(api.getApiId() + "::ad6c9b6", legacy);++ assertEquals(1, svc.listApiKeys(api.getApiId(), null, null).items().size());+ assertTrue(svc.validateApiKey(api.getApiId(), "ad6c9b6").isEmpty());+ svc.deleteApiKey(api.getApiId(), "ad6c9b6");+ assertEquals(0, svc.listApiKeys(api.getApiId(), null, null).items().size());}@Test@@ -63,9 +93,9 @@ class AppSyncServiceTest {GraphqlApi api = svc.createGraphqlApi(Map.of("name", "b", "authenticationType", "API_KEY"), "us-east-1");long expires = NOW.getEpochSecond() + Duration.ofDays(1).getSeconds();ApiKey created = svc.createApiKey(api.getApiId(), Map.of("expires", expires));- assertTrue(svc.validateApiKey(api.getApiId(), created.getApiKey()).isPresent());+ assertTrue(svc.validateApiKey(api.getApiId(), created.getId()).isPresent());clock.set(NOW.plus(Duration.ofDays(1)));- assertTrue(svc.validateApiKey(api.getApiId(), created.getApiKey()).isEmpty());+ assertTrue(svc.validateApiKey(api.getApiId(), created.getId()).isEmpty());}@Test@@ -104,7 +134,7 @@ class AppSyncServiceTest {GraphqlApi a = service.createGraphqlApi(Map.of("name", "c", "authenticationType", "API_KEY"), "us-east-1");GraphqlApi b = service.createGraphqlApi(Map.of("name", "d", "authenticationType", "API_KEY"), "us-east-1");ApiKey created = service.createApiKey(a.getApiId(), Map.of());- assertTrue(service.validateApiKey(b.getApiId(), created.getApiKey()).isEmpty());+ assertTrue(service.validateApiKey(b.getApiId(), created.getId()).isEmpty());}@Test@@ -307,6 +337,9 @@ class AppSyncServiceTest {if ("appsync-apis.json".equals(fileName)) {return (AccountAwareStorageBackend<V>) apiStore;}+ if ("appsync-apikeys.json".equals(fileName) && apiKeyStoreOverride != null) {+ return (AccountAwareStorageBackend<V>) apiKeyStoreOverride;+ }return AccountAwareStorageBackend.inMemory("000000000000");}};diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/ApiKeyAuthValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/ApiKeyAuthValidatorTest.javaindex a8cde1a125..2817d24604 100644--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/ApiKeyAuthValidatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/ApiKeyAuthValidatorTest.java@@ -23,12 +23,12 @@ class ApiKeyAuthValidatorTest {@Testvoid validKeyReturnsStoredKey() {ApiKey stored = new ApiKey();- stored.setApiKey("da2-abc");+ stored.setId("da2-abc");when(appSyncService.validateApiKey("api-1", "da2-abc")).thenReturn(Optional.of(stored));ApiKey result = new ApiKeyAuthValidator(appSyncService).validate("api-1", "da2-abc");- assertEquals("da2-abc", result.getApiKey());+ assertEquals("da2-abc", result.getId());}@Test