Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Mario Toffiafabcd6baf8c5
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotAuthorizerTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotAuthorizerTest.java
new file mode 100644
index 0000000000..1f1b5eba09
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotAuthorizerTest.java
@@ -0,0 +1,628 @@
+package com.floci.test;
+
+import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.regions.PartitionMetadata;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.iot.IotClient;
+import software.amazon.awssdk.services.iot.model.AuthorizerDescription;
+import software.amazon.awssdk.services.iot.model.AuthorizerStatus;
+import software.amazon.awssdk.services.iot.model.AuthorizerSummary;
+import software.amazon.awssdk.services.iot.model.CreateAuthorizerRequest;
+import software.amazon.awssdk.services.iot.model.CreateAuthorizerResponse;
+import software.amazon.awssdk.services.iot.model.DeleteConflictException;
+import software.amazon.awssdk.services.iot.model.InvalidRequestException;
+import software.amazon.awssdk.services.iot.model.IotException;
+import software.amazon.awssdk.services.iot.model.ListAuthorizersRequest;
+import software.amazon.awssdk.services.iot.model.ListAuthorizersResponse;
+import software.amazon.awssdk.services.iot.model.ResourceAlreadyExistsException;
+import software.amazon.awssdk.services.iot.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.iot.model.SetDefaultAuthorizerResponse;
+import software.amazon.awssdk.services.iot.model.Tag;
+import software.amazon.awssdk.services.iot.model.UpdateAuthorizerResponse;
+import software.amazon.awssdk.services.sts.StsClient;
+
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.KeyPairGenerator;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowableOfType;
+import static org.assertj.core.api.Assumptions.assumeThat;
+
+@DisplayName("IoT custom authorizer management")
+class IotAuthorizerTest {
+
+ private static IotClient iot;
+ private static String partition;
+ private static String region;
+ private static String account;
+ private static String rsaKey1;
+ private static String rsaKey2;
+ private static String rsa1024Key;
+ private static String ecKey;
+
+ private String prefix;
+ private final List<String> created = new ArrayList<>();
+
+ @BeforeAll
+ static void setUpClients() throws GeneralSecurityException {
+ iot = TestFixtures.iotClient();
+ Region clientRegion = iot.serviceClientConfiguration().region();
+ region = clientRegion.id();
+ partition = PartitionMetadata.of(clientRegion).id();
+ try (StsClient sts = TestFixtures.stsClient()) {
+ account = sts.getCallerIdentity().account();
+ }
+ rsaKey1 = publicKeyPem("RSA", 2048);
+ rsaKey2 = publicKeyPem("RSA", 2048);
+ rsa1024Key = publicKeyPem("RSA", 1024);
+ ecKey = publicKeyPem("EC", 256);
+ }
+
+ @AfterAll
+ static void closeClients() {
+ iot.close();
+ }
+
+ @BeforeEach
+ void setUpPrefix() {
+ prefix = "compat-auth-" + UUID.randomUUID().toString().substring(0, 8);
+ }
+
+ @AfterEach
+ void cleanUp() {
+ RuntimeException failure = null;
+ try {
+ String current = iot.describeDefaultAuthorizer(r -> { }).authorizerDescription().authorizerName();
+ if (created.contains(current)) {
+ iot.clearDefaultAuthorizer(r -> { });
+ }
+ } catch (ResourceNotFoundException expected) {
+ // No default authorizer is configured, so there is nothing of ours to clear.
+ } catch (RuntimeException e) {
+ failure = e;
+ }
+ for (String name : created) {
+ try {
+ AuthorizerDescription description = describe(name);
+ if (description.status() == AuthorizerStatus.ACTIVE) {
+ iot.updateAuthorizer(r -> r.authorizerName(name).status(AuthorizerStatus.INACTIVE));
+ }
+ iot.deleteAuthorizer(r -> r.authorizerName(name));
+ } catch (ResourceNotFoundException expected) {
+ // The test already deleted it, or the create under test was rejected.
+ } catch (RuntimeException e) {
+ if (failure == null) {
+ failure = e;
+ }
+ }
+ }
+ created.clear();
+ if (failure != null) {
+ throw failure;
+ }
+ }
+
+ @Test
+ @DisplayName("Create with signing disabled and no status yields an INACTIVE authorizer with defaults")
+ void createSigningDisabledAuthorizerWithDefaults() {
+ String name = name("plain");
+ String function = functionArn("fn");
+
+ CreateAuthorizerResponse response = create(name, b -> b.authorizerFunctionArn(function).signingDisabled(true));
+
+ assertThat(response.authorizerName()).isEqualTo(name);
+ assertThat(response.authorizerArn()).isEqualTo(authorizerArn(name));
+
+ AuthorizerDescription description = describe(name);
+ assertThat(description.authorizerName()).isEqualTo(name);
+ assertThat(description.authorizerArn()).isEqualTo(authorizerArn(name));
+ assertThat(description.authorizerFunctionArn()).isEqualTo(function);
+ assertThat(description.status()).isEqualTo(AuthorizerStatus.INACTIVE);
+ assertThat(description.signingDisabled()).isTrue();
+ assertThat(description.enableCachingForHttp()).isFalse();
+ assertThat(description.tokenKeyName()).isNull();
+ assertThat(description.hasTokenSigningPublicKeys())
+ .as("AWS returns tokenSigningPublicKeys as JSON null for a signing-disabled authorizer")
+ .isFalse();
+ assertThat(description.tokenSigningPublicKeys()).isEmpty();
+ assertThat(description.creationDate()).isNotNull().isEqualTo(description.lastModifiedDate());
+ }
+
+ @Test
+ @DisplayName("Create a signed authorizer stores the token key name and the PEM verbatim, text before the header included")
+ void createSignedAuthorizerStoresPublicKeyVerbatim() {
+ String name = name("signed");
+
+ CreateAuthorizerResponse response = create(name, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", rsaKey1)));
+
+ assertThat(response.authorizerName()).isEqualTo(name);
+ assertThat(response.authorizerArn()).isEqualTo(authorizerArn(name));
+ AuthorizerDescription description = describe(name);
+ assertThat(description.signingDisabled()).isFalse();
+ assertThat(description.tokenKeyName()).isEqualTo("tok");
+ assertThat(description.tokenSigningPublicKeys()).containsExactly(Map.entry("k1", rsaKey1));
+ assertThat(description.status()).isEqualTo(AuthorizerStatus.INACTIVE);
+ assertThat(description.enableCachingForHttp()).isFalse();
+
+ String prefixed = name("prefixed");
+ String prefixedPem = "junk\n" + rsaKey2;
+ create(prefixed, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", prefixedPem)));
+ assertThat(describe(prefixed).tokenSigningPublicKeys())
+ .as("text before the PEM header is skipped and the value is stored verbatim")
+ .containsExactly(Map.entry("k1", prefixedPem));
+ }
+
+ @Test
+ @DisplayName("Create rejects an invalid signing configuration with 400 InvalidRequestException")
+ void createRejectsInvalidSigningConfiguration() {
+ String noSigning = name("nosign");
+ assertCreateRejected(noSigning, b -> b.authorizerFunctionArn(functionArn("fn")),
+ "Token key name for authorizer " + noSigning + " cannot be null");
+
+ String disabledWithKeys = name("disabledkeys");
+ assertCreateRejected(disabledWithKeys, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .signingDisabled(true)
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", rsaKey1)),
+ "Token signing keys map must be null for authorizer " + disabledWithKeys
+ + " if using optional signature header");
+
+ String threeKeys = name("threekeys");
+ assertCreateRejected(threeKeys, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", rsaKey1, "k2", rsaKey2, "k3", rsaKey1)),
+ "Token signing keys map for authorizer " + threeKeys + " cannot contain more than 2 keys");
+
+ String garbage = name("garbage");
+ assertCreateRejected(garbage, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", "not-a-pem")),
+ "Authorizer " + garbage + " public key for key name k1 not a valid RSA key");
+
+ String ec = name("ec");
+ assertCreateRejected(ec, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", ecKey)),
+ "Authorizer " + ec + " public key for key name k1 not a valid RSA key");
+
+ String shortRsa = name("rsa1024");
+ assertCreateRejected(shortRsa, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", rsa1024Key)),
+ "Authorizer " + shortRsa + " public key for key name k1 invalid: Key must be 2048 bits but was 1024 bits");
+
+ List<String> body = rsaKey1.lines().filter(line -> !line.startsWith("-----")).toList();
+ String base64 = String.join("", body);
+ String bodyLines = String.join("\n", body);
+ Map<String, String> notRsa = new LinkedHashMap<>();
+ notRsa.put("rawb64", base64);
+ notRsa.put("bodyonly", bodyLines);
+ notRsa.put("oneline", "-----BEGIN PUBLIC KEY-----" + base64 + "-----END PUBLIC KEY-----");
+ notRsa.forEach((suffix, pem) -> {
+ String envelope = name(suffix);
+ assertCreateRejected(envelope, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", pem)),
+ "Authorizer " + envelope + " public key for key name k1 not a valid RSA key");
+ });
+
+ String noEnd = name("noend");
+ assertCreateRejected(noEnd, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", "-----BEGIN PUBLIC KEY-----\n" + bodyLines)),
+ "Cannot convert public key PEM for authorizer " + noEnd + " to RSA key");
+ }
+
+ @Test
+ @DisplayName("Create rejects a malformed authorizer name, token key name and function ARN")
+ void createRejectsMalformedNameAndFunctionArn() {
+ assertAwsError(() -> iot.createAuthorizer(r -> r.authorizerName("bad name!")
+ .authorizerFunctionArn(functionArn("fn"))
+ .signingDisabled(true)),
+ InvalidRequestException.class, 400,
+ "1 validation error detected: Value at 'authorizerName' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: [\\w=,@-]+");
+
+ assertAwsError(() -> iot.createAuthorizer(r -> r.authorizerName("!".repeat(129))
+ .authorizerFunctionArn(functionArn("fn"))
+ .signingDisabled(true)),
+ InvalidRequestException.class, 400,
+ "2 validation errors detected: Value at 'authorizerName' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: [\\w=,@-]+; "
+ + "Value at 'authorizerName' failed to satisfy constraint: "
+ + "Member must have length less than or equal to 128");
+
+ String emptyToken = name("emptytok");
+ assertCreateRejected(emptyToken, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("")
+ .tokenSigningPublicKeys(Map.of("k1", rsaKey1)),
+ "2 validation errors detected: Value at 'tokenKeyName' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: [a-zA-Z0-9_-]+; "
+ + "Value at 'tokenKeyName' failed to satisfy constraint: "
+ + "Member must have length greater than or equal to 1");
+
+ String badArn = name("badarn");
+ assertCreateRejected(badArn, b -> b.authorizerFunctionArn("not-an-arn").signingDisabled(true),
+ "Lambda function arn for authorizer " + badArn + " is not in proper ARN syntax");
+ }
+
+ @Test
+ @DisplayName("A duplicate create returns 409 and leaves the original unchanged")
+ void duplicateCreateIsRejected() {
+ String name = name("dup");
+ String function = functionArn("fn");
+ create(name, b -> b.authorizerFunctionArn(function).signingDisabled(true));
+ AuthorizerDescription before = describe(name);
+
+ assertAwsError(() -> iot.createAuthorizer(r -> r.authorizerName(name)
+ .authorizerFunctionArn(functionArn("other"))
+ .signingDisabled(true)
+ .status(AuthorizerStatus.ACTIVE)),
+ ResourceAlreadyExistsException.class, 409,
+ "Authorizer " + name + " already exist for this account");
+
+ assertThat(describe(name)).isEqualTo(before);
+ }
+
+ @Test
+ @DisplayName("Describe, update and delete of a missing authorizer return 404")
+ void missingAuthorizerIsNotFound() {
+ String name = name("missing");
+ String message = "Authorizer " + name + " not found";
+
+ assertAwsError(() -> iot.describeAuthorizer(r -> r.authorizerName(name)),
+ ResourceNotFoundException.class, 404, message);
+ assertAwsError(() -> iot.updateAuthorizer(r -> r.authorizerName(name).status(AuthorizerStatus.ACTIVE)),
+ ResourceNotFoundException.class, 404, message);
+ assertAwsError(() -> iot.deleteAuthorizer(r -> r.authorizerName(name)),
+ ResourceNotFoundException.class, 404, message);
+ }
+
+ @Test
+ @DisplayName("Describe, update and delete validate the authorizer name before looking it up")
+ void pathOperationsValidateTheName() {
+ String constraint = "Value at 'authorizerName' failed to satisfy constraint: ";
+ String pattern = constraint + "Member must satisfy regular expression pattern: [\\w=,@-]+";
+ String badName = "1 validation error detected: " + pattern;
+ String overlong = "!".repeat(129);
+ String bothViolated = "2 validation errors detected: " + pattern + "; " + constraint
+ + "Member must have length less than or equal to 128";
+
+ assertAwsError(() -> iot.describeAuthorizer(r -> r.authorizerName("bad name!")),
+ InvalidRequestException.class, 400, badName);
+ assertAwsError(() -> iot.describeAuthorizer(r -> r.authorizerName(overlong)),
+ InvalidRequestException.class, 400, bothViolated);
+ assertAwsError(() -> iot.updateAuthorizer(r -> r.authorizerName("bad name!").status(AuthorizerStatus.INACTIVE)),
+ InvalidRequestException.class, 400, badName);
+ assertAwsError(() -> iot.updateAuthorizer(r -> r.authorizerName(overlong).status(AuthorizerStatus.INACTIVE)),
+ InvalidRequestException.class, 400, bothViolated);
+ assertAwsError(() -> iot.deleteAuthorizer(r -> r.authorizerName("bad name!")),
+ InvalidRequestException.class, 400, badName);
+ assertAwsError(() -> iot.deleteAuthorizer(r -> r.authorizerName(overlong)),
+ InvalidRequestException.class, 400, bothViolated);
+ }
+
+ @Test
+ @DisplayName("Update changes only the fields sent and bumps lastModifiedDate on a status change")
+ void updateAppliesOnlyTheFieldsSent() throws InterruptedException {
+ String name = name("upd");
+ String firstFunction = functionArn("fn1");
+ String secondFunction = functionArn("fn2");
+ create(name, b -> b.authorizerFunctionArn(firstFunction).signingDisabled(true));
+ AuthorizerDescription original = describe(name);
+
+ Thread.sleep(1100);
+ UpdateAuthorizerResponse response =
+ iot.updateAuthorizer(r -> r.authorizerName(name).status(AuthorizerStatus.ACTIVE));
+ assertThat(response.authorizerName()).isEqualTo(name);
+ assertThat(response.authorizerArn()).isEqualTo(authorizerArn(name));
+ AuthorizerDescription active = describe(name);
+ assertThat(active.status()).isEqualTo(AuthorizerStatus.ACTIVE);
+ assertThat(active.authorizerFunctionArn()).isEqualTo(firstFunction);
+ assertThat(active.signingDisabled()).isTrue();
+ assertThat(active.enableCachingForHttp()).isFalse();
+ assertThat(active.tokenKeyName()).isNull();
+ assertThat(active.creationDate()).isEqualTo(original.creationDate());
+ assertThat(active.lastModifiedDate()).isAfter(original.lastModifiedDate());
+
+ iot.updateAuthorizer(r -> r.authorizerName(name).enableCachingForHttp(true));
+ AuthorizerDescription caching = describe(name);
+ assertThat(caching.enableCachingForHttp()).isTrue();
+ assertThat(caching.status()).isEqualTo(AuthorizerStatus.ACTIVE);
+ assertThat(caching.authorizerFunctionArn()).isEqualTo(firstFunction);
+
+ iot.updateAuthorizer(r -> r.authorizerName(name).authorizerFunctionArn(secondFunction));
+ AuthorizerDescription moved = describe(name);
+ assertThat(moved.authorizerFunctionArn()).isEqualTo(secondFunction);
+ assertThat(moved.status()).isEqualTo(AuthorizerStatus.ACTIVE);
+ assertThat(moved.enableCachingForHttp()).isTrue();
+ assertThat(moved.signingDisabled()).isTrue();
+
+ Thread.sleep(1100);
+ iot.updateAuthorizer(r -> r.authorizerName(name).status(AuthorizerStatus.INACTIVE));
+ AuthorizerDescription inactive = describe(name);
+ assertThat(inactive.status()).isEqualTo(AuthorizerStatus.INACTIVE);
+ assertThat(inactive.authorizerFunctionArn()).isEqualTo(secondFunction);
+ assertThat(inactive.enableCachingForHttp()).isTrue();
+ assertThat(inactive.creationDate()).isEqualTo(original.creationDate());
+ assertThat(inactive.lastModifiedDate()).isAfter(moved.lastModifiedDate());
+ }
+
+ @Test
+ @DisplayName("Update merges signing keys per key name and refuses a third key")
+ void updateMergesSigningKeys() {
+ String name = name("merge");
+ create(name, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .tokenKeyName("tok")
+ .tokenSigningPublicKeys(Map.of("k1", rsaKey1)));
+
+ iot.updateAuthorizer(r -> r.authorizerName(name).tokenSigningPublicKeys(Map.of("k2", rsaKey2)));
+ AuthorizerDescription merged = describe(name);
+ assertThat(merged.tokenSigningPublicKeys())
+ .containsOnly(Map.entry("k1", rsaKey1), Map.entry("k2", rsaKey2));
+ assertThat(merged.tokenKeyName()).isEqualTo("tok");
+
+ assertAwsError(() -> iot.updateAuthorizer(r -> r.authorizerName(name)
+ .tokenSigningPublicKeys(Map.of("k3", rsaKey1))),
+ InvalidRequestException.class, 400,
+ "Number of signing keys for authorizer " + name + " must neither be zero nor greater than 2");
+ assertThat(describe(name).tokenSigningPublicKeys())
+ .containsOnly(Map.entry("k1", rsaKey1), Map.entry("k2", rsaKey2));
+ }
+
+ @Test
+ @DisplayName("Delete refuses an ACTIVE authorizer, deletes an INACTIVE one and frees the name")
+ void deleteRequiresInactiveStatus() {
+ String name = name("del");
+ create(name, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .signingDisabled(true)
+ .status(AuthorizerStatus.ACTIVE));
+
+ assertAwsError(() -> iot.deleteAuthorizer(r -> r.authorizerName(name)),
+ InvalidRequestException.class, 400,
+ "Cannot delete authorizer " + name + " in ACTIVE status. Update status to INACTIVE and delete.");
+ assertThat(describe(name).status()).isEqualTo(AuthorizerStatus.ACTIVE);
+
+ iot.updateAuthorizer(r -> r.authorizerName(name).status(AuthorizerStatus.INACTIVE));
+ iot.deleteAuthorizer(r -> r.authorizerName(name));
+ assertAwsError(() -> iot.describeAuthorizer(r -> r.authorizerName(name)),
+ ResourceNotFoundException.class, 404, "Authorizer " + name + " not found");
+
+ CreateAuthorizerResponse recreated =
+ create(name, b -> b.authorizerFunctionArn(functionArn("fn")).signingDisabled(true));
+ assertThat(recreated.authorizerArn()).isEqualTo(authorizerArn(name));
+ assertThat(describe(name).status()).isEqualTo(AuthorizerStatus.INACTIVE);
+ }
+
+ @Test
+ @DisplayName("ListAuthorizers orders by creation time, filters by status and pages with nextMarker")
+ void listAuthorizersOrdersFiltersAndPages() {
+ String first = name("l1");
+ String second = name("l2");
+ String third = name("l3");
+ for (String name : List.of(first, second, third)) {
+ create(name, b -> b.authorizerFunctionArn(functionArn("fn")).signingDisabled(true));
+ }
+ iot.updateAuthorizer(r -> r.authorizerName(second).status(AuthorizerStatus.ACTIVE));
+
+ List<AuthorizerSummary> newestFirst = ours(listAll(b -> { }));
+ assertThat(newestFirst).extracting(AuthorizerSummary::authorizerName)
+ .containsExactly(third, second, first);
+ assertThat(newestFirst).allSatisfy(summary ->
+ assertThat(summary.authorizerArn()).isEqualTo(authorizerArn(summary.authorizerName())));
+
+ assertThat(ours(listAll(b -> b.ascendingOrder(true)))).extracting(AuthorizerSummary::authorizerName)
+ .containsExactly(first, second, third);
+ assertThat(ours(listAll(b -> b.status(AuthorizerStatus.ACTIVE))))
+ .extracting(AuthorizerSummary::authorizerName).containsExactly(second);
+ assertThat(ours(listAll(b -> b.status(AuthorizerStatus.INACTIVE))))
+ .extracting(AuthorizerSummary::authorizerName).containsExactly(third, first);
+
+ List<String> paged = new ArrayList<>();
+ String marker = null;
+ int pages = 0;
+ do {
+ String current = marker;
+ ListAuthorizersResponse page = iot.listAuthorizers(r -> r.pageSize(1).marker(current));
+ assertThat(page.authorizers()).as("pageSize 1 returns one item per page").hasSize(1);
+ page.authorizers().forEach(summary -> paged.add(summary.authorizerName()));
+ marker = page.nextMarker();
+ pages++;
+ } while (marker != null && pages < 1000);
+ assertThat(marker).as("the last page carries no nextMarker").isNull();
+ assertThat(paged.stream().filter(n -> n.startsWith(prefix)).toList())
+ .containsExactly(third, second, first);
+ }
+
+ @Test
+ @DisplayName("Default authorizer set, replace, describe, delete conflict and clear")
+ void defaultAuthorizerLifecycle() {
+ String existingDefault = currentDefaultName();
+ assumeThat(existingDefault)
+ .as("the account already has a default authorizer that this test did not create")
+ .isNull();
+ assertAwsError(() -> iot.describeDefaultAuthorizer(r -> { }),
+ ResourceNotFoundException.class, 404, "Default authorizer not found");
+
+ String first = name("d1");
+ String second = name("d2");
+ create(first, b -> b.authorizerFunctionArn(functionArn("fn")).signingDisabled(true));
+ create(second, b -> b.authorizerFunctionArn(functionArn("fn")).signingDisabled(true));
+
+ SetDefaultAuthorizerResponse set = iot.setDefaultAuthorizer(r -> r.authorizerName(first));
+ assertThat(set.authorizerName()).isEqualTo(first);
+ assertThat(set.authorizerArn()).isEqualTo(authorizerArn(first));
+
+ assertAwsError(() -> iot.setDefaultAuthorizer(r -> r.authorizerName(first)),
+ ResourceAlreadyExistsException.class, 409,
+ "Duplicate default authorizer " + first + " already configured for this account");
+
+ SetDefaultAuthorizerResponse replaced = iot.setDefaultAuthorizer(r -> r.authorizerName(second));
+ assertThat(replaced.authorizerName()).isEqualTo(second);
+ assertThat(replaced.authorizerArn()).isEqualTo(authorizerArn(second));
+ assertThat(iot.describeDefaultAuthorizer(r -> { }).authorizerDescription())
+ .isEqualTo(describe(second));
+
+ assertAwsError(() -> iot.deleteAuthorizer(r -> r.authorizerName(second)),
+ DeleteConflictException.class, 409,
+ "Cannot delete default authorizer " + second + ". Change default and retry delete.");
+ assertThat(describe(second).status()).isEqualTo(AuthorizerStatus.INACTIVE);
+
+ iot.clearDefaultAuthorizer(r -> { });
+ assertAwsError(() -> iot.describeDefaultAuthorizer(r -> { }),
+ ResourceNotFoundException.class, 404, "Default authorizer not found");
+ assertAwsError(() -> iot.clearDefaultAuthorizer(r -> { }),
+ ResourceNotFoundException.class, 404, "Default authorizer not found");
+ }
+
+ @Test
+ @DisplayName("SetDefaultAuthorizer validates the authorizer name before looking it up")
+ void setDefaultAuthorizerValidatesTheName() {
+ String constraint = "Value at 'authorizerName' failed to satisfy constraint: ";
+ String pattern = constraint + "Member must satisfy regular expression pattern: [\\w=,@-]+";
+
+ assertAwsError(() -> iot.setDefaultAuthorizer(r -> { }), InvalidRequestException.class, 400,
+ "1 validation error detected: " + constraint + "Member must not be null");
+ assertAwsError(() -> iot.setDefaultAuthorizer(r -> r.authorizerName("")), InvalidRequestException.class, 400,
+ "2 validation errors detected: " + pattern + "; " + constraint
+ + "Member must have length greater than or equal to 1");
+ assertAwsError(() -> iot.setDefaultAuthorizer(r -> r.authorizerName("bad name!")),
+ InvalidRequestException.class, 400, "1 validation error detected: " + pattern);
+ assertAwsError(() -> iot.setDefaultAuthorizer(r -> r.authorizerName("!".repeat(129))),
+ InvalidRequestException.class, 400,
+ "2 validation errors detected: " + pattern + "; " + constraint
+ + "Member must have length less than or equal to 128");
+
+ String missing = name("nodefault");
+ assertAwsError(() -> iot.setDefaultAuthorizer(r -> r.authorizerName(missing)),
+ ResourceNotFoundException.class, 404, "Authorizer " + missing + " not found");
+ }
+
+ @Test
+ @DisplayName("Tags on an authorizer ARN are created, overwritten, removed and listed")
+ void tagsOnAuthorizerArn() {
+ String name = name("tags");
+ String arn = authorizerArn(name);
+ create(name, b -> b.authorizerFunctionArn(functionArn("fn"))
+ .signingDisabled(true)
+ .tags(tag("env", "dev"), tag("team", "a")));
+ assertThat(tags(arn)).containsOnly(Map.entry("env", "dev"), Map.entry("team", "a"));
+
+ iot.tagResource(r -> r.resourceArn(arn).tags(tag("team", "b"), tag("owner", "x")));
+ assertThat(tags(arn)).containsOnly(Map.entry("env", "dev"), Map.entry("team", "b"), Map.entry("owner", "x"));
+
+ iot.untagResource(r -> r.resourceArn(arn).tagKeys("env"));
+ assertThat(tags(arn)).containsOnly(Map.entry("team", "b"), Map.entry("owner", "x"));
+ }
+
+ @Test
+ @DisplayName("Tags on a missing authorizer ARN list empty and refuse TagResource with 404")
+ void tagsOnMissingAuthorizer() {
+ String name = name("notag");
+ String arn = authorizerArn(name);
+
+ assertThat(iot.listTagsForResource(r -> r.resourceArn(arn)).tags()).isEmpty();
+ assertAwsError(() -> iot.tagResource(r -> r.resourceArn(arn).tags(tag("k", "v"))),
+ ResourceNotFoundException.class, 404, "Authorizer " + name + " not found");
+ }
+
+ private String name(String suffix) {
+ return prefix + "-" + suffix;
+ }
+
+ private String functionArn(String suffix) {
+ return "arn:" + partition + ":lambda:" + region + ":" + account + ":function:" + prefix + "-" + suffix;
+ }
+
+ private String authorizerArn(String name) {
+ return "arn:" + partition + ":iot:" + region + ":" + account + ":authorizer/" + name;
+ }
+
+ private CreateAuthorizerResponse create(String name, Consumer<CreateAuthorizerRequest.Builder> request) {
+ created.add(name);
+ return iot.createAuthorizer(b -> request.accept(b.authorizerName(name)));
+ }
+
+ private AuthorizerDescription describe(String name) {
+ return iot.describeAuthorizer(r -> r.authorizerName(name)).authorizerDescription();
+ }
+
+ private String currentDefaultName() {
+ try {
+ return iot.describeDefaultAuthorizer(r -> { }).authorizerDescription().authorizerName();
+ } catch (ResourceNotFoundException expected) {
+ // No default authorizer is configured in this account and region.
+ return null;
+ }
+ }
+
+ private void assertCreateRejected(String name, Consumer<CreateAuthorizerRequest.Builder> request,
+ String message) {
+ assertAwsError(() -> create(name, request), InvalidRequestException.class, 400, message);
+ assertAwsError(() -> iot.describeAuthorizer(r -> r.authorizerName(name)),
+ ResourceNotFoundException.class, 404, "Authorizer " + name + " not found");
+ }
+
+ private List<AuthorizerSummary> listAll(Consumer<ListAuthorizersRequest.Builder> filter) {
+ List<AuthorizerSummary> all = new ArrayList<>();
+ String marker = null;
+ do {
+ String current = marker;
+ ListAuthorizersResponse page = iot.listAuthorizers(b -> {
+ filter.accept(b);
+ b.marker(current);
+ });
+ all.addAll(page.authorizers());
+ marker = page.nextMarker();
+ } while (marker != null);
+ return all;
+ }
+
+ private List<AuthorizerSummary> ours(List<AuthorizerSummary> summaries) {
+ return summaries.stream().filter(s -> s.authorizerName().startsWith(prefix)).toList();
+ }
+
+ private Map<String, String> tags(String arn) {
+ return iot.listTagsForResource(r -> r.resourceArn(arn)).tags().stream()
+ .collect(Collectors.toMap(Tag::key, Tag::value, (a, b) -> b, LinkedHashMap::new));
+ }
+
+ private static Tag tag(String key, String value) {
+ return Tag.builder().key(key).value(value).build();
+ }
+
+ private static <T extends IotException> void assertAwsError(ThrowingCallable call, Class<T> type,
+ int status, String message) {
+ T error = catchThrowableOfType(call, type);
+ assertThat(error).as("expected %s: %s", type.getSimpleName(), message).isNotNull();
+ assertThat(error.statusCode()).isEqualTo(status);
+ assertThat(error.awsErrorDetails().errorMessage()).isEqualTo(message);
+ }
+
+ private static String publicKeyPem(String algorithm, int bits) throws GeneralSecurityException {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm);
+ generator.initialize(bits);
+ byte[] der = generator.generateKeyPair().getPublic().getEncoded();
+ String body = Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(der);
+ return "-----BEGIN PUBLIC KEY-----\n" + body + "\n-----END PUBLIC KEY-----";
+ }
+}
diff --git a/docs/services/index.md b/docs/services/index.md
index cf9eb99a9f..559a355ebc 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -142,7 +142,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [BCM Data Exports](bcm-data-exports.md) | `POST /` + `X-Amz-Target: AWSBillingAndCostManagementDataExports.*` | JSON 1.1 | 7 |
| [Transfer Family](transfer.md) | `POST /` + `X-Amz-Target: TransferService.*` | JSON 1.1 | 17 |
| [DataSync](datasync.md) | `POST /` + `X-Amz-Target: FmrsService.*` | JSON 1.1 | 48 |
-| [IoT Core](iot.md) | `/things/...`, `/endpoint`, rules/policies REST paths | REST JSON | 62 |
+| [IoT Core](iot.md) | `/things/...`, `/endpoint`, rules/policies REST paths | REST JSON | 70 |
| [IoT Data](iot.md) | `/things/{thingName}/shadow`, MQTT topics | REST JSON | 11 |
**Lambda, ElastiCache, RDS, MSK, MWAA, ECS, EKS, and OpenSearch** spin up real Docker containers and support IAM authentication and SigV4 request signing, the same auth flow as production AWS. **RDS Data API** executes SQL against the local RDS containers through AWS-compatible REST JSON routes.
diff --git a/docs/services/iot.md b/docs/services/iot.md
index 10ae4bdbf5..50b9a43b5d 100644
--- a/docs/services/iot.md
+++ b/docs/services/iot.md
@@ -67,6 +67,25 @@ Current limitations:
- A custom domain does not change where the broker listens or what `DescribeEndpoint` returns (see [Endpoint address](#endpoint-address)), and pointing DNS at the emulator is outside its scope.
- Server certificate ARNs are stored as given and reported `VALID`; they are not checked against ACM.
+## Authorizers
+
+Status: control plane only.
+
+`CreateAuthorizer`, `DescribeAuthorizer`, `UpdateAuthorizer`, `DeleteAuthorizer`, `ListAuthorizers`, `SetDefaultAuthorizer`, `DescribeDefaultAuthorizer` and `ClearDefaultAuthorizer` are served on the REST-JSON paths the AWS SDKs use, with the shapes, error codes and messages measured against AWS:
+
+- A new authorizer is `INACTIVE` with HTTP caching off unless the request says otherwise. Unless `signingDisabled` is `true`, it needs a `tokenKeyName` and one or two RSA-2048 public keys in PEM form; a signing-disabled authorizer takes no keys. The function ARN is checked for ARN syntax only and is never resolved.
+- `DescribeAuthorizer` returns every member; an unset token key name or key map is JSON `null`, and tags are not shown.
+- `UpdateAuthorizer` changes only the members sent and merges signing keys by key name, refusing a third key. Any member sent moves `lastModifiedDate`; an empty body does not.
+- `DeleteAuthorizer` refuses an `ACTIVE` authorizer (`InvalidRequestException`) and the default authorizer (`DeleteConflictException`).
+- `ListAuthorizers` returns the newest authorizer first (`isAscendingOrder=true` reverses it), filters by `status` and pages with `marker` and `pageSize` (1 to 250).
+- Setting the authorizer that already is the default fails with `ResourceAlreadyExistsException`; setting another one replaces it.
+- Tags work through `TagResource`, `UntagResource` and `ListTagsForResource` on the authorizer ARN.
+
+Current limitations:
+
+- Authorizers are not evaluated: no connection or HTTP publish invokes the function, and `TestInvokeAuthorizer` is not served (see [MQTT over WebSocket](#mqtt-over-websocket)).
+- CloudFormation `AWS::IoT::Authorizer` is not provisioned.
+
## MQTT Broker
Status: complete.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 830b0ffbef..6e748bb50d 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -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),
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotAuthorizerController.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotAuthorizerController.java
new file mode 100644
index 0000000000..930458b68b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotAuthorizerController.java
@@ -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);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotAuthorizerService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotAuthorizerService.java
new file mode 100644
index 0000000000..50fd374997
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotAuthorizerService.java
@@ -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;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationService.java
index 5ffa5b96b9..e4d156dd44 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationService.java
@@ -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;
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotTagHandler.java
index 6f5a5afd18..9e991b1d79 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotTagHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotTagHandler.java
@@ -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/");
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotAuthorizer.java
new file mode 100644
index 0000000000..d272a6dac1
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotAuthorizer.java
@@ -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); }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotAuthorizerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotAuthorizerIntegrationTest.java
new file mode 100644
index 0000000000..6670e8cc4c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotAuthorizerIntegrationTest.java
@@ -0,0 +1,290 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.path.json.JsonPath;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasKey;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Drives the custom authorizer routes the way the AWS SDKs do (REST-JSON under
+ * {@code /authorizer}, {@code /authorizers/} and {@code /default-authorizer}) and checks the wire
+ * shapes and errors AWS IoT returns.
+ */
+@QuarkusTest
+class IotAuthorizerIntegrationTest {
+
+ private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:it-auth";
+ private static final String ARN_PREFIX = "arn:aws:iot:us-east-1:000000000000:authorizer/";
+ private static final String UNSIGNED = """
+ {"authorizerFunctionArn": "%s", "signingDisabled": true}
+ """.formatted(FUNCTION_ARN);
+
+ private static void create(String name) {
+ given().contentType("application/json").body(UNSIGNED)
+ .when().post("/authorizer/" + name)
+ .then().statusCode(200);
+ }
+
+ private static void delete(String name) {
+ given().when().delete("/authorizer/" + name).then().statusCode(200).body(equalTo("{}"));
+ }
+
+ private static void setStatus(String name, String status) {
+ given().contentType("application/json").body("{\"status\": \"" + status + "\"}")
+ .when().put("/authorizer/" + name)
+ .then().statusCode(200)
+ .body("authorizerName", equalTo(name))
+ .body("authorizerArn", equalTo(ARN_PREFIX + name));
+ }
+
+ @Test
+ void createAndDescribeUseTheAwsWireShape() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {"authorizerFunctionArn": "%s", "signingDisabled": true, "tags": [{"Key": "env", "Value": "it"}]}
+ """.formatted(FUNCTION_ARN))
+ .when()
+ .post("/authorizer/it-auth-shape")
+ .then()
+ .statusCode(200)
+ .body("size()", equalTo(2))
+ .body("authorizerName", equalTo("it-auth-shape"))
+ .body("authorizerArn", equalTo(ARN_PREFIX + "it-auth-shape"));
+
+ String body = given()
+ .when()
+ .get("/authorizer/it-auth-shape")
+ .then()
+ .statusCode(200)
+ .body("authorizerDescription.authorizerName", equalTo("it-auth-shape"))
+ .body("authorizerDescription.authorizerArn", equalTo(ARN_PREFIX + "it-auth-shape"))
+ .body("authorizerDescription.authorizerFunctionArn", equalTo(FUNCTION_ARN))
+ .body("authorizerDescription.status", equalTo("INACTIVE"))
+ .body("authorizerDescription.signingDisabled", equalTo(true))
+ .body("authorizerDescription.enableCachingForHttp", equalTo(false))
+ .body("authorizerDescription", hasKey("tokenKeyName"))
+ .body("authorizerDescription.tokenKeyName", nullValue())
+ .body("authorizerDescription", hasKey("tokenSigningPublicKeys"))
+ .body("authorizerDescription.tokenSigningPublicKeys", nullValue())
+ .body("authorizerDescription", not(hasKey("tags")))
+ .extract().asString();
+ assertTrue(body.matches(".*\"creationDate\":\\d\\.\\d+E9[,}].*"), body);
+ JsonPath description = JsonPath.from(body);
+ assertEquals(description.getString("authorizerDescription.creationDate"),
+ description.getString("authorizerDescription.lastModifiedDate"));
+
+ delete("it-auth-shape");
+ }
+
+ @Test
+ void errorsCarryTheAwsTypeStatusAndMessage() {
+ create("it-auth-err");
+
+ given().contentType("application/json").body(UNSIGNED)
+ .when().post("/authorizer/it-auth-err")
+ .then()
+ .statusCode(409)
+ .header("X-Amzn-ErrorType", "ResourceAlreadyExistsException")
+ .body("message", equalTo("Authorizer it-auth-err already exist for this account"))
+ .body("resourceId", equalTo("it-auth-err"))
+ .body("resourceArn", equalTo(ARN_PREFIX + "it-auth-err"));
+
+ given().when().get("/authorizer/it-auth-missing")
+ .then()
+ .statusCode(404)
+ .header("X-Amzn-ErrorType", "ResourceNotFoundException")
+ .body("message", equalTo("Authorizer it-auth-missing not found"));
+
+ given().when().get("/authorizer/{name}", "bad name!")
+ .then()
+ .statusCode(400)
+ .header("X-Amzn-ErrorType", "InvalidRequestException")
+ .body("message", equalTo("1 validation error detected: Value at 'authorizerName' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: [\\w=,@-]+"));
+
+ given().contentType("application/json")
+ .body("{\"authorizerFunctionArn\": \"not-an-arn\", \"signingDisabled\": true}")
+ .when().post("/authorizer/it-auth-badarn")
+ .then()
+ .statusCode(400)
+ .header("X-Amzn-ErrorType", "InvalidRequestException")
+ .body("message", equalTo("Lambda function arn for authorizer it-auth-badarn is not in proper ARN syntax"));
+
+ setStatus("it-auth-err", "ACTIVE");
+ given().when().delete("/authorizer/it-auth-err")
+ .then()
+ .statusCode(400)
+ .header("X-Amzn-ErrorType", "InvalidRequestException")
+ .body("message", equalTo("Cannot delete authorizer it-auth-err in ACTIVE status. Update status to INACTIVE and delete."));
+
+ setStatus("it-auth-err", "INACTIVE");
+ delete("it-auth-err");
+
+ given().contentType("application/json").body("{}")
+ .when().post("/default-authorizer")
+ .then()
+ .statusCode(400)
+ .header("X-Amzn-ErrorType", "InvalidRequestException")
+ .body("message", equalTo("1 validation error detected: Value at 'authorizerName' failed to satisfy constraint: "
+ + "Member must not be null"));
+ }
+
+ @Test
+ void listAuthorizersOrdersFiltersAndPagesOnTheSdkPath() {
+ for (String name : List.of("it-list-1", "it-list-2", "it-list-3")) {
+ create(name);
+ }
+ setStatus("it-list-2", "ACTIVE");
+
+ given().queryParam("isAscendingOrder", true)
+ .when().get("/authorizers/")
+ .then().statusCode(200)
+ .body("authorizers.authorizerName", contains("it-list-1", "it-list-2", "it-list-3"))
+ .body("authorizers[0].size()", equalTo(2))
+ .body("authorizers[0].authorizerArn", equalTo(ARN_PREFIX + "it-list-1"));
+ given().queryParam("status", "INACTIVE")
+ .when().get("/authorizers/")
+ .then().statusCode(200)
+ .body("authorizers.authorizerName", contains("it-list-3", "it-list-1"));
+
+ List<String> paged = new ArrayList<>();
+ String marker = null;
+ do {
+ RequestSpecification request = given().queryParam("pageSize", 1);
+ if (marker != null) {
+ request.queryParam("marker", marker);
+ }
+ JsonPath page = request
+ .when().get("/authorizers/")
+ .then().statusCode(200).body("authorizers", not(empty())).body("$", hasKey("nextMarker"))
+ .extract().jsonPath();
+ paged.addAll(page.getList("authorizers.authorizerName"));
+ marker = page.getString("nextMarker");
+ } while (marker != null && paged.size() < 10);
+ assertEquals(List.of("it-list-3", "it-list-2", "it-list-1"), paged);
+ assertNull(marker);
+
+ given().queryParam("marker", "garbage")
+ .when().get("/authorizers/")
+ .then().statusCode(400)
+ .header("X-Amzn-ErrorType", "InvalidRequestException")
+ .body("message", equalTo("Invalid/Malformed marker passed for listAuthorizers"));
+
+ setStatus("it-list-2", "INACTIVE");
+ List.of("it-list-1", "it-list-2", "it-list-3").forEach(IotAuthorizerIntegrationTest::delete);
+ }
+
+ @Test
+ void defaultAuthorizerIsSetDescribedAndCleared() {
+ create("it-auth-default");
+
+ given().contentType("application/json").body("{\"authorizerName\": \"it-auth-default\"}")
+ .when().post("/default-authorizer")
+ .then().statusCode(200)
+ .body("size()", equalTo(2))
+ .body("authorizerName", equalTo("it-auth-default"))
+ .body("authorizerArn", equalTo(ARN_PREFIX + "it-auth-default"));
+
+ given().when().get("/default-authorizer")
+ .then().statusCode(200)
+ .body("authorizerDescription.authorizerName", equalTo("it-auth-default"))
+ .body("authorizerDescription.status", equalTo("INACTIVE"));
+
+ given().when().delete("/authorizer/it-auth-default")
+ .then().statusCode(409)
+ .header("X-Amzn-ErrorType", "DeleteConflictException")
+ .body("message", equalTo("Cannot delete default authorizer it-auth-default. Change default and retry delete."));
+
+ given().when().delete("/default-authorizer").then().statusCode(200).body(equalTo("{}"));
+ given().when().get("/default-authorizer")
+ .then().statusCode(404)
+ .header("X-Amzn-ErrorType", "ResourceNotFoundException")
+ .body("message", equalTo("Default authorizer not found"));
+
+ delete("it-auth-default");
+ }
+
+ @Test
+ void tagsOnAnAuthorizerArnGoThroughTheIotTagRoutes() {
+ String arn = ARN_PREFIX + "it-auth-tags";
+ given().contentType("application/json")
+ .body("""
+ {"authorizerFunctionArn": "%s", "signingDisabled": true, "tags": [{"Key": "env", "Value": "dev"}]}
+ """.formatted(FUNCTION_ARN))
+ .when().post("/authorizer/it-auth-tags")
+ .then().statusCode(200);
+
+ given().contentType("application/json")
+ .body("{\"resourceArn\": \"" + arn + "\", \"tags\": [{\"Key\": \"team\", \"Value\": \"a\"}]}")
+ .when().post("/tags")
+ .then().statusCode(200);
+ given().contentType("application/json")
+ .body("{\"resourceArn\": \"" + arn + "\", \"tagKeys\": [\"env\"]}")
+ .when().post("/untag")
+ .then().statusCode(200);
+
+ given().queryParam("resourceArn", arn)
+ .when().get("/tags")
+ .then().statusCode(200)
+ .body("tags.Key", contains("team"))
+ .body("tags.Value", contains("a"));
+
+ String missing = ARN_PREFIX + "it-auth-gone";
+ given().queryParam("resourceArn", missing)
+ .when().get("/tags")
+ .then().statusCode(200).body("tags", empty());
+ given().contentType("application/json")
+ .body("{\"resourceArn\": \"" + missing + "\", \"tags\": [{\"Key\": \"k\", \"Value\": \"v\"}]}")
+ .when().post("/tags")
+ .then().statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"))
+ .body("message", equalTo("Authorizer it-auth-gone not found"));
+
+ delete("it-auth-tags");
+ }
+
+ @Test
+ void authorizerTextOutsideTheArnResourceIsTaggedLikeAnyOtherIotArn() {
+ for (String arn : List.of("arn:aws:iot:authorizer/:000000000000:x", "arn:aws:iot:us-east-1:000000000000:x")) {
+ given().queryParam("resourceArn", arn)
+ .when().get("/tags")
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"))
+ .body("message", equalTo("Invalid resource ARN: " + arn));
+ given().contentType("application/json")
+ .body("{\"resourceArn\": \"" + arn + "\", \"tags\": [{\"Key\": \"k\", \"Value\": \"v\"}]}")
+ .when().post("/tags")
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"))
+ .body("message", equalTo("Invalid resource ARN: " + arn));
+ given().contentType("application/json")
+ .body("{\"resourceArn\": \"" + arn + "\", \"tagKeys\": [\"k\"]}")
+ .when().post("/untag")
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"))
+ .body("message", equalTo("Invalid resource ARN: " + arn));
+ }
+
+ given().contentType("application/json")
+ .body("{\"resourceArn\": \"not-an-arn\", \"tagKeys\": [\"k\"]}")
+ .when().post("/untag")
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"))
+ .body("message", equalTo("Invalid resource ARN: not-an-arn"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotAuthorizerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotAuthorizerServiceTest.java
new file mode 100644
index 0000000000..1d0504106f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotAuthorizerServiceTest.java
@@ -0,0 +1,494 @@
+package io.github.hectorvent.floci.services.iot;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.iot.model.IotAuthorizer;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class IotAuthorizerServiceTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:auth";
+ private static final String ARN_PREFIX = "arn:aws:iot:us-east-1:000000000000:authorizer/";
+
+ private static String rsaKey1;
+ private static String rsaKey2;
+ private static String rsa1024Key;
+ private static String ecKey;
+ private static String privateKey;
+
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final IotAuthorizerService service =
+ new IotAuthorizerService(new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"));
+
+ @BeforeAll
+ static void generateKeys() throws GeneralSecurityException {
+ KeyPair rsa = keyPair("RSA", 2048);
+ rsaKey1 = pem("PUBLIC KEY", rsa.getPublic().getEncoded());
+ privateKey = pem("PRIVATE KEY", rsa.getPrivate().getEncoded());
+ rsaKey2 = pem("PUBLIC KEY", keyPair("RSA", 2048).getPublic().getEncoded());
+ rsa1024Key = pem("PUBLIC KEY", keyPair("RSA", 1024).getPublic().getEncoded());
+ ecKey = pem("PUBLIC KEY", keyPair("EC", 256).getPublic().getEncoded());
+ }
+
+ private static KeyPair keyPair(String algorithm, int bits) throws GeneralSecurityException {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm);
+ generator.initialize(bits);
+ return generator.generateKeyPair();
+ }
+
+ private static String pem(String type, byte[] der) {
+ return "-----BEGIN " + type + "-----\n"
+ + Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(der)
+ + "\n-----END " + type + "-----";
+ }
+
+ private ObjectNode unsigned() {
+ return mapper.createObjectNode().put("authorizerFunctionArn", FUNCTION_ARN).put("signingDisabled", true);
+ }
+
+ private ObjectNode signed(Map<String, String> keys) {
+ ObjectNode request = mapper.createObjectNode().put("authorizerFunctionArn", FUNCTION_ARN).put("tokenKeyName", "tok");
+ request.set("tokenSigningPublicKeys", mapper.valueToTree(keys));
+ return request;
+ }
+
+ private ObjectNode keysOnly(Map<String, String> keys) {
+ ObjectNode request = mapper.createObjectNode();
+ request.set("tokenSigningPublicKeys", mapper.valueToTree(keys));
+ return request;
+ }
+
+ private static AwsException assertAwsError(String code, int status, String message, Executable call) {
+ AwsException failure = assertThrows(AwsException.class, call);
+ assertEquals(code, failure.getErrorCode());
+ assertEquals(status, failure.getHttpStatus());
+ assertEquals(message, failure.getMessage());
+ return failure;
+ }
+
+ private static void assertInvalid(String message, Executable call) {
+ assertAwsError("InvalidRequestException", 400, message, call);
+ }
+
+ private List<String> names(IotService.Page<IotAuthorizer> page) {
+ return page.items().stream().map(IotAuthorizer::getAuthorizerName).toList();
+ }
+
+ @Test
+ void createWithSigningDisabledAppliesTheAwsDefaults() {
+ IotAuthorizer created = service.createAuthorizer("plain", unsigned(), REGION);
+
+ assertEquals("plain", created.getAuthorizerName());
+ assertEquals(ARN_PREFIX + "plain", created.getAuthorizerArn());
+ assertEquals(FUNCTION_ARN, created.getAuthorizerFunctionArn());
+ assertEquals("INACTIVE", created.getStatus());
+ assertTrue(created.isSigningDisabled());
+ assertFalse(created.isEnableCachingForHttp());
+ assertNull(created.getTokenKeyName());
+ assertNull(created.getTokenSigningPublicKeys());
+ assertEquals(created.getCreationDate(), created.getLastModifiedDate());
+ assertEquals(created.getAuthorizerArn(), service.describeAuthorizer("plain", REGION).getAuthorizerArn());
+ }
+
+ @Test
+ void createSignedAuthorizerKeepsThePemVerbatim() {
+ ObjectNode request = signed(Map.of("k1", rsaKey1 + "\n")).put("status", "ACTIVE").put("enableCachingForHttp", true);
+
+ IotAuthorizer created = service.createAuthorizer("signed", request, REGION);
+
+ assertFalse(created.isSigningDisabled());
+ assertEquals("tok", created.getTokenKeyName());
+ assertEquals(Map.of("k1", rsaKey1 + "\n"), created.getTokenSigningPublicKeys());
+ assertEquals("ACTIVE", created.getStatus());
+ assertTrue(created.isEnableCachingForHttp());
+ }
+
+ /** The envelopes measured on AWS, which reads the PEM line by line. */
+ static Stream<Arguments> malformedPemEnvelopes() {
+ List<String> body = rsaKey1.lines().filter(line -> !line.startsWith("-----")).toList();
+ String base64 = String.join("", body);
+ String bodyLines = String.join("\n", body);
+ String notRsa = "Authorizer a public key for key name k1 not a valid RSA key";
+ return Stream.of(
+ Arguments.of("raw base64, no envelope", base64, notRsa),
+ Arguments.of("body lines, no envelope", bodyLines, notRsa),
+ Arguments.of("indented header line", "\n " + rsaKey1 + " \n", notRsa),
+ Arguments.of("envelope on one line", "-----BEGIN PUBLIC KEY-----" + base64 + "-----END PUBLIC KEY-----", notRsa),
+ Arguments.of("header without end line", "-----BEGIN PUBLIC KEY-----\n" + bodyLines,
+ "Cannot convert public key PEM for authorizer a to RSA key"));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("malformedPemEnvelopes")
+ void createRejectsAPemEnvelopeAwsCannotRead(String label, String pem, String message) {
+ assertInvalid(message, () -> service.createAuthorizer("a", signed(Map.of("k1", pem)), REGION));
+ }
+
+ @Test
+ void createSkipsTextBeforeThePemHeaderAndKeepsTheValueVerbatim() {
+ String pem = "junk\n" + rsaKey1;
+
+ IotAuthorizer created = service.createAuthorizer("prefixed", signed(Map.of("k1", pem)), REGION);
+
+ assertEquals(Map.of("k1", pem), created.getTokenSigningPublicKeys());
+ assertEquals(Map.of("k1", pem), service.describeAuthorizer("prefixed", REGION).getTokenSigningPublicKeys());
+ }
+
+ @Test
+ void createAcceptsSigningDisabledWithATokenKeyNameAndAnyWellFormedFunctionArn() {
+ ObjectNode request = unsigned().put("tokenKeyName", "tok")
+ .put("authorizerFunctionArn", "arn:aws:lambda:eu-west-1:111122223333:function:elsewhere");
+
+ assertEquals("tok", service.createAuthorizer("loose", request, REGION).getTokenKeyName());
+ }
+
+ @Test
+ void createRejectsAnInvalidSigningConfigurationWithTheAwsMessages() {
+ Map<ObjectNode, String> cases = new LinkedHashMap<>();
+ cases.put(mapper.createObjectNode().put("authorizerFunctionArn", FUNCTION_ARN),
+ "Token key name for authorizer a cannot be null");
+ cases.put(mapper.createObjectNode().put("authorizerFunctionArn", FUNCTION_ARN).put("tokenKeyName", "tok"),
+ "Token signing keys map for authorizer a cannot be null or empty. There must be at least one and at most two token signing public keys in the map");
+ cases.put(signed(Map.of("k1", rsaKey1)).put("tokenKeyName", (String) null),
+ "Token key name for authorizer a cannot be null");
+ cases.put(signed(Map.of("k1", rsaKey1)).put("signingDisabled", true),
+ "Token signing keys map must be null for authorizer a if using optional signature header");
+ cases.put(signed(Map.of("k1", rsaKey1, "k2", rsaKey2, "k3", rsaKey1)),
+ "Token signing keys map for authorizer a cannot contain more than 2 keys");
+ cases.put(signed(Map.of("k1", "")), "Token signing public keys for authorizer a cannot be null or empty");
+ cases.put(signed(Map.of("k1", "not-a-pem")), "Authorizer a public key for key name k1 not a valid RSA key");
+ cases.put(signed(Map.of("k1", ecKey)), "Authorizer a public key for key name k1 not a valid RSA key");
+ cases.put(signed(Map.of("k1", rsa1024Key)),
+ "Authorizer a public key for key name k1 invalid: Key must be 2048 bits but was 1024 bits");
+ cases.put(signed(Map.of("k1", privateKey)), "Cannot convert public key PEM for authorizer a to RSA key");
+
+ cases.forEach((request, message) -> assertInvalid(message, () -> service.createAuthorizer("a", request, REGION)));
+ assertAwsError("ResourceNotFoundException", 404, "Authorizer a not found",
+ () -> service.describeAuthorizer("a", REGION));
+ }
+
+ @Test
+ void createRejectsMalformedMembersWithTheAwsValidationMessages() {
+ String prefix = "1 validation error detected: Value at ";
+ assertInvalid(prefix + "'authorizerName' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\w=,@-]+",
+ () -> service.createAuthorizer("bad name!", unsigned(), REGION));
+ assertInvalid(prefix + "'authorizerName' failed to satisfy constraint: Member must have length less than or equal to 128",
+ () -> service.createAuthorizer("a".repeat(129), unsigned(), REGION));
+ assertInvalid(prefix + "'authorizerFunctionArn' failed to satisfy constraint: Member must not be null",
+ () -> service.createAuthorizer("a", unsigned().putNull("authorizerFunctionArn"), REGION));
+ assertInvalid(prefix + "'status' failed to satisfy constraint: Member must satisfy enum value set: [ACTIVE, INACTIVE]",
+ () -> service.createAuthorizer("a", unsigned().put("status", "BOGUS"), REGION));
+ assertInvalid(prefix + "'tokenKeyName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_-]+",
+ () -> service.createAuthorizer("a", unsigned().put("tokenKeyName", "bad name!"), REGION));
+ assertInvalid(prefix + "'tokenKeyName' failed to satisfy constraint: Member must have length less than or equal to 128",
+ () -> service.createAuthorizer("a", unsigned().put("tokenKeyName", "t".repeat(129)), REGION));
+ String nameConstraint = "Value at 'authorizerName' failed to satisfy constraint: ";
+ assertInvalid("2 validation errors detected: " + nameConstraint + "Member must satisfy regular expression pattern: [\\w=,@-]+; "
+ + nameConstraint + "Member must have length less than or equal to 128",
+ () -> service.createAuthorizer("!".repeat(129), unsigned(), REGION));
+ String tokenConstraint = "Value at 'tokenKeyName' failed to satisfy constraint: ";
+ assertInvalid("2 validation errors detected: " + tokenConstraint + "Member must satisfy regular expression pattern: [a-zA-Z0-9_-]+; "
+ + tokenConstraint + "Member must have length greater than or equal to 1",
+ () -> service.createAuthorizer("a", unsigned().put("tokenKeyName", ""), REGION));
+ assertInvalid("2 validation errors detected: " + tokenConstraint + "Member must satisfy regular expression pattern: [a-zA-Z0-9_-]+; "
+ + tokenConstraint + "Member must have length less than or equal to 128",
+ () -> service.createAuthorizer("a", unsigned().put("tokenKeyName", "!".repeat(129)), REGION));
+ assertInvalid(prefix + "'tokenSigningPublicKeys' failed to satisfy constraint: 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:_-]+]",
+ () -> service.createAuthorizer("a", signed(Map.of("bad key", rsaKey1)), REGION));
+ for (String arn : List.of("not-an-arn", "arn:aws:sqs:us-east-1:000000000000:queue")) {
+ assertInvalid("Lambda function arn for authorizer a is not in proper ARN syntax",
+ () -> service.createAuthorizer("a", unsigned().put("authorizerFunctionArn", arn), REGION));
+ }
+ }
+
+ @Test
+ void createRejectsADuplicateNameAndKeepsTheOriginal() {
+ Instant created = service.createAuthorizer("dup", unsigned(), REGION).getLastModifiedDate();
+
+ AwsException failure = assertAwsError("ResourceAlreadyExistsException", 409,
+ "Authorizer dup already exist for this account",
+ () -> service.createAuthorizer("dup", unsigned().put("status", "ACTIVE"), REGION));
+
+ assertEquals(Map.of("resourceId", "dup", "resourceArn", ARN_PREFIX + "dup"), failure.getExtendedData());
+ assertEquals("INACTIVE", service.describeAuthorizer("dup", REGION).getStatus());
+ assertEquals(created, service.describeAuthorizer("dup", REGION).getLastModifiedDate());
+ }
+
+ @Test
+ void missingAuthorizerIsNotFound() {
+ String message = "Authorizer missing not found";
+ assertAwsError("ResourceNotFoundException", 404, message, () -> service.describeAuthorizer("missing", REGION));
+ assertAwsError("ResourceNotFoundException", 404, message,
+ () -> service.updateAuthorizer("missing", mapper.createObjectNode(), REGION));
+ assertAwsError("ResourceNotFoundException", 404, message, () -> service.deleteAuthorizer("missing", REGION));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @ValueSource(strings = {"describe", "update", "delete"})
+ void pathOperationsValidateTheNameBeforeTheLookup(String operation) {
+ String constraint = "Value at 'authorizerName' failed to satisfy constraint: ";
+ String pattern = constraint + "Member must satisfy regular expression pattern: [\\w=,@-]+";
+ String tooLong = constraint + "Member must have length less than or equal to 128";
+
+ assertInvalid("1 validation error detected: " + pattern, byName(operation, "bad name!"));
+ assertInvalid("1 validation error detected: " + tooLong, byName(operation, "a".repeat(129)));
+ assertInvalid("2 validation errors detected: " + pattern + "; " + tooLong, byName(operation, "!".repeat(129)));
+ assertAwsError("ResourceNotFoundException", 404, "Authorizer absent not found", byName(operation, "absent"));
+ }
+
+ private Executable byName(String operation, String name) {
+ return switch (operation) {
+ case "describe" -> () -> service.describeAuthorizer(name, REGION);
+ case "update" -> () -> service.updateAuthorizer(name, mapper.createObjectNode().put("status", "INACTIVE"), REGION);
+ case "delete" -> () -> service.deleteAuthorizer(name, REGION);
+ default -> throw new IllegalArgumentException(operation);
+ };
+ }
+
+ @Test
+ void updateChangesOnlyTheFieldsSentAndBumpsLastModifiedDate() throws InterruptedException {
+ Instant created = service.createAuthorizer("upd", unsigned(), REGION).getLastModifiedDate();
+ Thread.sleep(5);
+
+ service.updateAuthorizer("upd", mapper.createObjectNode(), REGION);
+ assertEquals(created, service.describeAuthorizer("upd", REGION).getLastModifiedDate());
+
+ IotAuthorizer active = service.updateAuthorizer("upd", mapper.createObjectNode().put("status", "ACTIVE"), REGION);
+ assertEquals("ACTIVE", active.getStatus());
+ assertTrue(active.getLastModifiedDate().isAfter(created));
+ assertEquals(created, active.getCreationDate());
+
+ IotAuthorizer moved = service.updateAuthorizer("upd", mapper.createObjectNode()
+ .put("authorizerFunctionArn", FUNCTION_ARN + "2").put("enableCachingForHttp", true)
+ .put("tokenKeyName", "tok"), REGION);
+ assertEquals(FUNCTION_ARN + "2", moved.getAuthorizerFunctionArn());
+ assertTrue(moved.isEnableCachingForHttp());
+ assertEquals("tok", moved.getTokenKeyName());
+ assertEquals("ACTIVE", moved.getStatus());
+ assertTrue(moved.isSigningDisabled());
+ assertNull(moved.getTokenSigningPublicKeys());
+ }
+
+ @Test
+ void updateValidatesLikeCreateAndChangesNothingOnFailure() {
+ service.createAuthorizer("val", unsigned(), REGION);
+
+ assertInvalid("1 validation error detected: Value at 'status' failed to satisfy constraint: Member must satisfy enum value set: [ACTIVE, INACTIVE]",
+ () -> service.updateAuthorizer("val", mapper.createObjectNode().put("status", "BOGUS"), REGION));
+ assertInvalid("Lambda function arn for authorizer val is not in proper ARN syntax",
+ () -> service.updateAuthorizer("val", mapper.createObjectNode().put("authorizerFunctionArn", "nope"), REGION));
+ assertInvalid("Token signing keys map must be null for authorizer val if using optional signature header",
+ () -> service.updateAuthorizer("val", keysOnly(Map.of("k1", rsaKey1)), REGION));
+ assertEquals(FUNCTION_ARN, service.describeAuthorizer("val", REGION).getAuthorizerFunctionArn());
+ }
+
+ @Test
+ void updateMergesSigningKeysPerKeyNameAndRefusesAThird() throws InterruptedException {
+ service.createAuthorizer("merge", signed(Map.of("k1", rsaKey1)), REGION);
+
+ service.updateAuthorizer("merge", keysOnly(Map.of("k2", rsaKey2)), REGION);
+ assertEquals(Map.of("k1", rsaKey1, "k2", rsaKey2), service.describeAuthorizer("merge", REGION).getTokenSigningPublicKeys());
+
+ service.updateAuthorizer("merge", keysOnly(Map.of("k1", rsaKey2)), REGION);
+ assertEquals(Map.of("k1", rsaKey2, "k2", rsaKey2), service.describeAuthorizer("merge", REGION).getTokenSigningPublicKeys());
+
+ assertInvalid("Number of signing keys for authorizer merge must neither be zero nor greater than 2",
+ () -> service.updateAuthorizer("merge", keysOnly(Map.of("k3", rsaKey1)), REGION));
+ assertInvalid("Token signing keys map for authorizer merge cannot contain more than 2 keys",
+ () -> service.updateAuthorizer("merge", keysOnly(Map.of("k1", rsaKey1, "k2", rsaKey1, "k3", rsaKey1)), REGION));
+ assertInvalid("Authorizer merge public key for key name k1 not a valid RSA key",
+ () -> service.updateAuthorizer("merge", keysOnly(Map.of("k1", ecKey)), REGION));
+ assertEquals(Map.of("k1", rsaKey2, "k2", rsaKey2), service.describeAuthorizer("merge", REGION).getTokenSigningPublicKeys());
+
+ Instant before = service.describeAuthorizer("merge", REGION).getLastModifiedDate();
+ Thread.sleep(5);
+ IotAuthorizer emptied = service.updateAuthorizer("merge", keysOnly(Map.of()), REGION);
+ assertEquals(Map.of("k1", rsaKey2, "k2", rsaKey2), emptied.getTokenSigningPublicKeys());
+ assertTrue(emptied.getLastModifiedDate().isAfter(before));
+ }
+
+ @Test
+ void deleteRefusesAnActiveOrDefaultAuthorizerAndFreesTheName() {
+ service.createAuthorizer("del", unsigned().put("status", "ACTIVE"), REGION);
+ assertInvalid("Cannot delete authorizer del in ACTIVE status. Update status to INACTIVE and delete.",
+ () -> service.deleteAuthorizer("del", REGION));
+
+ service.setDefaultAuthorizer("del", REGION);
+ assertInvalid("Cannot delete authorizer del in ACTIVE status. Update status to INACTIVE and delete.",
+ () -> service.deleteAuthorizer("del", REGION));
+
+ service.updateAuthorizer("del", mapper.createObjectNode().put("status", "INACTIVE"), REGION);
+ assertAwsError("DeleteConflictException", 409,
+ "Cannot delete default authorizer del. Change default and retry delete.",
+ () -> service.deleteAuthorizer("del", REGION));
+
+ service.clearDefaultAuthorizer(REGION);
+ service.deleteAuthorizer("del", REGION);
+ assertAwsError("ResourceNotFoundException", 404, "Authorizer del not found",
+ () -> service.describeAuthorizer("del", REGION));
+ assertEquals("INACTIVE", service.createAuthorizer("del", unsigned(), REGION).getStatus());
+ }
+
+ @Test
+ void defaultAuthorizerIsSetReplacedDescribedAndCleared() {
+ String none = "Default authorizer not found";
+ assertAwsError("ResourceNotFoundException", 404, none, () -> service.describeDefaultAuthorizer(REGION));
+ assertAwsError("ResourceNotFoundException", 404, none, () -> service.clearDefaultAuthorizer(REGION));
+ assertAwsError("ResourceNotFoundException", 404, "Authorizer d1 not found",
+ () -> service.setDefaultAuthorizer("d1", REGION));
+ service.createAuthorizer("d1", unsigned(), REGION);
+ service.createAuthorizer("d2", unsigned(), REGION);
+
+ assertEquals(ARN_PREFIX + "d1", service.setDefaultAuthorizer("d1", REGION).getAuthorizerArn());
+ AwsException duplicate = assertAwsError("ResourceAlreadyExistsException", 409,
+ "Duplicate default authorizer d1 already configured for this account",
+ () -> service.setDefaultAuthorizer("d1", REGION));
+ assertEquals(Map.of("resourceId", "d1", "resourceArn", ARN_PREFIX + "d1"), duplicate.getExtendedData());
+
+ service.setDefaultAuthorizer("d2", REGION);
+ assertEquals("d2", service.describeDefaultAuthorizer(REGION).getAuthorizerName());
+ service.deleteAuthorizer("d1", REGION);
+
+ service.clearDefaultAuthorizer(REGION);
+ assertAwsError("ResourceNotFoundException", 404, none, () -> service.describeDefaultAuthorizer(REGION));
+ assertAwsError("ResourceNotFoundException", 404, none, () -> service.describeDefaultAuthorizer("eu-west-1"));
+ }
+
+ @Test
+ void setDefaultValidatesTheNameBeforeTheLookupAndKeepsTheDefault() {
+ service.createAuthorizer("keep", unsigned(), REGION);
+ service.setDefaultAuthorizer("keep", REGION);
+ String constraint = "Value at 'authorizerName' failed to satisfy constraint: ";
+ String pattern = constraint + "Member must satisfy regular expression pattern: [\\w=,@-]+";
+ String tooLong = constraint + "Member must have length less than or equal to 128";
+
+ assertInvalid("1 validation error detected: " + constraint + "Member must not be null",
+ () -> service.setDefaultAuthorizer(null, REGION));
+ assertInvalid("2 validation errors detected: " + pattern + "; " + constraint + "Member must have length greater than or equal to 1",
+ () -> service.setDefaultAuthorizer("", REGION));
+ assertInvalid("1 validation error detected: " + pattern, () -> service.setDefaultAuthorizer("bad name!", REGION));
+ assertInvalid("1 validation error detected: " + tooLong, () -> service.setDefaultAuthorizer("a".repeat(129), REGION));
+ assertInvalid("2 validation errors detected: " + pattern + "; " + tooLong,
+ () -> service.setDefaultAuthorizer("!".repeat(129), REGION));
+ assertAwsError("ResourceNotFoundException", 404, "Authorizer absent not found",
+ () -> service.setDefaultAuthorizer("absent", REGION));
+
+ assertEquals("keep", service.describeDefaultAuthorizer(REGION).getAuthorizerName());
+ }
+
+ @Test
+ void listOrdersByCreationFiltersByStatusAndPages() throws InterruptedException {
+ for (String name : List.of("l2", "l3", "l1")) {
+ service.createAuthorizer(name, unsigned(), REGION);
+ Thread.sleep(2);
+ }
+ service.updateAuthorizer("l3", mapper.createObjectNode().put("status", "ACTIVE"), REGION);
+ service.createAuthorizer("elsewhere", unsigned(), "eu-west-1");
+
+ assertEquals(List.of("l1", "l3", "l2"), names(service.listAuthorizers(REGION, null, false, null, null)));
+ assertEquals(List.of("l2", "l3", "l1"), names(service.listAuthorizers(REGION, null, true, null, null)));
+ assertEquals(List.of("l3"), names(service.listAuthorizers(REGION, "ACTIVE", false, null, null)));
+ assertEquals(List.of("l1", "l2"), names(service.listAuthorizers(REGION, "INACTIVE", false, null, null)));
+
+ IotService.Page<IotAuthorizer> first = service.listAuthorizers(REGION, null, false, null, 2);
+ assertEquals(List.of("l1", "l3"), names(first));
+ IotService.Page<IotAuthorizer> last = service.listAuthorizers(REGION, null, false, first.nextToken(), 2);
+ assertEquals(List.of("l2"), names(last));
+ assertNull(last.nextToken());
+ }
+
+ @Test
+ void listRejectsAnInvalidPageSizeStatusOrMarker() {
+ String prefix = "1 validation error detected: Value at ";
+ assertInvalid(prefix + "'pageSize' failed to satisfy constraint: Member must have value greater than or equal to 1",
+ () -> service.listAuthorizers(REGION, null, false, null, 0));
+ assertInvalid(prefix + "'pageSize' failed to satisfy constraint: Member must have value less than or equal to 250",
+ () -> service.listAuthorizers(REGION, null, false, null, 251));
+ assertInvalid(prefix + "'status' failed to satisfy constraint: Member must satisfy enum value set: [ACTIVE, INACTIVE]",
+ () -> service.listAuthorizers(REGION, "BOGUS", false, null, null));
+ assertInvalid("Invalid/Malformed marker passed for listAuthorizers",
+ () -> service.listAuthorizers(REGION, null, false, "garbage", null));
+ assertTrue(service.listAuthorizers(REGION, null, false, null, 250).items().isEmpty());
+ }
+
+ @Test
+ void tagsAreSetAtCreateChangedByArnAndRefusedOnAMissingAuthorizer() {
+ ObjectNode request = unsigned();
+ request.putArray("tags").addObject().put("Key", "env").put("Value", "dev");
+ String arn = service.createAuthorizer("tags", request, REGION).getAuthorizerArn();
+ assertEquals(Map.of("env", "dev"), service.listTagsForResource(arn));
+
+ service.tagResource(arn, Map.of("env", "prod", "team", "a"));
+ service.untagResource(arn, List.of("team", "absent"));
+ assertEquals(Map.of("env", "prod"), service.listTagsForResource(arn));
+
+ String missing = ARN_PREFIX + "gone";
+ assertEquals(Map.of(), service.listTagsForResource(missing));
+ assertAwsError("ResourceNotFoundException", 404, "Authorizer gone not found",
+ () -> service.tagResource(missing, Map.of("k", "v")));
+ assertAwsError("ResourceNotFoundException", 404, "Authorizer gone not found",
+ () -> service.untagResource(missing, List.of("k")));
+ }
+
+ @Test
+ void tagOperationsDoNotResolveASameNamedArnFromAnotherAccount() {
+ ObjectNode request = unsigned();
+ request.putArray("tags").addObject().put("Key", "env").put("Value", "dev");
+ service.createAuthorizer("shared", request, REGION);
+ String foreign = "arn:aws:iot:us-east-1:111122223333:authorizer/shared";
+
+ assertEquals(Map.of(), service.listTagsForResource(foreign));
+ assertAwsError("ResourceNotFoundException", 404, "Authorizer shared not found",
+ () -> service.tagResource(foreign, Map.of("k", "v")));
+ assertEquals(Map.of("env", "dev"), service.listTagsForResource(ARN_PREFIX + "shared"));
+ }
+
+ @Test
+ void authorizerSurvivesTheJsonRoundTripPersistentStorageUses() throws Exception {
+ ObjectNode request = signed(Map.of("k1", rsaKey1));
+ request.putArray("tags").addObject().put("Key", "env").put("Value", "dev");
+ service.createAuthorizer("persisted", request, REGION);
+ IotAuthorizer created = service.setDefaultAuthorizer("persisted", REGION);
+
+ // The same mapper setup PersistentStorage uses: defaults plus java.time.
+ ObjectMapper persistence = new ObjectMapper().registerModule(new JavaTimeModule());
+ String json = persistence.writeValueAsString(created);
+ IotAuthorizer reloaded = persistence.readValue(json, IotAuthorizer.class);
+
+ assertEquals(json, persistence.writeValueAsString(reloaded));
+ assertTrue(reloaded.isDefaultAuthorizer());
+ assertEquals(created.getCreationDate(), reloaded.getCreationDate());
+ assertEquals(created.getTokenSigningPublicKeys(), reloaded.getTokenSigningPublicKeys());
+ assertEquals(created.getTags(), reloaded.getTags());
+ }
+}