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

@@ -318,10 +318,44 @@ func TestIoT(t *testing.T) {
principals, err := svc.ListThingPrincipals(ctx, &iot.ListThingPrincipalsInput{ThingName: aws.String(thingName)})
require.NoError(t, err)
assert.Contains(t, principals.Principals, certArn)
principalsV2, err := svc.ListThingPrincipalsV2(ctx, &iot.ListThingPrincipalsV2Input{ThingName: aws.String(thingName)})
require.NoError(t, err)
require.Len(t, principalsV2.ThingPrincipalObjects, 1)
assert.Equal(t, certArn, aws.ToString(principalsV2.ThingPrincipalObjects[0].Principal))
assert.Equal(t, iottypes.ThingPrincipalTypeNonExclusiveThing, principalsV2.ThingPrincipalObjects[0].ThingPrincipalType)
thingsV2, err := svc.ListPrincipalThingsV2(ctx, &iot.ListPrincipalThingsV2Input{Principal: aws.String(certArn)})
require.NoError(t, err)
require.Len(t, thingsV2.PrincipalThingObjects, 1)
assert.Equal(t, thingName, aws.ToString(thingsV2.PrincipalThingObjects[0].ThingName))
assert.Equal(t, iottypes.ThingPrincipalTypeNonExclusiveThing, thingsV2.PrincipalThingObjects[0].ThingPrincipalType)
_, err = svc.DetachThingPrincipal(ctx, &iot.DetachThingPrincipalInput{ThingName: aws.String(thingName), Principal: aws.String(certArn)})
require.NoError(t, err)
})
t.Run("RegisterCertificateWithoutCA", func(t *testing.T) {
certPEM, _ := generateSelfSignedCert()
registered, err := svc.RegisterCertificateWithoutCA(ctx, &iot.RegisterCertificateWithoutCAInput{
CertificatePem: aws.String(string(certPEM)),
Status: iottypes.CertificateStatusActive,
})
require.NoError(t, err)
described, err := svc.DescribeCertificate(ctx, &iot.DescribeCertificateInput{CertificateId: registered.CertificateId})
require.NoError(t, err)
assert.Equal(t, iottypes.CertificateStatusActive, described.CertificateDescription.Status)
assert.Equal(t, iottypes.CertificateModeSniOnly, described.CertificateDescription.CertificateMode)
_, err = svc.RegisterCertificateWithoutCA(ctx, &iot.RegisterCertificateWithoutCAInput{CertificatePem: aws.String(string(certPEM))})
var exists *iottypes.ResourceAlreadyExistsException
require.ErrorAs(t, err, &exists)
assert.Equal(t, aws.ToString(registered.CertificateId), aws.ToString(exists.ResourceId))
assert.Equal(t, aws.ToString(registered.CertificateArn), aws.ToString(exists.ResourceArn))
_, err = svc.UpdateCertificate(ctx, &iot.UpdateCertificateInput{CertificateId: registered.CertificateId, NewStatus: iottypes.CertificateStatusInactive})
require.NoError(t, err)
_, err = svc.DeleteCertificate(ctx, &iot.DeleteCertificateInput{CertificateId: registered.CertificateId})
require.NoError(t, err)
})
t.Run("IoTDataShadowsAndPublish", func(t *testing.T) {
dataSvc := testutil.IoTDataClient()
thingName := "go-iot-shadow-thing"
+1 -1
View File
@@ -143,7 +143,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 | 75 |
| [IoT Core](iot.md) | `/things/...`, `/endpoint`, rules/policies REST paths | REST JSON | 78 |
| [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.
+3 -3
View File
@@ -9,9 +9,9 @@ Status: complete for the local emulator slice.
Supported MVP 1 behavior:
- Thing CRUD with idempotent identical `CreateThing`, duplicate-conflict semantics, `UpdateThing.expectedVersion`, and list pagination.
- Certificate basics: `CreateKeysAndCertificate`, `CreateCertificateFromCsr`, `DescribeCertificate`, `ListCertificates`, `UpdateCertificate`, and `DeleteCertificate` with active/attached delete constraints. `CreateKeysAndCertificate` returns a real X.509 client certificate issued by Floci's local CA (`GET /_floci/ca.pem`) with a fresh RSA 2048 key pair, valid until 2049-12-31T23:59:59Z as on AWS, and `certificateId` is the SHA-256 of the certificate's DER encoding as on AWS. `DescribeCertificate` reports `validity` and `certificateMode`. `CreateCertificateFromCsr` signs the request's public key (RSA of at least 2048 bits, or EC on P-256, P-384 or P-521) with the same CA and, as on AWS, returns no private key.
- Certificate basics: `CreateKeysAndCertificate`, `CreateCertificateFromCsr`, `DescribeCertificate`, `ListCertificates`, `UpdateCertificate`, and `DeleteCertificate` with active/attached delete constraints. `CreateKeysAndCertificate` returns a real X.509 client certificate issued by Floci's local CA (`GET /_floci/ca.pem`) with a fresh RSA 2048 key pair, valid until 2049-12-31T23:59:59Z as on AWS, and `certificateId` is the SHA-256 of the certificate's DER encoding as on AWS. `DescribeCertificate` reports `validity` and `certificateMode`. `CreateCertificateFromCsr` signs the request's public key (RSA of at least 2048 bits, or EC on P-256, P-384 or P-521) with the same CA and, as on AWS, returns no private key. `RegisterCertificateWithoutCA` registers a certificate from any issuer, as on AWS: no CA is checked, the status defaults to `INACTIVE`, `DescribeCertificate` reports `certificateMode` `SNI_ONLY`, a certificate already registered is `ResourceAlreadyExistsException`, and a PEM that does not parse is `CertificateValidationException`.
- Policy basics: `CreatePolicy`, `GetPolicy`, `ListPolicies`, `DeletePolicy`, policy version lifecycle, `AttachPolicy`, `DetachPolicy`, `ListAttachedPolicies`, and `ListTargetsForPolicy`.
- Thing principal basics: `AttachThingPrincipal`, `DetachThingPrincipal`, `ListThingPrincipals`, and `ListPrincipalThings`.
- Thing principal basics: `AttachThingPrincipal`, `DetachThingPrincipal`, `ListThingPrincipals`, `ListPrincipalThings`, and the paginated `ListThingPrincipalsV2` and `ListPrincipalThingsV2`. Exclusive attachment is not modelled, so the V2 lists report every attachment as `NON_EXCLUSIVE_THING`, and a `thingPrincipalType` filter of `EXCLUSIVE_THING` returns none.
- Tags for things, certificates, policies, and topic rules.
- IoT Data retained messages: retained `Publish`, `GetRetainedMessage`, and paginated `ListRetainedMessages`.
- Shadow null-delete and version-conflict behavior for HTTP and shared service paths.
@@ -199,7 +199,7 @@ mosquitto_sub -h localhost -p 8883 --cafile ca.pem --cert device.crt --key devic
The connection is admitted when all of these hold, otherwise the broker answers `CONNACK` not authorized (return code `5`, reason code `0x87` on MQTT 5) and closes the connection:
1. A certificate was presented and the SHA-256 of its DER encoding is a registered `certificateId` (`CreateKeysAndCertificate` or `CreateCertificateFromCsr`), in any account and region. Who signed it does not matter, registration does, as on AWS.
1. A certificate was presented and the SHA-256 of its DER encoding is a registered `certificateId` (`CreateKeysAndCertificate`, `CreateCertificateFromCsr` or `RegisterCertificateWithoutCA`), in any account and region. Who signed it does not matter, registration does, as on AWS. AWS selects the account from the server name, which Floci does not yet do, so a certificate registered in more than one account is refused. Within one account, the registration in the alphabetically first region is used.
2. The certificate is `ACTIVE` and inside its validity dates.
3. The default versions of the policies attached to the certificate (`AttachPolicy` with the certificate ARN as target, in the certificate's own account and region) allow `iot:Connect` on `arn:aws:iot:<region>:<account>:client/<clientId>`. No attached policy means deny, and an explicit `Deny` wins.
@@ -179,6 +179,23 @@ public class IotController {
}
}
@POST
@Path("/certificate/register-no-ca")
public Response registerCertificateWithoutCa(@Context HttpHeaders headers, String body) {
try {
JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
IotCertificate certificate = iotService.registerCertificateWithoutCa(
request.path("certificatePem").asText(null), request.path("status").asText(null),
regionResolver.resolveRegion(headers));
ObjectNode response = objectMapper.createObjectNode();
response.put("certificateArn", certificate.getCertificateArn());
response.put("certificateId", certificate.getCertificateId());
return Response.ok(response).build();
} catch (JsonProcessingException e) {
throw new AwsException("InvalidRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/certificates/{certificateId}")
public Response describeCertificate(@Context HttpHeaders headers,
@@ -199,6 +216,7 @@ public class IotController {
item.put("certificateArn", certificate.getCertificateArn());
item.put("certificateId", certificate.getCertificateId());
item.put("status", certificate.getStatus());
item.put("certificateMode", certificateMode(certificate));
putEpoch(item, "creationDate", certificate.getCreationDate());
}
return Response.ok(response).build();
@@ -449,6 +467,30 @@ public class IotController {
return Response.ok(response).build();
}
@GET
@Path("/things/{thingName}/principals-v2")
public Response listThingPrincipalsV2(@Context HttpHeaders headers,
@PathParam("thingName") String thingName,
@QueryParam("thingPrincipalType") String thingPrincipalType,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
return Response.ok(buildThingPrincipalPage(iotService.listThingPrincipalsV2(
thingName, thingPrincipalType, regionResolver.resolveRegion(headers), maxResults, nextToken),
"thingPrincipalObjects", "principal")).build();
}
@GET
@Path("/principals/things-v2")
public Response listPrincipalThingsV2(@Context HttpHeaders headers,
@HeaderParam("x-amzn-principal") String principal,
@QueryParam("thingPrincipalType") String thingPrincipalType,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
return Response.ok(buildThingPrincipalPage(iotService.listPrincipalThingsV2(
principal, thingPrincipalType, regionResolver.resolveRegion(headers), maxResults, nextToken),
"principalThingObjects", "thingName")).build();
}
@POST
@Path("/thing-types/{thingTypeName}")
public Response createThingType(@Context HttpHeaders headers,
@@ -939,13 +981,32 @@ public class IotController {
return response;
}
private ObjectNode buildThingPrincipalPage(IotService.Page<String> page, String arrayName, String itemField) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode objects = response.putArray(arrayName);
for (String item : page.items()) {
objects.addObject()
.put(itemField, item)
.put("thingPrincipalType", IotService.NON_EXCLUSIVE_THING);
}
if (page.nextToken() != null) {
response.put("nextToken", page.nextToken());
}
return response;
}
/** Records stored before the mode was kept are {@code DEFAULT}, as every certificate then was. */
private static String certificateMode(IotCertificate certificate) {
return certificate.getCertificateMode() != null ? certificate.getCertificateMode() : "DEFAULT";
}
private ObjectNode buildCertificateDescription(IotCertificate certificate) {
ObjectNode description = objectMapper.createObjectNode();
description.put("certificateArn", certificate.getCertificateArn());
description.put("certificateId", certificate.getCertificateId());
description.put("certificatePem", certificate.getCertificatePem());
description.put("status", certificate.getStatus());
description.put("certificateMode", "DEFAULT");
description.put("certificateMode", certificateMode(certificate));
putEpoch(description, "creationDate", certificate.getCreationDate());
if (certificate.getNotBefore() != null && certificate.getNotAfter() != null) {
ObjectNode validity = description.putObject("validity");
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.CertificateMaterialException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -79,6 +80,9 @@ public class IotService {
private static final Logger LOG = Logger.getLogger(IotService.class);
public static final String NON_EXCLUSIVE_THING = "NON_EXCLUSIVE_THING";
private static final String EXCLUSIVE_THING = "EXCLUSIVE_THING";
static final String DEFAULT_ENDPOINT_TYPE = "iot:Data-ATS";
private static final Pattern THING_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
@@ -89,6 +93,8 @@ public class IotService {
/** One lock for every policy version write and the policy delete, so a cap check, an append and a delete cannot interleave. */
private final Object policyWriteLock = new Object();
/** Makes the duplicate check and the store write of RegisterCertificateWithoutCA one step. */
private final Object certificateRegistrationLock = new Object();
/** One lock for every shadow update and delete, so a shadow's previous, current and version stay consistent. */
private final Object shadowWriteLock = new Object();
@@ -350,6 +356,39 @@ public class IotService {
return certificate;
}
/** As on AWS, the certificate is trusted because it is registered: no CA is checked, and its mode is {@code SNI_ONLY}. */
public IotCertificate registerCertificateWithoutCa(String certificatePem, String status, String region) {
startMqttIfEnabled();
if (certificatePem == null || certificatePem.isBlank()) {
throw new AwsException("InvalidRequestException", "certificatePem is required", 400);
}
String effectiveStatus = status == null ? "INACTIVE" : status;
validateCertificateStatus(effectiveStatus);
IotCertificate certificate = new IotCertificate();
try {
fill(certificate, Pem.parseCertificate(certificatePem));
} catch (CertificateMaterialException e) {
throw new AwsException("CertificateValidationException", e.getMessage(), 400);
} catch (Exception e) {
throw new AwsException("InternalFailureException", "Could not read device certificate: " + e.getMessage(), 500);
}
String key = certificateKey(region, certificate.getCertificateId());
certificate.setCertificateArn(regionResolver.buildArn("iot", region, "cert/" + certificate.getCertificateId()));
certificate.setStatus(effectiveStatus);
certificate.setCertificateMode("SNI_ONLY");
certificate.setCreationDate(Instant.now());
synchronized (certificateRegistrationLock) {
if (certificateStore.get(key).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException", "Certificate already exists: " + certificate.getCertificateId(), 409,
Map.of("resourceId", certificate.getCertificateId(), "resourceArn", certificate.getCertificateArn()));
}
certificateStore.put(key, certificate);
}
// A device that connected before may now be registered in a second account.
certificateLocations.remove(certificate.getCertificateId());
return certificate;
}
/** As on AWS, the private key is returned once and never kept: the stored record has none. */
private static IotCertificate withoutPrivateKey(IotCertificate certificate) {
IotCertificate stored = new IotCertificate();
@@ -358,6 +397,7 @@ public class IotService {
stored.setCertificatePem(certificate.getCertificatePem());
stored.setPublicKey(certificate.getPublicKey());
stored.setStatus(certificate.getStatus());
stored.setCertificateMode(certificate.getCertificateMode());
stored.setCreationDate(certificate.getCreationDate());
stored.setNotBefore(certificate.getNotBefore());
stored.setNotAfter(certificate.getNotAfter());
@@ -449,7 +489,8 @@ public class IotService {
* across every account partition: a connecting device carries no request context. The
* partition and key a certificate was found under are remembered, so a device's next connect
* is one keyed read; a remembered location that no longer resolves is dropped and the scan
* runs again.
* runs again. AWS picks the account from the server name; Floci cannot yet, so a certificate
* registered in more than one account is refused rather than admitted under one of them.
*/
public Optional<RegisteredDevice> findRegisteredCertificate(X509Certificate presented) {
String certificateId;
@@ -467,14 +508,28 @@ public class IotService {
}
certificateLocations.remove(certificateId, known);
}
// compute serializes this scan with the remove in registerCertificateWithoutCa, so a
// registration in a second account cannot leave a stale location cached.
CertificateLocation location = certificateLocations.compute(certificateId, (id, stale) -> locateRegistration(id));
if (location == null) {
return Optional.empty();
}
return getForAccount(certificateStore, location.accountId(), location.key())
.map(certificate -> new RegisteredDevice(location.accountId(), regionOfCertificateKey(location.key()), certificate));
}
private CertificateLocation locateRegistration(String certificateId) {
String suffix = ":" + certificateId;
Optional<AccountAwareStorageBackend.AccountEntry<IotCertificate>> found =
registeredCertificates(key -> key.startsWith("cert:") && key.endsWith(suffix)).stream()
.sorted(Comparator.comparing((AccountAwareStorageBackend.AccountEntry<IotCertificate> entry) -> entry.accountId())
.thenComparing(AccountAwareStorageBackend.AccountEntry::key))
.findFirst();
found.ifPresent(entry -> certificateLocations.put(certificateId, new CertificateLocation(entry.accountId(), entry.key())));
return found.map(entry -> new RegisteredDevice(entry.accountId(), regionOfCertificateKey(entry.key()), entry.value()));
List<AccountAwareStorageBackend.AccountEntry<IotCertificate>> registrations =
registeredCertificates(key -> key.startsWith("cert:") && key.endsWith(suffix));
if (registrations.stream().map(AccountAwareStorageBackend.AccountEntry::accountId).distinct().count() > 1) {
LOG.debugv("Refusing device certificate {0}: it is registered in more than one account", certificateId);
return null;
}
return registrations.stream()
.min(Comparator.comparing(AccountAwareStorageBackend.AccountEntry::key))
.map(entry -> new CertificateLocation(entry.accountId(), entry.key()))
.orElse(null);
}
private static String regionOfCertificateKey(String key) {
@@ -784,6 +839,39 @@ public class IotService {
return things;
}
public Page<String> listThingPrincipalsV2(String thingName, String thingPrincipalType, String region,
Integer maxResults, String nextToken) {
validateV2PageSize(maxResults);
return paginate(ofThingPrincipalType(thingPrincipalType, listThingPrincipals(thingName, region)), maxResults, nextToken);
}
public Page<String> listPrincipalThingsV2(String principal, String thingPrincipalType, String region,
Integer maxResults, String nextToken) {
if (principal == null || principal.isBlank()) {
throw new AwsException("InvalidRequestException", "Principal is required", 400);
}
validateV2PageSize(maxResults);
return paginate(ofThingPrincipalType(thingPrincipalType, listPrincipalThings(principal, region)), maxResults, nextToken);
}
/** The V2 principal lists accept 1 to 250 results per page, as on AWS. */
private static void validateV2PageSize(Integer maxResults) {
if (maxResults != null && (maxResults < 1 || maxResults > 250)) {
throw new AwsException("InvalidRequestException", "maxResults must be between 1 and 250", 400);
}
}
/** Exclusive attachment is not modelled, so every attachment is {@code NON_EXCLUSIVE_THING}. */
private static List<String> ofThingPrincipalType(String thingPrincipalType, Set<String> attachments) {
if (thingPrincipalType == null || NON_EXCLUSIVE_THING.equals(thingPrincipalType)) {
return List.copyOf(attachments);
}
if (EXCLUSIVE_THING.equals(thingPrincipalType)) {
return List.of();
}
throw new AwsException("InvalidRequestException", "Unsupported thingPrincipalType: " + thingPrincipalType, 400);
}
public List<IotPolicy> listAttachedPolicies(String target, String region) {
String prefix = "policy-attachment:" + region + ":";
return policyAttachmentStore.keys().stream()
@@ -14,6 +14,7 @@ public class IotCertificate {
private String publicKey;
private String privateKey;
private String status;
private String certificateMode;
private Instant creationDate;
private Instant notBefore;
private Instant notAfter;
@@ -31,6 +32,8 @@ public class IotCertificate {
public void setPrivateKey(String privateKey) { this.privateKey = privateKey; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getCertificateMode() { return certificateMode; }
public void setCertificateMode(String certificateMode) { this.certificateMode = certificateMode; }
public Instant getCreationDate() { return creationDate; }
public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; }
public Instant getNotBefore() { return notBefore; }
@@ -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);