Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(iot): real device certificates issued by the local CA (#3079)

Mario Toffiac67e5985944d
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java
index 699873df5b..16143aa29a 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java
@@ -10,6 +10,7 @@ import software.amazon.awssdk.services.iot.model.AttributePayload;
import software.amazon.awssdk.services.iot.model.AttachPolicyRequest;
import software.amazon.awssdk.services.iot.model.AttachThingPrincipalRequest;
import software.amazon.awssdk.services.iot.model.AuthorizerConfig;
+import software.amazon.awssdk.services.iot.model.CertificateMode;
import software.amazon.awssdk.services.iot.model.CertificateStatus;
import software.amazon.awssdk.services.iot.model.Action;
import software.amazon.awssdk.services.iot.model.AddThingToThingGroupRequest;
@@ -363,6 +364,11 @@ class IotTest {
.certificateId(cert.certificateId())
.build());
assertThat(described.certificateDescription().status()).isEqualTo(CertificateStatus.ACTIVE);
+ assertThat(described.certificateDescription().certificateMode()).isEqualTo(CertificateMode.DEFAULT);
+ assertThat(described.certificateDescription().validity().notAfter())
+ .isEqualTo(java.time.Instant.parse("2049-12-31T23:59:59Z"));
+ assertThat(cert.certificateId()).matches("[0-9a-f]{64}");
+ assertThat(cert.keyPair().privateKey()).startsWith("-----BEGIN RSA PRIVATE KEY-----");
var certs = iot.listCertificates(ListCertificatesRequest.builder().build());
assertThat(certs.certificates()).anyMatch(item -> cert.certificateArn().equals(item.certificateArn()));
diff --git a/compatibility-tests/sdk-test-python/tests/test_iot.py b/compatibility-tests/sdk-test-python/tests/test_iot.py
index 484bb0a3e5..5f58566cb1 100644
--- a/compatibility-tests/sdk-test-python/tests/test_iot.py
+++ b/compatibility-tests/sdk-test-python/tests/test_iot.py
@@ -4,6 +4,22 @@ import socket
import struct
+def _csr_pem(common_name):
+ """A real PKCS#10 request: the device keeps its key, Floci signs its public key as AWS does."""
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import rsa
+ from cryptography.x509.oid import NameOID
+
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ csr = (
+ x509.CertificateSigningRequestBuilder()
+ .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]))
+ .sign(key, hashes.SHA256())
+ )
+ return csr.public_bytes(serialization.Encoding.PEM).decode("ascii")
+
+
def test_describe_endpoint(iot_client):
response = iot_client.describe_endpoint(endpointType="iot:Data-ATS")
@@ -181,10 +197,11 @@ def test_certificate_delete_csr_policy_versions_and_attachment_reads(iot_client,
assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
csr_cert = iot_client.create_certificate_from_csr(
- certificateSigningRequest="-----BEGIN CERTIFICATE REQUEST-----\nfloci\n-----END CERTIFICATE REQUEST-----",
+ certificateSigningRequest=_csr_pem("device-from-csr"),
setAsActive=False,
)
assert "BEGIN CERTIFICATE" in csr_cert["certificatePem"]
+ assert "keyPair" not in csr_cert
policy_name = f"{unique_name}-versioned-policy"
policy_document = json.dumps({"Version": "2012-10-17", "Statement": []})
diff --git a/docs/configuration/tls.md b/docs/configuration/tls.md
index 9c7886dbb0..64a58a8fad 100644
--- a/docs/configuration/tls.md
+++ b/docs/configuration/tls.md
@@ -8,7 +8,7 @@ Floci supports optional TLS, enabling `https://` for all REST/JSON/Query endpoin
docker run -e FLOCI_TLS_ENABLED=true -p 4566:4566 floci/floci:latest
```
-Then point your SDK at `https://localhost:4566` and trust Floci's local CA in the processes that talk to it. Every certificate Floci issues (its HTTPS endpoint, every ACM certificate and, in a later release, IoT device certificates) chains to that one CA:
+Then point your SDK at `https://localhost:4566` and trust Floci's local CA in the processes that talk to it. Every certificate Floci issues (its HTTPS endpoint, IoT device certificates, and in a later release ACM certificates) chains to that one CA:
```bash
curl -s http://localhost:4566/_floci/ca.pem -o floci-root-ca.pem
@@ -85,14 +85,6 @@ services:
The generated certificate will include `floci` in its SANs, so TLS validation succeeds when `app` connects to `https://floci:4566`. Fetch `ca.pem` from Floci into `app` (an entrypoint `curl`, or a shared volume mounted from `{persistent-path}/tls/`) so the bundle path above exists.
-### Custom Domains Learned at Runtime
-
-A wildcard SAN matches one label only, so `*.localhost.floci.io` covers `api.localhost.floci.io` but not `api.dev.localhost.floci.io`. For names like that, Floci can add an exact hostname to the server certificate while it runs: the certificate is reissued by the local CA with the same key and the new name, and the HTTPS listener switches to it at once. No restart, no new CA, nothing new for clients to trust. Learned names are recorded in `{persistent-path}/tls/floci-server.metadata.json`, so they survive restarts and a regeneration after a `FLOCI_HOSTNAME` change; `POST /_floci/state/reset` drops them.
-
-Only a name under a local suffix is accepted: `localhost`, `localhost.floci.io`, `localhost.localstack.cloud`, `FLOCI_HOSTNAME`, the `FLOCI_BASE_URL` host, and every `FLOCI_DNS_EXTRA_SUFFIXES` entry. Any other name is refused with a warning, so a Floci certificate can never cover a public name. This only applies to the generated certificate; a user-provided one is never changed.
-
-Names are added by the custom domain operations: API Gateway `CreateDomainName`, IoT Core `CreateDomainConfiguration` with a `domainName`, and Cognito `CreateUserPoolDomain` with a `CustomDomainConfig`. The AWS operation succeeds either way; a name outside the local suffixes, or a reissue that fails, is logged as a warning.
-
## User-Provided Certificates
To use your own certificate (e.g., from a corporate CA or mkcert):
@@ -107,7 +99,7 @@ docker run \
floci/floci:latest
```
-When custom certificate paths are provided, `FLOCI_TLS_SELF_SIGNED` is ignored and the HTTPS server uses your certificate; no server certificate is generated. `GET /_floci/ca.pem` then returns a PEM bundle: your certificate file first, then Floci's local CA, which is created on first use and is the CA that will sign the certificates Floci itself issues (IoT device certificates, in a follow-up). Put the CA or the full chain in your certificate file if clients fetch their trust anchor from Floci; a bare leaf only lets them pin that one certificate.
+When custom certificate paths are provided, `FLOCI_TLS_SELF_SIGNED` is ignored and the HTTPS server uses your certificate; no server certificate is generated. `GET /_floci/ca.pem` then returns a PEM bundle: your certificate file first, then Floci's local CA, which is created on first use and signs the certificates Floci itself issues (IoT device certificates). Put the CA or the full chain in your certificate file if clients fetch their trust anchor from Floci; a bare leaf only lets them pin that one certificate.
## WebSocket (wss://)
diff --git a/docs/services/iot.md b/docs/services/iot.md
index 11a4b6ff56..74b4534033 100644
--- a/docs/services/iot.md
+++ b/docs/services/iot.md
@@ -9,7 +9,7 @@ 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.
+- 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.
- Policy basics: `CreatePolicy`, `GetPolicy`, `ListPolicies`, `DeletePolicy`, policy version lifecycle, `AttachPolicy`, `DetachPolicy`, `ListAttachedPolicies`, and `ListTargetsForPolicy`.
- Thing principal basics: `AttachThingPrincipal`, `DetachThingPrincipal`, `ListThingPrincipals`, and `ListPrincipalThings`.
- Tags for things, certificates, policies, and topic rules.
@@ -19,7 +19,7 @@ Supported MVP 1 behavior:
Current MVP 1 limitations:
-- Certificate CSR handling creates emulator-local certificates; it does not perform real CA signing.
+- The MQTT listener does not verify device certificates yet.
- MQTT auth remains permissive; certificate and policy resources are modeled for provisioning compatibility, not enforced as broker authorization yet.
- Rules support basic topic filter extraction and action dispatch only; SQL projection, WHERE evaluation, and substitutions remain follow-up scope.
diff --git a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java
index e2269ac9ea..c6b43bf977 100644
--- a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java
+++ b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java
@@ -2,9 +2,22 @@ package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import org.bouncycastle.asn1.ASN1ObjectIdentifier;
+import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
+import org.bouncycastle.asn1.pkcs.RSAPublicKey;
+import org.bouncycastle.asn1.sec.SECObjectIdentifiers;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
+import org.bouncycastle.asn1.x9.X962Parameters;
+import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
+import org.bouncycastle.openssl.PEMParser;
+import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;
import org.jboss.logging.Logger;
import java.io.IOException;
+import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributeView;
@@ -14,8 +27,10 @@ import java.security.PrivateKey;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
+import java.time.Instant;
import java.util.HexFormat;
import java.util.List;
+import java.util.Set;
/**
* Floci's one local root CA. Every certificate the emulator hands out that a client is expected
@@ -33,6 +48,12 @@ public final class FlociCertificateAuthority {
public static final String CA_CERT_NAME = "floci-root-ca.crt";
public static final String CA_KEY_NAME = "floci-root-ca.key";
static final String COMMON_NAME = "Floci Local CA";
+ /** AWS IoT-issued client certificates all expire at this instant, whenever they were created. */
+ public static final Instant DEVICE_CERTIFICATE_NOT_AFTER = Instant.parse("2049-12-31T23:59:59Z");
+ /** A new CA outlives every device certificate it will sign, so a chain never expires before its leaf. */
+ static final Instant CA_NOT_AFTER = Instant.parse("2050-12-31T23:59:59Z");
+ private static final long TEN_YEARS_IN_DAYS = 3650;
+ private static final long ONE_YEAR_IN_DAYS = 365;
private final Path certificatePath;
private final X509Certificate certificate;
@@ -85,7 +106,7 @@ public final class FlociCertificateAuthority {
}
Files.createDirectories(tlsDir);
restrictToOwnerOnly(tlsDir, "rwx------");
- CertificateGenerator.GeneratedCertificate generated = generator.generateCaCertificate(COMMON_NAME);
+ CertificateGenerator.GeneratedCertificate generated = generator.generateCaCertificate(COMMON_NAME, caNotAfter(Instant.now()));
Files.writeString(certFile, generated.certificatePem());
writePrivateKey(keyFile, generated.privateKeyPem());
FlociCertificateAuthority ca = new FlociCertificateAuthority(certFile,
@@ -145,10 +166,62 @@ public final class FlociCertificateAuthority {
CertificateGenerator.LeafUsage.SERVER);
}
- /** A {@code clientAuth} leaf, for IoT device certificates. Always a fresh RSA 2048 key pair. */
+ /**
+ * A {@code clientAuth} leaf for an IoT device: a fresh RSA 2048 key pair and, as on AWS, validity
+ * until the end of 2049, never past the CA's own expiry.
+ */
public CertificateGenerator.GeneratedCertificate issueClientCertificate(String commonName) {
return generator.generateIssuedCertificate(commonName, List.of(), KeyAlgorithm.RSA_2048, null, issuer(),
- CertificateGenerator.LeafUsage.CLIENT);
+ CertificateGenerator.LeafUsage.CLIENT, deviceCertificateNotAfter());
+ }
+
+ /**
+ * The end of validity for a device certificate: AWS's fixed 2049 date, capped at the CA's own
+ * expiry so a CA created before that date was adopted (ten years) never signs a leaf that
+ * outlives it. Once 2049 has passed, one year from now, the same cap applied.
+ */
+ public Instant deviceCertificateNotAfter() {
+ return deviceCertificateNotAfter(Instant.now());
+ }
+
+ Instant deviceCertificateNotAfter(Instant now) {
+ Instant caNotAfter = certificate.getNotAfter().toInstant();
+ Instant wanted = DEVICE_CERTIFICATE_NOT_AFTER.isAfter(now)
+ ? DEVICE_CERTIFICATE_NOT_AFTER
+ : now.plus(ONE_YEAR_IN_DAYS, java.time.temporal.ChronoUnit.DAYS);
+ return caNotAfter.isBefore(wanted) ? caNotAfter : wanted;
+ }
+
+ /** A new CA ends in 2050, or ten years from now when that is later, so it is never born expired. */
+ static Instant caNotAfter(Instant now) {
+ Instant tenYears = now.plus(TEN_YEARS_IN_DAYS, java.time.temporal.ChronoUnit.DAYS);
+ return tenYears.isAfter(CA_NOT_AFTER) ? tenYears : CA_NOT_AFTER;
+ }
+
+ /**
+ * Signs an external PKCS#10 request as a {@code clientAuth} leaf. The subject DN comes from
+ * the CSR; requested extensions are ignored (AWS IoT ignores them too). Throws
+ * {@link IllegalArgumentException} when the PEM is not a CSR or its self-signature fails.
+ */
+ public X509Certificate signClientCsr(String csrPem) {
+ try (PEMParser parser = new PEMParser(new StringReader(csrPem))) {
+ Object parsed = parser.readObject();
+ if (!(parsed instanceof PKCS10CertificationRequest csr)) {
+ throw new IllegalArgumentException("certificateSigningRequest is not a PEM CERTIFICATE REQUEST");
+ }
+ requireAcceptedKey(csr.getSubjectPublicKeyInfo());
+ PublicKey subjectKey = new JcaPKCS10CertificationRequest(csr).getPublicKey();
+ if (!csr.isSignatureValid(new JcaContentVerifierProviderBuilder().build(subjectKey))) {
+ throw new IllegalArgumentException("certificateSigningRequest signature does not verify");
+ }
+ X500Name issuerDn = X500Name.getInstance(certificate.getSubjectX500Principal().getEncoded());
+ return generator.signCertificate(csr.getSubject(), subjectKey, issuerDn, key, List.of(), false,
+ CertificateGenerator.LeafUsage.CLIENT, Instant.now(), deviceCertificateNotAfter());
+ } catch (IllegalArgumentException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new IllegalArgumentException("certificateSigningRequest could not be parsed: " + e.getMessage(), e);
+ }
}
/** True when {@code cert} names this CA as issuer and its signature checks against our key. */
@@ -165,6 +238,30 @@ public final class FlociCertificateAuthority {
}
}
+ private static final Set<ASN1ObjectIdentifier> ACCEPTED_CURVES = Set.of(
+ SECObjectIdentifiers.secp256r1, SECObjectIdentifiers.secp384r1, SECObjectIdentifiers.secp521r1);
+
+ /**
+ * AWS IoT accepts an RSA key of at least 2048 bits or an EC key on NIST P-256, P-384 or P-521.
+ * The curve is read from the request's named-curve identifier, so a curve that merely shares a
+ * field size (secp256k1) or explicit curve parameters are refused as well.
+ */
+ private static void requireAcceptedKey(SubjectPublicKeyInfo key) throws Exception {
+ ASN1ObjectIdentifier algorithm = key.getAlgorithm().getAlgorithm();
+ if (PKCSObjectIdentifiers.rsaEncryption.equals(algorithm)
+ && RSAPublicKey.getInstance(key.parsePublicKey()).getModulus().bitLength() >= 2048) {
+ return;
+ }
+ if (X9ObjectIdentifiers.id_ecPublicKey.equals(algorithm)) {
+ X962Parameters parameters = X962Parameters.getInstance(key.getAlgorithm().getParameters());
+ if (parameters.isNamedCurve() && ACCEPTED_CURVES.contains((ASN1ObjectIdentifier) parameters.getParameters())) {
+ return;
+ }
+ }
+ throw new IllegalArgumentException("certificateSigningRequest key must be RSA of at least 2048 bits "
+ + "or EC on NIST P-256, P-384 or P-521");
+ }
+
/**
* Writes a private key so that, where the file system has POSIX permissions, no other user can
* read it at any point: the file is created owner-only before the first byte is written. A
diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java
index c66b6b945c..eb4bfc3500 100644
--- a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java
@@ -125,11 +125,16 @@ public class CertificateGenerator {
* every client in the emulator's reach accepts it and it keeps key generation under a second.
*/
public GeneratedCertificate generateCaCertificate(String commonName) {
+ return generateCaCertificate(commonName, Instant.now().plus(3650, ChronoUnit.DAYS));
+ }
+
+ /** Same as {@link #generateCaCertificate(String)} with an explicit end of validity. */
+ public GeneratedCertificate generateCaCertificate(String commonName, Instant notAfter) {
try {
KeyPair keyPair = generateKeyPair(KeyAlgorithm.RSA_2048);
X500Name dn = new X500Name("CN=" + commonName);
X509Certificate cert = signCertificate(dn, keyPair.getPublic(), dn, keyPair.getPrivate(),
- List.of(), true, null, 3650);
+ List.of(), true, null, Instant.now(), notAfter);
return toGenerated(cert, keyPair.getPrivate(), dn.toString(), dn.toString());
} catch (Exception e) {
LOG.error("Failed to generate CA certificate", e);
@@ -149,6 +154,14 @@ public class CertificateGenerator {
public GeneratedCertificate generateIssuedCertificate(String domainName, List<String> sans,
KeyAlgorithm keyAlgorithm, KeyPair subjectKeyPair,
Issuer issuer, LeafUsage usage) {
+ return generateIssuedCertificate(domainName, sans, keyAlgorithm, subjectKeyPair, issuer, usage,
+ Instant.now().plus(365, ChronoUnit.DAYS));
+ }
+
+ /** Same as {@link #generateIssuedCertificate(String, List, KeyAlgorithm, KeyPair, Issuer, LeafUsage)} with an explicit end of validity. */
+ public GeneratedCertificate generateIssuedCertificate(String domainName, List<String> sans,
+ KeyAlgorithm keyAlgorithm, KeyPair subjectKeyPair,
+ Issuer issuer, LeafUsage usage, Instant notAfter) {
try {
if (subjectKeyPair != null && !isOfAlgorithm(subjectKeyPair.getPublic(), keyAlgorithm)) {
throw new IllegalArgumentException("supplied key pair is not the requested " + keyAlgorithm);
@@ -160,7 +173,7 @@ public class CertificateGenerator {
X500Name subject = new X500Name("CN=" + domainName);
X500Name issuerDn = X500Name.getInstance(issuer.certificate().getSubjectX500Principal().getEncoded());
X509Certificate cert = signCertificate(subject, keyPair.getPublic(), issuerDn, issuer.key(),
- withDomainFirst(domainName, sans), false, usage, 365);
+ withDomainFirst(domainName, sans), false, usage, Instant.now(), notAfter);
cert.verify(issuer.certificate().getPublicKey());
return toGenerated(cert, keyPair.getPrivate(), subject.toString(),
issuer.certificate().getSubjectX500Principal().getName());
@@ -229,10 +242,17 @@ public class CertificateGenerator {
PrivateKey issuerKey, List<String> sans, boolean asCa,
LeafUsage usage, int validityDays) throws Exception {
Instant now = Instant.now();
+ return signCertificate(subject, subjectKey, issuerDn, issuerKey, sans, asCa, usage, now,
+ now.plus(validityDays, ChronoUnit.DAYS));
+ }
+
+ /** Same as {@link #signCertificate(X500Name, PublicKey, X500Name, PrivateKey, List, boolean, LeafUsage, int)} with an explicit validity window. */
+ public X509Certificate signCertificate(X500Name subject, PublicKey subjectKey, X500Name issuerDn,
+ PrivateKey issuerKey, List<String> sans, boolean asCa,
+ LeafUsage usage, Instant notBefore, Instant notAfter) throws Exception {
BigInteger serial = new BigInteger(128, SECURE_RANDOM);
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
- issuerDn, serial, Date.from(now), Date.from(now.plus(validityDays, ChronoUnit.DAYS)),
- subject, subjectKey);
+ issuerDn, serial, Date.from(notBefore), Date.from(notAfter), subject, subjectKey);
if (sans != null && !sans.isEmpty()) {
List<GeneralName> sanList = new ArrayList<>();
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java
index 58329e1e2f..45b259d7ff 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java
@@ -945,7 +945,13 @@ public class IotController {
description.put("certificateId", certificate.getCertificateId());
description.put("certificatePem", certificate.getCertificatePem());
description.put("status", certificate.getStatus());
+ description.put("certificateMode", "DEFAULT");
putEpoch(description, "creationDate", certificate.getCreationDate());
+ if (certificate.getNotBefore() != null && certificate.getNotAfter() != null) {
+ ObjectNode validity = description.putObject("validity");
+ putEpoch(validity, "notBefore", certificate.getNotBefore());
+ putEpoch(validity, "notAfter", certificate.getNotAfter());
+ }
return description;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
index 2d5d972ea3..a54b7c92e1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
@@ -7,6 +7,7 @@ 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.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.RegionResolver;
@@ -22,6 +23,7 @@ import io.github.hectorvent.floci.services.iot.model.IotShadow;
import io.github.hectorvent.floci.services.iot.model.IotThingGroup;
import io.github.hectorvent.floci.services.iot.model.IotThingType;
import io.github.hectorvent.floci.services.iot.model.IotTopicRule;
+import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.iot.model.Thing;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
@@ -39,12 +41,15 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashSet;
+import java.util.HexFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -92,6 +97,7 @@ public class IotService {
private final LambdaService lambdaService;
private final FirehoseService firehoseService;
private final CloudWatchLogsService cloudWatchLogsService;
+ private final FlociCertificateAuthority certificateAuthority;
@Inject
public IotService(StorageFactory storageFactory,
@@ -107,7 +113,8 @@ public class IotService {
DynamoDbService dynamoDbService,
LambdaService lambdaService,
FirehoseService firehoseService,
- CloudWatchLogsService cloudWatchLogsService) {
+ CloudWatchLogsService cloudWatchLogsService,
+ FlociCertificateAuthority certificateAuthority) {
this(storageFactory.create("iot", "iot-things.json", new TypeReference<Map<String, Thing>>() {}),
storageFactory.create("iot", "iot-certificates.json", new TypeReference<Map<String, IotCertificate>>() {}),
storageFactory.create("iot", "iot-policies.json", new TypeReference<Map<String, IotPolicy>>() {}),
@@ -122,7 +129,7 @@ public class IotService {
storageFactory.create("iot", "iot-thing-groups.json", new TypeReference<Map<String, IotThingGroup>>() {}),
storageFactory.create("iot", "iot-thing-group-memberships.json", new TypeReference<Map<String, Set<String>>>() {}),
config, regionResolver, objectMapper, publishEventRecorder, mqttBrokerService, sqsService, snsService,
- s3Service, kinesisService, dynamoDbService, lambdaService, firehoseService, cloudWatchLogsService);
+ s3Service, kinesisService, dynamoDbService, lambdaService, firehoseService, cloudWatchLogsService, certificateAuthority);
}
IotService(StorageBackend<String, Thing> thingStore,
@@ -150,7 +157,8 @@ public class IotService {
DynamoDbService dynamoDbService,
LambdaService lambdaService,
FirehoseService firehoseService,
- CloudWatchLogsService cloudWatchLogsService) {
+ CloudWatchLogsService cloudWatchLogsService,
+ FlociCertificateAuthority certificateAuthority) {
this.thingStore = thingStore;
this.certificateStore = certificateStore;
this.policyStore = policyStore;
@@ -177,6 +185,7 @@ public class IotService {
this.lambdaService = lambdaService;
this.firehoseService = firehoseService;
this.cloudWatchLogsService = cloudWatchLogsService;
+ this.certificateAuthority = certificateAuthority;
}
public String describeEndpoint(String endpointType) {
@@ -297,19 +306,70 @@ public class IotService {
private IotCertificate createCertificate(boolean setAsActive, String certificateSigningRequest, String region) {
startMqttIfEnabled();
- String id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
IotCertificate certificate = new IotCertificate();
- certificate.setCertificateId(id);
- certificate.setCertificateArn(regionResolver.buildArn("iot", region, "cert/" + id));
- certificate.setCertificatePem("-----BEGIN CERTIFICATE-----\n" + id + "\n-----END CERTIFICATE-----");
- certificate.setPublicKey("-----BEGIN PUBLIC KEY-----\n" + (certificateSigningRequest == null ? id : certificateSigningRequest.hashCode()) + "\n-----END PUBLIC KEY-----");
- certificate.setPrivateKey("-----BEGIN PRIVATE KEY-----\n" + id + "\n-----END PRIVATE KEY-----");
+ if (certificateSigningRequest == null) {
+ issueFromLocalCa(certificate);
+ } else {
+ issueFromCsr(certificate, certificateSigningRequest);
+ }
+ certificate.setCertificateArn(regionResolver.buildArn("iot", region, "cert/" + certificate.getCertificateId()));
certificate.setStatus(setAsActive ? "ACTIVE" : "INACTIVE");
certificate.setCreationDate(Instant.now());
- certificateStore.put(certificateKey(region, id), certificate);
+ certificateStore.put(certificateKey(region, certificate.getCertificateId()), withoutPrivateKey(certificate));
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();
+ stored.setCertificateId(certificate.getCertificateId());
+ stored.setCertificateArn(certificate.getCertificateArn());
+ stored.setCertificatePem(certificate.getCertificatePem());
+ stored.setPublicKey(certificate.getPublicKey());
+ stored.setStatus(certificate.getStatus());
+ stored.setCreationDate(certificate.getCreationDate());
+ stored.setNotBefore(certificate.getNotBefore());
+ stored.setNotAfter(certificate.getNotAfter());
+ stored.setTags(certificate.getTags());
+ return stored;
+ }
+
+ /** As on AWS: a fresh RSA 2048 pair, the subject {@code AWS IoT Certificate}, and the private key returned once. */
+ private void issueFromLocalCa(IotCertificate certificate) {
+ CertificateGenerator.GeneratedCertificate issued = certificateAuthority.issueClientCertificate("AWS IoT Certificate");
+ try {
+ fill(certificate, new CertificateGenerator().parseCertificate(issued.certificatePem()));
+ certificate.setPrivateKey(issued.privateKeyPem());
+ } catch (Exception e) {
+ throw new AwsException("InternalFailureException", "Could not issue device certificate: " + e.getMessage(), 500);
+ }
+ }
+
+ /** The device keeps its key: only the certificate and its public key are stored. */
+ private void issueFromCsr(IotCertificate certificate, String csrPem) {
+ X509Certificate x509;
+ try {
+ x509 = certificateAuthority.signClientCsr(csrPem);
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
+ try {
+ fill(certificate, x509);
+ } catch (Exception e) {
+ throw new AwsException("InternalFailureException", "Could not encode device certificate: " + e.getMessage(), 500);
+ }
+ }
+
+ /** AWS IoT's certificateId is the lowercase hex SHA-256 of the certificate's DER encoding. */
+ private static void fill(IotCertificate certificate, X509Certificate x509) throws Exception {
+ CertificateGenerator pem = new CertificateGenerator();
+ certificate.setCertificateId(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(x509.getEncoded())));
+ certificate.setCertificatePem(pem.toPem(x509));
+ certificate.setPublicKey(pem.toPem(x509.getPublicKey()));
+ certificate.setNotBefore(x509.getNotBefore().toInstant());
+ certificate.setNotAfter(x509.getNotAfter().toInstant());
+ }
+
public IotCertificate describeCertificate(String certificateId, String region) {
return certificateStore.get(certificateKey(region, certificateId))
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Certificate not found: " + certificateId, 404));
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotCertificate.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotCertificate.java
index 0343a5051e..db05418b73 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotCertificate.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotCertificate.java
@@ -15,6 +15,8 @@ public class IotCertificate {
private String privateKey;
private String status;
private Instant creationDate;
+ private Instant notBefore;
+ private Instant notAfter;
private Map<String, String> tags = new TreeMap<>();
public String getCertificateId() { return certificateId; }
@@ -31,6 +33,10 @@ public class IotCertificate {
public void setStatus(String status) { this.status = status; }
public Instant getCreationDate() { return creationDate; }
public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; }
+ public Instant getNotBefore() { return notBefore; }
+ public void setNotBefore(Instant notBefore) { this.notBefore = notBefore; }
+ public Instant getNotAfter() { return notAfter; }
+ public void setNotAfter(Instant notAfter) { this.notAfter = notAfter; }
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/config/FlociCertificateAuthorityTest.java b/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.java
index bda8eb5685..8c7395b569 100644
--- a/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.java
+++ b/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.java
@@ -160,6 +160,44 @@ class FlociCertificateAuthorityTest {
assertEquals("CN=AWS IoT Certificate", cert.getSubjectX500Principal().getName());
assertEquals(List.of("1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage());
assertTrue(ca.isIssuedByUs(cert));
+ assertEquals(java.time.Instant.parse("2049-12-31T23:59:59Z"), cert.getNotAfter().toInstant(), "AWS's fixed expiry");
+ assertEquals(java.time.Instant.parse("2050-12-31T23:59:59Z"), ca.certificate().getNotAfter().toInstant(),
+ "a new CA outlives the device certificates it signs");
+ }
+
+ @Test
+ void expiryRulesStayValidAfterTheFixedDates() {
+ java.time.Instant in2051 = java.time.Instant.parse("2051-06-01T00:00:00Z");
+ assertEquals(in2051.plus(3650, java.time.temporal.ChronoUnit.DAYS), FlociCertificateAuthority.caNotAfter(in2051),
+ "a CA created after 2050 lives ten years instead of being born expired");
+ assertEquals(java.time.Instant.parse("2050-12-31T23:59:59Z"),
+ FlociCertificateAuthority.caNotAfter(java.time.Instant.parse("2026-09-05T00:00:00Z")));
+
+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
+ assertEquals(ca.certificate().getNotAfter().toInstant(),
+ ca.deviceCertificateNotAfter(java.time.Instant.parse("2050-06-01T00:00:00Z")),
+ "after 2049 a device certificate lives a year, capped at the CA's expiry: never born expired");
+ assertTrue(ca.deviceCertificateNotAfter(java.time.Instant.parse("2050-06-01T00:00:00Z"))
+ .isAfter(java.time.Instant.parse("2050-06-01T00:00:00Z")));
+ assertEquals(java.time.Instant.parse("2049-12-31T23:59:59Z"),
+ ca.deviceCertificateNotAfter(java.time.Instant.parse("2026-09-05T00:00:00Z")));
+ }
+
+ @Test
+ void deviceCertificateNeverOutlivesAShortLivedCa() throws Exception {
+ CertificateGenerator gen = new CertificateGenerator();
+ var shortLived = gen.generateCaCertificate(FlociCertificateAuthority.COMMON_NAME,
+ java.time.Instant.now().plus(30, java.time.temporal.ChronoUnit.DAYS));
+ Files.writeString(tempDir.resolve("floci-root-ca.crt"), shortLived.certificatePem());
+ Files.writeString(tempDir.resolve("floci-root-ca.key"), shortLived.privateKeyPem());
+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
+ assertEquals(parse(shortLived.certificatePem()), ca.certificate(), "the short-lived CA is kept as is");
+
+ X509Certificate leaf = parse(ca.issueClientCertificate("device").certificatePem());
+ X509Certificate fromCsr = ca.signClientCsr(csrPem("CN=device", rsaKeyPair(2048)));
+
+ assertEquals(ca.certificate().getNotAfter(), leaf.getNotAfter(), "capped at the CA's expiry");
+ assertEquals(ca.certificate().getNotAfter(), fromCsr.getNotAfter(), "the CSR path is capped the same way");
}
@Test
@@ -184,6 +222,61 @@ class FlociCertificateAuthorityTest {
assertFalse(ca.isIssuedByUs(parse(forged.certificatePem())), "same issuer name, wrong signature");
}
+ @Test
+ void signsACsrAsAClientLeafWithTheCsrSubjectAndKey() throws Exception {
+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
+ java.security.KeyPair deviceKey = rsaKeyPair(2048);
+
+ X509Certificate cert = ca.signClientCsr(csrPem("CN=device-42,O=Example", deviceKey));
+
+ cert.verify(ca.certificate().getPublicKey());
+ assertEquals(deviceKey.getPublic(), cert.getPublicKey());
+ assertEquals(new javax.security.auth.x500.X500Principal(
+ new org.bouncycastle.asn1.x500.X500Name("CN=device-42,O=Example").getEncoded()), cert.getSubjectX500Principal());
+ assertEquals(List.of("1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage());
+ assertEquals(-1, cert.getBasicConstraints());
+ assertTrue(ca.isIssuedByUs(cert));
+ }
+
+ @Test
+ void refusesWhatIsNotACsr() throws Exception {
+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
+
+ var notPem = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
+ () -> ca.signClientCsr("hello"));
+ assertTrue(notPem.getMessage().contains("certificateSigningRequest"), notPem.getMessage());
+ var certificate = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
+ () -> ca.signClientCsr(ca.caPem()));
+ assertTrue(certificate.getMessage().contains("not a PEM CERTIFICATE REQUEST"), certificate.getMessage());
+ }
+
+ @Test
+ void refusesAWeakRsaKey() throws Exception {
+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
+ String weak = csrPem("CN=weak", rsaKeyPair(1024));
+
+ var refused = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
+ () -> ca.signClientCsr(weak));
+ assertTrue(refused.getMessage().contains("2048"), refused.getMessage());
+ }
+
+ private static java.security.KeyPair rsaKeyPair(int bits) throws Exception {
+ java.security.KeyPairGenerator kpg = java.security.KeyPairGenerator.getInstance("RSA");
+ kpg.initialize(bits);
+ return kpg.generateKeyPair();
+ }
+
+ private static String csrPem(String subject, java.security.KeyPair keyPair) throws Exception {
+ var csr = new org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder(
+ new org.bouncycastle.asn1.x500.X500Name(subject), keyPair.getPublic())
+ .build(new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate()));
+ java.io.StringWriter out = new java.io.StringWriter();
+ try (var writer = new org.bouncycastle.openssl.jcajce.JcaPEMWriter(out)) {
+ writer.writeObject(csr);
+ }
+ return out.toString();
+ }
+
private static X509Certificate parse(String pem) {
return new CertificateGenerator().parseCertificate(pem);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceCertificateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceCertificateIntegrationTest.java
new file mode 100644
index 0000000000..4bcda37f82
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceCertificateIntegrationTest.java
@@ -0,0 +1,363 @@
+package io.github.hectorvent.floci.services.iot;
+
+import io.github.hectorvent.floci.services.acm.CertificateGenerator;
+import io.github.hectorvent.floci.services.iot.model.IotCertificate;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.path.json.JsonPath;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.MessageDigest;
+import java.security.PrivateKey;
+import java.security.Signature;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Base64;
+import java.util.HexFormat;
+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.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Device certificates are real X.509 leaves issued by the local CA, with the AWS certificate id
+ * (lowercase hex SHA-256 of the DER) and, for {@code CreateKeysAndCertificate}, a key pair that
+ * matches the certificate.
+ */
+@QuarkusTest
+class IotDeviceCertificateIntegrationTest {
+
+ @jakarta.inject.Inject
+ IotService iotService;
+
+ @org.junit.jupiter.api.BeforeAll
+ static void bouncyCastle() {
+ if (java.security.Security.getProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) == null) {
+ java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
+ }
+ }
+
+ @Test
+ void createKeysAndCertificateIssuesARealClientCertificate() throws Exception {
+ JsonPath body = given()
+ .contentType("application/json")
+ .queryParam("setAsActive", true)
+ .body("{}")
+ .when()
+ .post("/keys-and-certificate")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath();
+
+ X509Certificate cert = parse(body.getString("certificatePem"));
+ X509Certificate ca = parse(given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString());
+
+ cert.verify(ca.getPublicKey());
+ assertEquals(ca.getSubjectX500Principal(), cert.getIssuerX500Principal());
+ assertEquals("CN=AWS IoT Certificate", cert.getSubjectX500Principal().getName());
+ assertEquals(List.of("1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage(), "clientAuth");
+ assertEquals(-1, cert.getBasicConstraints());
+ assertEquals("RSA", cert.getPublicKey().getAlgorithm());
+ assertEquals(2048, ((java.security.interfaces.RSAPublicKey) cert.getPublicKey()).getModulus().bitLength());
+ assertEquals(expectedNotAfter(ca), cert.getNotAfter().toInstant(),
+ "AWS IoT-issued certificates all expire at the end of 2049, never past the CA");
+ assertTrue(!cert.getNotBefore().toInstant().isAfter(java.time.Instant.now()), "valid from issue time");
+
+ String expectedId = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(cert.getEncoded()));
+ assertEquals(expectedId, body.getString("certificateId"), "AWS certificateId is sha256(DER), lowercase hex");
+ assertTrue(body.getString("certificateArn").endsWith(":cert/" + expectedId));
+
+ String privateKeyPem = body.getString("keyPair.PrivateKey");
+ assertTrue(privateKeyPem.startsWith("-----BEGIN RSA PRIVATE KEY-----"), "AWS returns a PKCS#1 RSA key");
+ PrivateKey privateKey = new CertificateGenerator().parsePrivateKey(privateKeyPem);
+ Signature signer = Signature.getInstance("SHA256withRSA");
+ signer.initSign(privateKey);
+ signer.update("floci".getBytes(StandardCharsets.UTF_8));
+ byte[] sig = signer.sign();
+ Signature verifier = Signature.getInstance("SHA256withRSA");
+ verifier.initVerify(cert.getPublicKey());
+ verifier.update("floci".getBytes(StandardCharsets.UTF_8));
+ assertTrue(verifier.verify(sig), "private key must match the certificate's public key");
+
+ String publicKeyPem = body.getString("keyPair.PublicKey");
+ assertTrue(publicKeyPem.startsWith("-----BEGIN PUBLIC KEY-----"));
+ assertEquals(Base64.getEncoder().encodeToString(cert.getPublicKey().getEncoded()),
+ publicKeyPem.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "")
+ .replaceAll("\\s", ""));
+ }
+
+ @Test
+ void thePrivateKeyIsReturnedOnceAndNeverStored() {
+ JsonPath created = create();
+
+ IotCertificate stored = iotService.describeCertificate(created.getString("certificateId"), "us-east-1");
+ assertNull(stored.getPrivateKey(), "AWS keeps no copy of a device's private key");
+ assertEquals(created.getString("certificatePem"), stored.getCertificatePem());
+ assertEquals(created.getString("keyPair.PublicKey"), stored.getPublicKey());
+ }
+
+ @Test
+ void twoCertificatesNeverShareAnIdOrAKey() throws Exception {
+ JsonPath first = create();
+ JsonPath second = create();
+
+ assertTrue(!first.getString("certificateId").equals(second.getString("certificateId")));
+ assertTrue(!first.getString("keyPair.PrivateKey").equals(second.getString("keyPair.PrivateKey")));
+ assertTrue(!parse(first.getString("certificatePem")).getSerialNumber()
+ .equals(parse(second.getString("certificatePem")).getSerialNumber()));
+ }
+
+ @Test
+ void createCertificateFromCsrSignsTheCsrKeyAndReturnsNoPrivateKey() throws Exception {
+ KeyPair deviceKey = rsaKeyPair();
+ String csrPem = csrPem("CN=thing-0001,O=Example", deviceKey);
+
+ JsonPath body = given()
+ .contentType("application/json")
+ .queryParam("setAsActive", true)
+ .body(Map.of("certificateSigningRequest", csrPem))
+ .when()
+ .post("/certificates")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath();
+
+ X509Certificate cert = parse(body.getString("certificatePem"));
+ X509Certificate ca = parse(given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString());
+
+ cert.verify(ca.getPublicKey());
+ assertEquals(deviceKey.getPublic(), cert.getPublicKey(), "the CSR's key is the certificate's key");
+ assertEquals(new javax.security.auth.x500.X500Principal(new X500Name("CN=thing-0001,O=Example").getEncoded()),
+ cert.getSubjectX500Principal(), "the CSR's subject is the certificate's subject");
+ assertEquals(List.of("1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage(), "clientAuth");
+ assertEquals(-1, cert.getBasicConstraints());
+ assertEquals(expectedNotAfter(ca), cert.getNotAfter().toInstant());
+ String expectedId = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(cert.getEncoded()));
+ assertEquals(expectedId, body.getString("certificateId"));
+ assertNull(body.get("keyPair"), "AWS never returns a private key for a CSR: the device holds it");
+ }
+
+ @Test
+ void reusingACsrYieldsADistinctCertificate() throws Exception {
+ String csrPem = csrPem("CN=reused", rsaKeyPair());
+
+ JsonPath first = fromCsr(csrPem);
+ JsonPath second = fromCsr(csrPem);
+
+ assertTrue(!first.getString("certificateId").equals(second.getString("certificateId")),
+ "AWS: reusing the same CSR results in a distinct certificate");
+ assertEquals(parse(first.getString("certificatePem")).getPublicKey(),
+ parse(second.getString("certificatePem")).getPublicKey());
+ }
+
+ @Test
+ void createCertificateFromCsrAcceptsAnEcKey() throws Exception {
+ KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
+ kpg.initialize(new java.security.spec.ECGenParameterSpec("secp256r1"));
+ KeyPair deviceKey = kpg.generateKeyPair();
+ PKCS10CertificationRequest csr = new JcaPKCS10CertificationRequestBuilder(
+ new X500Name("CN=ec-device"), deviceKey.getPublic())
+ .build(new JcaContentSignerBuilder("SHA256withECDSA").build(deviceKey.getPrivate()));
+
+ JsonPath body = fromCsr(toPem(csr));
+
+ X509Certificate cert = parse(body.getString("certificatePem"));
+ assertEquals(deviceKey.getPublic(), cert.getPublicKey());
+ assertEquals("EC", cert.getPublicKey().getAlgorithm());
+ }
+
+ @Test
+ void createCertificateFromCsrAcceptsP384AndRefusesSecp256k1() throws Exception {
+ JsonPath accepted = fromCsr(ecCsrPem("secp384r1", "CN=p384"));
+ assertEquals("EC", parse(accepted.getString("certificatePem")).getPublicKey().getAlgorithm());
+
+ given()
+ .contentType("application/json")
+ .body(Map.of("certificateSigningRequest", ecCsrPem("secp256k1", "CN=k1")))
+ .when()
+ .post("/certificates")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("InvalidRequestException"))
+ .body("message", containsString("P-256"));
+ }
+
+ @Test
+ void createCertificateFromCsrRejectsGarbage() {
+ given()
+ .contentType("application/json")
+ .body(Map.of("certificateSigningRequest",
+ "-----BEGIN CERTIFICATE REQUEST-----\nbm90IGEgY3Ny\n-----END CERTIFICATE REQUEST-----"))
+ .when()
+ .post("/certificates")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("InvalidRequestException"))
+ .body("message", containsString("certificateSigningRequest"));
+ }
+
+ @Test
+ void createCertificateFromCsrRejectsAWeakKey() throws Exception {
+ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
+ kpg.initialize(1024);
+
+ given()
+ .contentType("application/json")
+ .body(Map.of("certificateSigningRequest", csrPem("CN=weak", kpg.generateKeyPair())))
+ .when()
+ .post("/certificates")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("InvalidRequestException"))
+ .body("message", containsString("2048"));
+ }
+
+ @Test
+ void createCertificateFromCsrRejectsACertificateInPlaceOfACsr() throws Exception {
+ String certificatePem = create().getString("certificatePem");
+
+ given()
+ .contentType("application/json")
+ .body(Map.of("certificateSigningRequest", certificatePem))
+ .when()
+ .post("/certificates")
+ .then()
+ .statusCode(400)
+ .body("__type", containsString("InvalidRequestException"));
+ }
+
+ @Test
+ void createCertificateFromCsrRejectsATamperedSignature() throws Exception {
+ KeyPair deviceKey = rsaKeyPair();
+ KeyPair otherKey = rsaKeyPair();
+ // The request names deviceKey's public key but is signed with otherKey: proof of possession fails.
+ PKCS10CertificationRequest csr = new JcaPKCS10CertificationRequestBuilder(
+ new X500Name("CN=forged"), deviceKey.getPublic())
+ .build(new JcaContentSignerBuilder("SHA256withRSA").build(otherKey.getPrivate()));
+
+ given()
+ .contentType("application/json")
+ .body(Map.of("certificateSigningRequest", toPem(csr)))
+ .when()
+ .post("/certificates")
+ .then()
+ .statusCode(400)
+ .body("message", containsString("signature"));
+ }
+
+ @Test
+ void describeCertificateReturnsTheSamePem() throws Exception {
+ JsonPath created = given()
+ .contentType("application/json")
+ .queryParam("setAsActive", false)
+ .body("{}")
+ .when()
+ .post("/keys-and-certificate")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath();
+
+ String body = given()
+ .when()
+ .get("/certificates/" + created.getString("certificateId"))
+ .then()
+ .statusCode(200)
+ .body("certificateDescription.certificatePem", equalTo(created.getString("certificatePem")))
+ .body("certificateDescription.certificateId", equalTo(created.getString("certificateId")))
+ .body("certificateDescription.status", equalTo("INACTIVE"))
+ .body("certificateDescription.certificateMode", equalTo("DEFAULT"))
+ .extract().asString();
+
+ // Read with Jackson: RestAssured's JsonPath narrows large epoch doubles to float precision.
+ com.fasterxml.jackson.databind.JsonNode described = new com.fasterxml.jackson.databind.ObjectMapper().readTree(body)
+ .path("certificateDescription");
+ X509Certificate ca = parse(given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString());
+ assertEquals(expectedNotAfter(ca).getEpochSecond(), described.path("validity").path("notAfter").asLong(),
+ "validity.notAfter is 2049-12-31T23:59:59Z as epoch seconds (or the CA's expiry, if earlier)");
+ long notBefore = described.path("validity").path("notBefore").asLong();
+ long creation = described.path("creationDate").asLong();
+ assertTrue(Math.abs(notBefore - creation) <= 2, "the certificate is valid from its creation");
+ }
+
+ private static JsonPath create() {
+ return given()
+ .contentType("application/json")
+ .queryParam("setAsActive", true)
+ .body("{}")
+ .when()
+ .post("/keys-and-certificate")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath();
+ }
+
+ private static JsonPath fromCsr(String csrPem) {
+ return given()
+ .contentType("application/json")
+ .queryParam("setAsActive", false)
+ .body(Map.of("certificateSigningRequest", csrPem))
+ .when()
+ .post("/certificates")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath();
+ }
+
+ /** Built with the BouncyCastle provider so curves the JDK dropped (secp256k1) can be requested. */
+ private static String ecCsrPem(String curve, String subject) throws Exception {
+ KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "BC");
+ kpg.initialize(new java.security.spec.ECGenParameterSpec(curve));
+ KeyPair keyPair = kpg.generateKeyPair();
+ PKCS10CertificationRequest csr = new JcaPKCS10CertificationRequestBuilder(
+ new X500Name(subject), keyPair.getPublic())
+ .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(keyPair.getPrivate()));
+ return toPem(csr);
+ }
+
+ private static KeyPair rsaKeyPair() throws Exception {
+ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
+ kpg.initialize(2048);
+ return kpg.generateKeyPair();
+ }
+
+ private static String csrPem(String subject, KeyPair keyPair) throws Exception {
+ PKCS10CertificationRequest csr = new JcaPKCS10CertificationRequestBuilder(
+ new X500Name(subject), keyPair.getPublic())
+ .build(new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate()));
+ return toPem(csr);
+ }
+
+ private static String toPem(Object object) throws Exception {
+ StringWriter out = new StringWriter();
+ try (JcaPEMWriter writer = new JcaPEMWriter(out)) {
+ writer.writeObject(object);
+ }
+ return out.toString();
+ }
+
+ /** AWS's fixed 2049 expiry, capped at the CA's own: a CA created before this change lives ten years. */
+ private static java.time.Instant expectedNotAfter(X509Certificate ca) {
+ java.time.Instant aws = java.time.Instant.parse("2049-12-31T23:59:59Z");
+ java.time.Instant caNotAfter = ca.getNotAfter().toInstant();
+ return caNotAfter.isBefore(aws) ? caNotAfter : aws;
+ }
+
+ private static X509Certificate parse(String pem) throws Exception {
+ return (X509Certificate) CertificateFactory.getInstance("X.509")
+ .generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java
index ad8a466e3c..2b8303b333 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java
@@ -10,6 +10,7 @@ import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
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;
@@ -384,11 +385,11 @@ class IotIntegrationTest {
.post("/keys-and-certificate")
.then()
.statusCode(200)
- .body("certificateId", notNullValue())
+ .body("certificateId", matchesPattern("[0-9a-f]{64}"))
.body("certificateArn", containsString(":iot:us-east-1:000000000000:cert/"))
.body("certificatePem", containsString("BEGIN CERTIFICATE"))
.body("keyPair.PublicKey", containsString("BEGIN PUBLIC KEY"))
- .body("keyPair.PrivateKey", containsString("BEGIN PRIVATE KEY"))
+ .body("keyPair.PrivateKey", containsString("BEGIN RSA PRIVATE KEY"))
.extract()
.path("certificateArn");
String certificateId = certificateArn.substring(certificateArn.lastIndexOf('/') + 1);
@@ -490,7 +491,7 @@ class IotIntegrationTest {
@Test
@Order(17)
- void certificateDeleteCsrStatusAndTagsMatchMvpLifecycle() {
+ void certificateDeleteCsrStatusAndTagsMatchMvpLifecycle() throws Exception {
String activeArn = given()
.queryParam("setAsActive", true)
.when()
@@ -563,7 +564,7 @@ class IotIntegrationTest {
String csrArn = given()
.contentType("application/json")
.queryParam("setAsActive", false)
- .body("{\"certificateSigningRequest\":\"-----BEGIN CERTIFICATE REQUEST-----\\nfloci\\n-----END CERTIFICATE REQUEST-----\"}")
+ .body(java.util.Map.of("certificateSigningRequest", csrPem()))
.when()
.post("/certificates")
.then()
@@ -760,4 +761,18 @@ class IotIntegrationTest {
.path("thingArn");
}
+
+ private static String csrPem() throws Exception {
+ java.security.KeyPairGenerator kpg = java.security.KeyPairGenerator.getInstance("RSA");
+ kpg.initialize(2048);
+ java.security.KeyPair kp = kpg.generateKeyPair();
+ var csr = new org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder(
+ new org.bouncycastle.asn1.x500.X500Name("CN=round-trip"), kp.getPublic())
+ .build(new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA").build(kp.getPrivate()));
+ java.io.StringWriter out = new java.io.StringWriter();
+ try (var w = new org.bouncycastle.openssl.jcajce.JcaPEMWriter(out)) {
+ w.writeObject(csr);
+ }
+ return out.toString();
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java
index 073f0a8dde..5b24f371bd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java
@@ -95,7 +95,8 @@ class IotServiceTest {
dynamoDb,
lambda,
firehose,
- logs);
+ logs,
+ mock(io.github.hectorvent.floci.config.FlociCertificateAuthority.class));
}
private IotTopicRule createRule(String name, String payloadJson) throws Exception {