fix(apigateway): complete API Gateway API key responses (#3817)

Return timestamps, stage keys, tags, and customer ID across create, get, list,
and update operations to prevent Terraform provider crashes and state drift.
Generate opaque IDs by default while preserving legacy generateDistinctId=false behavior.
Keep API key values hidden unless explicitly requested.
Add REST, SDK, and CloudFormation regression coverage.
This commit is contained in:
Attila Kis authored and GitHub committed 2026-09-17 16:01:43 -04:00
1 parent 30b491a546
commit ad20699a6b
9 files changed
+244 -71

No files matched your search

@@ -0,0 +1,91 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
import software.amazon.awssdk.services.apigateway.model.ApiKey;
import software.amazon.awssdk.services.apigateway.model.CreateApiKeyResponse;
import software.amazon.awssdk.services.apigateway.model.GetApiKeyResponse;
import software.amazon.awssdk.services.apigateway.model.GetApiKeysResponse;
import software.amazon.awssdk.services.apigateway.model.PatchOperation;
import software.amazon.awssdk.services.apigateway.model.UpdateApiKeyResponse;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("API Gateway API keys")
class ApiGatewayApiKeyCompatibilityTest {
@Test
@DisplayName("API key responses expose the complete AWS SDK shape")
void apiKeyResponsesExposeCompleteShape() {
ApiGatewayClient apiGateway = TestFixtures.apiGatewayClient();
String value = "11112222333344445555666677778888";
CreateApiKeyResponse created = apiGateway.createApiKey(request -> request
.name(TestFixtures.uniqueName("apigw-key"))
.enabled(true)
.customerId("marketplace-customer-1")
.value(value));
try {
assertThat(created.id()).isNotBlank().isNotEqualTo(value);
assertThat(created.value()).isEqualTo(value);
assertThat(created.customerId()).isEqualTo("marketplace-customer-1");
assertCompleteShape(created.createdDate(), created.lastUpdatedDate(),
created.hasStageKeys(), created.stageKeys(), created.hasTags(), created.tags());
GetApiKeyResponse read = apiGateway.getApiKey(request -> request.apiKey(created.id()));
assertThat(read.value()).isNull();
assertThat(read.customerId()).isEqualTo("marketplace-customer-1");
assertCompleteShape(read.createdDate(), read.lastUpdatedDate(),
read.hasStageKeys(), read.stageKeys(), read.hasTags(), read.tags());
GetApiKeyResponse readWithValue = apiGateway.getApiKey(request -> request
.apiKey(created.id())
.includeValue(true));
assertThat(readWithValue.value()).isEqualTo(value);
GetApiKeysResponse listed = apiGateway.getApiKeys();
ApiKey listedKey = listed.items().stream()
.filter(key -> created.id().equals(key.id()))
.findFirst()
.orElseThrow();
assertThat(listedKey.value()).isNull();
assertThat(listedKey.customerId()).isEqualTo("marketplace-customer-1");
assertCompleteShape(listedKey.createdDate(), listedKey.lastUpdatedDate(),
listedKey.hasStageKeys(), listedKey.stageKeys(), listedKey.hasTags(), listedKey.tags());
UpdateApiKeyResponse updated = apiGateway.updateApiKey(request -> request
.apiKey(created.id())
.patchOperations(PatchOperation.builder()
.op("replace")
.path("/customerId")
.value("marketplace-customer-2")
.build()));
assertThat(updated.value()).isNull();
assertThat(updated.customerId()).isEqualTo("marketplace-customer-2");
assertCompleteShape(updated.createdDate(), updated.lastUpdatedDate(),
updated.hasStageKeys(), updated.stageKeys(), updated.hasTags(), updated.tags());
} finally {
apiGateway.deleteApiKey(request -> request.apiKey(created.id()));
apiGateway.close();
}
}
private static void assertCompleteShape(Instant createdDate,
Instant lastUpdatedDate,
boolean hasStageKeys,
List<String> stageKeys,
boolean hasTags,
Map<String, String> tags) {
assertThat(createdDate).isNotNull();
assertThat(lastUpdatedDate).isNotNull();
assertThat(hasStageKeys).isTrue();
assertThat(stageKeys).isEmpty();
assertThat(hasTags).isTrue();
assertThat(tags).isEmpty();
}
}
+5 -11
View File
@@ -92,17 +92,11 @@ column defaults to `true`. Duplicate key values are reported in the `warnings` a
#### `generateDistinctId`
Controls whether the key's `id` and `value` fields are distinct. AWS's undocumented default behaviour is that they are **the same string** unless `generateDistinctId=true` is explicitly requested.
| `generateDistinctId` | `id` | `value` |
|---|---|---|
| absent (default) | same as `value` | caller-supplied `value`, or a generated UUID-derived string |
| `false` | same as `value` | caller-supplied `value`, or a generated UUID-derived string |
| `true` | opaque short token (`shortId`) | caller-supplied `value`, or a generated UUID-derived string |
When `generateDistinctId` is absent or `false`, a single shared string is used for both `id` and `value`. If the caller supplies a `value` in the request body, that string is used for both; otherwise a UUID-derived string is generated and assigned to both.
When `generateDistinctId=true`, `id` is set to an opaque short token independent of `value`.
API key identifiers are generated independently from their secret values when `generateDistinctId`
is absent, matching current AWS behavior, or explicitly set to `true`. The deprecated explicit
`generateDistinctId=false` behavior is retained for compatibility and uses the key value as its
identifier. A caller-supplied `value` remains available only from create responses and reads that
explicitly request values.
#### Revocation
@@ -770,7 +770,9 @@ public class ApiGatewayController {
String region = regionResolver.resolveRegion(headers);
List<Map<String, String>> patchOperations = parsePatchOperations(body);
ApiKey key = service.updateApiKey(region, apiKeyId, patchOperations);
return Response.ok(toApiKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build();
ObjectNode node = toApiKeyNode(key);
node.remove("value");
return Response.ok(node.toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@@ -2297,11 +2299,20 @@ public class ApiGatewayController {
node.put("name", k.getName());
node.put("value", k.getValue());
node.put("enabled", k.isEnabled());
node.put("createdDate", k.getCreatedDate());
node.put("lastUpdatedDate", k.getLastUpdatedDate());
if (k.getCustomerId() != null) {
node.put("customerId", k.getCustomerId());
}
if (k.getDescription() != null) {
node.put("description", k.getDescription());
}
if (k.getTags() != null && !k.getTags().isEmpty()) {
ObjectNode tags = node.putObject("tags");
ArrayNode stageKeys = node.putArray("stageKeys");
if (k.getStageKeys() != null) {
k.getStageKeys().forEach(stageKeys::add);
}
ObjectNode tags = node.putObject("tags");
if (k.getTags() != null) {
k.getTags().forEach(tags::put);
}
return node;
@@ -1003,22 +1003,29 @@ public class ApiGatewayService {
apiKey.setCreatedDate(System.currentTimeMillis() / 1000L);
apiKey.setLastUpdatedDate(apiKey.getCreatedDate());
apiKey.setDescription((String) request.get("description"));
apiKey.setCustomerId((String) request.get("customerId"));
boolean generateDistinctId = Boolean.TRUE.equals(request.get("generateDistinctId"));
String suppliedValue = (String) request.get("value");
String keyValue = (suppliedValue != null && !suppliedValue.isBlank())
? suppliedValue
: UUID.randomUUID().toString().replace("-", "");
boolean generateDistinctId = !Boolean.FALSE.equals(request.get("generateDistinctId"));
apiKey.setId(generateDistinctId ? shortId(10) : keyValue);
apiKey.setValue(keyValue);
if (!generateDistinctId) {
String sharedValue = (suppliedValue != null && !suppliedValue.isBlank())
? suppliedValue
: UUID.randomUUID().toString().replace("-", "");
apiKey.setId(sharedValue);
apiKey.setValue(sharedValue);
} else {
apiKey.setId(shortId(10));
apiKey.setValue((suppliedValue != null && !suppliedValue.isBlank())
? suppliedValue
: UUID.randomUUID().toString().replace("-", ""));
List<String> stageKeys = new ArrayList<>();
if (request.get("stageKeys") instanceof List<?> rawStageKeys) {
for (Object rawStageKey : rawStageKeys) {
if (rawStageKey instanceof Map<?, ?> stageKey) {
Object restApiId = stageKey.get("restApiId");
Object stageName = stageKey.get("stageName");
if (restApiId != null && stageName != null) {
stageKeys.add(restApiId + "/" + stageName);
}
}
}
}
apiKey.setStageKeys(stageKeys);
Map<String, String> tags = new HashMap<>();
if (request.get("tags") instanceof Map<?, ?> rawTags) {
@@ -1146,6 +1153,7 @@ public class ApiGatewayService {
case "/name" -> key.setName(op.get("value"));
case "/description" -> key.setDescription(op.get("value"));
case "/enabled" -> key.setEnabled(Boolean.parseBoolean(op.get("value")));
case "/customerId" -> key.setCustomerId(op.get("value"));
}
}
}
@@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@@ -12,10 +14,12 @@ public class ApiKey {
private String id;
private String name;
private String value;
private String customerId;
private boolean enabled;
private long createdDate;
private long lastUpdatedDate;
private String description;
private List<String> stageKeys = new ArrayList<>();
private Map<String, String> tags = new HashMap<>();
public ApiKey() {}
@@ -29,6 +33,9 @@ public class ApiKey {
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
public String getCustomerId() { return customerId; }
public void setCustomerId(String customerId) { this.customerId = customerId; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
@@ -41,6 +48,9 @@ public class ApiKey {
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public List<String> getStageKeys() { return stageKeys; }
public void setStageKeys(List<String> stageKeys) { this.stageKeys = stageKeys != null ? stageKeys : new ArrayList<>(); }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new HashMap<>(); }
}
@@ -23,8 +23,7 @@ import java.util.Set;
* <p>Description, Enabled and Tags update in place. Name, Value and GenerateDistinctId are
* createOnly in the registry schema: AWS replaces the key for a change to any of them, and this
* provisioner has no replacement path, so such a change is reported rather than applied to a key
* whose value callers already hold. CustomerId and the deprecated StageKeys have no counterpart in
* {@link ApiKey} and are accepted without effect.
* whose value callers already hold. The deprecated StageKeys property is accepted without effect.
*/
@ApplicationScoped
public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
@@ -69,6 +68,10 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
Map<String, Object> request = new HashMap<>();
request.put("name", name);
request.put("description", ctx.resolveOptional(props, "Description"));
String customerId = ctx.resolveOptional(props, "CustomerId");
if (customerId != null && !customerId.isBlank()) {
request.put("customerId", customerId);
}
Boolean enabled = resolveBoolean(props, "Enabled", ctx);
if (enabled != null) {
request.put("enabled", enabled);
@@ -97,15 +100,19 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
if (value != null && !value.isBlank()) {
rejectIfChanged("Value", existing.getValue(), value);
}
// createApiKey gives a key with GenerateDistinctId=false its value as its id, so whether the
// two differ records which mode the key was created in.
boolean requestedDistinct = Boolean.TRUE.equals(resolveBoolean(props, "GenerateDistinctId", ctx));
boolean existingDistinct = !Objects.equals(existing.getId(), existing.getValue());
if (requestedDistinct != existingDistinct) {
throw replacementNotSupported("GenerateDistinctId");
Boolean requestedDistinct = resolveBoolean(props, "GenerateDistinctId", ctx);
if (requestedDistinct != null) {
boolean existingDistinct = !Objects.equals(existing.getId(), existing.getValue());
if (requestedDistinct != existingDistinct) {
throw replacementNotSupported("GenerateDistinctId");
}
}
List<Map<String, String>> patches = new ArrayList<>();
String customerId = ctx.resolveOptional(props, "CustomerId");
if (!Objects.equals(blankToNull(customerId), blankToNull(existing.getCustomerId()))) {
patches.add(patch("/customerId", customerId));
}
String description = ctx.resolveOptional(props, "Description");
if (!Objects.equals(blankToNull(description), blankToNull(existing.getDescription()))) {
patches.add(patch("/description", description));
@@ -27,7 +27,7 @@ class ApiGatewayApiKeyIntegrationTest {
@Test @Order(1)
void createApiKeyPersistsTags() {
String body = """
{"name":"k","enabled":true,"tags":{"Team":"platform","Project":"demo"}}
{"name":"k","enabled":true,"customerId":"marketplace-customer-1","tags":{"Team":"platform","Project":"demo"}}
""";
apiKeyId = given()
.contentType(ContentType.JSON)
@@ -37,7 +37,11 @@ class ApiGatewayApiKeyIntegrationTest {
.statusCode(201)
.body("id", notNullValue())
.body("name", equalTo("k"))
.body("customerId", equalTo("marketplace-customer-1"))
.body("enabled", equalTo(true))
.body("createdDate", greaterThan(0))
.body("lastUpdatedDate", greaterThan(0))
.body("stageKeys", empty())
.body("tags.Team", equalTo("platform"))
.body("tags.Project", equalTo("demo"))
.extract().path("id");
@@ -50,6 +54,10 @@ class ApiGatewayApiKeyIntegrationTest {
.then()
.statusCode(200)
.body("id", equalTo(apiKeyId))
.body("customerId", equalTo("marketplace-customer-1"))
.body("createdDate", greaterThan(0))
.body("lastUpdatedDate", greaterThan(0))
.body("stageKeys", empty())
.body("tags.Team", equalTo("platform"))
.body("tags.Project", equalTo("demo"))
.body("value", nullValue());
@@ -70,6 +78,10 @@ class ApiGatewayApiKeyIntegrationTest {
.when().get("/apikeys")
.then()
.statusCode(200)
.body("item.find { it.id == '" + apiKeyId + "' }.createdDate", greaterThan(0))
.body("item.find { it.id == '" + apiKeyId + "' }.lastUpdatedDate", greaterThan(0))
.body("item.find { it.id == '" + apiKeyId + "' }.stageKeys", empty())
.body("item.find { it.id == '" + apiKeyId + "' }.customerId", equalTo("marketplace-customer-1"))
.body("item.find { it.id == '" + apiKeyId + "' }.tags.Team", equalTo("platform"))
.body("item.find { it.id == '" + apiKeyId + "' }.value", nullValue());
@@ -103,10 +115,35 @@ class ApiGatewayApiKeyIntegrationTest {
.then()
.statusCode(200)
.body("id", equalTo(apiKeyId))
.body("name", equalTo("updated-name"));
.body("name", equalTo("updated-name"))
.body("customerId", equalTo("marketplace-customer-1"))
.body("createdDate", greaterThan(0))
.body("lastUpdatedDate", greaterThan(0))
.body("stageKeys", empty())
.body("value", nullValue());
}
@Test @Order(7)
void updateApiKeyCustomerId() {
String body = """
{"patchOperations":[{"op":"replace","path":"/customerId","value":"marketplace-customer-2"}]}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().patch("/apikeys/" + apiKeyId)
.then()
.statusCode(200)
.body("customerId", equalTo("marketplace-customer-2"));
given()
.when().get("/apikeys/" + apiKeyId)
.then()
.statusCode(200)
.body("customerId", equalTo("marketplace-customer-2"));
}
@Test @Order(8)
void updateApiKeyDescription() {
String body = """
{"patchOperations":[{"op":"replace","path":"/description","value":"a test key"}]}
@@ -120,7 +157,7 @@ class ApiGatewayApiKeyIntegrationTest {
.body("description", equalTo("a test key"));
}
@Test @Order(8)
@Test @Order(9)
void updateApiKeyEnabled() {
String body = """
{"patchOperations":[{"op":"replace","path":"/enabled","value":"false"}]}
@@ -134,7 +171,7 @@ class ApiGatewayApiKeyIntegrationTest {
.body("enabled", equalTo(false));
}
@Test @Order(9)
@Test @Order(10)
void updateApiKeyNotFound() {
String body = """
{"patchOperations":[{"op":"replace","path":"/name","value":"x"}]}
@@ -150,7 +187,7 @@ class ApiGatewayApiKeyIntegrationTest {
.body("message", equalTo("Invalid API Key identifier specified"));
}
@Test @Order(10)
@Test @Order(11)
void deleteApiKey() {
given()
.when().delete("/apikeys/" + apiKeyId)
@@ -158,7 +195,7 @@ class ApiGatewayApiKeyIntegrationTest {
.statusCode(202);
}
@Test @Order(11)
@Test @Order(12)
void deleteApiKeyAlreadyGone() {
given()
.when().delete("/apikeys/" + apiKeyId)
@@ -169,51 +206,57 @@ class ApiGatewayApiKeyIntegrationTest {
.body("message", equalTo("Invalid API Key identifier specified"));
}
@Test @Order(12)
@Test @Order(13)
void createApiKey_generateDistinctIdFalse_idEqualsValue() {
String body = """
{"name":"shared-id-key","enabled":true,"generateDistinctId":false}
{"name":"distinct-id-key-false","enabled":true,"generateDistinctId":false,"value":"11112222333344445555666677778888"}
""";
String sharedId = given()
String keyId = given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/apikeys")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("tags", anEmptyMap())
.body("stageKeys", empty())
.extract().path("id");
given()
.when().get("/apikeys/" + sharedId + "?includeValue=true")
.when().get("/apikeys/" + keyId + "?includeValue=true")
.then()
.statusCode(200)
.body("id", equalTo(sharedId))
.body("value", equalTo(sharedId));
}
@Test @Order(13)
void createApiKey_generateDistinctIdAbsent_idEqualsValue() {
String body = """
{"name":"default-id-key","enabled":true}
""";
String sharedId = given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/apikeys")
.then()
.statusCode(201)
.body("id", notNullValue())
.extract().path("id");
given()
.when().get("/apikeys/" + sharedId + "?includeValue=true")
.then()
.statusCode(200)
.body("id", equalTo(sharedId))
.body("value", equalTo(sharedId));
.body("id", equalTo(keyId))
.body("value", equalTo("11112222333344445555666677778888"))
.body("value", equalTo(keyId))
.body("tags", anEmptyMap())
.body("stageKeys", empty());
}
@Test @Order(14)
void createApiKey_generateDistinctIdAbsent_idDiffersFromValue() {
String body = """
{"name":"default-id-key","enabled":true,"value":"99992222333344445555666677778888"}
""";
String keyId = given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/apikeys")
.then()
.statusCode(201)
.body("id", notNullValue())
.extract().path("id");
given()
.when().get("/apikeys/" + keyId + "?includeValue=true")
.then()
.statusCode(200)
.body("id", equalTo(keyId))
.body("value", equalTo("99992222333344445555666677778888"))
.body("value", not(equalTo(keyId)));
}
@Test @Order(15)
void createApiKey_generateDistinctIdTrue_idDistinctFromValue() {
String body = """
{"name":"distinct-id-key","enabled":true,"generateDistinctId":true}
@@ -234,7 +277,7 @@ class ApiGatewayApiKeyIntegrationTest {
.body("id", equalTo(keyId))
.body("value", not(equalTo(keyId)));
}
@Test @Order(15)
@Test @Order(16)
void getDeletedApiKeyNotFound() {
given()
.when().get("/apikeys/" + apiKeyId)
@@ -91,7 +91,7 @@ class ApiGatewayApiKeyCfnIntegrationTest {
.body("description", equalTo("first"))
.body("enabled", equalTo(false))
.body("tags.stack", equalTo("v1"))
.body("value", equalTo(namedId));
.body("value", not(equalTo(namedId)));
// A key with no properties gets a CloudFormation-style generated name and AWS's defaults.
getApiKey(unnamedId)
@@ -87,6 +87,7 @@ class ApiGatewayApiKeyCfnProvisionerTest {
.thenReturn(key("abc123", "my-key", "0123456789abcdef0123", false, "a key", Map.of("team", "core")));
ObjectNode props = tags("team", "core")
.put("Name", "my-key")
.put("CustomerId", "marketplace-customer-1")
.put("Description", "a key")
.put("Enabled", "false")
.put("GenerateDistinctId", "true")
@@ -101,6 +102,7 @@ class ApiGatewayApiKeyCfnProvisionerTest {
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
verify(apiGateway).createApiKey(eq(REGION), request.capture());
assertEquals("my-key", request.getValue().get("name"));
assertEquals("marketplace-customer-1", request.getValue().get("customerId"));
assertEquals("a key", request.getValue().get("description"));
assertEquals(Boolean.FALSE, request.getValue().get("enabled"));
assertEquals(Boolean.TRUE, request.getValue().get("generateDistinctId"));
@@ -126,9 +128,14 @@ class ApiGatewayApiKeyCfnProvisionerTest {
@Test
void updatePatchesDescriptionAndEnabledInPlace() {
ApiKey existing = key("abc123", "my-key", "abc123", false, "old", Map.of());
existing.setCustomerId("marketplace-customer-1");
when(apiGateway.findApiKey(REGION, "abc123")).thenReturn(Optional.of(existing));
when(apiGateway.updateApiKey(eq(REGION), eq("abc123"), anyList())).thenReturn(existing);
ObjectNode props = mapper.createObjectNode().put("Name", "my-key").put("Description", "new").put("Enabled", "true");
ObjectNode props = mapper.createObjectNode()
.put("Name", "my-key")
.put("CustomerId", "marketplace-customer-2")
.put("Description", "new")
.put("Enabled", "true");
StackResource r = resource("abc123");
provisioner.provision(r, props, ctx("abc123"));
@@ -141,6 +148,8 @@ class ApiGatewayApiKeyCfnProvisionerTest {
"/description".equals(op.get("path")) && "new".equals(op.get("value"))));
assertTrue(patches.getValue().stream().anyMatch(op ->
"/enabled".equals(op.get("path")) && "true".equals(op.get("value"))));
assertTrue(patches.getValue().stream().anyMatch(op ->
"/customerId".equals(op.get("path")) && "marketplace-customer-2".equals(op.get("value"))));
assertEquals("abc123", r.getPhysicalId());
assertEquals("abc123", r.getAttributes().get("APIKeyId"));
}