feat(iot): manage custom authorizers (#4826)

* test(iot): cover custom authorizer management against AWS

* feat(iot): manage custom authorizers

Serve CreateAuthorizer, DescribeAuthorizer, UpdateAuthorizer,
DeleteAuthorizer, ListAuthorizers, SetDefaultAuthorizer,
DescribeDefaultAuthorizer and ClearDefaultAuthorizer on the AWS REST-JSON
paths, with the validation, messages, defaults, key merge, delete rules,
ordering and paging measured against AWS. Authorizer ARNs are tagged
through the existing IoT tag routes. Authorizers are stored, not evaluated.

Closes #4821

* fix(iot): read authorizer public key PEM line by line like AWS

A key without its PEM header line, or with an indented or inline header, is not a valid RSA key, a header without its end line cannot convert, and text before the header is skipped, as measured on AWS.

* fix(iot): validate authorizer names like AWS, SetDefaultAuthorizer included

A name member reports every violated constraint in one message, the pattern first, and a missing one must not be null. SetDefaultAuthorizer validates authorizerName before the lookup, as measured on AWS.

* fix(iot): validate the authorizer name on describe, update and delete like AWS

DescribeAuthorizer, UpdateAuthorizer and DeleteAuthorizer now reject a malformed or overlong authorizerName path member with AWS's 400 InvalidRequestException messages instead of a 404, measured on eu-west-1.

* fix(iot): route tag calls to the authorizer service on the ARN resource

IotTagHandler matched ":authorizer/" anywhere in the ARN, so an ARN with that text outside the resource field reached the authorizer service and failed with a 500. It now routes on the parsed resource prefix, and any other IoT ARN goes through IotService as before.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-04 17:20:12 -04:00
1 parent 2749cd6fcd
commit fabcd6baf8
11 files changed
+2055 -7

No files matched your search

@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController;
import io.github.hectorvent.floci.services.eks.EksController;
import io.github.hectorvent.floci.services.fis.FisController;
import io.github.hectorvent.floci.services.mwaa.MwaaController;
import io.github.hectorvent.floci.services.iot.IotAuthorizerController;
import io.github.hectorvent.floci.services.iot.IotController;
import io.github.hectorvent.floci.services.iot.IotDomainConfigurationController;
import io.github.hectorvent.floci.services.iot.IotDataController;
@@ -646,7 +647,8 @@ public class ResolvedServiceCatalog {
// DescribeJobExecution, StartNextPendingJobExecution, UpdateJobExecution)
// signs under its own name while IotController serves its /things/*/jobs routes
Set.of(), Set.of("iot", "execute-api", "iot-jobs-data"), Set.of(),
Set.of(IotController.class, IotDomainConfigurationController.class)),
Set.of(IotController.class, IotDomainConfigurationController.class,
IotAuthorizerController.class)),
descriptor("iotdata", "iotdata", config.services().iotdata().enabled(), true,
"iot", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.core.JsonProcessingException;
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 io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iot.model.IotAuthorizer;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
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;
/**
* REST-JSON routes for AWS IoT custom authorizers: CreateAuthorizer, DescribeAuthorizer,
* UpdateAuthorizer, DeleteAuthorizer, ListAuthorizers, SetDefaultAuthorizer,
* DescribeDefaultAuthorizer and ClearDefaultAuthorizer, on the paths and shapes the AWS SDKs use.
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class IotAuthorizerController {
private final IotAuthorizerService authorizerService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public IotAuthorizerController(IotAuthorizerService authorizerService, RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.authorizerService = authorizerService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@POST
@Path("/authorizer/{authorizerName}")
public Response createAuthorizer(@Context HttpHeaders headers, @PathParam("authorizerName") String authorizerName,
String body) {
return Response.ok(nameAndArn(authorizerService.createAuthorizer(
authorizerName, readJson(body), regionResolver.resolveRegion(headers)))).build();
}
@GET
@Path("/authorizer/{authorizerName}")
public Response describeAuthorizer(@Context HttpHeaders headers, @PathParam("authorizerName") String authorizerName) {
return described(authorizerService.describeAuthorizer(authorizerName, regionResolver.resolveRegion(headers)));
}
@PUT
@Path("/authorizer/{authorizerName}")
public Response updateAuthorizer(@Context HttpHeaders headers, @PathParam("authorizerName") String authorizerName,
String body) {
return Response.ok(nameAndArn(authorizerService.updateAuthorizer(
authorizerName, readJson(body), regionResolver.resolveRegion(headers)))).build();
}
@DELETE
@Path("/authorizer/{authorizerName}")
@Consumes(MediaType.WILDCARD)
public Response deleteAuthorizer(@Context HttpHeaders headers, @PathParam("authorizerName") String authorizerName) {
authorizerService.deleteAuthorizer(authorizerName, regionResolver.resolveRegion(headers));
return Response.ok(objectMapper.createObjectNode()).build();
}
@GET
@Path("/authorizers")
public Response listAuthorizers(@Context HttpHeaders headers,
@QueryParam("pageSize") Integer pageSize,
@QueryParam("marker") String marker,
@QueryParam("isAscendingOrder") boolean ascending,
@QueryParam("status") String status) {
IotService.Page<IotAuthorizer> page = authorizerService.listAuthorizers(
regionResolver.resolveRegion(headers), status, ascending, marker, pageSize);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode authorizers = response.putArray("authorizers");
page.items().forEach(authorizer -> authorizers.add(nameAndArn(authorizer)));
response.put("nextMarker", page.nextToken());
return Response.ok(response).build();
}
@POST
@Path("/default-authorizer")
public Response setDefaultAuthorizer(@Context HttpHeaders headers, String body) {
return Response.ok(nameAndArn(authorizerService.setDefaultAuthorizer(
readJson(body).path("authorizerName").asText(null), regionResolver.resolveRegion(headers)))).build();
}
@GET
@Path("/default-authorizer")
public Response describeDefaultAuthorizer(@Context HttpHeaders headers) {
return described(authorizerService.describeDefaultAuthorizer(regionResolver.resolveRegion(headers)));
}
@DELETE
@Path("/default-authorizer")
@Consumes(MediaType.WILDCARD)
public Response clearDefaultAuthorizer(@Context HttpHeaders headers) {
authorizerService.clearDefaultAuthorizer(regionResolver.resolveRegion(headers));
return Response.ok(objectMapper.createObjectNode()).build();
}
private ObjectNode nameAndArn(IotAuthorizer authorizer) {
ObjectNode response = objectMapper.createObjectNode();
response.put("authorizerName", authorizer.getAuthorizerName());
response.put("authorizerArn", authorizer.getAuthorizerArn());
return response;
}
/** Every member, as AWS sends them: an unset token key name and key map are JSON null, tags never appear. */
private Response described(IotAuthorizer authorizer) {
ObjectNode response = objectMapper.createObjectNode();
ObjectNode description = response.putObject("authorizerDescription");
description.put("authorizerArn", authorizer.getAuthorizerArn());
description.put("authorizerFunctionArn", authorizer.getAuthorizerFunctionArn());
description.put("authorizerName", authorizer.getAuthorizerName());
description.put("creationDate", authorizer.getCreationDate().toEpochMilli() / 1000.0);
description.put("enableCachingForHttp", authorizer.isEnableCachingForHttp());
description.put("lastModifiedDate", authorizer.getLastModifiedDate().toEpochMilli() / 1000.0);
description.put("signingDisabled", authorizer.isSigningDisabled());
description.put("status", authorizer.getStatus());
description.put("tokenKeyName", authorizer.getTokenKeyName());
description.set("tokenSigningPublicKeys", objectMapper.valueToTree(authorizer.getTokenSigningPublicKeys()));
return Response.ok(response).build();
}
private JsonNode readJson(String body) {
try {
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
} catch (JsonProcessingException e) {
throw new AwsException("InvalidRequestException", e.getMessage(), 400);
}
}
}
@@ -0,0 +1,405 @@
package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
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.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iot.model.IotAuthorizer;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* AWS IoT Core custom authorizers: the records CreateAuthorizer and its peers manage, and the
* account's default authorizer. The function ARN is checked for ARN syntax only, as on AWS; nothing
* here invokes the function or gates a connection.
*/
@ApplicationScoped
public class IotAuthorizerService {
private static final Pattern NAME_PATTERN = Pattern.compile("[\\w=,@-]+");
private static final Pattern TOKEN_KEY_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9_-]+");
private static final Pattern KEY_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
private static final Set<String> STATUSES = Set.of("ACTIVE", "INACTIVE");
private final StorageBackend<String, IotAuthorizer> store;
private final RegionResolver regionResolver;
/** Guards every read-modify-write on the store, the default-authorizer flag included. */
private final Object lock = new Object();
@Inject
public IotAuthorizerService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory.create("iot", "iot-authorizers.json", new TypeReference<Map<String, IotAuthorizer>>() {}),
regionResolver);
}
IotAuthorizerService(StorageBackend<String, IotAuthorizer> store, RegionResolver regionResolver) {
this.store = store;
this.regionResolver = regionResolver;
}
public IotAuthorizer createAuthorizer(String name, JsonNode body, String region) {
requireNameLike("authorizerName", name, NAME_PATTERN);
String functionArn = body.path("authorizerFunctionArn").asText(null);
if (functionArn == null) {
throw constraint("authorizerFunctionArn", "Member must not be null");
}
String status = status(body.path("status").asText(null));
String tokenKeyName = tokenKeyName(body);
Map<String, String> keys = keys(body);
requireFunctionArn(name, functionArn);
boolean signingDisabled = body.path("signingDisabled").asBoolean(false);
if (signingDisabled && keys != null) {
throw keysMustBeNull(name);
}
if (!signingDisabled) {
if (tokenKeyName == null) {
throw invalid("Token key name for authorizer " + name + " cannot be null");
}
if (keys == null || keys.isEmpty()) {
throw invalid("Token signing keys map for authorizer " + name + " cannot be null or empty. "
+ "There must be at least one and at most two token signing public keys in the map");
}
requireKeys(name, keys);
}
IotAuthorizer authorizer = new IotAuthorizer();
authorizer.setAuthorizerName(name);
authorizer.setAuthorizerArn(regionResolver.buildArn("iot", region, "authorizer/" + name));
authorizer.setAuthorizerFunctionArn(functionArn);
authorizer.setTokenKeyName(tokenKeyName);
authorizer.setTokenSigningPublicKeys(keys);
authorizer.setStatus(status == null ? "INACTIVE" : status);
authorizer.setSigningDisabled(signingDisabled);
authorizer.setEnableCachingForHttp(body.path("enableCachingForHttp").asBoolean(false));
Instant now = Instant.now();
authorizer.setCreationDate(now);
authorizer.setLastModifiedDate(now);
authorizer.setTags(IotDomainConfigurationService.parseTags(body.path("tags")));
synchronized (lock) {
if (store.get(key(region, name)).isPresent()) {
throw alreadyExists("Authorizer " + name + " already exist for this account", authorizer);
}
store.put(key(region, name), authorizer);
}
return authorizer;
}
public IotAuthorizer describeAuthorizer(String name, String region) {
requireNameLike("authorizerName", name, NAME_PATTERN);
return store.get(key(region, name))
.orElseThrow(() -> notFound("Authorizer " + name + " not found"));
}
/** A partial update: absent members stay, signing keys merge per key name. */
public IotAuthorizer updateAuthorizer(String name, JsonNode body, String region) {
requireNameLike("authorizerName", name, NAME_PATTERN);
String functionArn = body.path("authorizerFunctionArn").asText(null);
String status = status(body.path("status").asText(null));
String tokenKeyName = tokenKeyName(body);
Map<String, String> keys = keys(body);
JsonNode caching = body.path("enableCachingForHttp");
if (functionArn != null) {
requireFunctionArn(name, functionArn);
}
synchronized (lock) {
IotAuthorizer authorizer = describeAuthorizer(name, region);
if (keys != null) {
if (authorizer.isSigningDisabled()) {
throw keysMustBeNull(name);
}
requireKeys(name, keys);
Map<String, String> merged = new LinkedHashMap<>(authorizer.getTokenSigningPublicKeys());
merged.putAll(keys);
if (merged.size() > 2) {
throw invalid("Number of signing keys for authorizer " + name + " must neither be zero nor greater than 2");
}
authorizer.setTokenSigningPublicKeys(merged);
}
if (functionArn != null) {
authorizer.setAuthorizerFunctionArn(functionArn);
}
if (status != null) {
authorizer.setStatus(status);
}
if (tokenKeyName != null) {
authorizer.setTokenKeyName(tokenKeyName);
}
if (caching.isBoolean()) {
authorizer.setEnableCachingForHttp(caching.booleanValue());
}
// ponytail: AWS bumps on any member sent; whether an unchanged value bumps it is unmeasured.
if (functionArn != null || status != null || tokenKeyName != null || keys != null || caching.isBoolean()) {
authorizer.setLastModifiedDate(Instant.now());
}
store.put(key(region, name), authorizer);
return authorizer;
}
}
public void deleteAuthorizer(String name, String region) {
synchronized (lock) {
IotAuthorizer authorizer = describeAuthorizer(name, region);
// ponytail: which check wins for an ACTIVE default authorizer is unmeasured; ACTIVE goes first.
if ("ACTIVE".equals(authorizer.getStatus())) {
throw invalid("Cannot delete authorizer " + name + " in ACTIVE status. Update status to INACTIVE and delete.");
}
if (authorizer.isDefaultAuthorizer()) {
throw new AwsException("DeleteConflictException",
"Cannot delete default authorizer " + name + ". Change default and retry delete.", 409);
}
store.delete(key(region, name));
}
}
/** Newest first unless ascending; the marker is the offset of the next item. */
public IotService.Page<IotAuthorizer> listAuthorizers(String region, String status, boolean ascending,
String marker, Integer pageSize) {
if (pageSize != null && pageSize < 1) {
throw constraint("pageSize", "Member must have value greater than or equal to 1");
}
if (pageSize != null && pageSize > 250) {
throw constraint("pageSize", "Member must have value less than or equal to 250");
}
status(status);
Comparator<IotAuthorizer> byCreation = Comparator.comparing(IotAuthorizer::getCreationDate)
.thenComparing(IotAuthorizer::getAuthorizerName);
List<IotAuthorizer> items = authorizers(region).stream()
.filter(authorizer -> status == null || status.equals(authorizer.getStatus()))
.sorted(ascending ? byCreation : byCreation.reversed())
.toList();
// ponytail: an offset, not AWS's encrypted token; SDKs pass it back opaquely either way.
int start;
try {
start = marker == null || marker.isEmpty() ? 0 : Math.min(items.size(), Math.max(0, Integer.parseInt(marker)));
} catch (NumberFormatException e) {
throw invalid("Invalid/Malformed marker passed for listAuthorizers");
}
int end = pageSize == null ? items.size() : Math.min(items.size(), start + pageSize);
return new IotService.Page<>(items.subList(start, end), end < items.size() ? Integer.toString(end) : null);
}
public IotAuthorizer setDefaultAuthorizer(String name, String region) {
synchronized (lock) {
IotAuthorizer authorizer = describeAuthorizer(name, region);
if (authorizer.isDefaultAuthorizer()) {
throw alreadyExists("Duplicate default authorizer " + name + " already configured for this account", authorizer);
}
defaultAuthorizer(region).ifPresent(previous -> saveDefault(previous, false, region));
saveDefault(authorizer, true, region);
return authorizer;
}
}
public IotAuthorizer describeDefaultAuthorizer(String region) {
synchronized (lock) {
return defaultAuthorizer(region).orElseThrow(() -> notFound("Default authorizer not found"));
}
}
public void clearDefaultAuthorizer(String region) {
synchronized (lock) {
saveDefault(describeDefaultAuthorizer(region), false, region);
}
}
/** A missing authorizer, or one in another account or partition, has no tags to list, as on AWS; tagging it is a 404. */
public Map<String, String> listTagsForResource(String resourceArn) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
return store.get(key(arn.region(), nameFromArn(arn)))
.filter(authorizer -> resourceArn.equals(authorizer.getAuthorizerArn()))
.map(IotAuthorizer::getTags).orElse(Map.of());
}
public void tagResource(String resourceArn, Map<String, String> tags) {
updateTags(resourceArn, current -> current.putAll(tags));
}
public void untagResource(String resourceArn, List<String> tagKeys) {
updateTags(resourceArn, current -> tagKeys.forEach(current::remove));
}
private void updateTags(String resourceArn, Consumer<Map<String, String>> change) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
String name = nameFromArn(arn);
synchronized (lock) {
IotAuthorizer authorizer = store.get(key(arn.region(), name))
.filter(stored -> resourceArn.equals(stored.getAuthorizerArn()))
.orElseThrow(() -> notFound("Authorizer " + name + " not found"));
Map<String, String> tags = new TreeMap<>(authorizer.getTags());
change.accept(tags);
authorizer.setTags(tags);
store.put(key(arn.region(), name), authorizer);
}
}
private Optional<IotAuthorizer> defaultAuthorizer(String region) {
return authorizers(region).stream().filter(IotAuthorizer::isDefaultAuthorizer).findFirst();
}
private void saveDefault(IotAuthorizer authorizer, boolean isDefault, String region) {
authorizer.setDefaultAuthorizer(isDefault);
store.put(key(region, authorizer.getAuthorizerName()), authorizer);
}
private List<IotAuthorizer> authorizers(String region) {
String prefix = key(region, "");
return store.scan(storeKey -> storeKey.startsWith(prefix));
}
private static String nameFromArn(AwsArnUtils.Arn arn) {
return arn.resource().substring("authorizer/".length());
}
private static String status(String status) {
if (status != null && !STATUSES.contains(status)) {
throw constraint("status", "Member must satisfy enum value set: [ACTIVE, INACTIVE]");
}
return status;
}
private static String tokenKeyName(JsonNode body) {
String tokenKeyName = body.path("tokenKeyName").asText(null);
if (tokenKeyName != null) {
requireNameLike("tokenKeyName", tokenKeyName, TOKEN_KEY_NAME_PATTERN);
}
return tokenKeyName;
}
/** The request's key map in request order, or null when absent. */
private static Map<String, String> keys(JsonNode body) {
JsonNode node = body.path("tokenSigningPublicKeys");
if (!node.isObject()) {
return null;
}
Map<String, String> keys = new LinkedHashMap<>();
for (Map.Entry<String, JsonNode> entry : node.properties()) {
if (!KEY_NAME_PATTERN.matcher(entry.getKey()).matches()) {
throw constraint("tokenSigningPublicKeys", "Map keys must satisfy constraint: [Member must have length "
+ "less than or equal to 128, Member must have length greater than or equal to 1, "
+ "Member must satisfy regular expression pattern: [a-zA-Z0-9:_-]+]");
}
keys.put(entry.getKey(), entry.getValue().asText(null));
}
return keys;
}
private static void requireKeys(String name, Map<String, String> keys) {
if (keys.size() > 2) {
throw invalid("Token signing keys map for authorizer " + name + " cannot contain more than 2 keys");
}
keys.forEach((keyName, pem) -> requireRsa2048(name, keyName, pem));
}
private static void requireRsa2048(String name, String keyName, String pem) {
if (pem == null || pem.isEmpty()) {
throw invalid("Token signing public keys for authorizer " + name + " cannot be null or empty");
}
// ponytail: a line scan stands in for AWS's PEM object parser: text before the header is skipped,
// no header line is not a key, a header without its end line cannot convert, and a private key
// header is told apart first.
if (pem.contains("PRIVATE KEY")) {
throw invalid("Cannot convert public key PEM for authorizer " + name + " to RSA key");
}
List<String> lines = pem.lines().toList();
int begin = lines.indexOf("-----BEGIN PUBLIC KEY-----");
if (begin < 0) {
throw invalid("Authorizer " + name + " public key for key name " + keyName + " not a valid RSA key");
}
List<String> rest = lines.subList(begin + 1, lines.size());
int end = rest.indexOf("-----END PUBLIC KEY-----");
if (end < 0) {
throw invalid("Cannot convert public key PEM for authorizer " + name + " to RSA key");
}
RSAPublicKey key;
try {
byte[] der = Base64.getDecoder().decode(String.join("", rest.subList(0, end)));
key = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(der));
} catch (GeneralSecurityException | IllegalArgumentException e) {
throw invalid("Authorizer " + name + " public key for key name " + keyName + " not a valid RSA key");
}
int bits = key.getModulus().bitLength();
if (bits != 2048) {
throw invalid("Authorizer " + name + " public key for key name " + keyName
+ " invalid: Key must be 2048 bits but was " + bits + " bits");
}
}
private static void requireFunctionArn(String name, String functionArn) {
if (AwsArnUtils.resourceIfArnFor(functionArn, "lambda").filter(r -> r.startsWith("function:")).isEmpty()) {
throw invalid("Lambda function arn for authorizer " + name + " is not in proper ARN syntax");
}
}
/** AWS reports every violated constraint of the member, the pattern first, as the measured messages show. */
private static void requireNameLike(String field, String value, Pattern pattern) {
if (value == null) {
throw constraint(field, "Member must not be null");
}
List<String> violations = new ArrayList<>();
if (!pattern.matcher(value).matches()) {
violations.add("Member must satisfy regular expression pattern: " + pattern.pattern());
}
if (value.isEmpty()) {
violations.add("Member must have length greater than or equal to 1");
}
if (value.length() > 128) {
violations.add("Member must have length less than or equal to 128");
}
if (!violations.isEmpty()) {
throw constraints(field, violations);
}
}
private static AwsException keysMustBeNull(String name) {
return invalid("Token signing keys map must be null for authorizer " + name + " if using optional signature header");
}
private static AwsException alreadyExists(String message, IotAuthorizer authorizer) {
return new AwsException("ResourceAlreadyExistsException", message, 409,
Map.of("resourceId", authorizer.getAuthorizerName(), "resourceArn", authorizer.getAuthorizerArn()));
}
private static AwsException constraint(String field, String constraint) {
return constraints(field, List.of(constraint));
}
private static AwsException constraints(String field, List<String> constraints) {
return invalid(constraints.size() + " validation error" + (constraints.size() == 1 ? "" : "s") + " detected: "
+ constraints.stream()
.map(constraint -> "Value at '" + field + "' failed to satisfy constraint: " + constraint)
.collect(Collectors.joining("; ")));
}
private static AwsException invalid(String message) {
return new AwsException("InvalidRequestException", message, 400);
}
private static AwsException notFound(String message) {
return new AwsException("ResourceNotFoundException", message, 404);
}
private static String key(String region, String name) {
return "authorizer:" + region + ":" + name;
}
}
@@ -352,7 +352,7 @@ public class IotDomainConfigurationService {
return new ClientCertificateConfig(text(node, "clientCertificateCallbackArn"));
}
private static Map<String, String> parseTags(JsonNode node) {
static Map<String, String> parseTags(JsonNode node) {
Map<String, String> tags = new TreeMap<>();
if (!present(node)) {
return tags;
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iot;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.TagHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -12,11 +13,14 @@ public class IotTagHandler implements TagHandler {
private final IotService iotService;
private final IotDomainConfigurationService domainConfigurationService;
private final IotAuthorizerService authorizerService;
@Inject
public IotTagHandler(IotService iotService, IotDomainConfigurationService domainConfigurationService) {
public IotTagHandler(IotService iotService, IotDomainConfigurationService domainConfigurationService,
IotAuthorizerService authorizerService) {
this.iotService = iotService;
this.domainConfigurationService = domainConfigurationService;
this.authorizerService = authorizerService;
}
@Override
@@ -31,6 +35,9 @@ public class IotTagHandler implements TagHandler {
@Override
public Map<String, String> listTags(String region, String arn) {
if (isAuthorizer(arn)) {
return authorizerService.listTagsForResource(arn);
}
return isDomainConfiguration(arn)
? domainConfigurationService.listTagsForResource(arn)
: iotService.listTagsForResource(arn);
@@ -38,7 +45,9 @@ public class IotTagHandler implements TagHandler {
@Override
public void tagResource(String region, String arn, Map<String, String> tags) {
if (isDomainConfiguration(arn)) {
if (isAuthorizer(arn)) {
authorizerService.tagResource(arn, tags);
} else if (isDomainConfiguration(arn)) {
domainConfigurationService.tagResource(arn, tags);
} else {
iotService.tagResource(arn, tags);
@@ -47,15 +56,21 @@ public class IotTagHandler implements TagHandler {
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
if (isDomainConfiguration(arn)) {
if (isAuthorizer(arn)) {
authorizerService.untagResource(arn, tagKeys);
} else if (isDomainConfiguration(arn)) {
domainConfigurationService.untagResource(arn, tagKeys);
} else {
iotService.untagResource(arn, tagKeys);
}
}
/** Domain configurations have their own service; every other IoT resource is tagged through IotService. */
/** Domain configurations and authorizers have their own services; every other IoT resource is tagged through IotService. */
private static boolean isDomainConfiguration(String arn) {
return arn != null && arn.contains(":domainconfiguration/");
}
private static boolean isAuthorizer(String arn) {
return AwsArnUtils.isArn(arn) && AwsArnUtils.parse(arn).resource().startsWith("authorizer/");
}
}
@@ -0,0 +1,49 @@
package io.github.hectorvent.floci.services.iot.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
import java.util.TreeMap;
/** A custom authorizer as AWS IoT Core reports it through DescribeAuthorizer, plus its tags and default flag. */
@RegisterForReflection
public class IotAuthorizer {
private String authorizerName;
private String authorizerArn;
private String authorizerFunctionArn;
private String tokenKeyName;
private Map<String, String> tokenSigningPublicKeys;
private String status;
private boolean signingDisabled;
private boolean enableCachingForHttp;
private Instant creationDate;
private Instant lastModifiedDate;
private boolean defaultAuthorizer;
private Map<String, String> tags = new TreeMap<>();
public String getAuthorizerName() { return authorizerName; }
public void setAuthorizerName(String authorizerName) { this.authorizerName = authorizerName; }
public String getAuthorizerArn() { return authorizerArn; }
public void setAuthorizerArn(String authorizerArn) { this.authorizerArn = authorizerArn; }
public String getAuthorizerFunctionArn() { return authorizerFunctionArn; }
public void setAuthorizerFunctionArn(String authorizerFunctionArn) { this.authorizerFunctionArn = authorizerFunctionArn; }
public String getTokenKeyName() { return tokenKeyName; }
public void setTokenKeyName(String tokenKeyName) { this.tokenKeyName = tokenKeyName; }
public Map<String, String> getTokenSigningPublicKeys() { return tokenSigningPublicKeys; }
public void setTokenSigningPublicKeys(Map<String, String> tokenSigningPublicKeys) { this.tokenSigningPublicKeys = tokenSigningPublicKeys; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public boolean isSigningDisabled() { return signingDisabled; }
public void setSigningDisabled(boolean signingDisabled) { this.signingDisabled = signingDisabled; }
public boolean isEnableCachingForHttp() { return enableCachingForHttp; }
public void setEnableCachingForHttp(boolean enableCachingForHttp) { this.enableCachingForHttp = enableCachingForHttp; }
public Instant getCreationDate() { return creationDate; }
public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; }
public Instant getLastModifiedDate() { return lastModifiedDate; }
public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }
public boolean isDefaultAuthorizer() { return defaultAuthorizer; }
public void setDefaultAuthorizer(boolean defaultAuthorizer) { this.defaultAuthorizer = defaultAuthorizer; }
public Map<String, String> getTags() { return tags == null ? Map.of() : tags; }
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new TreeMap<>() : new TreeMap<>(tags); }
}