feat(iot): add RegisterCertificateWithoutCA and the V2 principal lists (#5772)

* feat(iot): add RegisterCertificateWithoutCA and the V2 principal lists

RegisterCertificateWithoutCA registers a certificate from any issuer in
SNI_ONLY mode. ListThingPrincipalsV2 and ListPrincipalThingsV2 page the
thing principal attachments and report each one as NON_EXCLUSIVE_THING,
because Floci does not model exclusive attachment.

* fix(iot): validate the principal and page size of the V2 principal lists

ListPrincipalThingsV2 requires a principal, and both V2 lists accept 1 to
250 results per page, as on AWS. Tests cover these checks and the
RegisterCertificateWithoutCA rejection of a missing PEM and an unknown
status.

* fix(iot): refuse a device certificate registered in more than one account

AWS selects the account from the server name, which Floci does not do
yet. The MQTT TLS listener therefore refuses a certificate that more
than one account registers, instead of admitting it under the lowest
account ID. RegisterCertificateWithoutCA drops the cached location, and
the lookup runs under compute, so a connect cannot cache a stale account.

* fix(iot): make the RegisterCertificateWithoutCA duplicate check atomic

A lock holds the duplicate check and the store write together, as
CreateAuthorizer does, so two identical registrations at the same moment
store one certificate and the other caller gets the 409. The 409 carries
resourceId and resourceArn, as AWS lists for this call.
This commit is contained in:
Joel Klint authored and GitHub committed 2026-10-18 14:50:15 -04:00
1 parent 4204ee2ea5
commit e3e06a1122
9 files changed
+447 -15

No files matched your search

@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.iot;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.quarkus.test.junit.QuarkusTest;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
@@ -9,13 +11,18 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -798,6 +805,166 @@ class IotIntegrationTest {
.body("policyVersionId", equalTo("6"));
}
@Test
@Order(21)
void registerCertificateWithoutCaTrustsAnyIssuer() {
String certificatePem = new CertificateGenerator()
.generateSelfSignedCertificate("no-ca-device", List.of(), KeyAlgorithm.RSA_2048)
.certificatePem();
Map<String, String> registered = given()
.contentType("application/json")
.body(Map.of("certificatePem", certificatePem, "status", "ACTIVE"))
.when()
.post("/certificate/register-no-ca")
.then()
.statusCode(200)
.body("certificateId", matchesPattern("[0-9a-f]{64}"))
.body("certificateArn", containsString(":iot:us-east-1:000000000000:cert/"))
.extract()
.path("");
String certificateId = registered.get("certificateId");
given()
.when()
.get("/certificates/" + certificateId)
.then()
.statusCode(200)
.body("certificateDescription.status", equalTo("ACTIVE"))
.body("certificateDescription.certificateMode", equalTo("SNI_ONLY"))
.body("certificateDescription.certificatePem", equalTo(certificatePem));
given()
.when()
.get("/certificates")
.then()
.statusCode(200)
.body("certificates.find { it.certificateId == '" + certificateId + "' }.certificateMode", equalTo("SNI_ONLY"));
given()
.contentType("application/json")
.body(Map.of("certificatePem", certificatePem))
.when()
.post("/certificate/register-no-ca")
.then()
.statusCode(409)
.body("__type", equalTo("ResourceAlreadyExistsException"))
.body("resourceId", equalTo(certificateId))
.body("resourceArn", equalTo(registered.get("certificateArn")));
given()
.contentType("application/json")
.body(Map.of("certificatePem", "not a certificate"))
.when()
.post("/certificate/register-no-ca")
.then()
.statusCode(400)
.body("__type", equalTo("CertificateValidationException"));
given()
.contentType("application/json")
.body("{}")
.when()
.post("/certificate/register-no-ca")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
given()
.contentType("application/json")
.body(Map.of("certificatePem", certificatePem, "status", "UNKNOWN"))
.when()
.post("/certificate/register-no-ca")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
@Test
@Order(22)
void principalListsV2ReportTheAttachmentType() {
String certificateArn = given()
.queryParam("setAsActive", true)
.when()
.post("/keys-and-certificate")
.then()
.statusCode(200)
.extract()
.path("certificateArn");
createThingAndReturnArn("v2-principal-thing-a");
createThingAndReturnArn("v2-principal-thing-b");
for (String thingName : List.of("v2-principal-thing-a", "v2-principal-thing-b")) {
given()
.queryParam("principal", certificateArn)
.when()
.put("/things/" + thingName + "/principals")
.then()
.statusCode(200);
}
given()
.when()
.get("/things/v2-principal-thing-a/principals-v2")
.then()
.statusCode(200)
.body("thingPrincipalObjects.principal", equalTo(List.of(certificateArn)))
.body("thingPrincipalObjects.thingPrincipalType", equalTo(List.of("NON_EXCLUSIVE_THING")));
given()
.header("x-amzn-principal", certificateArn)
.queryParam("maxResults", 1)
.when()
.get("/principals/things-v2")
.then()
.statusCode(200)
.body("principalThingObjects.thingName", equalTo(List.of("v2-principal-thing-a")))
.body("principalThingObjects.thingPrincipalType", equalTo(List.of("NON_EXCLUSIVE_THING")))
.body("nextToken", equalTo("1"));
given()
.header("x-amzn-principal", certificateArn)
.queryParam("nextToken", "1")
.when()
.get("/principals/things-v2")
.then()
.statusCode(200)
.body("principalThingObjects.thingName", equalTo(List.of("v2-principal-thing-b")))
.body("nextToken", nullValue());
given()
.header("x-amzn-principal", certificateArn)
.queryParam("thingPrincipalType", "EXCLUSIVE_THING")
.when()
.get("/principals/things-v2")
.then()
.statusCode(200)
.body("principalThingObjects", empty());
given()
.when()
.get("/principals/things-v2")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
given()
.header("x-amzn-principal", certificateArn)
.queryParam("maxResults", 0)
.when()
.get("/principals/things-v2")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
given()
.queryParam("maxResults", 251)
.when()
.get("/things/v2-principal-thing-a/principals-v2")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
private String createThingAndReturnArn(String thingName) {
return given()
.contentType("application/json")
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.iot.IotService.RegisteredDevice;
import io.github.hectorvent.floci.services.iot.model.IotCertificate;
import io.github.hectorvent.floci.services.iot.model.IotPolicy;
@@ -94,6 +96,37 @@ class IotServiceDeviceAuthTest {
assertEquals(created.getCertificateId(), device.certificate().getCertificateId());
}
@Test
void aCertificateRegisteredInTwoAccountsIsRefused() {
IotCertificate registered = service.registerCertificateWithoutCa(selfSignedPem(), "ACTIVE", REGION);
support.certificates.putForAccount(OTHER_ACCOUNT, "cert:" + REGION + ":" + registered.getCertificateId(),
service.describeCertificate(registered.getCertificateId(), REGION));
assertTrue(service.findRegisteredCertificate(parse(registered)).isEmpty());
}
@Test
void aSecondAccountRegisteringAKnownDeviceRefusesItsNextConnect() {
String pem = selfSignedPem();
IotCertificate elsewhere = service.registerCertificateWithoutCa(pem, "ACTIVE", "eu-west-1");
support.certificates.delete("cert:eu-west-1:" + elsewhere.getCertificateId());
support.certificates.putForAccount(OTHER_ACCOUNT, "cert:eu-west-1:" + elsewhere.getCertificateId(), elsewhere);
assertEquals(OTHER_ACCOUNT, service.findRegisteredCertificate(parse(elsewhere)).orElseThrow().accountId());
service.registerCertificateWithoutCa(pem, "ACTIVE", REGION);
assertTrue(service.findRegisteredCertificate(parse(elsewhere)).isEmpty());
}
@Test
void aCertificateRegisteredInTwoRegionsOfOneAccountIsFound() {
String pem = selfSignedPem();
service.registerCertificateWithoutCa(pem, "ACTIVE", "eu-west-1");
IotCertificate registered = service.registerCertificateWithoutCa(pem, "ACTIVE", REGION);
assertEquals(ACCOUNT, service.findRegisteredCertificate(parse(registered)).orElseThrow().accountId());
}
@Test
void plainStoresWithoutAccountPartitionsWorkTheSameWay() {
IotService plain = new IotServiceTestSupport(REGION, ca, false).service;
@@ -477,6 +510,12 @@ class IotServiceDeviceAuthTest {
return service.isConnectAllowed(device, clientId, "127.0.0.1", null);
}
private static String selfSignedPem() {
return new CertificateGenerator()
.generateSelfSignedCertificate("device", List.of(), KeyAlgorithm.RSA_2048)
.certificatePem();
}
private static X509Certificate parse(IotCertificate certificate) {
return Pem.parseCertificate(certificate.getCertificatePem());
}
@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbItemAccess;
@@ -67,8 +69,9 @@ import static org.mockito.Mockito.when;
* Rules engine behaviour of {@link IotService} with in-memory stores and mocked action targets:
* one failing action never fails the publish or the other actions, the error action receives the
* failure document, and the {@code firehose} and {@code cloudwatchLogs} actions deliver the payload.
* Also the five-version cap on a policy, including under racing creates, and the device shadow
* events that reach MQTT subscribers and topic rules on the AWS response topics.
* Also the five-version cap on a policy, including under racing creates, the device shadow
* events that reach MQTT subscribers and topic rules on the AWS response topics, and one stored
* registration when identical RegisterCertificateWithoutCA calls race.
*/
class IotServiceTest {
@@ -587,6 +590,43 @@ class IotServiceTest {
assertEquals("6", service.getPolicy("capped", REGION).getDefaultVersionId());
}
@Test
void racingIdenticalRegistrationsStoreOneCertificateAndRejectTheRest() throws Exception {
String pem = new CertificateGenerator()
.generateSelfSignedCertificate("raced-device", List.of(), KeyAlgorithm.RSA_2048)
.certificatePem();
int writers = 8;
CountDownLatch start = new CountDownLatch(1);
ExecutorService pool = Executors.newFixedThreadPool(writers);
List<Future<Boolean>> outcomes = new ArrayList<>();
try {
for (int i = 0; i < writers; i++) {
outcomes.add(pool.submit(() -> {
start.await();
try {
service.registerCertificateWithoutCa(pem, "ACTIVE", REGION);
return true;
} catch (AwsException e) {
assertEquals("ResourceAlreadyExistsException", e.getErrorCode());
return false;
}
}));
}
start.countDown();
int registered = 0;
for (Future<Boolean> outcome : outcomes) {
if (outcome.get()) {
registered++;
}
}
assertEquals(1, registered);
assertEquals(1, service.listCertificates(REGION).size());
assertEquals("SNI_ONLY", service.listCertificates(REGION).getFirst().getCertificateMode());
} finally {
pool.shutdownNow();
}
}
@Test
void racingVersionCreatesNeverPushAPolicyPastFiveVersions() throws Exception {
service.createPolicy("raced", "{\"v\":1}", REGION);