refactor(apigateway): centralize /tags/{arn} routing in SharedTagsController (#330)

* refactor(apigateway): extract ApiGatewayTagHandler

Introduce TagHandler interface under core/common/ and move ARN parsing
plus service delegation from ApiGatewayTagsController into a new
ApiGatewayTagHandler implementation. The controller now only
translates between HTTP/JSON and the handler API. No routing or
behavior changes — groundwork for a shared /tags/{arn} dispatcher.

* refactor(apigateway): centralize /tags/{arn} routing in SharedTagsController

Introduce SharedTagsController at /tags/{arn} which dispatches to the
TagHandler whose serviceKey matches the service segment of the request
ARN (arn:aws:<service>:...). This unblocks future services that share
the same REST tag path (EventBridge Scheduler, EFS, ...) — they only
need to provide a TagHandler bean.

- Delete ApiGatewayTagsController; the SharedTagsController now owns
  all /tags/{arn} routes and delegates to ApiGatewayTagHandler.
- Remove the duplicate getTags method that lived on ApiGatewayController
  as dead code; its path literal conflicted with the new dispatcher.

No behavior change: existing ApiGatewayIntegrationTest still passes
(28/28), and the full suite remains green (1715/1715).

* fix(tags): address review feedback on SharedTagsController

Address Copilot review comments on floci-io/floci#330:

- TagHandler Javadoc: correct the dispatch description. The class-level
  and serviceKey() docs still claimed "Authorization credential scope"
  from an earlier design iteration; the actual dispatch uses the
  service segment of the request ARN. Update both to reflect reality
  so future handlers pick the right serviceKey value.
- SharedTagsController @Consumes: move application/json from the class
  level to the PUT method only. The old ApiGatewayTagsController had
  no class-level @Consumes, so GET/DELETE clients that omit
  Content-Type continued to work; the new class-level annotation would
  surface 415 for those clients. Narrowing restores the prior behavior.
- SharedTagsController constructor: fail fast on duplicate TagHandler
  registrations. The previous map.put would silently overwrite if two
  beans returned the same serviceKey, producing non-deterministic
  routing. Use putIfAbsent + IllegalStateException with both class
  names so boot-time errors point directly at the conflict.

* fix(tags): unify error message for unregistered service
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-04-11 09:49:02 -05:00
1 parent 8149c21c9c
commit d74affa0bc
5 files changed
+211 -109

No files matched your search

@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Dispatcher for AWS services that share the REST {@code /tags/{resourceArn}} path
* (API Gateway, EventBridge Scheduler, EFS, ...).
*
* <p>AWS distinguishes these services by hostname, but floci serves every service on a
* single port, so the path alone is ambiguous. This controller resolves the owning
* service from the {@code service} segment of the request ARN
* ({@code arn:aws:<service>:<region>:<account>:<resource>}) and dispatches to the
* matching {@link TagHandler}.
*/
@Path("/tags")
@Produces(MediaType.APPLICATION_JSON)
public class SharedTagsController {
private final Map<String, TagHandler> handlersByServiceKey;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public SharedTagsController(Instance<TagHandler> handlers,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
Map<String, TagHandler> map = new HashMap<>();
for (TagHandler h : handlers) {
String serviceKey = h.serviceKey();
TagHandler existing = map.putIfAbsent(serviceKey, h);
if (existing != null) {
throw new IllegalStateException(
"Duplicate TagHandler registration for service key '" + serviceKey
+ "': " + existing.getClass().getName()
+ " and " + h.getClass().getName());
}
}
this.handlersByServiceKey = Map.copyOf(map);
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@GET
@Path("/{arn: .*}")
public Response listTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {
TagHandler handler = resolveHandler(arn);
String region = regionResolver.resolveRegion(headers);
Map<String, String> tags = handler.listTags(region, arn);
ObjectNode root = objectMapper.createObjectNode();
ObjectNode tagsNode = root.putObject("tags");
tags.forEach(tagsNode::put);
return Response.ok(root).build();
}
@PUT
@Path("/{arn: .*}")
@Consumes(MediaType.APPLICATION_JSON)
public Response tagResource(@Context HttpHeaders headers,
@PathParam("arn") String arn,
String body) {
TagHandler handler = resolveHandler(arn);
String region = regionResolver.resolveRegion(headers);
try {
JsonNode node = objectMapper.readTree(body);
Map<String, String> tags = new HashMap<>();
node.path("tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
handler.tagResource(region, arn, tags);
return Response.noContent().build();
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/{arn: .*}")
public Response untagResource(@Context HttpHeaders headers,
@PathParam("arn") String arn,
@QueryParam("tagKeys") List<String> tagKeys) {
TagHandler handler = resolveHandler(arn);
String region = regionResolver.resolveRegion(headers);
handler.untagResource(region, arn, tagKeys);
return Response.noContent().build();
}
private TagHandler resolveHandler(String arn) {
// arn:aws:<service>:<region>:<account>:<resource>
String[] parts = arn.split(":", 6);
if (parts.length < 6 || !"arn".equals(parts[0])) {
throw new AwsException("BadRequestException",
"Invalid resource ARN: " + arn, 400);
}
String serviceKey = parts[2];
TagHandler handler = handlersByServiceKey.get(serviceKey);
if (handler == null) {
// Surface an unregistered service as an invalid-ARN error so floci's
// internal routing isn't leaked to the client.
throw new AwsException("BadRequestException",
"Invalid resource ARN: " + arn, 400);
}
return handler;
}
}
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.core.common;
import java.util.List;
import java.util.Map;
/**
* Per-service handler for the REST tag endpoints that share the {@code /tags/{resourceArn}}
* path (API Gateway, EventBridge Scheduler, EFS, etc.).
*
* <p>A single {@code SharedTagsController} routes all {@code /tags/{arn}} requests and
* dispatches to the implementation whose {@link #serviceKey()} matches the {@code service}
* segment of the request ARN ({@code arn:aws:<service>:<region>:<account>:<resource>}).
*
* <p>Implementations are responsible for parsing their own ARN resource format and raising
* {@link io.github.hectorvent.floci.core.common.AwsException} on invalid input.
*/
public interface TagHandler {
/**
* The ARN {@code service} segment this handler responds to (e.g. {@code "apigateway"},
* {@code "scheduler"}, {@code "elasticfilesystem"}). The {@code SharedTagsController}
* dispatcher extracts the third colon-separated component of the request ARN and looks
* up the handler whose {@code serviceKey()} equals that value.
*/
String serviceKey();
Map<String, String> listTags(String region, String arn);
void tagResource(String region, String arn, Map<String, String> tags);
void untagResource(String region, String arn, List<String> tagKeys);
}
@@ -1020,20 +1020,6 @@ public class ApiGatewayController {
return Response.noContent().build();
}
// ──────────────────────────── Tags ────────────────────────────
@GET
@Path("/tags/{arn: .*}")
public Response getTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {
String region = regionResolver.resolveRegion(headers);
String apiId = apiIdFromArn(arn);
Map<String, String> tags = service.getTags(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ObjectNode tagsNode = root.putObject("tags");
tags.forEach(tagsNode::put);
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
// ──────────────────────────── Helpers ────────────────────────────
private ObjectNode toApiNode(RestApi api) {
@@ -1259,9 +1245,4 @@ public class ApiGatewayController {
return node;
}
private String apiIdFromArn(String arn) {
String[] parts = arn.split("/restapis/");
if (parts.length < 2) return arn;
return parts[1].split("/")[0];
}
}
@@ -0,0 +1,55 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.TagHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
/**
* {@link TagHandler} implementation for API Gateway.
*
* <p>ARN format: {@code arn:aws:apigateway:<region>::/restapis/<apiId>}.
* The {@code apiId} is the canonical identifier the underlying {@link ApiGatewayService}
* uses for its tag store.
*/
@ApplicationScoped
public class ApiGatewayTagHandler implements TagHandler {
private final ApiGatewayService service;
@Inject
public ApiGatewayTagHandler(ApiGatewayService service) {
this.service = service;
}
@Override
public String serviceKey() {
return "apigateway";
}
@Override
public Map<String, String> listTags(String region, String arn) {
return service.getTags(region, apiIdFromArn(arn));
}
@Override
public void tagResource(String region, String arn, Map<String, String> tags) {
service.tagResource(region, apiIdFromArn(arn), tags);
}
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
service.untagResource(region, apiIdFromArn(arn), tagKeys);
}
private static String apiIdFromArn(String arn) {
String[] parts = arn.split("/restapis/");
if (parts.length < 2) {
throw new AwsException("BadRequestException", "Invalid resource ARN: " + arn, 400);
}
return parts[1].split("/")[0];
}
}
@@ -1,90 +0,0 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
/**
* AWS API Gateway tag endpoints at /tags/{resourceArn}.
*/
@Path("/tags")
@Produces(MediaType.APPLICATION_JSON)
public class ApiGatewayTagsController {
private final ApiGatewayService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public ApiGatewayTagsController(ApiGatewayService service, RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@GET
@Path("/{arn: .*}")
public Response getTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {
String region = regionResolver.resolveRegion(headers);
String apiId = apiIdFromArn(arn);
Map<String, String> tags = service.getTags(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ObjectNode tagsNode = root.putObject("tags");
tags.forEach(tagsNode::put);
return Response.ok(root).build();
}
@PUT
@Path("/{arn: .*}")
public Response tagResource(@Context HttpHeaders headers,
@PathParam("arn") String arn,
String body) {
String region = regionResolver.resolveRegion(headers);
String apiId = apiIdFromArn(arn);
try {
JsonNode node = objectMapper.readTree(body);
Map<String, String> tags = new java.util.HashMap<>();
node.path("tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
service.tagResource(region, apiId, tags);
return Response.noContent().build();
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/{arn: .*}")
public Response untagResource(@Context HttpHeaders headers,
@PathParam("arn") String arn,
@QueryParam("tagKeys") List<String> tagKeys) {
String region = regionResolver.resolveRegion(headers);
String apiId = apiIdFromArn(arn);
service.untagResource(region, apiId, tagKeys);
return Response.noContent().build();
}
/**
* Extracts apiId from ARN: arn:aws:apigateway:region::/restapis/{apiId}
*/
private String apiIdFromArn(String arn) {
String[] parts = arn.split("/restapis/");
if (parts.length < 2) {
throw new AwsException("BadRequestException", "Invalid resource ARN: " + arn, 400);
}
return parts[1].split("/")[0];
}
}