feat(scheduler): support TagResource, UntagResource, ListTagsForResource (#700)

* feat(scheduler): support TagResource, UntagResource, ListTagsForResource

Implements the three remaining EventBridge Scheduler tag APIs by
extending the shared /tags/{arn} dispatcher. Tags apply to schedule
groups only, matching AWS behavior; ARNs pointing at individual
schedules return ValidationException.

A survey of all ~75 AWS services that share the /tags/{arn} path
shows three independent shape axes — body key (`tags` lower vs
`Tags` capital), body structure (map vs list of {Key, Value}), and
untag query parameter name (`tagKeys` vs `TagKeys`) — and most
"capital Tags" services still use lowercase tagKeys query, so these
axes vary independently. TagHandler exposes them as five orthogonal
default methods rather than a coarse-grained enum:

- tagsBodyKey()           defaults to "tags"
- tagsBodyIsList()        defaults to false (map)
- tagKeysQueryName()      defaults to "tagKeys"
- tagResourceUsesPut()    defaults to false (POST)
- strictTagValidation()   defaults to false (lenient parsing)

The defaults match the most common AWS shape (~73 services use
lowercase tags map + POST + lowercase tagKeys) so handlers like
EKS, Pipes, and AppConfig need no overrides. The dispatcher
returns 405 MethodNotAllowedException for the unused HTTP method
per handler. Strict input validation (missing Tags, wrong-shaped
Tags, missing TagKeys, entries missing Key or Value) is enforced
when strictTagValidation() is true, mirroring the AWS Scheduler
error shape; lenient handlers retain the looser parsing they had
before.

SchedulerTagHandler overrides tagsBodyKey, tagsBodyIsList,
tagKeysQueryName, and strictTagValidation. ApiGatewayTagHandler
overrides tagResourceUsesPut to true. AppConfigIntegrationTest
switches its tagApplication call from PUT to POST to match the
AWS spec for AppConfig (was relying on the dispatcher's prior
leniency on HTTP method).

* fix(tags): normalize empty body and reject non-object payloads

Address Copilot review on floci-io/floci#700.

- doTagResource normalizes null/blank request bodies to "{}" before
  passing to ObjectMapper.readTree, mirroring SchedulerController's
  parseTags. Previously an empty body raised a Jackson parse error
  that strict handlers surfaced as a ValidationException with a raw
  Java/Jackson message instead of the structured AWS error shape.
- parseTags adds a strict-only check that the JSON root is an
  object. A request body like a JSON array or string used to fall
  through to "Value null at 'Tags' ..." which misleads about the
  actual problem; it now reports that the payload itself must be a
  JSON object.

SchedulerIntegrationTest covers both paths with a 400 assertion.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-05-04 17:22:12 -05:00
1 parent 99204e2caf
commit 8e30c09d0a
11 files changed
+615 -23

No files matched your search

@@ -2,6 +2,7 @@ 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.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
@@ -13,11 +14,11 @@ 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 jakarta.ws.rs.core.UriInfo;
import java.util.HashMap;
import java.util.List;
@@ -25,7 +26,7 @@ import java.util.Map;
/**
* Dispatcher for AWS services that share the REST {@code /tags/{resourceArn}} path
* (API Gateway, EventBridge Scheduler, EFS, ...).
* (API Gateway, EventBridge Scheduler, EKS, ...).
*
* <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
@@ -67,10 +68,7 @@ public class SharedTagsController {
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();
return Response.ok(buildListResponse(handler, tags)).build();
}
@POST
@@ -79,41 +77,131 @@ public class SharedTagsController {
public Response tagResourcePost(@Context HttpHeaders headers,
@PathParam("arn") String arn,
String body) {
return tagResource(headers, arn, body);
TagHandler handler = resolveHandler(arn);
if (handler.tagResourceUsesPut()) {
throw new AwsException("MethodNotAllowedException",
"POST is not supported for " + handler.serviceKey() + " tag resources; use PUT.", 405);
}
return doTagResource(headers, handler, arn, body);
}
@PUT
@Path("/{arn: .*}")
@Consumes(MediaType.APPLICATION_JSON)
public Response tagResource(@Context HttpHeaders headers,
@PathParam("arn") String arn,
String body) {
public Response tagResourcePut(@Context HttpHeaders headers,
@PathParam("arn") String arn,
String body) {
TagHandler handler = resolveHandler(arn);
if (!handler.tagResourceUsesPut()) {
throw new AwsException("MethodNotAllowedException",
"PUT is not supported for " + handler.serviceKey() + " tag resources; use POST.", 405);
}
return doTagResource(headers, handler, arn, body);
}
private Response doTagResource(HttpHeaders headers, TagHandler handler, String arn, String body) {
String region = regionResolver.resolveRegion(headers);
String effectiveBody = (body == null || body.isBlank()) ? "{}" : body;
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()));
JsonNode node = objectMapper.readTree(effectiveBody);
Map<String, String> tags = parseTags(handler, node);
handler.tagResource(region, arn, tags);
return Response.noContent().build();
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
String code = handler.strictTagValidation() ? "ValidationException" : "BadRequestException";
throw new AwsException(code, e.getMessage(), 400);
}
}
@DELETE
@Path("/{arn: .*}")
public Response untagResource(@Context HttpHeaders headers,
@PathParam("arn") String arn,
@QueryParam("tagKeys") List<String> tagKeys) {
@Context UriInfo uriInfo,
@PathParam("arn") String arn) {
TagHandler handler = resolveHandler(arn);
String region = regionResolver.resolveRegion(headers);
List<String> tagKeys = readTagKeys(handler, uriInfo);
handler.untagResource(region, arn, tagKeys);
return Response.noContent().build();
}
private ObjectNode buildListResponse(TagHandler handler, Map<String, String> tags) {
ObjectNode root = objectMapper.createObjectNode();
String key = handler.tagsBodyKey();
if (handler.tagsBodyIsList()) {
ArrayNode arr = root.putArray(key);
tags.forEach((k, v) -> {
ObjectNode entry = arr.addObject();
entry.put("Key", k);
entry.put("Value", v);
});
} else {
ObjectNode tagsNode = root.putObject(key);
tags.forEach(tagsNode::put);
}
return root;
}
private Map<String, String> parseTags(TagHandler handler, JsonNode node) {
Map<String, String> tags = new HashMap<>();
String key = handler.tagsBodyKey();
if (handler.strictTagValidation() && !node.isObject()) {
throw new AwsException("ValidationException",
"1 validation error detected: Request payload must be a JSON object", 400);
}
JsonNode tagNode = node.get(key);
if (tagNode == null || tagNode.isNull()) {
if (handler.strictTagValidation()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value null at '" + key + "' failed to satisfy constraint: Member must not be null", 400);
}
return tags;
}
if (handler.tagsBodyIsList()) {
if (!tagNode.isArray()) {
if (handler.strictTagValidation()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at '" + key + "' failed to satisfy constraint: Member must be a list", 400);
}
return tags;
}
for (JsonNode entry : tagNode) {
JsonNode k = entry.get("Key");
JsonNode v = entry.get("Value");
if (k == null || k.isNull() || v == null || v.isNull()) {
if (handler.strictTagValidation()) {
throw new AwsException("ValidationException",
"1 validation error detected: Tag entries at '" + key + "' must have non-null Key and Value", 400);
}
continue;
}
tags.put(k.asText(), v.asText());
}
} else {
if (!tagNode.isObject()) {
if (handler.strictTagValidation()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at '" + key + "' failed to satisfy constraint: Member must be a map", 400);
}
return tags;
}
tagNode.fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
}
return tags;
}
private List<String> readTagKeys(TagHandler handler, UriInfo uriInfo) {
String paramName = handler.tagKeysQueryName();
List<String> values = uriInfo.getQueryParameters().get(paramName);
if (handler.strictTagValidation() && (values == null || values.isEmpty())) {
throw new AwsException("ValidationException",
"1 validation error detected: Value null at '" + paramName + "' failed to satisfy constraint: Member must not be null", 400);
}
return (values == null) ? List.of() : List.copyOf(values);
}
private TagHandler resolveHandler(String arn) {
// arn:aws:<service>:<region>:<account>:<resource>
String[] parts = arn.split(":", 6);
@@ -5,12 +5,29 @@ 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.).
* path (API Gateway, EventBridge Scheduler, EKS, 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>AWS services on this path are not internally consistent in their wire format. Three
* shape choices are independent:
* <ul>
* <li>{@link #tagsBodyKey()} — the JSON key for the tag payload ({@code "tags"} or
* {@code "Tags"}).
* <li>{@link #tagsBodyIsList()} — whether the body holds a list of {@code {Key, Value}}
* objects rather than a string-to-string map.
* <li>{@link #tagKeysQueryName()} — the query parameter name for {@code UntagResource}
* ({@code "tagKeys"} or {@code "TagKeys"}). Surprisingly, most services that use
* capitalized {@code "Tags"} in the body still use lowercase {@code "tagKeys"} here.
* </ul>
* The defaults match the most common AWS shape (lowercase {@code "tags"} map +
* lowercase {@code "tagKeys"} + POST), which covers ~73 services. EKS and Pipes can use
* the defaults unmodified; API Gateway shares the same body shape but must override
* {@link #tagResourceUsesPut()} because AWS defines it with PUT. Handlers whose service
* deviates on any axis override the relevant method(s) only.
*
* <p>Implementations are responsible for parsing their own ARN resource format and raising
* {@link io.github.hectorvent.floci.core.common.AwsException} on invalid input.
*/
@@ -18,12 +35,69 @@ 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.
* {@code "scheduler"}, {@code "eks"}). 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();
/**
* JSON key for the tag payload on {@code TagResource} and {@code ListTagsForResource}.
* Defaults to lowercase {@code "tags"}. Override to {@code "Tags"} for services whose
* AWS spec capitalizes the key. EventBridge Scheduler is the only floci-registered
* handler that overrides today; ~40 other AWS services share the same AWS spec and
* would also need to override if they were added.
*/
default String tagsBodyKey() {
return "tags";
}
/**
* Whether the {@code TagResource} body and {@code ListTagsForResource} response hold a
* list of {@code {Key, Value}} objects rather than a string-to-string map. Defaults to
* {@code false} (map). Override to {@code true} for services that use the list shape
* (EventBridge Scheduler, NetworkManager, Recycle Bin).
*/
default boolean tagsBodyIsList() {
return false;
}
/**
* Whether the dispatcher should reject malformed {@code TagResource} and
* {@code UntagResource} payloads with {@code ValidationException} instead of silently
* coercing them to a no-op. Defaults to {@code false} for back-compat with the looser
* parsing that pre-existing handlers have always relied on. AWS-spec-strict services
* (notably EventBridge Scheduler) override to {@code true}.
*
* <p>This is independent of {@link #tagsBodyIsList()}: a future map-shaped handler
* that needs strict validation can opt in here without flipping the body shape.
*/
default boolean strictTagValidation() {
return false;
}
/**
* Query parameter name for {@code UntagResource}. Defaults to lowercase
* {@code "tagKeys"}, which matches the great majority of AWS services — including
* most that use capitalized {@code "Tags"} in the body. Override to {@code "TagKeys"}
* only for services that capitalize the query parameter as well (EventBridge Scheduler
* is the lone such service in floci today).
*/
default String tagKeysQueryName() {
return "tagKeys";
}
/**
* Whether {@code TagResource} uses {@code PUT /tags/{arn}}. Defaults to {@code false}
* (POST), matching the great majority of AWS services. Override to {@code true} for
* services that AWS defines with PUT (notably API Gateway, plus a handful of others).
* The dispatcher rejects the unused HTTP method with
* {@code 405 MethodNotAllowedException}.
*/
default boolean tagResourceUsesPut() {
return false;
}
Map<String, String> listTags(String region, String arn);
void tagResource(String region, String arn, Map<String, String> tags);
@@ -30,6 +30,11 @@ public class ApiGatewayTagHandler implements TagHandler {
return "apigateway";
}
@Override
public boolean tagResourceUsesPut() {
return true;
}
@Override
public Map<String, String> listTags(String region, String arn) {
return service.getTags(region, apiIdFromArn(arn));
@@ -128,6 +128,31 @@ public class SchedulerService {
LOG.infov("Deleted schedule group: {0} (removed {1} schedules)", name, orphanKeys.size());
}
public Map<String, String> getScheduleGroupTags(String name, String region) {
ScheduleGroup group = getScheduleGroup(name, region);
return Map.copyOf(group.getTags());
}
public void tagScheduleGroup(String name, String region, Map<String, String> tags) {
if (tags == null || tags.isEmpty()) {
return;
}
ScheduleGroup group = getScheduleGroup(name, region);
group.getTags().putAll(tags);
group.setLastModificationDate(Instant.now());
groupStore.put(groupKey(region, group.getName()), group);
}
public void untagScheduleGroup(String name, String region, List<String> tagKeys) {
if (tagKeys == null || tagKeys.isEmpty()) {
return;
}
ScheduleGroup group = getScheduleGroup(name, region);
tagKeys.forEach(group.getTags()::remove);
group.setLastModificationDate(Instant.now());
groupStore.put(groupKey(region, group.getName()), group);
}
public List<ScheduleGroup> listScheduleGroups(String namePrefix, String region) {
getOrCreateDefaultGroup(region);
String storagePrefix = "group:" + region + ":";
@@ -0,0 +1,86 @@
package io.github.hectorvent.floci.services.scheduler;
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 EventBridge Scheduler.
*
* <p>ARN format: {@code arn:aws:scheduler:<region>:<account>:schedule-group/<name>}.
* AWS only permits tags on schedule groups; ARNs pointing at individual schedules
* ({@code schedule/<group>/<name>}) are rejected with {@code ValidationException} to
* mirror AWS behavior.
*/
@ApplicationScoped
public class SchedulerTagHandler implements TagHandler {
private final SchedulerService service;
@Inject
public SchedulerTagHandler(SchedulerService service) {
this.service = service;
}
@Override
public String serviceKey() {
return "scheduler";
}
@Override
public String tagsBodyKey() {
return "Tags";
}
@Override
public boolean tagsBodyIsList() {
return true;
}
@Override
public String tagKeysQueryName() {
return "TagKeys";
}
@Override
public boolean strictTagValidation() {
return true;
}
@Override
public Map<String, String> listTags(String region, String arn) {
return service.getScheduleGroupTags(groupNameFromArn(arn), region);
}
@Override
public void tagResource(String region, String arn, Map<String, String> tags) {
service.tagScheduleGroup(groupNameFromArn(arn), region, tags);
}
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
service.untagScheduleGroup(groupNameFromArn(arn), region, tagKeys);
}
private static String groupNameFromArn(String arn) {
String[] parts = arn.split(":", 6);
if (parts.length < 6) {
throw new AwsException("ValidationException", "Invalid resource ARN: " + arn, 400);
}
String resource = parts[5];
String prefix = "schedule-group/";
if (!resource.startsWith(prefix)) {
throw new AwsException("ValidationException",
"Tags are only supported on schedule groups: " + arn, 400);
}
String name = resource.substring(prefix.length());
if (name.isBlank() || name.contains("/")) {
throw new AwsException("ValidationException", "Invalid resource ARN: " + arn, 400);
}
return name;
}
}