From a0123f8f69c1692c5ec81d571df69341331bb5e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20Gamboa?= Date: Wed, 25 Nov 2026 00:40:15 -0300 Subject: [PATCH] feat(cloudfront): distribution tenants for multi-tenant distributions (#9398) --- README.md | 2 +- .../CloudFrontDistributionTenantTest.java | 149 ++++++ docs/services/cloudformation.md | 2 +- docs/services/cloudfront.md | 71 ++- docs/services/index.md | 2 +- .../CloudFrontCfnProvisioner.java | 133 ++++- .../cloudfront/CloudFrontController.java | 304 +++++++++++ .../cloudfront/CloudFrontService.java | 353 ++++++++++++- .../cloudfront/model/DistributionTenant.java | 66 +++ .../model/TenantCustomizations.java | 41 ++ .../create-only-properties.json | 3 + ...rontDistributionTenantIntegrationTest.java | 165 ++++++ .../CloudFrontCfnProvisionerTest.java | 169 ++++++- .../cloudfront/CloudFrontControllerTest.java | 44 ++ ...tDistributionTenantSdkIntegrationTest.java | 425 ++++++++++++++++ ...oudFrontDistributionTenantServiceTest.java | 472 ++++++++++++++++++ .../cloudformation/change-exempt.tsv | 1 + .../cloudformation/getatt-attribute-gaps.tsv | 1 + .../cloudformation/schema-surface.tsv | 1 + .../supported-resource-types.tsv | 1 + .../cloudformation/writable-property-gaps.tsv | 3 + 21 files changed, 2395 insertions(+), 13 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontDistributionTenantTest.java create mode 100644 src/main/java/io/floci/aws/services/cloudfront/model/DistributionTenant.java create mode 100644 src/main/java/io/floci/aws/services/cloudfront/model/TenantCustomizations.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudFrontDistributionTenantIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudfront/CloudFrontDistributionTenantSdkIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudfront/CloudFrontDistributionTenantServiceTest.java diff --git a/README.md b/README.md index 253e5f7ee4..f13116b493 100644 --- a/README.md +++ b/README.md @@ -390,7 +390,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | AWS Config | In-process | Config rules, evaluation-driven compliance (PutEvaluations, compliance details and summaries), configuration recorders, delivery channels, retention configuration, conformance packs, tagging | | Organizations | In-process | Organizations, roots, nested OUs, member accounts, all policy types with `FullAWSAccess` and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable Floci accounts and member accounts can read the organization they belong to | | CloudTrail | In-process | Trails, event selectors (S3 data events with bucket/prefix matching), `StartLogging`/`StopLogging`, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits `AccessDenied` records | -| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, functions, key value stores, tagging, multi-tenant connection groups | +| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, functions, key value stores, tagging, multi-tenant connection groups and distribution tenants | | WAF v2 | In-process | Web ACLs, IP sets, regex pattern sets, rule groups, logging configs, resource associations, tagging (REGIONAL and CLOUDFRONT scopes) | | AWS Resource Groups | In-process | Five capacity-pool operations: stored groups, verified EC2 reservation membership, scoped pagination and group deletion; no dynamic queries or capacity allocation | | Resource Explorer 2 | In-process | All 32 management APIs: index and view lifecycle, multi-Region setup tasks, the full search query grammar, and tagging; 30 services expose their resources for search, gathered live rather than from an index | diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontDistributionTenantTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontDistributionTenantTest.java new file mode 100644 index 0000000000..29dccccbdb --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontDistributionTenantTest.java @@ -0,0 +1,149 @@ +package com.floci.test; + +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudfront.CloudFrontClient; +import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse; +import software.amazon.awssdk.services.cloudfront.model.DefaultCacheBehavior; +import software.amazon.awssdk.services.cloudfront.model.DistributionConfig; +import software.amazon.awssdk.services.cloudfront.model.DistributionTenantSummary; +import software.amazon.awssdk.services.cloudfront.model.DomainItem; +import software.amazon.awssdk.services.cloudfront.model.EntityAlreadyExistsException; +import software.amazon.awssdk.services.cloudfront.model.EntityNotFoundException; +import software.amazon.awssdk.services.cloudfront.model.GetDistributionTenantByDomainResponse; +import software.amazon.awssdk.services.cloudfront.model.GetDistributionTenantResponse; +import software.amazon.awssdk.services.cloudfront.model.InvalidIfMatchVersionException; +import software.amazon.awssdk.services.cloudfront.model.NoSuchDistributionException; +import software.amazon.awssdk.services.cloudfront.model.Origin; +import software.amazon.awssdk.services.cloudfront.model.Origins; +import software.amazon.awssdk.services.cloudfront.model.Parameter; +import software.amazon.awssdk.services.cloudfront.model.PreconditionFailedException; +import software.amazon.awssdk.services.cloudfront.model.ResourceNotDisabledException; +import software.amazon.awssdk.services.cloudfront.model.S3OriginConfig; +import software.amazon.awssdk.services.cloudfront.model.ViewerCertificate; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CloudFrontDistributionTenantTest { + + @Test + void roundTripsDistributionTenantsWithTheAwsSdk() { + String unique = TestFixtures.uniqueName(); + String name = "compat-tenant-" + unique; + String domain = "compat-" + unique + ".example.com"; + + try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) { + String distributionId = cloudFront.createDistribution(request -> request + .distributionConfig(tenantOnlyConfig(unique))) + .distribution().id(); + String tenantId = null; + try { + CreateDistributionTenantResponse created = cloudFront.createDistributionTenant(request -> request + .distributionId(distributionId) + .name(name) + .domains(DomainItem.builder().domain(domain).build()) + .parameters(Parameter.builder().name("origin_path").value("/compat").build())); + tenantId = created.distributionTenant().id(); + String id = tenantId; + assertTrue(id.startsWith("dt_")); + assertTrue(created.distributionTenant().arn().endsWith(":distribution-tenant/" + id)); + assertTrue(created.distributionTenant().enabled()); + assertNotNull(created.distributionTenant().connectionGroupId()); + assertEquals("active", created.distributionTenant().domains().get(0).statusAsString()); + + GetDistributionTenantResponse byId = + cloudFront.getDistributionTenant(request -> request.identifier(id)); + assertEquals(created.eTag(), byId.eTag()); + assertEquals(id, cloudFront.getDistributionTenant(request -> request.identifier(name)) + .distributionTenant().id()); + assertEquals(id, cloudFront.getDistributionTenant( + request -> request.identifier(created.distributionTenant().arn())) + .distributionTenant().id()); + GetDistributionTenantByDomainResponse byDomain = + cloudFront.getDistributionTenantByDomain(request -> request.domain(domain)); + assertEquals(id, byDomain.distributionTenant().id()); + + DistributionTenantSummary listed = cloudFront.listDistributionTenants(request -> request + .associationFilter(filter -> filter.distributionId(distributionId))) + .distributionTenantList().get(0); + assertEquals(id, listed.id()); + assertEquals(created.eTag(), listed.eTag()); + + assertThrows(EntityAlreadyExistsException.class, () -> cloudFront.createDistributionTenant( + request -> request.distributionId(distributionId).name(name) + .domains(DomainItem.builder().domain("other-" + unique + ".example.com").build()))); + assertThrows(InvalidIfMatchVersionException.class, + () -> cloudFront.updateDistributionTenant(request -> request.id(id).enabled(false))); + assertThrows(PreconditionFailedException.class, + () -> cloudFront.updateDistributionTenant(request -> request + .id(id).ifMatch("E000000000000").enabled(false))); + assertThrows(ResourceNotDisabledException.class, + () -> cloudFront.deleteDistributionTenant(request -> request + .id(id).ifMatch(created.eTag()))); + + cloudFront.updateDistributionTenant(request -> request + .id(id).ifMatch(created.eTag()).enabled(false)); + GetDistributionTenantResponse updated = + cloudFront.getDistributionTenant(request -> request.identifier(id)); + assertFalse(updated.distributionTenant().enabled()); + + cloudFront.deleteDistributionTenant(request -> request.id(id).ifMatch(updated.eTag())); + tenantId = null; + assertThrows(EntityNotFoundException.class, + () -> cloudFront.getDistributionTenant(request -> request.identifier(id))); + } finally { + disableAndDelete(cloudFront, tenantId); + disableAndDeleteDistribution(cloudFront, distributionId); + } + } + } + + private static DistributionConfig tenantOnlyConfig(String unique) { + return DistributionConfig.builder() + .callerReference("compat-tenant-config-" + unique) + .comment("multi-tenant") + .enabled(true) + .origins(Origins.builder().quantity(1).items(Origin.builder() + .id("origin1") + .domainName("example-bucket.s3.us-east-1.amazonaws.com") + .s3OriginConfig(S3OriginConfig.builder().originAccessIdentity("").build()) + .build()).build()) + .defaultCacheBehavior(DefaultCacheBehavior.builder() + .targetOriginId("origin1") + .viewerProtocolPolicy("redirect-to-https") + .build()) + .viewerCertificate(ViewerCertificate.builder().cloudFrontDefaultCertificate(true).build()) + .connectionMode("tenant-only") + .build(); + } + + private static void disableAndDelete(CloudFrontClient cloudFront, String tenantId) { + if (tenantId == null) { + return; + } + try { + String etag = cloudFront.getDistributionTenant(request -> request.identifier(tenantId)).eTag(); + cloudFront.updateDistributionTenant(request -> request.id(tenantId).ifMatch(etag).enabled(false)); + String freshEtag = cloudFront.getDistributionTenant(request -> request.identifier(tenantId)).eTag(); + cloudFront.deleteDistributionTenant(request -> request.id(tenantId).ifMatch(freshEtag)); + } catch (EntityNotFoundException ignored) { + // teardown only: the emulator state is per-test, so a partially cleaned tenant cannot leak into another test + } + } + + private static void disableAndDeleteDistribution(CloudFrontClient cloudFront, String distributionId) { + try { + String etag = cloudFront.getDistribution(request -> request.id(distributionId)).eTag(); + cloudFront.updateDistribution(request -> request.id(distributionId).ifMatch(etag) + .distributionConfig(cloudFront.getDistributionConfig(byId -> byId.id(distributionId)) + .distributionConfig().toBuilder().enabled(false).build())); + String freshEtag = cloudFront.getDistribution(request -> request.id(distributionId)).eTag(); + cloudFront.deleteDistribution(request -> request.id(distributionId).ifMatch(freshEtag)); + } catch (NoSuchDistributionException ignored) { + // teardown only: a distribution that is already gone has nothing left to clean up + } + } +} diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 7d4e93302f..7be0daa953 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -256,7 +256,7 @@ cross-resource references. | Kinesis | `Stream` | | Kinesis Data Firehose | `DeliveryStream` (`DeliveryStreamName`, `Tags` and, from an S3 destination, `BucketARN`, `RoleARN`, `Prefix`, `ErrorOutputPrefix`, `CompressionFormat`, `BufferingHints`, `CloudWatchLoggingOptions` and `ProcessingConfiguration` are applied; other properties are ignored, and a destination member the template drops on update keeps its stored value, as on AWS) | | IoT Core | `Authorizer`, `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` | -| CloudFront | `CachePolicy`, `ConnectionGroup`, `Distribution`, `Function` (`KeyValueStoreAssociations` is ignored), `KeyGroup`, `OriginAccessControl`, `OriginRequestPolicy`, `PublicKey`, `ResponseHeadersPolicy` | +| CloudFront | `CachePolicy`, `ConnectionGroup`, `Distribution`, `DistributionTenant`, `Function` (`KeyValueStoreAssociations` is ignored), `KeyGroup`, `OriginAccessControl`, `OriginRequestPolicy`, `PublicKey`, `ResponseHeadersPolicy` | | CloudWatch | `Alarm`, `CompositeAlarm`, `Dashboard`. Composite alarms have backing definitions with name Ref and Arn GetAtt, rollback, and replacement cleanup. Composite actions are stored only; suppression properties are rejected. | | CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` | | WAFv2 | `IPSet`, `LoggingConfiguration`, `WebACL`, `WebACLAssociation` | diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md index b294f7be39..cb4c879cc6 100644 --- a/docs/services/cloudfront.md +++ b/docs/services/cloudfront.md @@ -53,6 +53,68 @@ and answer `InvalidIfMatchVersion` without it, `PreconditionFailed` on a stale v `Marker`, `MaxItems` and an optional `AssociationFilter.AnycastIpListId`, and returns `ConnectionGroupSummary` items carrying the group's `ETag`. +### Distribution Tenants + +A distribution tenant is a customer of a multi-tenant distribution: it carries its own domains, a +connection group, and optional parameters and customizations. The tenants' data plane (serving by +tenant domain), tenant invalidations, WAF association operations and managed certificate details are +not implemented. + +| Operation | Method | Path | +|---|---|---| +| `CreateDistributionTenant` | POST | `/2020-05-31/distribution-tenant` | +| `GetDistributionTenant` | GET | `/2020-05-31/distribution-tenant/{Identifier}` | +| `GetDistributionTenantByDomain` | GET | `/2020-05-31/distribution-tenant?domain` | +| `UpdateDistributionTenant` | PUT | `/2020-05-31/distribution-tenant/{Id}` | +| `DeleteDistributionTenant` | DELETE | `/2020-05-31/distribution-tenant/{Id}` | +| `ListDistributionTenants` | POST | `/2020-05-31/distribution-tenants` | +| `ListDistributionTenantsByCustomization` | POST | `/2020-05-31/distribution-tenants-by-customization` | + +The service model does not spell every outcome out, so these are Floci's readings of it: + +- `DistributionId` must name an existing distribution (`EntityNotFound` otherwise) whose + configuration has `ConnectionMode: tenant-only`. The model declares no code for a standard + distribution, so it is answered with `InvalidArgument`. A `ConnectionGroupId` that names no group + is `EntityNotFound`; an omitted one is the account's default connection group, and the id comes + back on the tenant. +- `Name` is unique per account (`EntityAlreadyExists`), fixed after creation, and held to the + pattern the request shape declares. A tenant is addressable by its id, name or ARN in + `GetDistributionTenant`; `UpdateDistributionTenant` and `DeleteDistributionTenant` take the id. + Ids are `dt_` followed by 24 characters, like connection group ids. The ARN names the account of + the request, as a connection group's does. +- At least one domain is required, and a tenant has up to 5 (the limit `UpdateDistributionTenant` + documents), answered with `EntityLimitExceeded` beyond that. A domain is unique, ignoring case, + across all tenants and all distribution `Aliases` (`CNAMEAlreadyExists`), in both directions: a + distribution cannot claim an alias a tenant holds, whether in its configuration or through + `AssociateAlias`, which also answers `CNAMEAlreadyExists` for a tenant's domain. Floci performs no DNS or certificate checks, so + every domain reads back with `Status: active`, and the tenant itself reads `Status: Deployed`. +- `Enabled` defaults to true. `DeleteDistributionTenant` requires the tenant to be disabled + (`ResourceNotDisabled`) and, like `UpdateDistributionTenant`, requires `If-Match`: it answers + `InvalidIfMatchVersion` without it and `PreconditionFailed` on a stale value. Every write rotates + the `ETag`. An update leaves alone what it omits and replaces `Domains`, `Parameters` and + `Customizations` wholesale when it carries them; it may also move the tenant to another + `tenant-only` distribution or connection group. +- `Parameters` and `Customizations` are validated for shape only (`Name` and `Value` are required, + parameter name pattern and value length, `WebAcl.Action` is required with a `WebAcl` and + `GeoRestrictions.RestrictionType` is held to its enumeration); each failure is `InvalidArgument`. A distribution's + `TenantConfig.ParameterDefinitions` is not modeled, so the parameters are stored as given and not + checked against the distribution. `ManagedCertificateRequest` is accepted and ignored. +- `AWS::CloudFront::DistributionTenant` updates are declarative: a template that drops + `ConnectionGroupId` moves the tenant back to the account's default connection group, which is what + a create without it picks. +- `ListDistributionTenants` takes `Marker`, `MaxItems` and an optional `AssociationFilter` by + `DistributionId` or `ConnectionGroupId`. `ListDistributionTenantsByCustomization` takes exactly one + of `WebACLArn` and `CertificateArn` and answers `InvalidArgument` for none or both. Both list + tenants by name and return `DistributionTenantSummary` items carrying the tenant's `ETag`. +- Tags use the CloudFront tag operations on the tenant's ARN, and are removed with the tenant. The + `Domains` and `Parameters` lists declare no member name, so the SDKs read their items as `member` + elements, which is how Floci writes them; a request is read by position. +- `DeleteConnectionGroup` answers `CannotDeleteEntityWhileInUse` for a group that a tenant still + references, after the `If-Match` checks and the default-group refusal and before the + `ResourceNotDisabled` check. +- Deleting a distribution that still has tenants is not refused: AWS documents no such error, so + the tenants keep their stored `DistributionId`. + ### Invalidations | Operation | Method | Path | @@ -263,7 +325,8 @@ These operations store what they are given and return it, so code that manages t `N...`. - OAI `CallerReference` uniqueness is enforced — duplicate `CallerReference` values return `CloudFrontOriginAccessIdentityAlreadyExists` (409). - CNAME aliases are globally unique. `AssociateAlias` atomically transfers an alias from its current - owner to the target distribution. Exact aliases take precedence over the most-specific matching + owner to the target distribution, except a domain a distribution tenant holds, which is refused + with `CNAMEAlreadyExists`. Exact aliases take precedence over the most-specific matching wildcard alias. - Viewer requests addressed to an enabled distribution's generated domain or alias are routed to the matching S3 or custom origin when the matched cache behavior's `AllowedMethods` includes the @@ -726,9 +789,9 @@ signatures must still return 403. Verify those cases through the proxy after con - `TestFunction` execution (function is stored, not executed) - Serving RTMP for a streaming distribution (deprecated by AWS) - VPC origins, Anycast IP lists -- Connection groups and distribution tenants (`CreateConnectionGroup`, `CreateDistributionTenant`, - etc.), their CloudFormation types, `ListDistributionsByConnectionMode`, and serving a - `tenant-only` distribution by a tenant's domain +- Serving a `tenant-only` distribution by a tenant's domain, tenant invalidations, web ACL + association and managed certificate details (`CreateInvalidationForDistributionTenant`, + `AssociateDistributionTenantWebACL`, `GetManagedCertificateDetails`, etc.) - Importing keys into a key value store from S3: `CreateKeyValueStore` with an `ImportSource` is rejected with `InvalidArgument` - Running CloudFront Functions, so the key value store can only be read and written through its API, not diff --git a/docs/services/index.md b/docs/services/index.md index 655df73b80..1418b7942d 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -148,7 +148,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 | | [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 | | [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/package-group*`, `/v1/list-associated-packages`, `/v1/get-associated-package-group`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 48 | -| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*`, `/2020-05-31/key-value-store/*` | REST XML | 104 | +| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*`, `/2020-05-31/key-value-store/*` | REST XML | 111 | | [CloudFront KeyValueStore](cloudfront.md#key-value-stores) | `/key-value-stores/*` | REST JSON | 6 | | [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*`, `/2013-04-01/delegationset/*` | REST XML | 31 | | [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 25 | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java index cdf8d08d4a..3c1f5cdec5 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java @@ -13,12 +13,14 @@ import io.floci.aws.services.cloudfront.model.ConnectionGroup; import io.floci.aws.services.cloudfront.model.DefaultCacheBehavior; import io.floci.aws.services.cloudfront.model.Distribution; import io.floci.aws.services.cloudfront.model.DistributionConfig; +import io.floci.aws.services.cloudfront.model.DistributionTenant; import io.floci.aws.services.cloudfront.model.KeyGroup; import io.floci.aws.services.cloudfront.model.Origin; import io.floci.aws.services.cloudfront.model.OriginAccessControl; import io.floci.aws.services.cloudfront.model.OriginRequestPolicy; import io.floci.aws.services.cloudfront.model.PublicKey; import io.floci.aws.services.cloudfront.model.ResponseHeadersPolicy; +import io.floci.aws.services.cloudfront.model.TenantCustomizations; import jakarta.enterprise.context.ApplicationScoped; import org.jboss.logging.Logger; @@ -70,6 +72,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { static final String KEY_GROUP = "AWS::CloudFront::KeyGroup"; static final String FUNCTION = "AWS::CloudFront::Function"; static final String CONNECTION_GROUP = "AWS::CloudFront::ConnectionGroup"; + static final String DISTRIBUTION_TENANT = "AWS::CloudFront::DistributionTenant"; static final String NO_SUCH_RESPONSE_HEADERS_POLICY = "NoSuchResponseHeadersPolicy"; static final String NO_SUCH_CACHE_POLICY = "NoSuchCachePolicy"; @@ -91,7 +94,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { @Override public Set resourceTypes() { return Set.of(DISTRIBUTION, RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY, - ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION, CONNECTION_GROUP); + ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION, CONNECTION_GROUP, DISTRIBUTION_TENANT); } @Override @@ -107,6 +110,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { case KEY_GROUP -> provisionKeyGroup(r, props, ctx); case FUNCTION -> provisionFunction(r, props, ctx); case CONNECTION_GROUP -> provisionConnectionGroup(r, props, ctx); + case DISTRIBUTION_TENANT -> provisionDistributionTenant(r, props, ctx); default -> throw new IllegalArgumentException("Unsupported resource type: " + r.getResourceType()); } ReplacementCleanup.record(r, ctx, attributesBefore); @@ -191,6 +195,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { cloudFrontService::deleteKeyGroup, NO_SUCH_KEY_GROUP); case FUNCTION -> deleteFunction(physicalId); case CONNECTION_GROUP -> deleteConnectionGroup(physicalId); + case DISTRIBUTION_TENANT -> deleteDistributionTenant(physicalId); default -> { } } } @@ -273,6 +278,128 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { provisioned.getLastModifiedTime() == null ? "" : provisioned.getLastModifiedTime().toString()); } + /** + * An enabled tenant refuses its delete with {@code ResourceNotDisabled}, so a stack delete, a + * replacement cleanup or a rollback disables it first with the etag it carries and deletes it + * with the fresh one the disable minted, as the registry schema's delete handler does (it asks + * for {@code UpdateDistributionTenant} as well as {@code DeleteDistributionTenant}). The tags + * kept under the ARN go with the tenant. Only the type's own not-found code is tolerated. + */ + private void deleteDistributionTenant(String physicalId) { + CfnDeletes.safeDelete("distribution tenant", physicalId, () -> { + DistributionTenant tenant = cloudFrontService.getDistributionTenant(physicalId); + String etag = tenant.getEtag(); + if (Boolean.TRUE.equals(tenant.getEnabled())) { + etag = cloudFrontService.updateDistributionTenant(physicalId, etag, null, null, null, null, + null, false).getEtag(); + } + cloudFrontService.deleteDistributionTenant(physicalId, etag); + }, ENTITY_NOT_FOUND); + } + + /** + * The tenant the template names is created on first use and updated in place afterwards: + * {@code Name} is the only create-only property the registry schema declares, so an update whose + * resolved {@code Name} differs from the prior tenant's replaces it, and the engine's + * replacement cleanup deletes the old tenant through {@link #deleteDistributionTenant} once the + * update commits. Otherwise the physical id only changes when the prior tenant is already gone. + * The schema's read-only members ({@code Id}, {@code Arn}, {@code ETag}, {@code Status} and the + * two timestamps) travel to {@code Fn::GetAtt} from the provisioned object; {@code DomainResults} + * is a list, which attributes as Floci keeps them (text) cannot hold. + * + *

An update is declarative: it drives the tags, {@code Customizations} and {@code Parameters} + * to the template's set, so a template that drops one clears it, and it reads an absent + * {@code Enabled} as the default, true, and a dropped {@code ConnectionGroupId} as the account's + * default connection group, which is what a create picks. {@code ManagedCertificateRequest}, + * {@code DomainMappings} and {@code OnDomainTakeover} are accepted and ignored: Floci issues no + * managed certificates and serves every domain the same way. + */ + private void provisionDistributionTenant(StackResource r, JsonNode props, ProvisionContext ctx) { + String distributionId = requireText(DISTRIBUTION_TENANT, "DistributionId", props, ctx); + String name = requireText(DISTRIBUTION_TENANT, "Name", props, ctx); + List domains = tenantDomains(props, ctx); + TenantCustomizations customizations = tenantCustomizations(props, ctx); + Map parameters = tenantParameters(props, ctx); + String connectionGroupId = ctx.resolveOptional(props, "ConnectionGroupId"); + Boolean enabled = ctx.resolveOptionalBoolean(props, "Enabled"); + Map tags = ctx.resolveTags(props, "Tags"); + + DistributionTenant provisioned; + DistributionTenant prior = prior(ctx, "distribution tenant", + cloudFrontService::getDistributionTenant, ENTITY_NOT_FOUND); + if (prior == null || !name.equals(prior.getName())) { + provisioned = cloudFrontService.createDistributionTenant(distributionId, name, domains, tags, + customizations, parameters, connectionGroupId, enabled); + } else { + String groupId = connectionGroupId == null || connectionGroupId.isBlank() + ? cloudFrontService.ensureDefaultConnectionGroup().getId() : connectionGroupId; + provisioned = cloudFrontService.updateDistributionTenant(prior.getId(), prior.getEtag(), + distributionId, domains, customizations == null ? new TenantCustomizations() : customizations, + parameters == null ? Map.of() : parameters, groupId, + enabled == null ? Boolean.TRUE : enabled); + reconcileTags(provisioned.getArn(), tags); + } + r.setPhysicalId(provisioned.getId()); + r.getAttributes().put("Id", provisioned.getId()); + r.getAttributes().put("Arn", provisioned.getArn()); + r.getAttributes().put("ETag", provisioned.getEtag()); + r.getAttributes().put("Status", provisioned.getStatus()); + r.getAttributes().put("CreatedTime", + provisioned.getCreatedTime() == null ? "" : provisioned.getCreatedTime().toString()); + r.getAttributes().put("LastModifiedTime", + provisioned.getLastModifiedTime() == null ? "" : provisioned.getLastModifiedTime().toString()); + } + + private static List tenantDomains(JsonNode props, ProvisionContext ctx) { + JsonNode raw = props.get("Domains"); + JsonNode resolved = raw == null || raw.isNull() ? null : ctx.engine().resolveNode(raw); + if (resolved == null || !resolved.isArray() || resolved.isEmpty()) { + throw new AwsException("ValidationError", DISTRIBUTION_TENANT + " requires Domains", 400); + } + List domains = new ArrayList<>(); + for (JsonNode domain : resolved) { + domains.add(domain.asText()); + } + return domains; + } + + private static Map tenantParameters(JsonNode props, ProvisionContext ctx) { + JsonNode raw = props.get("Parameters"); + JsonNode resolved = raw == null || raw.isNull() ? null : ctx.engine().resolveNode(raw); + if (resolved == null || !resolved.isArray()) { + return null; + } + Map parameters = new LinkedHashMap<>(); + for (JsonNode parameter : resolved) { + parameters.put(text(parameter, "Name"), text(parameter, "Value")); + } + return parameters; + } + + private static TenantCustomizations tenantCustomizations(JsonNode props, ProvisionContext ctx) { + JsonNode raw = props.get("Customizations"); + JsonNode resolved = raw == null || raw.isNull() ? null : ctx.engine().resolveNode(raw); + if (resolved == null || !resolved.isObject()) { + return null; + } + TenantCustomizations customizations = new TenantCustomizations(); + JsonNode webAcl = resolved.get("WebAcl"); + if (webAcl != null && webAcl.isObject()) { + customizations.setWebAclAction(text(webAcl, "Action")); + customizations.setWebAclArn(text(webAcl, "Arn")); + } + JsonNode certificate = resolved.get("Certificate"); + if (certificate != null && certificate.isObject()) { + customizations.setCertificateArn(text(certificate, "Arn")); + } + JsonNode geo = resolved.get("GeoRestrictions"); + if (geo != null && geo.isObject()) { + customizations.setGeoRestrictionType(text(geo, "RestrictionType")); + customizations.setGeoLocations(textList(geo, "Locations")); + } + return customizations; + } + private static void requireConnectionGroupName(String name) { if (name == null || name.isBlank()) { throw new AwsException("ValidationError", CONNECTION_GROUP + " requires Name", 400); @@ -415,7 +542,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { if (autoPublish) { cloudFrontService.publishFunction(name, provisioned.getEtag()); } - reconcileFunctionTags(arn, tags); + reconcileTags(arn, tags); } catch (RuntimeException failure) { if (prior == null) { // The stack keeps its prior id when this resource fails, so nothing else would @@ -454,7 +581,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { return arn.substring(arn.lastIndexOf('/') + 1); } - private void reconcileFunctionTags(String arn, Map desired) { + private void reconcileTags(String arn, Map desired) { List stale = ProvisionContext.staleTagKeys(cloudFrontService.listTagsForResource(arn), desired); if (!stale.isEmpty()) { cloudFrontService.untagResource(arn, stale); diff --git a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontController.java b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontController.java index 1f66bc619b..f5901b1699 100644 --- a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontController.java +++ b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontController.java @@ -329,6 +329,149 @@ public class CloudFrontController { return Response.ok(xml.build(), XML).build(); } + // ── Distribution tenants ────────────────────────────────────────────────── + + @POST + @Path("/distribution-tenant") + public Response createDistributionTenant(String body) { + try { + XmlParser.XmlElement request = XmlParser.extractElementTree(body, "CreateDistributionTenantRequest"); + DistributionTenant tenant = service.createDistributionTenant( + tenantText(request, "DistributionId"), + tenantText(request, "Name"), + tenantDomains(request), + parseTags(body), + tenantCustomizations(request), + tenantParameters(request), + tenantText(request, "ConnectionGroupId"), + xmlBoolean(tenantText(request, "Enabled"))); + return Response.created(URI.create("/2020-05-31/distribution-tenant/" + tenant.getId())) + .type(XML) + .header("ETag", tenant.getEtag()) + .entity(xmlDistributionTenant(tenant)) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/distribution-tenant/{Identifier}") + public Response getDistributionTenant(@PathParam("Identifier") String identifier) { + try { + DistributionTenant tenant = service.getDistributionTenant(identifier); + return Response.ok(xmlDistributionTenant(tenant), XML) + .header("ETag", tenant.getEtag()) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @GET + @Path("/distribution-tenant") + public Response getDistributionTenantByDomain(@QueryParam("domain") String domain) { + try { + DistributionTenant tenant = service.getDistributionTenantByDomain(domain); + return Response.ok(xmlDistributionTenant(tenant), XML) + .header("ETag", tenant.getEtag()) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @PUT + @Path("/distribution-tenant/{Id}") + public Response updateDistributionTenant(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch, + String body) { + try { + XmlParser.XmlElement request = XmlParser.extractElementTree(body, "UpdateDistributionTenantRequest"); + DistributionTenant tenant = service.updateDistributionTenant(id, ifMatch, + tenantText(request, "DistributionId"), + tenantDomains(request), + tenantCustomizations(request), + tenantParameters(request), + tenantText(request, "ConnectionGroupId"), + xmlBoolean(tenantText(request, "Enabled"))); + return Response.ok(xmlDistributionTenant(tenant), XML) + .header("ETag", tenant.getEtag()) + .build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @DELETE + @Path("/distribution-tenant/{Id}") + public Response deleteDistributionTenant(@PathParam("Id") String id, + @HeaderParam("If-Match") String ifMatch) { + try { + service.deleteDistributionTenant(id, ifMatch); + return Response.noContent().build(); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @POST + @Path("/distribution-tenants") + public Response listDistributionTenants(String body) { + try { + Map request = XmlParser.extractGroups(body, "ListDistributionTenantsRequest") + .stream().findFirst().orElse(Map.of()); + String distributionId = null; + String connectionGroupId = null; + for (Map filter : XmlParser.extractGroups(body, "AssociationFilter")) { + distributionId = blankToNull(filter.get("DistributionId")); + connectionGroupId = blankToNull(filter.get("ConnectionGroupId")); + } + int pageSize = pageSizeOf(parseMaxItems(request.get("MaxItems"))); + Page page = page( + service.listDistributionTenants(request.get("Marker"), paginationFetchLimit(pageSize), + distributionId, connectionGroupId), + pageSize, DistributionTenant::getName); + return distributionTenantListResponse("ListDistributionTenantsResult", page); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + @POST + @Path("/distribution-tenants-by-customization") + public Response listDistributionTenantsByCustomization(String body) { + try { + Map request = + XmlParser.extractGroups(body, "ListDistributionTenantsByCustomizationRequest") + .stream().findFirst().orElse(Map.of()); + int pageSize = pageSizeOf(parseMaxItems(request.get("MaxItems"))); + Page page = page( + service.listDistributionTenantsByCustomization(request.get("Marker"), + paginationFetchLimit(pageSize), blankToNull(request.get("WebACLArn")), + blankToNull(request.get("CertificateArn"))), + pageSize, DistributionTenant::getName); + return distributionTenantListResponse("ListDistributionTenantsByCustomizationResult", page); + } catch (AwsException e) { + return xmlErrorResponse(e); + } + } + + private static int pageSizeOf(Integer maxItems) { + return maxItems == null ? 100 : maxItems; + } + + private Response distributionTenantListResponse(String root, Page page) { + XmlBuilder xml = new XmlBuilder() + .start(root, NS) + .elem("NextMarker", page.nextMarker()) + .start("DistributionTenantList"); + for (DistributionTenant tenant : page.items()) { + xml.raw(xmlDistributionTenantSummary(tenant)); + } + return Response.ok(xml.end("DistributionTenantList").end(root).build(), XML).build(); + } + // ── Invalidations ───────────────────────────────────────────────────────── @POST @@ -4197,4 +4340,165 @@ public class CloudFrontController { } return null; } + + private static String tenantText(XmlParser.XmlElement request, String name) { + XmlParser.XmlElement child = request == null ? null : request.child(name); + return child == null || child.text().isEmpty() ? null : child.text(); + } + + /** The {@code Domains} members, or null when the request carries no {@code Domains}. */ + private static List tenantDomains(XmlParser.XmlElement request) { + XmlParser.XmlElement domains = request == null ? null : request.child("Domains"); + if (domains == null) { + return null; + } + List result = new ArrayList<>(); + for (XmlParser.XmlElement item : domains.children()) { + XmlParser.XmlElement domain = item.child("Domain"); + result.add(domain == null ? null : domain.text()); + } + return result; + } + + private static Map tenantParameters(XmlParser.XmlElement request) { + XmlParser.XmlElement parameters = request == null ? null : request.child("Parameters"); + if (parameters == null) { + return null; + } + Map result = new LinkedHashMap<>(); + for (XmlParser.XmlElement parameter : parameters.children()) { + result.put(tenantText(parameter, "Name"), tenantText(parameter, "Value")); + } + return result; + } + + private static TenantCustomizations tenantCustomizations(XmlParser.XmlElement request) { + XmlParser.XmlElement element = request == null ? null : request.child("Customizations"); + if (element == null) { + return null; + } + TenantCustomizations customizations = new TenantCustomizations(); + XmlParser.XmlElement webAcl = element.child("WebAcl"); + if (webAcl != null) { + customizations.setWebAclAction(tenantText(webAcl, "Action")); + customizations.setWebAclArn(tenantText(webAcl, "Arn")); + } + XmlParser.XmlElement certificate = element.child("Certificate"); + if (certificate != null) { + customizations.setCertificateArn(tenantText(certificate, "Arn")); + } + XmlParser.XmlElement geo = element.child("GeoRestrictions"); + if (geo != null) { + customizations.setGeoRestrictionType(tenantText(geo, "RestrictionType")); + XmlParser.XmlElement locations = geo.child("Locations"); + if (locations != null) { + List codes = new ArrayList<>(); + for (XmlParser.XmlElement location : locations.children()) { + codes.add(location.text()); + } + customizations.setGeoLocations(codes); + } + } + return customizations; + } + + private String xmlDistributionTenant(DistributionTenant tenant) { + XmlBuilder xml = new XmlBuilder().start("DistributionTenant", NS) + .elem("Id", tenant.getId()) + .elem("DistributionId", tenant.getDistributionId()) + .elem("Name", tenant.getName()) + .elem("Arn", tenant.getArn()); + appendTenantDomains(xml, tenant); + Map tags = service.listTagsForResource(tenant.getArn()); + if (!tags.isEmpty()) { + xml.start("Tags").start("Items"); + for (Map.Entry tag : tags.entrySet()) { + xml.start("Tag") + .elem("Key", tag.getKey()) + .elem("Value", tag.getValue()) + .end("Tag"); + } + xml.end("Items").end("Tags"); + } + appendTenantCustomizations(xml, tenant); + if (tenant.getParameters() != null && !tenant.getParameters().isEmpty()) { + xml.start("Parameters"); + for (Map.Entry parameter : tenant.getParameters().entrySet()) { + xml.start("member") + .elem("Name", parameter.getKey()) + .elem("Value", parameter.getValue()) + .end("member"); + } + xml.end("Parameters"); + } + xml.elem("ConnectionGroupId", tenant.getConnectionGroupId()) + .elem("CreatedTime", tenant.getCreatedTime().toString()) + .elem("LastModifiedTime", tenant.getLastModifiedTime().toString()) + .elem("Enabled", tenant.getEnabled()) + .elem("Status", tenant.getStatus()); + return xml.end("DistributionTenant").build(); + } + + private static String xmlDistributionTenantSummary(DistributionTenant tenant) { + XmlBuilder xml = new XmlBuilder().start("DistributionTenantSummary", NS) + .elem("Id", tenant.getId()) + .elem("DistributionId", tenant.getDistributionId()) + .elem("Name", tenant.getName()) + .elem("Arn", tenant.getArn()); + appendTenantDomains(xml, tenant); + xml.elem("ConnectionGroupId", tenant.getConnectionGroupId()); + appendTenantCustomizations(xml, tenant); + xml.elem("CreatedTime", tenant.getCreatedTime().toString()) + .elem("LastModifiedTime", tenant.getLastModifiedTime().toString()) + .elem("ETag", tenant.getEtag()) + .elem("Enabled", tenant.getEnabled()) + .elem("Status", tenant.getStatus()); + return xml.end("DistributionTenantSummary").build(); + } + + /** + * Every domain reads back {@code active}: Floci performs no DNS or certificate validation. The + * {@code Domains} and {@code Parameters} lists declare no member name, so the SDKs read their + * items as {@code member} elements; requests are read by position, whatever the items are called. + */ + private static void appendTenantDomains(XmlBuilder xml, DistributionTenant tenant) { + xml.start("Domains"); + for (String domain : tenant.getDomains()) { + xml.start("member") + .elem("Domain", domain) + .elem("Status", "active") + .end("member"); + } + xml.end("Domains"); + } + + private static void appendTenantCustomizations(XmlBuilder xml, DistributionTenant tenant) { + TenantCustomizations customizations = tenant.getCustomizations(); + if (customizations == null || customizations.isEmpty()) { + return; + } + xml.start("Customizations"); + if (customizations.getWebAclAction() != null) { + xml.start("WebAcl").elem("Action", customizations.getWebAclAction()); + if (customizations.getWebAclArn() != null) { + xml.elem("Arn", customizations.getWebAclArn()); + } + xml.end("WebAcl"); + } + if (customizations.getCertificateArn() != null) { + xml.start("Certificate").elem("Arn", customizations.getCertificateArn()).end("Certificate"); + } + if (customizations.getGeoRestrictionType() != null) { + xml.start("GeoRestrictions").elem("RestrictionType", customizations.getGeoRestrictionType()); + if (customizations.getGeoLocations() != null && !customizations.getGeoLocations().isEmpty()) { + xml.start("Locations"); + for (String location : customizations.getGeoLocations()) { + xml.elem("Location", location); + } + xml.end("Locations"); + } + xml.end("GeoRestrictions"); + } + xml.end("Customizations"); + } } diff --git a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontService.java b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontService.java index 0e147937a8..cdf5c3ffc6 100644 --- a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontService.java +++ b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontService.java @@ -23,6 +23,7 @@ import io.floci.aws.services.cloudfront.model.ContinuousDeploymentPolicy; import io.floci.aws.services.cloudfront.model.DefaultCacheBehavior; import io.floci.aws.services.cloudfront.model.Distribution; import io.floci.aws.services.cloudfront.model.DistributionConfig; +import io.floci.aws.services.cloudfront.model.DistributionTenant; import io.floci.aws.services.cloudfront.model.FieldLevelEncryptionConfig; import io.floci.aws.services.cloudfront.model.FieldLevelEncryptionProfile; import io.floci.aws.services.cloudfront.model.Invalidation; @@ -36,6 +37,7 @@ import io.floci.aws.services.cloudfront.model.PublicKey; import io.floci.aws.services.cloudfront.model.RealtimeLogConfig; import io.floci.aws.services.cloudfront.model.ResponseHeadersPolicy; import io.floci.aws.services.cloudfront.model.StreamingDistribution; +import io.floci.aws.services.cloudfront.model.TenantCustomizations; import io.floci.aws.services.iam.IamService; import io.floci.aws.services.iam.ServerCertificateReferenceProvider; import jakarta.enterprise.context.ApplicationScoped; @@ -95,6 +97,15 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { private static final Set CONNECTION_MODES = Set.of("direct", "tenant-only"); /** AWS names the account's automatically created connection group "default". */ private static final String DEFAULT_CONNECTION_GROUP_NAME = "default"; + /** A distribution tenant's Name: the pattern its request shape declares (3 to 128 characters). */ + private static final Pattern TENANT_NAME = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9-.]{1,126}[a-zA-Z0-9]"); + /** The pattern a tenant parameter's Name declares, and the length its Value is held to. */ + private static final Pattern TENANT_PARAMETER_NAME = Pattern.compile("[a-zA-Z0-9-_]{1,128}"); + private static final int TENANT_PARAMETER_VALUE_MAX_LENGTH = 256; + /** UpdateDistributionTenant documents "up to 5 domains" for a tenant. */ + private static final int TENANT_MAX_DOMAINS = 5; + private static final Set TENANT_WEB_ACL_ACTIONS = Set.of("override", "disable"); + private static final Set TENANT_GEO_RESTRICTION_TYPES = Set.of("blacklist", "whitelist", "none"); /** The documented maximum a connection group's Name may reach (AWS's own limit). */ private static final int CONNECTION_GROUP_NAME_MAX_LENGTH = 256; /** @@ -157,6 +168,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { private final AccountAwareStorageBackend distStore; private final AccountAwareStorageBackend connectionGroupStore; + private final AccountAwareStorageBackend tenantStore; private final StorageBackend> invalidationStore; private final StorageBackend cachePolicyStore; private final StorageBackend orpStore; @@ -207,6 +219,8 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { new TypeReference>() {}); this.connectionGroupStore = factory.create("cloudfront", "cloudfront-connection-groups.json", new TypeReference>() {}); + this.tenantStore = factory.create("cloudfront", "cloudfront-distribution-tenants.json", + new TypeReference>() {}); this.invalidationStore = factory.create("cloudfront", "cloudfront-invalidations.json", new TypeReference>>() {}); this.cachePolicyStore = factory.create("cloudfront", "cloudfront-cache-policies.json", @@ -783,6 +797,9 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { if (dist.getConfig() == null) { throw new AwsException("InvalidArgument", "The target distribution has no configuration.", 400); } + if (tenantHoldsDomain(alias)) { + throw domainTaken(); + } for (Distribution candidate : distStore.scan(k -> true)) { if (targetDistributionId.equals(candidate.getId()) || candidate.getConfig() == null || candidate.getConfig().getAliases() == null) { @@ -913,6 +930,9 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { if (requested == null || requested.isBlank()) { continue; } + if (tenantHoldsDomain(requested)) { + throw domainTaken(); + } for (Distribution existing : distStore.scan(k -> true)) { if (existing.getId().equals(currentDistributionId) || existing.getConfig() == null || existing.getConfig().getAliases() == null) { @@ -920,8 +940,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { } for (String assigned : existing.getConfig().getAliases()) { if (requested.equalsIgnoreCase(assigned)) { - throw new AwsException("CNAMEAlreadyExists", - "The CNAME you provided is already associated with a different resource.", 409); + throw domainTaken(); } } } @@ -1148,6 +1167,12 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { throw new AwsException("CannotDeleteEntityWhileInUse", "The default connection group cannot be deleted.", 409); } + for (DistributionTenant tenant : tenantStore.scan(k -> true)) { + if (id.equals(tenant.getConnectionGroupId())) { + throw new AwsException("CannotDeleteEntityWhileInUse", + "The connection group is still used by a distribution tenant.", 409); + } + } if (Boolean.TRUE.equals(group.getEnabled())) { throw new AwsException("ResourceNotDisabled", "The connection group has not been disabled.", 409); @@ -1221,6 +1246,330 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { return sb.toString(); } + // ── Distribution tenants ────────────────────────────────────────────────── + + public synchronized DistributionTenant createDistributionTenant(String distributionId, String name, + List domains, + Map tags, + TenantCustomizations customizations, + Map parameters, + String connectionGroupId, + Boolean enabled) { + requireTenantName(name); + requireTenantDomains(domains); + requireTenantOnlyDistribution(distributionId); + String groupId = connectionGroupId == null || connectionGroupId.isBlank() + ? ensureDefaultConnectionGroup().getId() + : getConnectionGroup(connectionGroupId).getId(); + validateTenantCustomizations(customizations); + validateTenantParameters(parameters); + for (DistributionTenant existing : tenantStore.scan(k -> true)) { + if (name.equals(existing.getName())) { + throw new AwsException("EntityAlreadyExists", + "The distribution tenant " + name + " already exists.", 409); + } + } + ensureTenantDomainsAvailable(domains, null); + DistributionTenant tenant = new DistributionTenant(); + String id = "dt_" + randomIdSuffix(24); + tenant.setId(id); + tenant.setArn(regionResolver.buildGlobalArn("cloudfront", "distribution-tenant/" + id)); + tenant.setName(name); + tenant.setDistributionId(distributionId); + tenant.setConnectionGroupId(groupId); + tenant.setDomains(new ArrayList<>(domains)); + tenant.setCustomizations(customizations); + tenant.setParameters(parameters == null || parameters.isEmpty() ? null : new LinkedHashMap<>(parameters)); + tenant.setEnabled(enabled == null || enabled); + tenant.setStatus("Deployed"); + tenant.setCreatedTime(Instant.now()); + tenant.setLastModifiedTime(tenant.getCreatedTime()); + tenant.setEtag("E" + randomIdSuffix(12)); + if (tags != null && !tags.isEmpty()) { + tagStore.put(tenant.getArn(), new LinkedHashMap<>(tags)); + } + tenantStore.put(id, tenant); + return tenant; + } + + /** + * A tenant is addressed by its id, name or ARN wherever the API documents {@code Identifier} + * ("You can specify the ARN, ID, or name of the distribution tenant"). + */ + public DistributionTenant getDistributionTenant(String identifier) { + if (identifier == null || identifier.isBlank()) { + throw tenantNotFound(); + } + if (AwsArnUtils.looksLikeArn(identifier)) { + for (DistributionTenant tenant : tenantStore.scan(k -> true)) { + if (identifier.equals(tenant.getArn())) { + return tenant; + } + } + throw tenantNotFound(); + } + DistributionTenant tenant = tenantStore.get(identifier).orElse(null); + if (tenant != null) { + return tenant; + } + for (DistributionTenant candidate : tenantStore.scan(k -> true)) { + if (identifier.equals(candidate.getName())) { + return candidate; + } + } + throw tenantNotFound(); + } + + public DistributionTenant getDistributionTenantByDomain(String domain) { + if (domain != null) { + for (DistributionTenant tenant : tenantStore.scan(k -> true)) { + if (containsIgnoreCase(tenant.getDomains(), domain)) { + return tenant; + } + } + } + throw tenantNotFound(); + } + + /** + * A member the request omits keeps its stored value; one it carries replaces the stored one + * ({@code Domains}, {@code Parameters} and {@code Customizations} wholesale). {@code Name} is + * immutable and {@code Tags} change through TagResource, so neither is a parameter here. + */ + public synchronized DistributionTenant updateDistributionTenant(String id, String ifMatch, + String distributionId, + List domains, + TenantCustomizations customizations, + Map parameters, + String connectionGroupId, + Boolean enabled) { + requireIfMatch(ifMatch); + DistributionTenant tenant = requireDistributionTenant(id); + if (!tenant.getEtag().equals(ifMatch)) { + throw new AwsException("PreconditionFailed", + "The specified If-Match didn't match the ETag header.", 412); + } + if (domains != null) { + requireTenantDomains(domains); + ensureTenantDomainsAvailable(domains, id); + } + if (distributionId != null && !distributionId.isBlank()) { + requireTenantOnlyDistribution(distributionId); + } + String groupId = connectionGroupId == null || connectionGroupId.isBlank() ? null + : getConnectionGroup(connectionGroupId).getId(); + validateTenantCustomizations(customizations); + validateTenantParameters(parameters); + if (distributionId != null && !distributionId.isBlank()) { + tenant.setDistributionId(distributionId); + } + if (groupId != null) { + tenant.setConnectionGroupId(groupId); + } + if (domains != null) { + tenant.setDomains(new ArrayList<>(domains)); + } + if (customizations != null) { + tenant.setCustomizations(customizations); + } + if (parameters != null) { + tenant.setParameters(parameters.isEmpty() ? null : new LinkedHashMap<>(parameters)); + } + if (enabled != null) { + tenant.setEnabled(enabled); + } + tenant.setLastModifiedTime(Instant.now()); + tenant.setEtag("E" + randomIdSuffix(12)); + tenantStore.put(id, tenant); + return tenant; + } + + public synchronized void deleteDistributionTenant(String id, String ifMatch) { + requireIfMatch(ifMatch); + DistributionTenant tenant = requireDistributionTenant(id); + if (!tenant.getEtag().equals(ifMatch)) { + throw new AwsException("PreconditionFailed", + "Your request is missing requirements for this operation. Update your request and try again.", + 412); + } + if (Boolean.TRUE.equals(tenant.getEnabled())) { + throw new AwsException("ResourceNotDisabled", + "You must disable the distribution tenant before you can delete it.", 409); + } + tenantStore.delete(id); + tagStore.delete(tenant.getArn()); + } + + public List listDistributionTenants(String marker, int maxItems, + String distributionIdFilter, + String connectionGroupIdFilter) { + List all = new ArrayList<>(tenantStore.scan(k -> true)); + all.removeIf(tenant -> distributionIdFilter != null + && !distributionIdFilter.equals(tenant.getDistributionId())); + all.removeIf(tenant -> connectionGroupIdFilter != null + && !connectionGroupIdFilter.equals(tenant.getConnectionGroupId())); + all.sort((a, b) -> a.getName().compareTo(b.getName())); + return paginate(all, marker, maxItems, DistributionTenant::getName); + } + + /** AWS: "You must specify either the CertificateArn parameter or WebACLArn parameter, but not both". */ + public List listDistributionTenantsByCustomization(String marker, int maxItems, + String webAclArn, + String certificateArn) { + boolean byWebAcl = webAclArn != null && !webAclArn.isBlank(); + boolean byCertificate = certificateArn != null && !certificateArn.isBlank(); + if (byWebAcl == byCertificate) { + throw new AwsException("InvalidArgument", + "You must specify either WebACLArn or CertificateArn, but not both.", 400); + } + List all = new ArrayList<>(tenantStore.scan(k -> true)); + all.removeIf(tenant -> { + TenantCustomizations customizations = tenant.getCustomizations(); + if (customizations == null) { + return true; + } + return byWebAcl ? !webAclArn.equals(customizations.getWebAclArn()) + : !certificateArn.equals(customizations.getCertificateArn()); + }); + all.sort((a, b) -> a.getName().compareTo(b.getName())); + return paginate(all, marker, maxItems, DistributionTenant::getName); + } + + private DistributionTenant requireDistributionTenant(String id) { + DistributionTenant tenant = id == null ? null : tenantStore.get(id).orElse(null); + if (tenant == null) { + throw tenantNotFound(); + } + return tenant; + } + + private static AwsException tenantNotFound() { + return new AwsException("EntityNotFound", "The specified distribution tenant doesn't exist.", 404); + } + + /** + * Only a multi-tenant distribution ({@code ConnectionMode: tenant-only}) can have tenants. + * The API declares no code for a standard distribution, so Floci reads it as + * {@code InvalidArgument}; a distribution that does not exist is {@code EntityNotFound}. + */ + private void requireTenantOnlyDistribution(String distributionId) { + Distribution dist = distributionId == null || distributionId.isBlank() ? null + : distStore.get(distributionId).orElse(null); + if (dist == null) { + throw new AwsException("EntityNotFound", "The specified distribution does not exist.", 404); + } + if (!"tenant-only".equals(effectiveConnectionMode(dist))) { + throw new AwsException("InvalidArgument", + "The distribution " + distributionId + " is not a multi-tenant distribution.", 400); + } + } + + private static void requireTenantName(String name) { + if (name == null || !TENANT_NAME.matcher(name).matches()) { + throw new AwsException("InvalidArgument", "The Name specified is not valid.", 400); + } + } + + private static void requireTenantDomains(List domains) { + if (domains == null || domains.isEmpty()) { + throw new AwsException("InvalidArgument", "At least one domain must be specified.", 400); + } + if (domains.size() > TENANT_MAX_DOMAINS) { + throw new AwsException("EntityLimitExceeded", + "A distribution tenant can have up to " + TENANT_MAX_DOMAINS + " domains.", 400); + } + Set seen = new HashSet<>(); + for (String domain : domains) { + if (domain == null || domain.isBlank()) { + throw new AwsException("InvalidArgument", "The Domain specified is not valid.", 400); + } + if (!seen.add(domain.toLowerCase(Locale.ROOT))) { + throw new AwsException("InvalidArgument", + "The domain " + domain + " is specified more than once.", 400); + } + } + } + + /** A domain belongs to one tenant or one distribution alias; the check is case-insensitive. */ + private void ensureTenantDomainsAvailable(List domains, String currentTenantId) { + for (String domain : domains) { + if (tenantHoldsDomain(domain, currentTenantId)) { + throw domainTaken(); + } + } + for (Distribution dist : distStore.scan(k -> true)) { + if (dist.getConfig() == null) { + continue; + } + for (String domain : domains) { + if (containsIgnoreCase(dist.getConfig().getAliases(), domain)) { + throw domainTaken(); + } + } + } + } + + private boolean tenantHoldsDomain(String domain) { + return tenantHoldsDomain(domain, null); + } + + private boolean tenantHoldsDomain(String domain, String exceptTenantId) { + for (DistributionTenant tenant : tenantStore.scan(k -> true)) { + if (!tenant.getId().equals(exceptTenantId) && containsIgnoreCase(tenant.getDomains(), domain)) { + return true; + } + } + return false; + } + + private static AwsException domainTaken() { + return new AwsException("CNAMEAlreadyExists", + "One or more of the CNAMEs you provided are already associated with a different resource.", 409); + } + + private static boolean containsIgnoreCase(List values, String candidate) { + if (values == null) { + return false; + } + for (String value : values) { + if (candidate != null && candidate.equalsIgnoreCase(value)) { + return true; + } + } + return false; + } + + private static void validateTenantCustomizations(TenantCustomizations customizations) { + if (customizations == null) { + return; + } + if (customizations.getWebAclArn() != null && customizations.getWebAclAction() == null) { + throw new AwsException("InvalidArgument", "The WebAcl Action must be specified.", 400); + } + if (customizations.getWebAclAction() != null + && !TENANT_WEB_ACL_ACTIONS.contains(customizations.getWebAclAction())) { + throw new AwsException("InvalidArgument", "The WebAcl Action specified is not valid.", 400); + } + if (customizations.getGeoRestrictionType() != null + && !TENANT_GEO_RESTRICTION_TYPES.contains(customizations.getGeoRestrictionType())) { + throw new AwsException("InvalidArgument", "The GeoRestrictions RestrictionType is not valid.", 400); + } + } + + private static void validateTenantParameters(Map parameters) { + if (parameters == null) { + return; + } + for (Map.Entry parameter : parameters.entrySet()) { + String value = parameter.getValue(); + if (parameter.getKey() == null || !TENANT_PARAMETER_NAME.matcher(parameter.getKey()).matches() + || value == null || value.isEmpty() || value.length() > TENANT_PARAMETER_VALUE_MAX_LENGTH) { + throw new AwsException("InvalidArgument", + "The Parameter " + parameter.getKey() + " is not valid.", 400); + } + } + } + // ── Invalidations ───────────────────────────────────────────────────────── public synchronized Invalidation createInvalidation(String distributionId, Invalidation inv) { diff --git a/src/main/java/io/floci/aws/services/cloudfront/model/DistributionTenant.java b/src/main/java/io/floci/aws/services/cloudfront/model/DistributionTenant.java new file mode 100644 index 0000000000..1730c3ce16 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudfront/model/DistributionTenant.java @@ -0,0 +1,66 @@ +package io.floci.aws.services.cloudfront.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +public class DistributionTenant { + + private String id; + private String arn; + private String name; + private String distributionId; + private String connectionGroupId; + private List domains; + private TenantCustomizations customizations; + private Map parameters; + private Boolean enabled; + private String status; + private Instant createdTime; + private Instant lastModifiedTime; + private String etag; + + public DistributionTenant() {} + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getDistributionId() { return distributionId; } + public void setDistributionId(String distributionId) { this.distributionId = distributionId; } + + public String getConnectionGroupId() { return connectionGroupId; } + public void setConnectionGroupId(String connectionGroupId) { this.connectionGroupId = connectionGroupId; } + + public List getDomains() { return domains; } + public void setDomains(List domains) { this.domains = domains; } + + public TenantCustomizations getCustomizations() { return customizations; } + public void setCustomizations(TenantCustomizations customizations) { this.customizations = customizations; } + + public Map getParameters() { return parameters; } + public void setParameters(Map parameters) { this.parameters = parameters; } + + public Boolean getEnabled() { return enabled; } + public void setEnabled(Boolean enabled) { this.enabled = enabled; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public Instant getCreatedTime() { return createdTime; } + public void setCreatedTime(Instant createdTime) { this.createdTime = createdTime; } + + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + + public String getEtag() { return etag; } + public void setEtag(String etag) { this.etag = etag; } +} diff --git a/src/main/java/io/floci/aws/services/cloudfront/model/TenantCustomizations.java b/src/main/java/io/floci/aws/services/cloudfront/model/TenantCustomizations.java new file mode 100644 index 0000000000..f163d4258f --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudfront/model/TenantCustomizations.java @@ -0,0 +1,41 @@ +package io.floci.aws.services.cloudfront.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +/** + * The customizations of a distribution tenant: the WAF web ACL and ACM certificate it overrides + * from its multi-tenant distribution, and its geographic restriction. A null member is a + * customization the tenant does not set. + */ +@RegisterForReflection +public class TenantCustomizations { + + private String webAclAction; + private String webAclArn; + private String certificateArn; + private String geoRestrictionType; + private List geoLocations; + + public TenantCustomizations() {} + + public String getWebAclAction() { return webAclAction; } + public void setWebAclAction(String webAclAction) { this.webAclAction = webAclAction; } + + public String getWebAclArn() { return webAclArn; } + public void setWebAclArn(String webAclArn) { this.webAclArn = webAclArn; } + + public String getCertificateArn() { return certificateArn; } + public void setCertificateArn(String certificateArn) { this.certificateArn = certificateArn; } + + public String getGeoRestrictionType() { return geoRestrictionType; } + public void setGeoRestrictionType(String geoRestrictionType) { this.geoRestrictionType = geoRestrictionType; } + + public List getGeoLocations() { return geoLocations; } + public void setGeoLocations(List geoLocations) { this.geoLocations = geoLocations; } + + public boolean isEmpty() { + return webAclAction == null && certificateArn == null && geoRestrictionType == null; + } +} diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index 382a6bbd7b..96ae7b4ebd 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -205,6 +205,9 @@ "Name" ], "AWS::CloudFront::Distribution": [], + "AWS::CloudFront::DistributionTenant": [ + "Name" + ], "AWS::CloudFront::Function": [ "Name" ], diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudFrontDistributionTenantIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudFrontDistributionTenantIntegrationTest.java new file mode 100644 index 0000000000..0748630f5f --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudFrontDistributionTenantIntegrationTest.java @@ -0,0 +1,165 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudfront.CloudFrontService; +import io.floci.aws.services.cloudfront.model.DistributionTenant; +import io.floci.aws.testing.CfnRequests; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * AWS::CloudFront::DistributionTenant through the stack lifecycle: a tenant-only distribution and + * its tenant, the exact {@code Ref} and {@code Fn::GetAtt} values from the registry schema's + * read-only members, an in-place update with its declarative tags and parameters, a replacement + * when the create-only {@code Name} changes, and DeleteStack of a tenant that is still enabled. + */ +@QuarkusTest +class CloudFormationCloudFrontDistributionTenantIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + + @Inject + CloudFrontService cloudFrontService; + + @Test + void tenantFollowsTheStackLifecycle() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-cloudfront-tenant-" + suffix; + + CfnRequests.deploy("CreateStack", stackName, template(suffix, "acme-" + suffix, true, + "[{\"Key\": \"Env\", \"Value\": \"test\"}]", "[{\"Name\": \"origin_path\", \"Value\": \"/a\"}]"), + CFN_AUTH, "CREATE_COMPLETE"); + + String tenantId = output(stackName, "TenantRef"); + assertEquals(tenantId, output(stackName, "TenantId")); + DistributionTenant tenant = cloudFrontService.getDistributionTenant(tenantId); + assertEquals("cfn-tenant-" + suffix, tenant.getName()); + assertEquals(List.of("acme-" + suffix + ".example.com"), tenant.getDomains()); + assertTrue(tenant.getEnabled()); + assertEquals(output(stackName, "DistributionId"), tenant.getDistributionId()); + assertTrue(tenant.getArn().endsWith(":distribution-tenant/" + tenantId)); + assertEquals(tenant.getArn(), output(stackName, "TenantArn")); + assertEquals(tenant.getEtag(), output(stackName, "TenantEtag")); + assertEquals(tenant.getStatus(), output(stackName, "TenantStatus")); + assertEquals(tenant.getCreatedTime().toString(), output(stackName, "TenantCreatedTime")); + assertEquals(tenant.getLastModifiedTime().toString(), output(stackName, "TenantLastModifiedTime")); + assertEquals(Map.of("Env", "test"), cloudFrontService.listTagsForResource(tenant.getArn())); + assertEquals(Map.of("origin_path", "/a"), tenant.getParameters()); + + CfnRequests.deploy("UpdateStack", stackName, template(suffix, "other-" + suffix, false, + "[{\"Key\": \"Team\", \"Value\": \"edge\"}]", "[]"), CFN_AUTH, "UPDATE_COMPLETE"); + DistributionTenant updated = cloudFrontService.getDistributionTenant(tenantId); + assertEquals(tenantId, output(stackName, "TenantRef"), "an update keeps the tenant"); + assertFalse(updated.getEnabled()); + assertEquals(List.of("other-" + suffix + ".example.com"), updated.getDomains()); + assertNull(updated.getParameters(), "a template that empties Parameters clears them"); + assertEquals(Map.of("Team", "edge"), cloudFrontService.listTagsForResource(updated.getArn())); + + deleteStack(stackName); + assertEquals("EntityNotFound", + assertThrows(AwsException.class, () -> cloudFrontService.getDistributionTenant(tenantId)) + .getErrorCode()); + } + + @Test + void aChangedNameReplacesTheTenant() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-cloudfront-tenant-rename-" + suffix; + + CfnRequests.deploy("CreateStack", stackName, template(suffix, "acme-" + suffix, true, "[]", "[]"), + CFN_AUTH, "CREATE_COMPLETE"); + String firstId = output(stackName, "TenantRef"); + + CfnRequests.deploy("UpdateStack", stackName, + template(suffix + "r", "renamed-" + suffix, true, "[]", "[]"), CFN_AUTH, "UPDATE_COMPLETE"); + String secondId = output(stackName, "TenantRef"); + assertEquals("cfn-tenant-" + suffix + "r", cloudFrontService.getDistributionTenant(secondId).getName()); + assertEquals("EntityNotFound", + assertThrows(AwsException.class, () -> cloudFrontService.getDistributionTenant(firstId)) + .getErrorCode(), + "the displaced tenant is deleted once the update commits"); + + deleteStack(stackName); + } + + @Test + void aStackWithAnEnabledTenantDeletesIt() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-cloudfront-tenant-enabled-" + suffix; + + CfnRequests.deploy("CreateStack", stackName, template(suffix, "acme-" + suffix, true, "[]", "[]"), + CFN_AUTH, "CREATE_COMPLETE"); + String tenantId = output(stackName, "TenantRef"); + assertTrue(cloudFrontService.getDistributionTenant(tenantId).getEnabled()); + + deleteStack(stackName); + assertEquals("EntityNotFound", + assertThrows(AwsException.class, () -> cloudFrontService.getDistributionTenant(tenantId)) + .getErrorCode()); + } + + private static String output(String stackName, String key) { + return CfnRequests.output(CfnRequests.describe(stackName, CFN_AUTH), key); + } + + private static String template(String suffix, String domainLabel, boolean enabled, String tagsJson, + String parametersJson) { + return """ + { + "Resources": { + "Dist": { + "Type": "AWS::CloudFront::Distribution", + "Properties": { + "DistributionConfig": { + "Enabled": true, + "ConnectionMode": "tenant-only", + "Origins": [{"Id": "origin1", "DomainName": "example-bucket.s3.us-east-1.amazonaws.com", + "S3OriginConfig": {"OriginAccessIdentity": ""}}], + "DefaultCacheBehavior": {"TargetOriginId": "origin1", + "ViewerProtocolPolicy": "redirect-to-https", + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6"} + } + } + }, + "Tenant": { + "Type": "AWS::CloudFront::DistributionTenant", + "Properties": { + "DistributionId": {"Ref": "Dist"}, + "Name": {"Fn::Sub": ["cfn-tenant-${Suffix}", {"Suffix": "%s"}]}, + "Domains": ["%s.example.com"], + "Enabled": %s, + "Tags": %s, + "Parameters": %s + } + } + }, + "Outputs": { + "DistributionId": {"Value": {"Ref": "Dist"}}, + "TenantRef": {"Value": {"Ref": "Tenant"}}, + "TenantId": {"Value": {"Fn::GetAtt": "Tenant.Id"}}, + "TenantArn": {"Value": {"Fn::GetAtt": "Tenant.Arn"}}, + "TenantEtag": {"Value": {"Fn::GetAtt": "Tenant.ETag"}}, + "TenantStatus": {"Value": {"Fn::GetAtt": "Tenant.Status"}}, + "TenantCreatedTime": {"Value": {"Fn::GetAtt": "Tenant.CreatedTime"}}, + "TenantLastModifiedTime": {"Value": {"Fn::GetAtt": "Tenant.LastModifiedTime"}} + } + } + """.formatted(suffix, domainLabel, enabled, tagsJson, parametersJson); + } + + private static void deleteStack(String stackName) { + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java index c593a34d58..fde89f33fe 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java @@ -11,12 +11,14 @@ import io.floci.aws.services.cloudfront.model.CloudFrontFunction; import io.floci.aws.services.cloudfront.model.ConnectionGroup; import io.floci.aws.services.cloudfront.model.Distribution; import io.floci.aws.services.cloudfront.model.DistributionConfig; +import io.floci.aws.services.cloudfront.model.DistributionTenant; import io.floci.aws.services.cloudfront.model.KeyGroup; import io.floci.aws.services.cloudfront.model.Origin; import io.floci.aws.services.cloudfront.model.OriginAccessControl; import io.floci.aws.services.cloudfront.model.OriginRequestPolicy; import io.floci.aws.services.cloudfront.model.PublicKey; import io.floci.aws.services.cloudfront.model.ResponseHeadersPolicy; +import io.floci.aws.services.cloudfront.model.TenantCustomizations; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; @@ -62,6 +64,7 @@ class CloudFrontCfnProvisionerTest { private static final String KEY_GROUP = "AWS::CloudFront::KeyGroup"; private static final String FUNCTION = "AWS::CloudFront::Function"; private static final String CONNECTION_GROUP_TYPE = "AWS::CloudFront::ConnectionGroup"; + private static final String TENANT_TYPE = "AWS::CloudFront::DistributionTenant"; private static final String FUNCTION_ARN = "arn:aws:cloudfront::000000000000:function/my-function"; private static final String REGION = "us-east-1"; private static final String ID = "5cc3b908-e619-4b99-88e5-2cf7f45965bd"; @@ -122,7 +125,8 @@ class CloudFrontCfnProvisionerTest { @Test void servesTheDistributionAndTheTypesItReferences() { assertEquals(Set.of(DISTRIBUTION, RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY, - ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION, "AWS::CloudFront::ConnectionGroup"), + ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION, "AWS::CloudFront::ConnectionGroup", + "AWS::CloudFront::DistributionTenant"), provisioner.resourceTypes()); } @@ -1412,4 +1416,167 @@ class CloudFrontCfnProvisionerTest { provisioner.delete(CONNECTION_GROUP_TYPE, ID, REGION); verify(cloudFront, Mockito.times(1)).deleteConnectionGroup(any(), any()); } + + private static DistributionTenant tenant(String id, String etag, String name) { + DistributionTenant t = new DistributionTenant(); + t.setId(id); + t.setEtag(etag); + t.setName(name); + t.setArn("arn:aws:cloudfront::000000000000:distribution-tenant/" + id); + t.setStatus("Deployed"); + t.setCreatedTime(MODIFIED); + t.setLastModifiedTime(MODIFIED); + return t; + } + + @Test + void provisionsDistributionTenantWithEveryReadOnlyGetAttTheSchemaDeclares() throws Exception { + when(cloudFront.createDistributionTenant(any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(tenant("dt_abc", ETAG, "acme")); + StackResource r = resource(TENANT_TYPE); + + provisioner.provision(r, json(""" + {"DistributionId": "EDIST", "Name": "acme", "Domains": ["acme.example.com"], + "Enabled": true, "ConnectionGroupId": "cg_x", + "Tags": [{"Key": "env", "Value": "test"}], + "Parameters": [{"Name": "origin_path", "Value": "/acme"}], + "Customizations": {"WebAcl": {"Action": "override", "Arn": "arn:acl"}, + "Certificate": {"Arn": "arn:cert"}, + "GeoRestrictions": {"RestrictionType": "whitelist", "Locations": ["US"]}}, + "ManagedCertificateRequest": {"ValidationTokenHost": "cloudfront"}} + """), connectionCtx(null)); + + ArgumentCaptor customizations = ArgumentCaptor.forClass(TenantCustomizations.class); + verify(cloudFront).createDistributionTenant(eq("EDIST"), eq("acme"), eq(List.of("acme.example.com")), + eq(Map.of("env", "test")), customizations.capture(), eq(Map.of("origin_path", "/acme")), + eq("cg_x"), eq(Boolean.TRUE)); + assertEquals("override", customizations.getValue().getWebAclAction()); + assertEquals("arn:acl", customizations.getValue().getWebAclArn()); + assertEquals("arn:cert", customizations.getValue().getCertificateArn()); + assertEquals("whitelist", customizations.getValue().getGeoRestrictionType()); + assertEquals(List.of("US"), customizations.getValue().getGeoLocations()); + assertEquals("dt_abc", r.getPhysicalId()); + assertEquals(Map.of("Id", "dt_abc", + "Arn", "arn:aws:cloudfront::000000000000:distribution-tenant/dt_abc", + "ETag", ETAG, + "Status", "Deployed", + "CreatedTime", MODIFIED.toString(), + "LastModifiedTime", MODIFIED.toString()), r.getAttributes()); + } + + @Test + void aTenantNeedsItsRequiredProperties() throws Exception { + assertThrows(AwsException.class, () -> provisioner.provision(resource(TENANT_TYPE), json(""" + {"Name": "acme", "Domains": ["a.example.com"]} + """), connectionCtx(null))); + assertThrows(AwsException.class, () -> provisioner.provision(resource(TENANT_TYPE), json(""" + {"DistributionId": "EDIST", "Domains": ["a.example.com"]} + """), connectionCtx(null))); + assertThrows(AwsException.class, () -> provisioner.provision(resource(TENANT_TYPE), json(""" + {"DistributionId": "EDIST", "Name": "acme"} + """), connectionCtx(null))); + } + + @Test + void updatesATenantInPlaceDeclarativelyWithThePriorEtag() throws Exception { + DistributionTenant prior = tenant("dt_prior", ETAG, "acme"); + when(cloudFront.getDistributionTenant("dt_prior")).thenReturn(prior); + ConnectionGroup defaultGroup = new ConnectionGroup(); + defaultGroup.setId("cg_default"); + when(cloudFront.ensureDefaultConnectionGroup()).thenReturn(defaultGroup); + when(cloudFront.listTagsForResource(prior.getArn())).thenReturn(Map.of("stale", "1")); + when(cloudFront.updateDistributionTenant(eq("dt_prior"), eq(ETAG), eq("EDIST"), + eq(List.of("b.example.com")), any(), eq(Map.of()), eq("cg_default"), + eq(Boolean.TRUE))).thenReturn(tenant("dt_prior", NEW_ETAG, "acme")); + StackResource r = resource(TENANT_TYPE, "dt_prior", Map.of("Id", "dt_prior")); + + provisioner.provision(r, json(""" + {"DistributionId": "EDIST", "Name": "acme", "Domains": ["b.example.com"], + "Tags": [{"Key": "env", "Value": "test"}]} + """), connectionCtx("dt_prior")); + + assertEquals("dt_prior", r.getPhysicalId()); + assertEquals(NEW_ETAG, r.getAttributes().get("ETag")); + verify(cloudFront, never()).createDistributionTenant(any(), any(), any(), any(), any(), any(), any(), + any()); + ArgumentCaptor cleared = ArgumentCaptor.forClass(TenantCustomizations.class); + verify(cloudFront).updateDistributionTenant(eq("dt_prior"), eq(ETAG), eq("EDIST"), any(), + cleared.capture(), any(), any(), any()); + assertTrue(cleared.getValue().isEmpty(), "a template that drops Customizations clears them"); + verify(cloudFront).untagResource(prior.getArn(), List.of("stale")); + verify(cloudFront).tagResource(prior.getArn(), Map.of("env", "test")); + } + + @Test + void anUpdateThatDropsTheConnectionGroupMovesTheTenantBackToTheDefaultGroup() throws Exception { + DistributionTenant prior = tenant("dt_prior", ETAG, "acme"); + when(cloudFront.getDistributionTenant("dt_prior")).thenReturn(prior); + ConnectionGroup defaultGroup = new ConnectionGroup(); + defaultGroup.setId("cg_default"); + when(cloudFront.ensureDefaultConnectionGroup()).thenReturn(defaultGroup); + when(cloudFront.updateDistributionTenant(any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(tenant("dt_prior", NEW_ETAG, "acme")); + StackResource r = resource(TENANT_TYPE, "dt_prior", Map.of("Id", "dt_prior")); + + provisioner.provision(r, json(""" + {"DistributionId": "EDIST", "Name": "acme", "Domains": ["b.example.com"]} + """), connectionCtx("dt_prior")); + + verify(cloudFront).updateDistributionTenant(eq("dt_prior"), eq(ETAG), eq("EDIST"), any(), any(), any(), + eq("cg_default"), any()); + } + + @Test + void aChangedNameReplacesTheTenantAndTheCleanupDeletesTheOldOne() throws Exception { + DistributionTenant prior = tenant("dt_prior", ETAG, "acme"); + prior.setEnabled(false); + when(cloudFront.getDistributionTenant("dt_prior")).thenReturn(prior); + DistributionTenant created = tenant("dt_new", NEW_ETAG, "renamed"); + when(cloudFront.createDistributionTenant(eq("EDIST"), eq("renamed"), any(), any(), any(), any(), any(), + any())).thenReturn(created); + StackResource r = resource(TENANT_TYPE, "dt_prior", Map.of("Id", "dt_prior")); + + provisioner.provision(r, json(""" + {"DistributionId": "EDIST", "Name": "renamed", "Domains": ["a.example.com"]} + """), connectionCtx("dt_prior")); + + assertEquals("dt_new", r.getPhysicalId()); + verify(cloudFront, never()).updateDistributionTenant(any(), any(), any(), any(), any(), any(), any(), + any()); + } + + @Test + void deleteOfAnEnabledTenantDisablesItFirstAndDeletesWithTheNewEtag() { + DistributionTenant enabled = tenant(ID, ETAG, "acme"); + enabled.setEnabled(true); + when(cloudFront.getDistributionTenant(ID)).thenReturn(enabled); + DistributionTenant disabled = tenant(ID, NEW_ETAG, "acme"); + when(cloudFront.updateDistributionTenant(ID, ETAG, null, null, null, null, null, false)) + .thenReturn(disabled); + + provisioner.delete(TENANT_TYPE, ID, REGION); + + verify(cloudFront).updateDistributionTenant(ID, ETAG, null, null, null, null, null, false); + verify(cloudFront).deleteDistributionTenant(ID, NEW_ETAG); + } + + @Test + void deleteOfADisabledTenantGoesStraightToTheServiceAndToleratesOnlyItsOwnNotFoundCode() { + DistributionTenant disabled = tenant(ID, ETAG, "acme"); + disabled.setEnabled(false); + when(cloudFront.getDistributionTenant(ID)).thenReturn(disabled); + + provisioner.delete(TENANT_TYPE, ID, REGION); + verify(cloudFront, never()).updateDistributionTenant(any(), any(), any(), any(), any(), any(), any(), + any()); + verify(cloudFront).deleteDistributionTenant(ID, ETAG); + + when(cloudFront.getDistributionTenant(ID)).thenThrow( + new AwsException("EntityNotFound", "The specified distribution tenant doesn't exist.", 404)); + provisioner.delete(TENANT_TYPE, ID, REGION); + verify(cloudFront, Mockito.times(1)).deleteDistributionTenant(any(), any()); + + doThrow(new AwsException("AccessDenied", "no", 403)).when(cloudFront).getDistributionTenant(ID); + assertThrows(AwsException.class, () -> provisioner.delete(TENANT_TYPE, ID, REGION)); + } } diff --git a/src/test/java/io/floci/aws/services/cloudfront/CloudFrontControllerTest.java b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontControllerTest.java index 77bc69025e..d1ce1828ea 100644 --- a/src/test/java/io/floci/aws/services/cloudfront/CloudFrontControllerTest.java +++ b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontControllerTest.java @@ -5,11 +5,13 @@ import io.floci.aws.services.cloudfront.model.CloudFrontFunction; import io.floci.aws.services.cloudfront.model.ConnectionGroup; import io.floci.aws.services.cloudfront.model.ContinuousDeploymentPolicy; import io.floci.aws.services.cloudfront.model.Distribution; +import io.floci.aws.services.cloudfront.model.DistributionTenant; import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.Base64; import java.util.List; import java.util.Map; @@ -866,6 +868,48 @@ class CloudFrontControllerTest { } } + @Test + void listDistributionTenantsStopsAtTheExactEndOfASecondPage() { + CloudFrontService service = mock(CloudFrontService.class); + DistributionTenant alpha = tenant("alpha"); + DistributionTenant beta = tenant("beta"); + DistributionTenant gamma = tenant("gamma"); + when(service.listDistributionTenants(null, 3, null, null)).thenReturn(List.of(alpha, beta, gamma)); + when(service.listDistributionTenants("beta", 3, null, null)).thenReturn(List.of(gamma)); + + CloudFrontController controller = new CloudFrontController(service); + + try (Response firstPage = controller.listDistributionTenants(listTenantsBody(null, 2)); + Response secondPage = controller.listDistributionTenants(listTenantsBody("beta", 2))) { + String firstXml = (String) firstPage.getEntity(); + String secondXml = (String) secondPage.getEntity(); + + assertEquals(List.of("alpha", "beta"), XmlParser.extractAll(firstXml, "Name")); + assertEquals("beta", XmlParser.extractFirst(firstXml, "NextMarker", null)); + assertEquals(List.of("gamma"), XmlParser.extractAll(secondXml, "Name")); + assertTrue(XmlParser.extractAll(secondXml, "NextMarker").isEmpty(), + "the final page carries no next marker"); + } + } + + private static String listTenantsBody(String marker, int maxItems) { + return """ + + %s%d + + """.formatted(marker == null ? "" : "" + marker + "", maxItems); + } + + private static DistributionTenant tenant(String name) { + DistributionTenant tenant = new DistributionTenant(); + tenant.setName(name); + tenant.setDomains(List.of(name + ".example.com")); + tenant.setEnabled(true); + tenant.setCreatedTime(Instant.EPOCH); + tenant.setLastModifiedTime(Instant.EPOCH); + return tenant; + } + private static String listConnectionGroupsBody(String marker, int maxItems) { return """ diff --git a/src/test/java/io/floci/aws/services/cloudfront/CloudFrontDistributionTenantSdkIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontDistributionTenantSdkIntegrationTest.java new file mode 100644 index 0000000000..23fad9a28c --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontDistributionTenantSdkIntegrationTest.java @@ -0,0 +1,425 @@ +package io.floci.aws.services.cloudfront; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudfront.CloudFrontClient; +import software.amazon.awssdk.services.cloudfront.model.CannotDeleteEntityWhileInUseException; +import software.amazon.awssdk.services.cloudfront.model.Certificate; +import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse; +import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse; +import software.amazon.awssdk.services.cloudfront.model.Customizations; +import software.amazon.awssdk.services.cloudfront.model.DefaultCacheBehavior; +import software.amazon.awssdk.services.cloudfront.model.DistributionConfig; +import software.amazon.awssdk.services.cloudfront.model.DistributionTenant; +import software.amazon.awssdk.services.cloudfront.model.DistributionTenantSummary; +import software.amazon.awssdk.services.cloudfront.model.DomainItem; +import software.amazon.awssdk.services.cloudfront.model.EntityAlreadyExistsException; +import software.amazon.awssdk.services.cloudfront.model.EntityNotFoundException; +import software.amazon.awssdk.services.cloudfront.model.GeoRestrictionCustomization; +import software.amazon.awssdk.services.cloudfront.model.GetDistributionTenantByDomainResponse; +import software.amazon.awssdk.services.cloudfront.model.GetDistributionTenantResponse; +import software.amazon.awssdk.services.cloudfront.model.InvalidIfMatchVersionException; +import software.amazon.awssdk.services.cloudfront.model.ListDistributionTenantsResponse; +import software.amazon.awssdk.services.cloudfront.model.NoSuchDistributionException; +import software.amazon.awssdk.services.cloudfront.model.Origin; +import software.amazon.awssdk.services.cloudfront.model.Origins; +import software.amazon.awssdk.services.cloudfront.model.Parameter; +import software.amazon.awssdk.services.cloudfront.model.PreconditionFailedException; +import software.amazon.awssdk.services.cloudfront.model.ResourceNotDisabledException; +import software.amazon.awssdk.services.cloudfront.model.S3OriginConfig; +import software.amazon.awssdk.services.cloudfront.model.Tag; +import software.amazon.awssdk.services.cloudfront.model.Tags; +import software.amazon.awssdk.services.cloudfront.model.UpdateDistributionTenantResponse; +import software.amazon.awssdk.services.cloudfront.model.ViewerCertificate; +import software.amazon.awssdk.services.cloudfront.model.WebAclCustomization; + +import java.net.URI; +import java.util.List; + +import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The distribution tenant management plane, validated with the real CloudFront SDK: every + * operation, the identifier forms Get accepts, the If-Match guarded writes and the modeled errors. + */ +@QuarkusTest +class CloudFrontDistributionTenantSdkIntegrationTest { + + private static final String CLOUDFRONT_NS = "http://cloudfront.amazonaws.com/doc/2020-05-31/"; + + @TestHTTPResource("/") + URI endpoint; + + @Test + void aTenantRoundTripsEveryMemberAndIsReadableByIdNameArnAndDomain() { + try (CloudFrontClient client = client()) { + String distributionId = createDistribution(client, "tenant-only"); + String stamp = stamp(); + String domain = "acme-" + stamp + ".example.com"; + CreateDistributionTenantResponse created = client.createDistributionTenant(request -> request + .distributionId(distributionId) + .name("tenant-" + stamp) + .domains(DomainItem.builder().domain(domain).build()) + .tags(Tags.builder().items(Tag.builder().key("env").value("test").build()).build()) + .customizations(Customizations.builder() + .webAcl(WebAclCustomization.builder().action("override") + .arn("arn:aws:wafv2:us-east-1:000000000000:global/webacl/x/y").build()) + .certificate(Certificate.builder() + .arn("arn:aws:acm:us-east-1:000000000000:certificate/abc").build()) + .geoRestrictions(GeoRestrictionCustomization.builder() + .restrictionType("whitelist").locations("US", "CA").build()) + .build()) + .parameters(Parameter.builder().name("origin_path").value("/acme").build())); + DistributionTenant tenant = created.distributionTenant(); + try { + assertEquals(201, created.sdkHttpResponse().statusCode()); + assertTrue(tenant.id().startsWith("dt_")); + assertTrue(tenant.arn().endsWith(":distribution-tenant/" + tenant.id())); + assertEquals(distributionId, tenant.distributionId()); + assertTrue(tenant.enabled()); + assertEquals("Deployed", tenant.status()); + assertNotNull(tenant.connectionGroupId()); + assertNotNull(tenant.createdTime()); + assertNotNull(tenant.lastModifiedTime()); + assertEquals(1, tenant.domains().size()); + assertEquals(domain, tenant.domains().getFirst().domain()); + assertEquals("active", tenant.domains().getFirst().statusAsString()); + assertEquals("env", tenant.tags().items().getFirst().key()); + assertEquals("override", tenant.customizations().webAcl().actionAsString()); + assertEquals("arn:aws:acm:us-east-1:000000000000:certificate/abc", + tenant.customizations().certificate().arn()); + assertEquals("whitelist", tenant.customizations().geoRestrictions().restrictionTypeAsString()); + assertEquals(List.of("US", "CA"), tenant.customizations().geoRestrictions().locations()); + assertEquals("origin_path", tenant.parameters().getFirst().name()); + assertEquals("/acme", tenant.parameters().getFirst().value()); + + GetDistributionTenantResponse byId = + client.getDistributionTenant(request -> request.identifier(tenant.id())); + assertEquals(tenant.id(), byId.distributionTenant().id()); + assertEquals(created.eTag(), byId.eTag()); + assertEquals(tenant.id(), client.getDistributionTenant( + request -> request.identifier(tenant.name())).distributionTenant().id()); + assertEquals(tenant.id(), client.getDistributionTenant( + request -> request.identifier(tenant.arn())).distributionTenant().id()); + GetDistributionTenantByDomainResponse byDomain = client.getDistributionTenantByDomain( + request -> request.domain(domain)); + assertEquals(tenant.id(), byDomain.distributionTenant().id()); + assertEquals(created.eTag(), byDomain.eTag()); + + assertAwsError("EntityNotFound", 404, + () -> client.getDistributionTenant(request -> request.identifier("dt_doesnotexist"))); + assertAwsError("EntityNotFound", 404, + () -> client.getDistributionTenantByDomain(request -> request.domain("none.example.com"))); + } finally { + disableAndDelete(client, tenant.id()); + disableAndDeleteDistribution(client, distributionId); + } + } + } + + @Test + void createRefusalsCarryTheirModeledErrors() { + try (CloudFrontClient client = client()) { + String tenantOnly = createDistribution(client, "tenant-only"); + String direct = createDistribution(client, "direct"); + String stamp = stamp(); + String name = "tenant-" + stamp; + String domain = "dup-" + stamp + ".example.com"; + CreateDistributionTenantResponse created = client.createDistributionTenant(request -> request + .distributionId(tenantOnly).name(name).domains(DomainItem.builder().domain(domain).build())); + try { + assertAwsError("EntityNotFound", 404, () -> client.createDistributionTenant(request -> request + .distributionId("EMISSING0000").name("tenant-m-" + stamp) + .domains(DomainItem.builder().domain("m-" + stamp + ".example.com").build()))); + assertAwsError("InvalidArgument", 400, () -> client.createDistributionTenant(request -> request + .distributionId(direct).name("tenant-d-" + stamp) + .domains(DomainItem.builder().domain("d-" + stamp + ".example.com").build()))); + assertAwsError("EntityNotFound", 404, () -> client.createDistributionTenant(request -> request + .distributionId(tenantOnly).name("tenant-g-" + stamp).connectionGroupId("cg_missing") + .domains(DomainItem.builder().domain("g-" + stamp + ".example.com").build()))); + assertAwsError("EntityAlreadyExists", 409, () -> client.createDistributionTenant(request -> request + .distributionId(tenantOnly).name(name) + .domains(DomainItem.builder().domain("n-" + stamp + ".example.com").build()))); + assertAwsError("CNAMEAlreadyExists", 409, () -> client.createDistributionTenant(request -> request + .distributionId(tenantOnly).name("tenant-c-" + stamp) + .domains(DomainItem.builder().domain(domain).build()))); + assertAwsError("InvalidArgument", 400, () -> client.createDistributionTenant(request -> request + .distributionId(tenantOnly).name("tenant-e-" + stamp))); + } finally { + disableAndDelete(client, created.distributionTenant().id()); + disableAndDeleteDistribution(client, tenantOnly); + disableAndDeleteDistribution(client, direct); + } + } + } + + @Test + void ifMatchGuardedWritesRotateTheEtagAndDeleteNeedsADisabledTenant() { + try (CloudFrontClient client = client()) { + String distributionId = createDistribution(client, "tenant-only"); + String stamp = stamp(); + CreateDistributionTenantResponse created = client.createDistributionTenant(request -> request + .distributionId(distributionId).name("tenant-" + stamp) + .domains(DomainItem.builder().domain("w-" + stamp + ".example.com").build())); + String id = created.distributionTenant().id(); + try { + assertAwsError("InvalidIfMatchVersion", 400, + () -> client.updateDistributionTenant(request -> request.id(id).enabled(false))); + assertAwsError("PreconditionFailed", 412, () -> client.updateDistributionTenant(request -> request + .id(id).ifMatch("E000000000000").enabled(false))); + assertAwsError("InvalidIfMatchVersion", 400, + () -> client.deleteDistributionTenant(request -> request.id(id))); + assertAwsError("ResourceNotDisabled", 409, () -> client.deleteDistributionTenant(request -> request + .id(id).ifMatch(created.eTag()))); + + String newDomain = "w2-" + stamp + ".example.com"; + UpdateDistributionTenantResponse updated = client.updateDistributionTenant(request -> request.id(id).ifMatch(created.eTag()) + .enabled(false) + .domains(DomainItem.builder().domain(newDomain).build()) + .parameters(Parameter.builder().name("k").value("v").build())); + assertFalse(updated.distributionTenant().enabled()); + assertEquals(newDomain, updated.distributionTenant().domains().getFirst().domain()); + assertEquals("v", updated.distributionTenant().parameters().getFirst().value()); + assertNotEquals(created.eTag(), updated.eTag()); + assertAwsError("PreconditionFailed", 412, () -> client.updateDistributionTenant(request -> request + .id(id).ifMatch(created.eTag()).enabled(true))); + + client.deleteDistributionTenant(request -> request.id(id).ifMatch(updated.eTag())); + assertAwsError("EntityNotFound", 404, + () -> client.getDistributionTenant(request -> request.identifier(id))); + assertAwsError("EntityNotFound", 404, () -> client.deleteDistributionTenant(request -> request + .id(id).ifMatch(updated.eTag()))); + } finally { + disableAndDelete(client, id); + disableAndDeleteDistribution(client, distributionId); + } + } + } + + @Test + void listingFiltersByAssociationAndCustomizationAndPages() { + try (CloudFrontClient client = client()) { + String first = createDistribution(client, "tenant-only"); + String second = createDistribution(client, "tenant-only"); + String stamp = stamp(); + String aclArn = "arn:aws:wafv2:us-east-1:000000000000:global/webacl/" + stamp + "/y"; + String certArn = "arn:aws:acm:us-east-1:000000000000:certificate/" + stamp; + CreateDistributionTenantResponse a = client.createDistributionTenant(request -> request + .distributionId(first).name("list-a-" + stamp) + .domains(DomainItem.builder().domain("la-" + stamp + ".example.com").build()) + .customizations(Customizations.builder().webAcl( + WebAclCustomization.builder().action("override").arn(aclArn).build()).build())); + CreateDistributionTenantResponse b = client.createDistributionTenant(request -> request + .distributionId(first).name("list-b-" + stamp) + .domains(DomainItem.builder().domain("lb-" + stamp + ".example.com").build()) + .customizations(Customizations.builder().certificate( + Certificate.builder().arn(certArn).build()).build())); + CreateDistributionTenantResponse c = client.createDistributionTenant(request -> request + .distributionId(second).name("list-c-" + stamp) + .domains(DomainItem.builder().domain("lc-" + stamp + ".example.com").build())); + try { + List onFirst = client.listDistributionTenants(request -> request + .associationFilter(filter -> filter.distributionId(first))) + .distributionTenantList().stream().map(DistributionTenantSummary::name).toList(); + assertEquals(List.of("list-a-" + stamp, "list-b-" + stamp), onFirst); + + String groupId = c.distributionTenant().connectionGroupId(); + assertTrue(client.listDistributionTenants(request -> request + .associationFilter(filter -> filter.connectionGroupId(groupId))) + .distributionTenantList().stream().anyMatch(t -> t.id().equals(c.distributionTenant().id()))); + + ListDistributionTenantsResponse page = client.listDistributionTenants(request -> request + .associationFilter(filter -> filter.distributionId(first)).maxItems(1)); + assertEquals(1, page.distributionTenantList().size()); + assertEquals("list-a-" + stamp, page.nextMarker()); + DistributionTenantSummary summary = page.distributionTenantList().getFirst(); + assertEquals(a.eTag(), summary.eTag()); + assertEquals("override", summary.customizations().webAcl().actionAsString()); + assertEquals("active", summary.domains().getFirst().statusAsString()); + + assertEquals(List.of("list-a-" + stamp), client.listDistributionTenantsByCustomization( + request -> request.webACLArn(aclArn)) + .distributionTenantList().stream().map(DistributionTenantSummary::name).toList()); + assertEquals(List.of("list-b-" + stamp), client.listDistributionTenantsByCustomization( + request -> request.certificateArn(certArn)) + .distributionTenantList().stream().map(DistributionTenantSummary::name).toList()); + assertAwsError("InvalidArgument", 400, + () -> client.listDistributionTenantsByCustomization(request -> request.maxItems(5))); + } finally { + disableAndDelete(client, a.distributionTenant().id()); + disableAndDelete(client, b.distributionTenant().id()); + disableAndDelete(client, c.distributionTenant().id()); + disableAndDeleteDistribution(client, first); + disableAndDeleteDistribution(client, second); + } + } + } + + @Test + void aConnectionGroupWithATenantCannotBeDeleted() { + try (CloudFrontClient client = client()) { + String distributionId = createDistribution(client, "tenant-only"); + String stamp = stamp(); + CreateConnectionGroupResponse group = client.createConnectionGroup(request -> request.name("cg-tenant-" + stamp).enabled(false)); + String groupId = group.connectionGroup().id(); + String tenantId = client.createDistributionTenant(request -> request + .distributionId(distributionId).name("tenant-" + stamp).connectionGroupId(groupId) + .domains(DomainItem.builder().domain("cg-" + stamp + ".example.com").build())) + .distributionTenant().id(); + try { + assertAwsError("CannotDeleteEntityWhileInUse", 409, () -> client.deleteConnectionGroup( + request -> request.id(groupId).ifMatch(group.eTag()))); + disableAndDelete(client, tenantId); + client.deleteConnectionGroup(request -> request.id(groupId).ifMatch(group.eTag())); + } finally { + disableAndDelete(client, tenantId); + disableAndDeleteDistribution(client, distributionId); + } + } + } + + @Test + void aTenantArnNamesTheAccountOfTheRequest() { + try (CloudFrontClient client = AwsTestClients.create(CloudFrontClient.builder(), "111122223333", + Region.US_EAST_1, endpoint)) { + String distributionId = createDistribution(client, "tenant-only"); + String stamp = stamp(); + DistributionTenant tenant = client.createDistributionTenant(request -> request + .distributionId(distributionId).name("acct-" + stamp) + .domains(DomainItem.builder().domain("acct-" + stamp + ".example.com").build())) + .distributionTenant(); + try { + assertTrue(tenant.arn().contains("::111122223333:distribution-tenant/" + tenant.id()), + tenant.arn()); + } finally { + disableAndDelete(client, tenant.id()); + disableAndDeleteDistribution(client, distributionId); + } + } + } + + @Test + void aParameterWithoutANameIsRefusedOnTheWire() { + try (CloudFrontClient client = client()) { + String distributionId = createDistribution(client, "tenant-only"); + String stamp = stamp(); + DistributionTenant tenant = client.createDistributionTenant(request -> request + .distributionId(distributionId).name("noname-" + stamp) + .domains(DomainItem.builder().domain("noname-" + stamp + ".example.com").build())) + .distributionTenant(); + try { + String create = "" + + "" + distributionId + "raw-" + stamp + "" + + "raw-" + stamp + ".example.com" + + "x" + + ""; + given().contentType("application/xml").body(create) + .when().post(endpoint + "2020-05-31/distribution-tenant") + .then().statusCode(400).body(containsString("InvalidArgument")); + + String update = "" + + "x" + + ""; + String etag = client.getDistributionTenant(request -> request.identifier(tenant.id())).eTag(); + given().contentType("application/xml").header("If-Match", etag).body(update) + .when().put(endpoint + "2020-05-31/distribution-tenant/" + tenant.id()) + .then().statusCode(400).body(containsString("InvalidArgument")); + } finally { + disableAndDelete(client, tenant.id()); + disableAndDeleteDistribution(client, distributionId); + } + } + } + + @Test + void tenantTagsFollowTheCloudFrontTagApi() { + try (CloudFrontClient client = client()) { + String distributionId = createDistribution(client, "tenant-only"); + String stamp = stamp(); + DistributionTenant tenant = client.createDistributionTenant(request -> request + .distributionId(distributionId).name("tag-" + stamp) + .domains(DomainItem.builder().domain("t-" + stamp + ".example.com").build()) + .tags(Tags.builder().items(Tag.builder().key("a").value("1").build()).build())) + .distributionTenant(); + try { + client.tagResource(request -> request.resource(tenant.arn()) + .tags(Tags.builder().items(Tag.builder().key("b").value("2").build()).build())); + assertEquals(2, client.listTagsForResource(request -> request.resource(tenant.arn())) + .tags().items().size()); + client.untagResource(request -> request.resource(tenant.arn()) + .tagKeys(keys -> keys.items("a"))); + assertEquals("b", client.listTagsForResource(request -> request.resource(tenant.arn())) + .tags().items().getFirst().key()); + assertEquals("b", client.getDistributionTenant(request -> request.identifier(tenant.id())) + .distributionTenant().tags().items().getFirst().key()); + } finally { + disableAndDelete(client, tenant.id()); + disableAndDeleteDistribution(client, distributionId); + } + } + } + + private String createDistribution(CloudFrontClient client, String connectionMode) { + DistributionConfig config = DistributionConfig.builder() + .callerReference("tenant-config-" + stamp()) + .comment("multi-tenant") + .enabled(true) + .origins(Origins.builder().quantity(1).items(Origin.builder() + .id("origin1") + .domainName("example-bucket.s3.us-east-1.amazonaws.com") + .s3OriginConfig(S3OriginConfig.builder().originAccessIdentity("").build()) + .build()).build()) + .defaultCacheBehavior(DefaultCacheBehavior.builder() + .targetOriginId("origin1") + .viewerProtocolPolicy("redirect-to-https") + .build()) + .viewerCertificate(ViewerCertificate.builder().cloudFrontDefaultCertificate(true).build()) + .connectionMode(connectionMode) + .build(); + return client.createDistribution(request -> request.distributionConfig(config)).distribution().id(); + } + + private void disableAndDeleteDistribution(CloudFrontClient client, String distributionId) { + try { + String etag = client.getDistribution(request -> request.id(distributionId)).eTag(); + client.updateDistribution(request -> request.id(distributionId).ifMatch(etag) + .distributionConfig(client.getDistributionConfig(byId -> byId.id(distributionId)) + .distributionConfig().toBuilder().enabled(false).build())); + String freshEtag = client.getDistribution(request -> request.id(distributionId)).eTag(); + client.deleteDistribution(request -> request.id(distributionId).ifMatch(freshEtag)); + } catch (NoSuchDistributionException | InvalidIfMatchVersionException | PreconditionFailedException + | ResourceNotDisabledException | CannotDeleteEntityWhileInUseException ignored) { + // teardown only: the emulator state is per-test, so a partially cleaned distribution cannot leak into another test + } + } + + private void disableAndDelete(CloudFrontClient client, String id) { + try { + String etag = client.getDistributionTenant(request -> request.identifier(id)).eTag(); + client.updateDistributionTenant(request -> request.id(id).ifMatch(etag).enabled(false)); + String freshEtag = client.getDistributionTenant(request -> request.identifier(id)).eTag(); + client.deleteDistributionTenant(request -> request.id(id).ifMatch(freshEtag)); + } catch (EntityNotFoundException | InvalidIfMatchVersionException | PreconditionFailedException + | ResourceNotDisabledException | EntityAlreadyExistsException ignored) { + // teardown only: the emulator state is per-test, so a partially cleaned tenant cannot leak into another test + } + } + + private static String stamp() { + return Long.toString(System.nanoTime(), 36); + } + + private CloudFrontClient client() { + return AwsTestClients.create(CloudFrontClient.builder(), "000000000000", Region.US_EAST_1, endpoint); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudfront/CloudFrontDistributionTenantServiceTest.java b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontDistributionTenantServiceTest.java new file mode 100644 index 0000000000..fe57dadf8d --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontDistributionTenantServiceTest.java @@ -0,0 +1,472 @@ +package io.floci.aws.services.cloudfront; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.cloudfront.model.ConnectionGroup; +import io.floci.aws.services.cloudfront.model.Distribution; +import io.floci.aws.services.cloudfront.model.DistributionConfig; +import io.floci.aws.services.cloudfront.model.DistributionTenant; +import io.floci.aws.services.cloudfront.model.TenantCustomizations; +import io.floci.aws.testing.ParallelLocks; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Distribution tenants in isolation: one account, one mocked storage factory. A tenant hangs off a + * {@code tenant-only} distribution and a connection group, so most cases start from the + * distribution that the CloudFront API requires to exist first. + */ +@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ) +class CloudFrontDistributionTenantServiceTest { + + private static final String ACCOUNT = "000000000000"; + + private final Map> stores = new HashMap<>(); + + private CloudFrontService service() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(invocation -> stores.computeIfAbsent(invocation.getArgument(1, String.class), + ignored -> AccountAwareStorageBackend.inMemory("000000000000"))); + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.DnsConfig dnsConfig = mock(EmulatorConfig.DnsConfig.class); + EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.CloudFrontServiceConfig cloudFrontConfig = mock(EmulatorConfig.CloudFrontServiceConfig.class); + + when(config.defaultAccountId()).thenReturn(ACCOUNT); + when(config.hostname()).thenReturn(Optional.empty()); + when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566"); + when(config.dns()).thenReturn(dnsConfig); + when(dnsConfig.extraSuffixes()).thenReturn(Optional.empty()); + when(config.services()).thenReturn(servicesConfig); + when(servicesConfig.cloudfront()).thenReturn(cloudFrontConfig); + when(cloudFrontConfig.domainSuffix()).thenReturn(Optional.empty()); + + return new CloudFrontService(storageFactory, config, new RegionResolver("us-east-1", ACCOUNT)); + } + + private static Distribution distribution(String connectionMode, String... aliases) { + DistributionConfig config = new DistributionConfig(); + config.setCallerReference("tenant-test-" + System.nanoTime()); + config.setConnectionMode(connectionMode); + if (aliases.length > 0) { + config.setAliases(List.of(aliases)); + } + Distribution dist = new Distribution(); + dist.setConfig(config); + return dist; + } + + private static String tenantOnly(CloudFrontService service) { + return service.createDistribution(distribution("tenant-only"), Map.of()).getId(); + } + + private static DistributionTenant create(CloudFrontService service, String distributionId, String name, + String... domains) { + return service.createDistributionTenant(distributionId, name, List.of(domains), Map.of(), null, + null, null, null); + } + + private static String errorCode(Runnable call) { + return assertThrows(AwsException.class, call::run).getErrorCode(); + } + + private static String errorMessage(Runnable call) { + return assertThrows(AwsException.class, call::run).getMessage(); + } + + @Test + void aTenantStartsEnabledOnTheDefaultConnectionGroupWithItsDomainsActive() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + + DistributionTenant tenant = create(service, distributionId, "acme", "acme.example.com"); + + assertTrue(tenant.getId().startsWith("dt_")); + assertTrue(tenant.getArn().startsWith("arn:aws:cloudfront::" + ACCOUNT + ":distribution-tenant/")); + assertTrue(tenant.getArn().endsWith("/" + tenant.getId())); + assertEquals(distributionId, tenant.getDistributionId()); + assertEquals("acme", tenant.getName()); + assertTrue(tenant.getEnabled()); + assertEquals("Deployed", tenant.getStatus()); + assertEquals(List.of("acme.example.com"), tenant.getDomains()); + assertNotNull(tenant.getEtag()); + assertNotNull(tenant.getCreatedTime()); + ConnectionGroup defaultGroup = service.ensureDefaultConnectionGroup(); + assertEquals(defaultGroup.getId(), tenant.getConnectionGroupId()); + } + + @Test + void aConnectionGroupStillReferencedByATenantCannotBeDeleted() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + ConnectionGroup group = service.createConnectionGroup("edge", null, false, true, null, null); + DistributionTenant tenant = service.createDistributionTenant(distributionId, "acme", + List.of("acme.example.com"), Map.of(), null, null, group.getId(), false); + + assertEquals("CannotDeleteEntityWhileInUse", + errorCode(() -> service.deleteConnectionGroup(group.getId(), group.getEtag()))); + + service.deleteDistributionTenant(tenant.getId(), tenant.getEtag()); + service.deleteConnectionGroup(group.getId(), group.getEtag()); + assertEquals("EntityNotFound", errorCode(() -> service.getConnectionGroup(group.getId()))); + } + + @Test + void aNamedConnectionGroupMustExistAndIsResolvedToItsId() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + ConnectionGroup group = service.createConnectionGroup("edge", null, true, true, null, null); + + DistributionTenant tenant = service.createDistributionTenant(distributionId, "acme", + List.of("acme.example.com"), Map.of(), null, null, group.getId(), false); + assertEquals(group.getId(), tenant.getConnectionGroupId()); + assertFalse(tenant.getEnabled()); + + assertEquals("EntityNotFound", errorCode(() -> service.createDistributionTenant(distributionId, "other", + List.of("other.example.com"), Map.of(), null, null, "cg_missing", null))); + } + + @Test + void theDistributionMustExistAndBeTenantOnly() { + CloudFrontService service = service(); + String direct = service.createDistribution(distribution("direct"), Map.of()).getId(); + String unset = service.createDistribution(distribution(null), Map.of()).getId(); + + assertEquals("EntityNotFound", errorCode(() -> create(service, "EMISSING", "aaa1", "a.example.com"))); + assertEquals("InvalidArgument", errorCode(() -> create(service, direct, "aaa2", "a.example.com"))); + assertEquals("InvalidArgument", errorCode(() -> create(service, unset, "aaa3", "a.example.com"))); + } + + @Test + void nameAndDomainsAreValidated() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + + assertEquals("InvalidArgument", errorCode(() -> create(service, distributionId, "", "a.example.com"))); + assertEquals("InvalidArgument", errorCode(() -> create(service, distributionId, "ab", "a.example.com"))); + assertEquals("InvalidArgument", errorCode(() -> create(service, distributionId, "-bad-", "a.example.com"))); + assertEquals("InvalidArgument", errorCode(() -> create(service, distributionId, "good-name"))); + assertEquals("InvalidArgument", errorCode(() -> create(service, distributionId, "good-name", + "a.example.com", "A.EXAMPLE.COM"))); + assertEquals("EntityLimitExceeded", errorCode(() -> create(service, distributionId, "good-name", + "1.example.com", "2.example.com", "3.example.com", "4.example.com", "5.example.com", + "6.example.com"))); + } + + @Test + void aNameIsUniquePerAccount() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + create(service, distributionId, "acme", "acme.example.com"); + + assertEquals("EntityAlreadyExists", errorCode(() -> create(service, distributionId, "acme", + "other.example.com"))); + } + + @Test + void aDomainIsUniqueAcrossTenantsAndDistributionAliases() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + service.createDistribution(distribution("direct", "www.taken.example.com"), Map.of()); + create(service, distributionId, "acme", "acme.example.com"); + + assertEquals("CNAMEAlreadyExists", errorCode(() -> create(service, distributionId, "beta", + "ACME.example.com"))); + assertEquals("CNAMEAlreadyExists", errorCode(() -> create(service, distributionId, "gamma", + "www.taken.example.com"))); + assertEquals("CNAMEAlreadyExists", errorCode(() -> service.createDistribution( + distribution("direct", "acme.example.com"), Map.of()))); + } + + @Test + void parametersAndCustomizationsAreStoredAndValidated() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + TenantCustomizations customizations = new TenantCustomizations(); + customizations.setWebAclAction("override"); + customizations.setWebAclArn("arn:aws:wafv2:us-east-1:000000000000:global/webacl/x/y"); + customizations.setGeoRestrictionType("whitelist"); + customizations.setGeoLocations(List.of("US", "CA")); + Map parameters = new LinkedHashMap<>(); + parameters.put("origin_path", "/acme"); + + DistributionTenant tenant = service.createDistributionTenant(distributionId, "acme", + List.of("acme.example.com"), Map.of(), customizations, parameters, null, null); + assertEquals("override", tenant.getCustomizations().getWebAclAction()); + assertEquals(List.of("US", "CA"), tenant.getCustomizations().getGeoLocations()); + assertEquals(Map.of("origin_path", "/acme"), tenant.getParameters()); + + TenantCustomizations badAction = new TenantCustomizations(); + badAction.setWebAclAction("bogus"); + assertEquals("InvalidArgument", errorCode(() -> service.createDistributionTenant(distributionId, "bad1", + List.of("b1.example.com"), Map.of(), badAction, null, null, null))); + TenantCustomizations badGeo = new TenantCustomizations(); + badGeo.setGeoRestrictionType("bogus"); + assertEquals("InvalidArgument", errorCode(() -> service.createDistributionTenant(distributionId, "bad2", + List.of("b2.example.com"), Map.of(), badGeo, null, null, null))); + Map badParameter = Map.of("not valid!", "x"); + assertEquals("InvalidArgument", errorCode(() -> service.createDistributionTenant(distributionId, "bad3", + List.of("b3.example.com"), Map.of(), null, badParameter, null, null))); + } + + @Test + void aTenantIsReadByIdNameArnAndDomain() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + DistributionTenant tenant = create(service, distributionId, "acme", "acme.example.com"); + + assertEquals(tenant.getId(), service.getDistributionTenant(tenant.getId()).getId()); + assertEquals(tenant.getId(), service.getDistributionTenant("acme").getId()); + assertEquals(tenant.getId(), service.getDistributionTenant(tenant.getArn()).getId()); + assertEquals(tenant.getId(), service.getDistributionTenantByDomain("ACME.example.com").getId()); + + assertEquals("EntityNotFound", errorCode(() -> service.getDistributionTenant("dt_missing"))); + assertEquals("EntityNotFound", errorCode(() -> service.getDistributionTenant( + "arn:aws:cloudfront::000000000000:distribution-tenant/dt_missing"))); + assertEquals("EntityNotFound", errorCode(() -> service.getDistributionTenantByDomain("no.example.com"))); + } + + @Test + void writesRequireTheCurrentEtagAndRotateIt() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + DistributionTenant tenant = create(service, distributionId, "acme", "acme.example.com"); + String id = tenant.getId(); + String first = tenant.getEtag(); + + assertEquals("InvalidIfMatchVersion", errorCode(() -> service.updateDistributionTenant(id, null, + null, null, null, null, null, false))); + assertEquals("PreconditionFailed", errorCode(() -> service.updateDistributionTenant(id, "stale", + null, null, null, null, null, false))); + assertEquals("EntityNotFound", errorCode(() -> service.updateDistributionTenant("dt_missing", first, + null, null, null, null, null, false))); + + DistributionTenant updated = service.updateDistributionTenant(id, first, null, + List.of("new.example.com"), null, Map.of("k", "v"), null, false); + assertNotEquals(first, updated.getEtag()); + assertFalse(updated.getEnabled()); + assertEquals(List.of("new.example.com"), updated.getDomains()); + assertEquals(Map.of("k", "v"), updated.getParameters()); + assertEquals("PreconditionFailed", errorCode(() -> service.updateDistributionTenant(id, first, + null, null, null, null, null, true))); + } + + @Test + void anUpdateKeepsWhatItOmitsAndChecksDomainsAgainstOtherTenants() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + DistributionTenant acme = create(service, distributionId, "acme", "acme.example.com"); + create(service, distributionId, "beta", "beta.example.com"); + + DistributionTenant touched = service.updateDistributionTenant(acme.getId(), acme.getEtag(), null, + null, null, null, null, null); + assertEquals(List.of("acme.example.com"), touched.getDomains()); + assertTrue(touched.getEnabled()); + + assertEquals("CNAMEAlreadyExists", errorCode(() -> service.updateDistributionTenant(acme.getId(), + touched.getEtag(), null, List.of("beta.example.com"), null, null, null, null))); + DistributionTenant same = service.updateDistributionTenant(acme.getId(), touched.getEtag(), null, + List.of("acme.example.com", "extra.example.com"), null, null, null, null); + assertEquals(2, same.getDomains().size()); + } + + @Test + void anUpdateCanMoveTheTenantToAnotherTenantOnlyDistributionOrGroup() { + CloudFrontService service = service(); + String first = tenantOnly(service); + String second = tenantOnly(service); + String direct = service.createDistribution(distribution("direct"), Map.of()).getId(); + ConnectionGroup group = service.createConnectionGroup("edge", null, true, true, null, null); + DistributionTenant tenant = create(service, first, "acme", "acme.example.com"); + + DistributionTenant moved = service.updateDistributionTenant(tenant.getId(), tenant.getEtag(), second, + null, null, null, group.getId(), null); + assertEquals(second, moved.getDistributionId()); + assertEquals(group.getId(), moved.getConnectionGroupId()); + + assertEquals("InvalidArgument", errorCode(() -> service.updateDistributionTenant(tenant.getId(), + moved.getEtag(), direct, null, null, null, null, null))); + assertEquals("EntityNotFound", errorCode(() -> service.updateDistributionTenant(tenant.getId(), + moved.getEtag(), "EMISSING", null, null, null, null, null))); + assertEquals("EntityNotFound", errorCode(() -> service.updateDistributionTenant(tenant.getId(), + moved.getEtag(), null, null, null, null, "cg_missing", null))); + } + + @Test + void aDeleteNeedsAnIfMatchADisabledTenantAndRemovesItsTags() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + DistributionTenant tenant = service.createDistributionTenant(distributionId, "acme", + List.of("acme.example.com"), Map.of("env", "test"), null, null, null, null); + assertEquals(Map.of("env", "test"), service.listTagsForResource(tenant.getArn())); + String id = tenant.getId(); + + assertEquals("InvalidIfMatchVersion", errorCode(() -> service.deleteDistributionTenant(id, null))); + assertEquals("PreconditionFailed", errorCode(() -> service.deleteDistributionTenant(id, "stale"))); + assertEquals("ResourceNotDisabled", errorCode(() -> service.deleteDistributionTenant(id, + tenant.getEtag()))); + + DistributionTenant disabled = service.updateDistributionTenant(id, tenant.getEtag(), null, null, null, + null, null, false); + service.deleteDistributionTenant(id, disabled.getEtag()); + + assertEquals("EntityNotFound", errorCode(() -> service.getDistributionTenant(id))); + assertEquals("EntityNotFound", errorCode(() -> service.deleteDistributionTenant(id, disabled.getEtag()))); + assertTrue(service.listTagsForResource(tenant.getArn()).isEmpty()); + create(service, distributionId, "acme", "acme.example.com"); + } + + @Test + void tagResourceWorksOnATenantArn() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + DistributionTenant tenant = create(service, distributionId, "acme", "acme.example.com"); + + service.tagResource(tenant.getArn(), Map.of("team", "edge")); + assertEquals(Map.of("team", "edge"), service.listTagsForResource(tenant.getArn())); + service.untagResource(tenant.getArn(), List.of("team")); + assertTrue(service.listTagsForResource(tenant.getArn()).isEmpty()); + } + + @Test + void listingFiltersByDistributionAndConnectionGroupAndPages() { + CloudFrontService service = service(); + String first = tenantOnly(service); + String second = tenantOnly(service); + ConnectionGroup group = service.createConnectionGroup("edge", null, true, true, null, null); + create(service, first, "alpha", "alpha.example.com"); + create(service, first, "beta", "beta.example.com"); + service.createDistributionTenant(second, "gamma", List.of("gamma.example.com"), Map.of(), null, null, + group.getId(), null); + + assertEquals(List.of("alpha", "beta", "gamma"), names(service.listDistributionTenants(null, 100, null, null))); + assertEquals(List.of("alpha", "beta"), names(service.listDistributionTenants(null, 100, first, null))); + assertEquals(List.of("gamma"), names(service.listDistributionTenants(null, 100, null, group.getId()))); + assertEquals(List.of("gamma"), names(service.listDistributionTenants(null, 100, second, group.getId()))); + assertEquals(List.of("beta", "gamma"), names(service.listDistributionTenants("alpha", 100, null, null))); + assertEquals(List.of("alpha", "beta"), names(service.listDistributionTenants(null, 2, null, null))); + } + + @Test + void listingByCustomizationNeedsExactlyOneFilter() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + TenantCustomizations withAcl = new TenantCustomizations(); + withAcl.setWebAclAction("override"); + withAcl.setWebAclArn("arn:aws:wafv2:us-east-1:000000000000:global/webacl/x/y"); + TenantCustomizations withCert = new TenantCustomizations(); + withCert.setCertificateArn("arn:aws:acm:us-east-1:000000000000:certificate/abc"); + service.createDistributionTenant(distributionId, "acl", List.of("acl.example.com"), Map.of(), withAcl, + null, null, null); + service.createDistributionTenant(distributionId, "cert", List.of("cert.example.com"), Map.of(), + withCert, null, null, null); + create(service, distributionId, "plain", "plain.example.com"); + + assertEquals(List.of("acl"), names(service.listDistributionTenantsByCustomization(null, 100, + withAcl.getWebAclArn(), null))); + assertEquals(List.of("cert"), names(service.listDistributionTenantsByCustomization(null, 100, null, + withCert.getCertificateArn()))); + assertEquals("InvalidArgument", errorCode(() -> service.listDistributionTenantsByCustomization(null, + 100, null, null))); + assertEquals("InvalidArgument", errorCode(() -> service.listDistributionTenantsByCustomization(null, + 100, "a", "b"))); + } + + @Test + void aTenantDomainCannotBeClaimedThroughAssociateAlias() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + create(service, distributionId, "acme", "acme.example.com"); + Distribution direct = service.createDistribution(distribution("direct"), Map.of()); + + assertEquals("CNAMEAlreadyExists", + errorCode(() -> service.associateAlias(direct.getId(), "ACME.example.com"))); + + List aliases = service.getDistribution(direct.getId()).getConfig().getAliases(); + assertTrue(aliases == null || aliases.isEmpty(), "a refused alias must leave the target untouched"); + } + + @Test + void aParameterWithoutNameOrValueIsInvalidArgumentOnCreateAndUpdate() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + DistributionTenant tenant = create(service, distributionId, "acme", "acme.example.com"); + Map noName = new LinkedHashMap<>(); + noName.put(null, "x"); + Map noValue = new LinkedHashMap<>(); + noValue.put("origin_path", null); + + for (Map parameters : List.of(noName, noValue)) { + assertEquals("InvalidArgument", errorCode(() -> service.createDistributionTenant(distributionId, + "bad", List.of("bad.example.com"), Map.of(), null, parameters, null, null))); + assertEquals("InvalidArgument", errorCode(() -> service.updateDistributionTenant(tenant.getId(), + tenant.getEtag(), null, null, null, parameters, null, null))); + } + } + + @Test + void aWebAclWithoutAnActionIsInvalidArgumentOnCreateAndUpdate() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + DistributionTenant tenant = create(service, distributionId, "acme", "acme.example.com"); + TenantCustomizations arnOnly = new TenantCustomizations(); + arnOnly.setWebAclArn("arn:aws:wafv2:us-east-1:000000000000:global/webacl/x/y"); + + assertEquals("InvalidArgument", errorCode(() -> service.createDistributionTenant(distributionId, + "bad", List.of("bad.example.com"), Map.of(), arnOnly, null, null, null))); + assertEquals("InvalidArgument", errorCode(() -> service.updateDistributionTenant(tenant.getId(), + tenant.getEtag(), null, null, arnOnly, null, null, null))); + } + + private static List names(List tenants) { + return tenants.stream().map(DistributionTenant::getName).toList(); + } + + @Test + void tenantErrorsUseTheSentencesAwsReturns() { + CloudFrontService service = service(); + String distributionId = tenantOnly(service); + service.createDistribution(distribution("direct", "www.taken.example.com"), Map.of()); + DistributionTenant tenant = create(service, distributionId, "acme", "acme.example.com"); + String id = tenant.getId(); + String missingTenant = "The specified distribution tenant doesn't exist."; + String taken = "One or more of the CNAMEs you provided are already associated with a different resource."; + + assertEquals(missingTenant, errorMessage(() -> service.getDistributionTenant("dt_missing"))); + assertEquals(missingTenant, errorMessage(() -> service.getDistributionTenantByDomain("ghost.example.com"))); + assertEquals("The specified distribution does not exist.", + errorMessage(() -> create(service, "EMISSING", "beta", "beta.example.com"))); + assertEquals("You must disable the distribution tenant before you can delete it.", + errorMessage(() -> service.deleteDistributionTenant(id, tenant.getEtag()))); + assertEquals("Your request is missing requirements for this operation. Update your request and try again.", + errorMessage(() -> service.deleteDistributionTenant(id, "stale"))); + assertEquals(taken, errorMessage(() -> create(service, distributionId, "beta", "ACME.example.com"))); + assertEquals(taken, errorMessage(() -> create(service, distributionId, "gamma", "www.taken.example.com"))); + assertEquals(taken, errorMessage(() -> service.createDistribution( + distribution("direct", "WWW.taken.example.com"), Map.of()))); + assertEquals(taken, errorMessage(() -> service.createDistribution( + distribution("direct", "acme.example.com"), Map.of()))); + } +} diff --git a/src/test/resources/cloudformation/change-exempt.tsv b/src/test/resources/cloudformation/change-exempt.tsv index 417f2d7edb..211e295998 100644 --- a/src/test/resources/cloudformation/change-exempt.tsv +++ b/src/test/resources/cloudformation/change-exempt.tsv @@ -46,6 +46,7 @@ AWS::CloudFormation::StackSet update not yet on the engine's changes (#6606) AWS::CloudFront::CachePolicy update not yet on the engine's changes (#6606) AWS::CloudFront::ConnectionGroup update not yet on the engine's changes (#6606) AWS::CloudFront::Distribution update not yet on the engine's changes (#6606) +AWS::CloudFront::DistributionTenant update not yet on the engine's changes (#6606) AWS::CloudFront::Function update not yet on the engine's changes (#6606) AWS::CloudFront::KeyGroup update not yet on the engine's changes (#6606) AWS::CloudFront::OriginAccessControl update not yet on the engine's changes (#6606) diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index dd63e7fbdc..8afc34fad1 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -1,5 +1,6 @@ AWS::AppConfig::ConfigurationProfile KmsKeyArn Floci's AppConfig keeps no KMS key on a profile, so KmsKeyIdentifier is accepted and not stored AWS::BedrockAgentCore::Runtime WorkloadIdentityDetails the dotted WorkloadIdentityDetails.WorkloadIdentityArn is set instead, the form AWS's GetAtt exposes for the nested object +AWS::CloudFront::DistributionTenant DomainResults a list of objects, which attributes as Floci keeps them (text) cannot hold; the tenant's domains read back through GetDistributionTenant AWS::CodePipeline::CustomActionType Id schema gives no description; the custom action has no separate id in Floci AWS::CodePipeline::Webhook Id schema gives no description; Floci keys webhooks by name AWS::DSQL::Cluster EncryptionDetails an object, which attributes as Floci keeps them (text) cannot hold; on AWS an output naming it fails with "Every Value member must be a string", and EncryptionDetails.EncryptionStatus is refused as no attribute of the schema diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index 0937361431..9681f5fa86 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -50,6 +50,7 @@ AWS::CloudFormation::StackSet StackSetId AdministrationRoleARN,AutoDeployment,Ca AWS::CloudFront::CachePolicy Id,LastModifiedTime CachePolicyConfig AWS::CloudFront::ConnectionGroup Arn,CreatedTime,ETag,Id,IsDefault,LastModifiedTime,RoutingEndpoint,Status AnycastIpListId,Enabled,Ipv6Enabled,Name,Tags,ViewerFallback AWS::CloudFront::Distribution DomainName,Id DistributionConfig,Tags +AWS::CloudFront::DistributionTenant Arn,CreatedTime,DomainResults,ETag,Id,LastModifiedTime,Status ConnectionGroupId,Customizations,DistributionId,DomainMappings,Domains,Enabled,ManagedCertificateRequest,Name,OnDomainTakeover,Parameters,Tags AWS::CloudFront::Function FunctionARN,Stage AutoPublish,FunctionCode,FunctionConfig,FunctionMetadata,Name,Tags AWS::CloudFront::KeyGroup Id,LastModifiedTime KeyGroupConfig AWS::CloudFront::OriginAccessControl Id OriginAccessControlConfig diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 3dadec1500..87187ca0a1 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -51,6 +51,7 @@ AWS::CloudFormation::StackSet StackSetCfnProvisioner AWS::CloudFront::CachePolicy CloudFrontCfnProvisioner AWS::CloudFront::ConnectionGroup CloudFrontCfnProvisioner AWS::CloudFront::Distribution CloudFrontCfnProvisioner +AWS::CloudFront::DistributionTenant CloudFrontCfnProvisioner AWS::CloudFront::Function CloudFrontCfnProvisioner AWS::CloudFront::KeyGroup CloudFrontCfnProvisioner AWS::CloudFront::OriginAccessControl CloudFrontCfnProvisioner diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index a781853994..dad56351e7 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -136,6 +136,9 @@ AWS::CloudFormation::StackSet CallAs accepted and ignored; local StackSets do no AWS::CloudFormation::StackSet ExecutionRoleName accepted and ignored; local StackSets deploy without assuming an execution role AWS::CloudFormation::StackSet OperationPreferences accepted and ignored; explicit StackSet deployments execute locally without scheduling preferences AWS::CloudFront::Distribution Tags accepted and ignored +AWS::CloudFront::DistributionTenant DomainMappings accepted and ignored: Floci serves every domain the same way +AWS::CloudFront::DistributionTenant ManagedCertificateRequest accepted and ignored: Floci issues no managed certificates +AWS::CloudFront::DistributionTenant OnDomainTakeover accepted and ignored: Floci has no domain takeover to allow or reject AWS::CloudFront::Function FunctionMetadata accepted and ignored AWS::CloudTrail::Trail AggregationConfigurations accepted and ignored AWS::CloudTrail::Trail CloudWatchLogsLogGroupArn accepted and ignored