mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 15:49:33 -05:00
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:
1 parent
4204ee2ea5
commit
e3e06a1122
9 files changed
+447
-15
No files matched your search
@@ -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; }
|
||||
|
||||
Reference in new issue
Block a user