feat(apigateway): support floci:override-id for v1 and v2 (#2045)

* feat(apigateway): support floci:override-id for v1 and v2

API IDs were generated randomly, so endpoint URLs changed on every
recreate. v1 accepted an undocumented `_custom_id_` tag and echoed it
back as a normal tag; v2 had no override at all. Other services already
pin IDs through the reserved `floci:override-id` tag.

Both CreateRestApi and CreateApi now accept `floci:override-id`, routed
through ReservedTags.getOverride so the value is validated rather than
used verbatim: non-blank, no whitespace or control characters, and no
`/`, `?`, `#`, since those break the endpoint URL. Override keys are
consumed rather than stored, so they no longer appear in the returned
tags, and supplying either key to TagResource is rejected because an ID
cannot change after creation.

`_custom_id_` keeps working as a deprecated fallback and is now stripped
the same way; `floci:override-id` wins when both are present so callers
can set both during a migration. The key stays API Gateway specific: the
shared strip and reject helpers are untouched, so KMS and Cognito still
treat `_custom_id_` as an ordinary tag.

Error code is BadRequestException, declared by CreateRestApi, CreateApi
and TagResource on both services. The shared reject helper's
ValidationException is declared by neither, which is why API Gateway gets
its own guard rather than reusing it.

Closes #1593

Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>

* fix(apigateway): reject duplicate override ids with ConflictException

CreateRestApi (v1) and CreateApi (v2) now return 409 ConflictException
when the resolved API id already exists in the region, instead of
silently overwriting the existing API, matching how KMS and Cognito
treat duplicate override ids.

---------

Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
This commit is contained in:
Hector VenturaandMarcel Herhold authored and GitHub committed 2026-07-29 23:40:27 -05:00
1 parent 86134e8c7f
commit 02385da37b
8 files changed
+430 -10

No files matched your search

+8
View File
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- **apigateway:** support the reserved `floci:override-id` tag on `CreateRestApi` (v1) and `CreateApi` (v2) to pin the generated API ID, unifying custom IDs with the tag KMS and Cognito already use. Override keys are stripped from the returned tags, validated (non-blank, no whitespace/control characters and no `/`, `?`, `#`) and rejected on `TagResource` with `BadRequestException`, which is what both services declare. The older API-Gateway-specific `_custom_id_` tag still works as a deprecated fallback and is now stripped too; `floci:override-id` wins when both are present. Creating an API whose override ID already exists in the region is rejected with `ConflictException` (409) instead of overwriting the existing API ([#1593](https://github.com/floci-io/floci/pull/1593))
### Changed
- **apigateway:** `_custom_id_` is no longer persisted in the tags returned for a REST API. It was previously echoed back as a normal tag.
## [1.5.34] - 2026-07-28
### Added
+32
View File
@@ -2,6 +2,38 @@
Floci supports both API Gateway v1 (REST APIs) and API Gateway v2 (HTTP APIs).
## Custom API IDs
API IDs are generated randomly, which means endpoint URLs change every time you recreate an API. To pin
one, pass the reserved `floci:override-id` tag on creation and Floci uses its value as the API ID. This
works for both v1 (`CreateRestApi`) and v2 (`CreateApi`), and matches the tag other services such as KMS
and Cognito already use.
```bash
aws apigateway create-rest-api \
--name my-api \
--tags '{"floci:override-id":"my-fixed-id","env":"test"}' \
--endpoint-url http://localhost:4566
# the API is now reachable at the stable id "my-fixed-id"
```
The override key is consumed rather than stored, so it never appears in the tags the API returns. Any
other tags in the same request are kept. Because an ID cannot change after creation, supplying either
override key to `TagResource` is rejected with `BadRequestException`.
Values must be non-blank and must not contain whitespace, control characters, or `/`, `?`, `#`, since
those would break the endpoint URL. An invalid value is rejected with `BadRequestException`.
Creating a second API with an override ID that already exists in the region is rejected with
`ConflictException` instead of overwriting the existing API, matching how KMS and Cognito treat
duplicate override IDs.
> [!NOTE]
> API Gateway previously used a `_custom_id_` tag for this. It still works so existing setups keep
> running, and it is now stripped from the returned tags the same way, but it is deprecated: prefer
> `floci:override-id`. If both are present, `floci:override-id` wins, which lets you set both during a
> migration. The `_custom_id_` key is API Gateway specific and is not reserved for any other service.
## API Gateway v1 (REST APIs) {#v1}
**Protocol:** REST JSON
@@ -13,9 +13,18 @@ public final class ReservedTags {
public static final String OVERRIDE_ID_KEY = RESERVED_PREFIX + "override-id";
public static final String OVERRIDE_COGNITO_CLIENT_ID_KEY = RESERVED_PREFIX + "override-cognito-client-id";
public static final String OVERRIDE_COGNITO_CLIENT_SECRET_KEY = RESERVED_PREFIX + "override-cognito-client-secret";
/**
* API Gateway accepted a custom id through this key before {@link #OVERRIDE_ID_KEY} existed. It is
* API Gateway specific and deprecated: still honored on create, but no longer persisted in the
* resource tags. Other services never supported it and must not start reserving it.
*/
public static final String DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY = "_custom_id_";
private static final String INVALID_PARAMETER_EXCEPTION = "InvalidParameterException";
private static final String VALIDATION_EXCEPTION = "ValidationException";
private static final String TAG_EXCEPTION = "TagException";
private static final String BAD_REQUEST_EXCEPTION = "BadRequestException";
private static final String CONTROL_CHARACTER_ERROR_MESSAGE = "Override %s must not contain control characters.";
private ReservedTags() {
@@ -29,6 +38,21 @@ public final class ReservedTags {
return getOverride(tags, OVERRIDE_ID_KEY, ReservedTags::validateOverrideId, "Resource ID", INVALID_PARAMETER_EXCEPTION);
}
/**
* API Gateway v1 and v2 override id. {@link #OVERRIDE_ID_KEY} wins when both keys are present, so a
* caller migrating off {@link #DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY} can set both during a rollout.
* Uses {@code BadRequestException}, which is what CreateRestApi and CreateApi declare.
*/
public static String extractOverrideApiId(Map<String, String> tags) {
String override = getOverride(tags, OVERRIDE_ID_KEY, ReservedTags::validateOverrideId,
"Resource ID", BAD_REQUEST_EXCEPTION);
if (override != null) {
return override;
}
return getOverride(tags, DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY, ReservedTags::validateOverrideId,
"Resource ID", BAD_REQUEST_EXCEPTION);
}
public static String extractOverrideCognitoClientId(Map<String, String> tags) {
return getOverride(tags, OVERRIDE_COGNITO_CLIENT_ID_KEY, ReservedTags::validateOverrideId, "Cognito Client ID", INVALID_PARAMETER_EXCEPTION);
}
@@ -50,6 +74,36 @@ public final class ReservedTags {
return stripped;
}
/**
* Like {@link #stripReservedTags(Map)} but also drops API Gateway's deprecated custom-id key, so an
* id override never survives into the tags the API returns.
*/
public static Map<String, String> stripApiGatewayReservedTags(Map<String, String> tags) {
Map<String, String> stripped = stripReservedTags(tags);
stripped.remove(DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY);
return stripped;
}
/**
* API Gateway update-path guard. An id override only makes sense at create time, so both the
* reserved keys and the deprecated custom-id key are rejected here, with API Gateway's declared
* error code rather than the {@code ValidationException} the shared guard uses.
*/
public static void rejectApiGatewayReservedTagsOnUpdate(Map<String, String> tags) {
if (tags == null) {
return;
}
for (String key : tags.keySet()) {
if (isReserved(key) || DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY.equals(key)) {
throw new AwsException(
BAD_REQUEST_EXCEPTION,
"Reserved tag key " + key + " can only be supplied during resource creation.",
400
);
}
}
}
public static void rejectReservedTagsOnUpdate(Map<String, String> tags) {
if (tags == null) {
return;
@@ -14,6 +14,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.Account;
@@ -172,15 +173,19 @@ public class ApiGatewayService {
Map<String, String> tags = request.get("tags") instanceof Map<?, ?> m
? (Map<String, String>) m : new HashMap<>();
String customId = tags.get("_custom_id_");
String apiId = (customId != null && !customId.isBlank()) ? customId : shortId(10);
String customId = ReservedTags.extractOverrideApiId(tags);
String apiId = customId != null ? customId : shortId(10);
if (apiStore.get(apiKey(region, apiId)).isPresent()) {
throw new AwsException("ConflictException",
"REST API with id '" + apiId + "' already exists", 409);
}
RestApi api = new RestApi();
api.setId(apiId);
api.setName(name);
api.setDescription(description);
api.setCreatedDate(System.currentTimeMillis() / 1000L);
api.setTags(tags);
api.setTags(ReservedTags.stripApiGatewayReservedTags(tags));
EndpointConfiguration endpointConfiguration = new EndpointConfiguration();
if (request.get(EPC_KEY) instanceof Map<?, ?> epMap) {
@@ -1045,6 +1050,7 @@ public class ApiGatewayService {
}
public void tagResource(String region, String apiId, Map<String, String> tags) {
ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);
RestApi api = getRestApi(region, apiId);
api.getTags().putAll(tags);
apiStore.put(apiKey(region, apiId), api);
@@ -4,6 +4,7 @@ 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.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import com.fasterxml.jackson.core.type.TypeReference;
@@ -81,8 +82,17 @@ public class ApiGatewayV2Service {
routeSelectionExpression = "${request.method} ${request.path}";
}
@SuppressWarnings("unchecked")
Map<String, String> tags = (Map<String, String>) request.get("tags");
String overrideId = ReservedTags.extractOverrideApiId(tags);
String apiId = overrideId != null ? overrideId : shortId(10);
if (apiStore.get(apiKey(region, apiId)).isPresent()) {
throw new AwsException("ConflictException",
"API with id '" + apiId + "' already exists", 409);
}
Api api = new Api();
api.setApiId(shortId(10));
api.setApiId(apiId);
api.setName(name);
api.setProtocolType(protocolType);
api.setCreatedDate(System.currentTimeMillis());
@@ -96,10 +106,8 @@ public class ApiGatewayV2Service {
api.setApiEndpoint(String.format("https://%s.execute-api.%s.amazonaws.com", api.getApiId(), region));
}
@SuppressWarnings("unchecked")
Map<String, String> tags = (Map<String, String>) request.get("tags");
if (tags != null) {
api.setTags(tags);
api.setTags(ReservedTags.stripApiGatewayReservedTags(tags));
}
@SuppressWarnings("unchecked")
@@ -162,6 +170,7 @@ public class ApiGatewayV2Service {
if (request.containsKey("tags")) {
@SuppressWarnings("unchecked")
Map<String, String> tags = (Map<String, String>) request.get("tags");
ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);
api.setTags(tags);
}
if (request.containsKey("corsConfiguration")) {
@@ -884,6 +893,7 @@ public class ApiGatewayV2Service {
}
public void tagResource(String resourceArn, Map<String, String> tags) {
ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);
String[] parsed = parseArn(resourceArn);
String region = parsed[0];
String apiId = parsed[1];
@@ -84,6 +84,116 @@ class ReservedTagsTest {
assertEquals("ValidationException", exception.getErrorCode());
}
// ──────────────────────────── API Gateway override id ────────────────────────────
@Test
void extractOverrideApiIdReturnsNullForNullInput() {
assertNull(ReservedTags.extractOverrideApiId(null));
}
@Test
void extractOverrideApiIdReturnsNullWhenNeitherKeyPresent() {
assertNull(ReservedTags.extractOverrideApiId(Map.of("env", "test")));
}
@Test
void extractOverrideApiIdReadsReservedOverrideKey() {
assertEquals("my-api", ReservedTags.extractOverrideApiId(
Map.of(ReservedTags.OVERRIDE_ID_KEY, "my-api", "env", "test")));
}
@Test
void extractOverrideApiIdFallsBackToDeprecatedCustomIdKey() {
assertEquals("legacy-api", ReservedTags.extractOverrideApiId(
Map.of(ReservedTags.DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY, "legacy-api")));
}
@Test
void extractOverrideApiIdPrefersReservedKeyOverDeprecatedKey() {
assertEquals("winner", ReservedTags.extractOverrideApiId(Map.of(
ReservedTags.OVERRIDE_ID_KEY, "winner",
ReservedTags.DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY, "loser")));
}
@Test
void extractOverrideApiIdRejectsBlankValueWithApiGatewayErrorCode() {
AwsException exception = assertThrows(
AwsException.class,
() -> ReservedTags.extractOverrideApiId(Map.of(ReservedTags.OVERRIDE_ID_KEY, " "))
);
assertEquals("BadRequestException", exception.getErrorCode());
assertEquals(400, exception.getHttpStatus());
}
@Test
void extractOverrideApiIdRejectsUnsupportedCharacters() {
for (String bad : new String[] {"has/slash", "has?query", "has#fragment"}) {
AwsException exception = assertThrows(
AwsException.class,
() -> ReservedTags.extractOverrideApiId(Map.of(ReservedTags.OVERRIDE_ID_KEY, bad)),
"expected rejection for " + bad
);
assertEquals("BadRequestException", exception.getErrorCode());
}
}
@Test
void extractOverrideApiIdValidatesTheDeprecatedKeyToo() {
AwsException exception = assertThrows(
AwsException.class,
() -> ReservedTags.extractOverrideApiId(
Map.of(ReservedTags.DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY, "has/slash"))
);
assertEquals("BadRequestException", exception.getErrorCode());
}
@Test
void stripApiGatewayReservedTagsRemovesBothOverrideKeys() {
Map<String, String> tags = new LinkedHashMap<>();
tags.put("env", "test");
tags.put(ReservedTags.OVERRIDE_ID_KEY, "my-api");
tags.put(ReservedTags.DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY, "legacy-api");
tags.put("team", "platform");
assertEquals(Map.of("env", "test", "team", "platform"),
ReservedTags.stripApiGatewayReservedTags(tags));
}
@Test
void stripReservedTagsLeavesDeprecatedCustomIdForOtherServices() {
// _custom_id_ is API Gateway specific. KMS and Cognito use the shared strip and must keep it.
Map<String, String> tags = Map.of(ReservedTags.DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY, "legacy-api");
assertEquals(tags, ReservedTags.stripReservedTags(tags));
}
@Test
void rejectApiGatewayReservedTagsOnUpdateAllowsNormalTags() {
assertDoesNotThrow(() -> ReservedTags.rejectApiGatewayReservedTagsOnUpdate(Map.of("env", "test")));
assertDoesNotThrow(() -> ReservedTags.rejectApiGatewayReservedTagsOnUpdate(null));
}
@Test
void rejectApiGatewayReservedTagsOnUpdateRejectsBothOverrideKeys() {
for (String key : new String[] {
ReservedTags.OVERRIDE_ID_KEY, ReservedTags.DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY}) {
AwsException exception = assertThrows(
AwsException.class,
() -> ReservedTags.rejectApiGatewayReservedTagsOnUpdate(Map.of(key, "too-late")),
"expected rejection for " + key
);
assertEquals("BadRequestException", exception.getErrorCode());
}
}
@Test
void rejectReservedTagsOnUpdateIgnoresDeprecatedCustomIdForOtherServices() {
assertDoesNotThrow(() -> ReservedTags.rejectReservedTagsOnUpdate(
Map.of(ReservedTags.DEPRECATED_API_GATEWAY_CUSTOM_ID_KEY, "legacy-api")));
}
@Test
void rejectUnknownReservedTagsRejectsReservedTagsWithUserPoolTaggingException() {
AwsException exception = assertThrows(
@@ -373,12 +373,12 @@ class ApiGatewayIntegrationTest {
.statusCode(404);
}
// ──────────────────────────── _custom_id_ tag ────────────────────────────
// ──────────────────────────── _custom_id_ tag (deprecated) ────────────────────────────
@Test @Order(50)
void createRestApi_customIdTag_usesTagValueAsApiId() {
String body = """
{"name":"custom-id-api","tags":{"_custom_id_":"MYCUSTOMNAME"}}
{"name":"custom-id-api","tags":{"_custom_id_":"MYCUSTOMNAME","env":"test"}}
""";
given()
.contentType(ContentType.JSON)
@@ -387,7 +387,9 @@ class ApiGatewayIntegrationTest {
.then()
.statusCode(201)
.body("id", equalTo("MYCUSTOMNAME"))
.body("tags._custom_id_", equalTo("MYCUSTOMNAME"));
// The override key is consumed, not persisted; unrelated tags survive.
.body("tags._custom_id_", nullValue())
.body("tags.env", equalTo("test"));
}
@Test @Order(51)
@@ -400,11 +402,109 @@ class ApiGatewayIntegrationTest {
.body("name", equalTo("custom-id-api"));
}
// ──────────────────────────── floci:override-id tag ────────────────────────────
@Test @Order(52)
void createRestApi_flociOverrideIdTag_usesTagValueAsApiId() {
String body = """
{"name":"override-id-api","tags":{"floci:override-id":"MYOVERRIDEID"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/restapis")
.then()
.statusCode(201)
.body("id", equalTo("MYOVERRIDEID"))
.body("tags._custom_id_", nullValue())
.body("tags.'floci:override-id'", nullValue());
}
@Test @Order(53)
void createRestApi_bothOverrideKeys_prefersFlociOverrideId() {
String body = """
{"name":"both-keys-api","tags":{"floci:override-id":"WINNER","_custom_id_":"LOSER"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/restapis")
.then()
.statusCode(201)
.body("id", equalTo("WINNER"));
}
@Test @Order(54)
void createRestApi_blankOverrideId_isRejected() {
String body = """
{"name":"blank-override-api","tags":{"floci:override-id":" "}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/restapis")
.then()
.statusCode(400)
.body("message", containsString("must not be blank"));
}
@Test @Order(55)
void createRestApi_overrideIdWithPathSeparator_isRejected() {
String body = """
{"name":"bad-override-api","tags":{"floci:override-id":"has/slash"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/restapis")
.then()
.statusCode(400)
.body("message", containsString("unsupported characters"));
}
@Test @Order(56)
void createRestApi_duplicateOverrideId_isRejectedWithConflict() {
String body = """
{"name":"duplicate-override-api","tags":{"floci:override-id":"MYOVERRIDEID"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/restapis")
.then()
.statusCode(409)
.body("message", containsString("already exists"));
// The original API is untouched.
given()
.when().get("/restapis/MYOVERRIDEID")
.then()
.statusCode(200)
.body("name", equalTo("override-id-api"));
}
@Test @Order(57)
void getRestApi_flociOverrideId_resolvesById() {
given()
.when().get("/restapis/MYOVERRIDEID")
.then()
.statusCode(200)
.body("id", equalTo("MYOVERRIDEID"))
.body("name", equalTo("override-id-api"));
}
@Test @Order(58)
void deleteRestApi_customId() {
given()
.when().delete("/restapis/MYCUSTOMNAME")
.then()
.statusCode(202);
given()
.when().delete("/restapis/MYOVERRIDEID")
.then()
.statusCode(202);
given()
.when().delete("/restapis/WINNER")
.then()
.statusCode(202);
}
}
@@ -330,4 +330,104 @@ class ApiGatewayV2IntegrationTest {
.then()
.statusCode(404);
}
// ──────────────────────────── Override IDs ────────────────────────────
@Test @Order(100)
void createApi_deprecatedCustomIdTag_usesTagValueAsApiId() {
given()
.contentType(ContentType.JSON)
.body("""
{"name":"custom-id-api","protocolType":"HTTP","tags":{"_custom_id_":"MYV2CUSTOM","env":"test"}}
""")
.when().post("/v2/apis")
.then()
.statusCode(201)
.body("apiId", equalTo("MYV2CUSTOM"))
.body("tags._custom_id_", nullValue())
.body("tags.env", equalTo("test"));
}
@Test @Order(101)
void createApi_flociOverrideIdTag_usesTagValueAsApiId() {
given()
.contentType(ContentType.JSON)
.body("""
{"name":"override-id-api","protocolType":"HTTP","tags":{"floci:override-id":"MYV2OVERRIDE"}}
""")
.when().post("/v2/apis")
.then()
.statusCode(201)
.body("apiId", equalTo("MYV2OVERRIDE"))
.body("tags.'floci:override-id'", nullValue());
}
@Test @Order(102)
void createApi_blankOverrideId_isRejected() {
given()
.contentType(ContentType.JSON)
.body("""
{"name":"blank-override","protocolType":"HTTP","tags":{"floci:override-id":" "}}
""")
.when().post("/v2/apis")
.then()
.statusCode(400);
}
@Test @Order(103)
void createApi_duplicateOverrideId_isRejectedWithConflict() {
given()
.contentType(ContentType.JSON)
.body("""
{"name":"duplicate-override","protocolType":"HTTP","tags":{"floci:override-id":"MYV2OVERRIDE"}}
""")
.when().post("/v2/apis")
.then()
.statusCode(409)
.body("message", containsString("already exists"));
given()
.when().get("/v2/apis/MYV2OVERRIDE")
.then()
.statusCode(200)
.body("name", equalTo("override-id-api"));
}
@Test @Order(104)
void getApi_overrideId_resolvesById() {
given()
.when().get("/v2/apis/MYV2CUSTOM")
.then()
.statusCode(200)
.body("apiId", equalTo("MYV2CUSTOM"));
}
@Test @Order(105)
void tagApi_withOverrideKey_isRejectedAfterCreation() {
given()
.contentType(ContentType.JSON)
.body("""
{"tags":{"floci:override-id":"TOOLATE"}}
""")
.when().post("/v2/tags/arn:aws:apigateway:us-east-1::/apis/MYV2OVERRIDE")
.then()
.statusCode(400);
}
@Test @Order(106)
void tagApi_withDeprecatedCustomIdKey_isRejectedAfterCreation() {
given()
.contentType(ContentType.JSON)
.body("""
{"tags":{"_custom_id_":"TOOLATE"}}
""")
.when().post("/v2/tags/arn:aws:apigateway:us-east-1::/apis/MYV2OVERRIDE")
.then()
.statusCode(400);
}
@Test @Order(107)
void deleteApis_customAndOverrideId() {
given().when().delete("/v2/apis/MYV2CUSTOM").then().statusCode(204);
given().when().delete("/v2/apis/MYV2OVERRIDE").then().statusCode(204);
}
}