mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(cloudfront): hold an ACM certificate in use while a distribution serves it (#6946)
This commit is contained in:
1 parent
a03e88b451
commit
de244061cf
5 files changed
+176
-16
No files matched your search
@@ -38,7 +38,7 @@
|
||||
- **Certificate Types:** `AMAZON_ISSUED` (default) and `PRIVATE` (when `CertificateAuthorityArn` is provided)
|
||||
- **Imported keys:** `ImportCertificate` requires a private key that matches the certificate. A rejected import leaves an existing certificate unchanged.
|
||||
- **Export:** Only `PRIVATE` type certificates can be exported with their private key
|
||||
- **In use:** `DescribeCertificate` lists under `InUseBy` the CloudFront distribution of each Cognito custom domain that uses the certificate, and `DeleteCertificate` refuses with `ResourceInUseException` while that list is not empty. Other consumers, such as load balancers and API Gateway domain names, are not tracked yet.
|
||||
- **In use:** `DescribeCertificate` lists under `InUseBy` the CloudFront distribution of each Cognito custom domain that uses the certificate and each CloudFront distribution whose `ViewerCertificate.ACMCertificateArn` names it, and `DeleteCertificate` refuses with `ResourceInUseException` while that list is not empty. Other consumers, such as load balancers and API Gateway domain names, are not tracked yet.
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -301,6 +301,9 @@ PUT, PATCH and DELETE).
|
||||
- `ViewerCertificate.IAMCertificateId` must be the `ServerCertificateId` of an uploaded IAM server
|
||||
certificate: distribution create and update reject an unknown one with `InvalidViewerCertificate`,
|
||||
and `DeleteServerCertificate` returns `DeleteConflict` while a distribution references it.
|
||||
- `ViewerCertificate.ACMCertificateArn` must name an existing ACM certificate: distribution create and
|
||||
update reject an unknown one with `InvalidViewerCertificate`. ACM lists the distribution's ARN under
|
||||
`InUseBy`, and `DeleteCertificate` returns `ResourceInUseException` while a distribution references it.
|
||||
- Up to 20 custom response headers policies can be created, and one policy can be associated with
|
||||
up to 100 distributions.
|
||||
- The five AWS managed response headers policy IDs are available and can be selected with
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.AcmCertificateReferenceProvider;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** ACM discovers this consumer lazily, after the CloudFront service has initialized. */
|
||||
@ApplicationScoped
|
||||
public class CloudFrontAcmCertificateReferences implements AcmCertificateReferenceProvider {
|
||||
private final CloudFrontService service;
|
||||
|
||||
@Inject
|
||||
public CloudFrontAcmCertificateReferences(CloudFrontService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CertificateReference> acmCertificateReferences() {
|
||||
return service.acmCertificateReferences();
|
||||
}
|
||||
|
||||
/** The emulated edge serves no TLS from the viewer certificate, so there is nothing to refresh. */
|
||||
@Override
|
||||
public void certificateReimported(String certificateArn, String region) {
|
||||
}
|
||||
}
|
||||
+64
-11
@@ -5,12 +5,14 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.LocalStackParity;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
|
||||
import io.github.hectorvent.floci.core.common.CloudFrontEdgeDomain;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.acm.AcmCertificateReferenceProvider.CertificateReference;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.CachePolicy;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;
|
||||
@@ -137,6 +139,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
private final String accountId;
|
||||
private final RegionResolver regionResolver;
|
||||
private final IamService iamService;
|
||||
private final CertificateReferenceResolver certificates;
|
||||
private final String configuredDomainSuffix;
|
||||
/**
|
||||
* Host suffixes under which every distribution is served as {@code <id><suffix>}, whatever
|
||||
@@ -151,13 +154,14 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
private final Pattern lambdaOriginHost;
|
||||
|
||||
public CloudFrontService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver) {
|
||||
this(factory, config, regionResolver, null);
|
||||
this(factory, config, regionResolver, null, null);
|
||||
}
|
||||
|
||||
@Inject
|
||||
public CloudFrontService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
IamService iamService) {
|
||||
IamService iamService, CertificateReferenceResolver certificates) {
|
||||
this.iamService = iamService;
|
||||
this.certificates = certificates;
|
||||
this.distStore = factory.create("cloudfront", "cloudfront-distributions.json",
|
||||
new TypeReference<Map<String, Distribution>>() {});
|
||||
this.invalidationStore = factory.create("cloudfront", "cloudfront-invalidations.json",
|
||||
@@ -269,6 +273,30 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
return references;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ACM certificates the distributions serve, each held by its distribution, so ACM lists the
|
||||
* distribution in {@code InUseBy} and refuses to delete the certificate. Like
|
||||
* {@link #serverCertificateReferences} it reads a copy of the store and takes no monitor.
|
||||
*/
|
||||
public List<CertificateReference> acmCertificateReferences() {
|
||||
List<CertificateReference> references = new ArrayList<>();
|
||||
for (Distribution distribution : distStore.scan(k -> true)) {
|
||||
String certificateArn = acmCertificateArn(distribution.getConfig());
|
||||
if (certificateArn != null) {
|
||||
references.add(new CertificateReference(certificateArn, distribution.getArn()));
|
||||
}
|
||||
}
|
||||
return references;
|
||||
}
|
||||
|
||||
private static String acmCertificateArn(DistributionConfig config) {
|
||||
if (config == null || config.getViewerCertificate() == null) {
|
||||
return null;
|
||||
}
|
||||
String certificateArn = config.getViewerCertificate().get("ACMCertificateArn");
|
||||
return certificateArn == null || certificateArn.isBlank() ? null : certificateArn;
|
||||
}
|
||||
|
||||
private static String iamCertificateId(DistributionConfig config) {
|
||||
if (config == null || config.getViewerCertificate() == null) {
|
||||
return null;
|
||||
@@ -285,24 +313,49 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
"The specified SSL certificate doesn't exist, isn't valid, "
|
||||
+ "or doesn't include a valid certificate chain.", 400);
|
||||
}
|
||||
String certificateArn = acmCertificateArn(config);
|
||||
if (certificateArn != null && !isExistingAcmCertificate(certificateArn)) {
|
||||
throw new AwsException("InvalidViewerCertificate",
|
||||
"The specified SSL certificate doesn't exist, isn't valid, "
|
||||
+ "or doesn't include a valid certificate chain.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a write that may record an IAM server certificate reference while IAM holds the lock
|
||||
* {@code DeleteServerCertificate} takes, so the certificate cannot be deleted between
|
||||
* Only an ACM certificate: the resolver also answers for IAM server certificates, but one named
|
||||
* here would never be held by {@link #serverCertificateReferences}, which reads
|
||||
* {@code IAMCertificateId}.
|
||||
*/
|
||||
private boolean isExistingAcmCertificate(String arn) {
|
||||
if (!AwsArnUtils.isArn(arn)) {
|
||||
return false;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
return "acm".equals(parsed.service())
|
||||
&& (certificates == null || certificates.exists(parsed.region(), arn));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a write that may record a certificate reference while the certificate's owner holds the
|
||||
* lock its delete takes, IAM's for {@code DeleteServerCertificate} and ACM's for
|
||||
* {@code DeleteCertificate}, so the certificate cannot be deleted between
|
||||
* {@link #validateViewerCertificate} and the store write. Without the guard the delete sees no
|
||||
* reference, because the distribution is not saved yet, and the distribution is left holding a
|
||||
* certificate that is gone.
|
||||
* certificate that is gone. IAM's lock is taken first, the order the resolver uses.
|
||||
*/
|
||||
private <T> T whileCertificatesHeld(DistributionConfig config, Supplier<T> action) {
|
||||
String certificateArn = acmCertificateArn(config);
|
||||
Supplier<T> acmHeld = certificates == null || certificateArn == null
|
||||
? action
|
||||
: () -> certificates.supplyWhileHeld(List.of(certificateArn), action);
|
||||
if (iamService == null || iamCertificateId(config) == null) {
|
||||
// Nothing to order. A distribution that names no IAM certificate cannot be left
|
||||
// holding one, and the scan reads a copy of the store rather than a live collection,
|
||||
// so this write cannot disturb it either. Taking the lock anyway would make every
|
||||
// distribution write wait on a certificate delete, and the other way round.
|
||||
return action.get();
|
||||
// Nothing to order with IAM. A distribution that names no IAM certificate cannot be
|
||||
// left holding one, and the scan reads a copy of the store rather than a live
|
||||
// collection, so this write cannot disturb it either. Taking the lock anyway would make
|
||||
// every distribution write wait on a certificate delete, and the other way round.
|
||||
return acmHeld.get();
|
||||
}
|
||||
return iamService.supplyWithServerCertificatesHeld(action);
|
||||
return iamService.supplyWithServerCertificatesHeld(acmHeld);
|
||||
}
|
||||
|
||||
private static void validateOriginSettings(DistributionConfig config) {
|
||||
|
||||
+80
-4
@@ -1,7 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.acm.AcmService;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.Certificate;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
|
||||
@@ -16,6 +18,7 @@ import org.junit.jupiter.api.Test;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
@@ -24,22 +27,27 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* A distribution's {@code ViewerCertificate.IAMCertificateId} is resolved against IAM, and the
|
||||
* certificate it names cannot be deleted while a distribution still holds it.
|
||||
* A distribution's {@code ViewerCertificate.IAMCertificateId} is resolved against IAM and its
|
||||
* {@code ACMCertificateArn} against ACM, and the certificate it names cannot be deleted while a
|
||||
* distribution still holds it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFrontViewerCertificateTest {
|
||||
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
|
||||
private static final String ACM_REGION = "us-east-1";
|
||||
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
|
||||
|
||||
private final CloudFrontService cloudFrontService;
|
||||
private final IamService iamService;
|
||||
private final AcmService acmService;
|
||||
|
||||
CloudFrontViewerCertificateTest(CloudFrontService cloudFrontService, IamService iamService) {
|
||||
CloudFrontViewerCertificateTest(CloudFrontService cloudFrontService, IamService iamService,
|
||||
AcmService acmService) {
|
||||
this.cloudFrontService = cloudFrontService;
|
||||
this.iamService = iamService;
|
||||
this.acmService = acmService;
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
@@ -53,7 +61,18 @@ class CloudFrontViewerCertificateTest {
|
||||
pair.privateKeyPem(), null, Map.of());
|
||||
}
|
||||
|
||||
private Certificate importAcmCertificate() {
|
||||
CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
|
||||
"cf.certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
|
||||
return acmService.importCertificate(pair.certificatePem(), pair.privateKeyPem(), null, null,
|
||||
Map.of(), ACM_REGION);
|
||||
}
|
||||
|
||||
private Distribution distributionWithCertificate(String certificateId) {
|
||||
return distributionWithViewerCertificate("IAMCertificateId", certificateId);
|
||||
}
|
||||
|
||||
private Distribution distributionWithViewerCertificate(String member, String certificate) {
|
||||
Origin origin = new Origin();
|
||||
origin.setId("cert-origin");
|
||||
origin.setDomainName("example.com");
|
||||
@@ -73,7 +92,7 @@ class CloudFrontViewerCertificateTest {
|
||||
config.setOrigins(List.of(origin));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Map<String, String> viewerCertificate = new LinkedHashMap<>();
|
||||
viewerCertificate.put("IAMCertificateId", certificateId);
|
||||
viewerCertificate.put(member, certificate);
|
||||
viewerCertificate.put("SSLSupportMethod", "sni-only");
|
||||
config.setViewerCertificate(viewerCertificate);
|
||||
|
||||
@@ -116,4 +135,61 @@ class CloudFrontViewerCertificateTest {
|
||||
.formParam("ServerCertificateName", name)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDistributionRejectsAnAcmCertificateThatDoesNotExist() {
|
||||
String missing = "arn:aws:acm:us-east-1:000000000000:certificate/" + UUID.randomUUID();
|
||||
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> cloudFrontService.createDistribution(
|
||||
distributionWithViewerCertificate("ACMCertificateArn", missing), Map.of()));
|
||||
|
||||
assertEquals("InvalidViewerCertificate", rejected.getErrorCode());
|
||||
assertEquals(400, rejected.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDistributionRejectsAnIamCertificateArnAsAnAcmCertificate() {
|
||||
ServerCertificate certificate = uploadCertificate("cf-cert-as-acm-" + suffix());
|
||||
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> cloudFrontService.createDistribution(
|
||||
distributionWithViewerCertificate("ACMCertificateArn", certificate.getArn()), Map.of()));
|
||||
|
||||
assertEquals("InvalidViewerCertificate", rejected.getErrorCode());
|
||||
assertEquals(400, rejected.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAcmCertificateIsHeldByTheDistributionUntilItIsGone() {
|
||||
String certificateArn = importAcmCertificate().getArn();
|
||||
|
||||
Distribution created = cloudFrontService.createDistribution(
|
||||
distributionWithViewerCertificate("ACMCertificateArn", certificateArn), Map.of());
|
||||
|
||||
assertEquals(List.of(created.getArn()), acmService.certificateInUseBy(certificateArn, ACM_REGION));
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> acmService.deleteCertificate(certificateArn, ACM_REGION));
|
||||
assertEquals("ResourceInUseException", refused.getErrorCode());
|
||||
assertEquals(400, refused.getHttpStatus());
|
||||
|
||||
cloudFrontService.removeDistribution(created.getId());
|
||||
|
||||
acmService.deleteCertificate(certificateArn, ACM_REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacingTheAcmCertificateReleasesTheOldOneAndHoldsTheNewOne() {
|
||||
String oldArn = importAcmCertificate().getArn();
|
||||
String newArn = importAcmCertificate().getArn();
|
||||
Distribution created = cloudFrontService.createDistribution(
|
||||
distributionWithViewerCertificate("ACMCertificateArn", oldArn), Map.of());
|
||||
|
||||
cloudFrontService.updateDistribution(created.getId(), created.getEtag(),
|
||||
distributionWithViewerCertificate("ACMCertificateArn", newArn));
|
||||
|
||||
acmService.deleteCertificate(oldArn, ACM_REGION);
|
||||
assertEquals(List.of(created.getArn()), acmService.certificateInUseBy(newArn, ACM_REGION));
|
||||
|
||||
cloudFrontService.removeDistribution(created.getId());
|
||||
acmService.deleteCertificate(newArn, ACM_REGION);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user