mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(apigateway): API key management — UpdateApiKey, DeleteApiKey, UsagePlan custom-id, generateDistinctId (#1883)
* feat(apigateway): implement UpdateApiKey and DeleteApiKey
Adds the two missing API key lifecycle operations for API Gateway v1:
- UpdateApiKey (PATCH /apikeys/{apiKeyId}): applies replace patch
operations for /name, /description and /enabled, 404 when absent
- DeleteApiKey (DELETE /apikeys/{apiKeyId}): 202 on success, 404 when
absent
Also adds a description field to the ApiKey model so it can be set on
create, returned in responses and patched via UpdateApiKey.
Integration tests cover each patch path, the 404 cases and a repeated
delete. Service docs updated to move both operations out of the Not
Implemented list.
* feat(apigateway): persist and return UsagePlan tags
CreateUsagePlan accepted a tags map but discarded it, so tags never
appeared in CreateUsagePlan, GetUsagePlan or GetUsagePlans responses.
Tags are now stored on the UsagePlan model and emitted by the
controller.
A _custom_id_ tag sets a deterministic plan ID, mirroring the existing
createRestApi behaviour. Tag values are coerced through String.valueOf
rather than an unchecked cast so a non-string value in the request body
cannot produce a ClassCastException on later reads.
The tags field defaults to an empty map, so usage plans already
persisted without it deserialize unchanged.
* fix(apigateway): treat an absent generateDistinctId as id == value
CreateApiKey generated a distinct short-token id whenever
generateDistinctId was absent, so the emulator's default disagreed with
AWS. Only an explicit generateDistinctId: true produces an id that
differs from the key value; absent and false both yield id == value.
A blank supplied value now falls back to a generated UUID on the
distinct-id path too, matching the guard the shared-value path already
had.
Integration tests cover all three states — absent, explicit false and
explicit true — and the service docs gain a table for the behaviour.
* refactor(apigateway): route UsagePlan custom IDs through ReservedTags
The usage plan override read the raw _custom_id_ key directly, which
diverged from createRestApi after #2045 made floci:override-id the
reserved key. It now calls ReservedTags.extractOverrideApiId, so the
plan gets the same validation (non-blank, no whitespace, no control
characters, no /?#) and the same precedence when both keys are present.
Persisted tags go through stripApiGatewayReservedTags, so neither
override key survives into CreateUsagePlan, GetUsagePlan or
GetUsagePlans responses.
Tests assert the reserved keys are absent from the returned tags and
cover the deprecated key, the precedence rule and both rejection paths.
* fix(apigateway): stop deleted and disabled API keys authenticating
A UsagePlanKey stores its own copy of the API key value, and the data
plane resolves requestContext.identity.apiKey by matching the x-api-key
header against those copies. Neither revocation path reached them:
- DeleteApiKey removed the key from apiKeyStore but left every usage
plan association behind, so a deleted key stayed listed by
GetUsagePlanKeys and kept being recognised on the data plane. It now
detaches the key from every plan in the region first, matching AWS.
- resolveApiKeyForRequest never read enabled, despite its javadoc
saying it matched enabled keys, so patching /enabled to false changed
nothing about request handling. It now requires the key to still exist
and be enabled, via a new non-throwing findApiKey lookup.
Floci has no apiKeyRequired gate, so a revoked key yields a null
identity.apiKey rather than a 403; the docs now say so explicitly. The
new integration test pins both paths and fails on all three assertions
without these changes.
This commit is contained in:
1 parent
f17dd1ed81
commit
b6765b3056
9 files changed
+683
-8
No files matched your search
+33
@@ -642,6 +642,32 @@ public class ApiGatewayController {
|
||||
return Response.ok(node.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/apikeys/{apiKeyId}")
|
||||
public Response updateApiKey(@Context HttpHeaders headers,
|
||||
@PathParam("apiKeyId") String apiKeyId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
|
||||
ApiKey key = service.updateApiKey(region, apiKeyId, patchOperations);
|
||||
return Response.ok(toApiKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/apikeys/{apiKeyId}")
|
||||
public Response deleteApiKey(@Context HttpHeaders headers,
|
||||
@PathParam("apiKeyId") String apiKeyId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteApiKey(region, apiKeyId);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/usageplans")
|
||||
public Response createUsagePlan(@Context HttpHeaders headers, String body) {
|
||||
@@ -1666,6 +1692,9 @@ public class ApiGatewayController {
|
||||
node.put("name", k.getName());
|
||||
node.put("value", k.getValue());
|
||||
node.put("enabled", k.isEnabled());
|
||||
if (k.getDescription() != null) {
|
||||
node.put("description", k.getDescription());
|
||||
}
|
||||
if (k.getTags() != null && !k.getTags().isEmpty()) {
|
||||
ObjectNode tags = node.putObject("tags");
|
||||
k.getTags().forEach(tags::put);
|
||||
@@ -1677,6 +1706,10 @@ public class ApiGatewayController {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", p.getId());
|
||||
node.put("name", p.getName());
|
||||
if (p.getTags() != null && !p.getTags().isEmpty()) {
|
||||
ObjectNode tags = node.putObject("tags");
|
||||
p.getTags().forEach(tags::put);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
+9
-2
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Integration;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
|
||||
@@ -602,9 +603,15 @@ public class ApiGatewayExecuteController {
|
||||
boolean planCoversStage = plan.getApiStages().stream()
|
||||
.anyMatch(s -> apiId.equals(s.apiId()) && stageName.equals(s.stage()));
|
||||
if (!planCoversStage) continue;
|
||||
// Check if any key in this plan matches the header value
|
||||
// Check if any key in this plan matches the header value. The usage plan key holds a copy
|
||||
// of the value, so the key itself must still exist and be enabled for the match to count.
|
||||
for (UsagePlanKey planKey : apiGatewayService.getUsagePlanKeys(region, plan.getId())) {
|
||||
if (keyHeader.equals(planKey.getValue())) {
|
||||
if (!keyHeader.equals(planKey.getValue())) {
|
||||
continue;
|
||||
}
|
||||
if (apiGatewayService.findApiKey(region, planKey.getId())
|
||||
.filter(ApiKey::isEnabled)
|
||||
.isPresent()) {
|
||||
return planKey.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
+62
-4
@@ -4,6 +4,7 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;
|
||||
@@ -706,12 +707,27 @@ public class ApiGatewayService {
|
||||
|
||||
public ApiKey createApiKey(String region, Map<String, Object> request) {
|
||||
ApiKey apiKey = new ApiKey();
|
||||
apiKey.setId(shortId(10));
|
||||
apiKey.setName((String) request.get("name"));
|
||||
apiKey.setValue((String) request.getOrDefault("value", UUID.randomUUID().toString().replace("-", "")));
|
||||
apiKey.setEnabled(!Boolean.FALSE.equals(request.get("enabled")));
|
||||
apiKey.setCreatedDate(System.currentTimeMillis() / 1000L);
|
||||
apiKey.setLastUpdatedDate(apiKey.getCreatedDate());
|
||||
apiKey.setDescription((String) request.get("description"));
|
||||
|
||||
boolean generateDistinctId = Boolean.TRUE.equals(request.get("generateDistinctId"));
|
||||
String suppliedValue = (String) request.get("value");
|
||||
|
||||
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("-", ""));
|
||||
}
|
||||
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
if (request.get("tags") instanceof Map<?, ?> rawTags) {
|
||||
@@ -725,27 +741,69 @@ public class ApiGatewayService {
|
||||
}
|
||||
|
||||
public ApiKey getApiKey(String region, String apiKeyId) {
|
||||
return apiKeyStore.get(apiKeyGlobalKey(region, apiKeyId))
|
||||
return findApiKey(region, apiKeyId)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API Key identifier specified", 404));
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-throwing key lookup for callers on the data plane, which must treat a missing key as
|
||||
* "not authenticated" rather than surface a management-plane 404.
|
||||
*/
|
||||
public Optional<ApiKey> findApiKey(String region, String apiKeyId) {
|
||||
return apiKeyStore.get(apiKeyGlobalKey(region, apiKeyId));
|
||||
}
|
||||
|
||||
public List<ApiKey> getApiKeys(String region) {
|
||||
String prefix = region + "::";
|
||||
return apiKeyStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleting a key detaches it from every usage plan, matching AWS. Usage plan keys hold their own
|
||||
* copy of the key value, so leaving the associations behind would keep a deleted key working as a
|
||||
* credential on the data plane and keep it listed by GetUsagePlanKeys.
|
||||
*/
|
||||
public void deleteApiKey(String region, String apiKeyId) {
|
||||
getApiKey(region, apiKeyId);
|
||||
for (UsagePlan plan : getUsagePlans(region)) {
|
||||
usagePlanKeyStore.delete(usagePlanKeyPathKey(region, plan.getId(), apiKeyId));
|
||||
}
|
||||
apiKeyStore.delete(apiKeyGlobalKey(region, apiKeyId));
|
||||
}
|
||||
|
||||
public ApiKey updateApiKey(String region, String apiKeyId, List<Map<String, String>> patchOperations) {
|
||||
ApiKey key = getApiKey(region, apiKeyId);
|
||||
if (patchOperations != null) {
|
||||
for (Map<String, String> op : patchOperations) {
|
||||
if (!"replace".equals(op.get("op"))) { continue; }
|
||||
switch (op.getOrDefault("path", "")) {
|
||||
case "/name" -> key.setName(op.get("value"));
|
||||
case "/description" -> key.setDescription(op.get("value"));
|
||||
case "/enabled" -> key.setEnabled(Boolean.parseBoolean(op.get("value")));
|
||||
}
|
||||
}
|
||||
}
|
||||
key.setLastUpdatedDate(System.currentTimeMillis() / 1000L);
|
||||
apiKeyStore.put(apiKeyGlobalKey(region, apiKeyId), key);
|
||||
return key;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Usage Plans ────────────────────────────
|
||||
|
||||
public UsagePlan createUsagePlan(String region, Map<String, Object> request) {
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
if (request.get("tags") instanceof Map<?, ?> rawTags) {
|
||||
rawTags.forEach((key, value) -> tags.put(String.valueOf(key), String.valueOf(value)));
|
||||
}
|
||||
|
||||
String customId = ReservedTags.extractOverrideApiId(tags);
|
||||
String planId = customId != null ? customId : shortId(10);
|
||||
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId(shortId(10));
|
||||
plan.setId(planId);
|
||||
plan.setName((String) request.get("name"));
|
||||
plan.setDescription((String) request.get("description"));
|
||||
plan.setTags(ReservedTags.stripApiGatewayReservedTags(tags));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> apiStages = (List<Map<String, Object>>) request.get("apiStages");
|
||||
|
||||
@@ -15,6 +15,7 @@ public class ApiKey {
|
||||
private boolean enabled;
|
||||
private long createdDate;
|
||||
private long lastUpdatedDate;
|
||||
private String description;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
|
||||
public ApiKey() {}
|
||||
@@ -37,6 +38,9 @@ public class ApiKey {
|
||||
public long getLastUpdatedDate() { return lastUpdatedDate; }
|
||||
public void setLastUpdatedDate(long lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new HashMap<>(); }
|
||||
}
|
||||
@@ -4,7 +4,9 @@ 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
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -13,6 +15,7 @@ public class UsagePlan {
|
||||
private String name;
|
||||
private String description;
|
||||
private List<ApiStage> apiStages = new ArrayList<>();
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
|
||||
public UsagePlan() {}
|
||||
|
||||
@@ -28,6 +31,9 @@ public class UsagePlan {
|
||||
public List<ApiStage> getApiStages() { return apiStages; }
|
||||
public void setApiStages(List<ApiStage> apiStages) { this.apiStages = apiStages; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new HashMap<>(); }
|
||||
|
||||
@RegisterForReflection
|
||||
public record ApiStage(String apiId, String stage) {}
|
||||
}
|
||||
Reference in new issue
Block a user