diff --git a/README.md b/README.md index 2e37411..9ec9860 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,17 @@ $renewRequired = $certificates->isRenewRequired('cdn.example.com', null); `issueCertificate()` returns a renew date when Fastly already has an issued or renewing certificate. For asynchronous states like `pending` or `processing`, it returns `null`. +When Fastly domain management owns the domain lifecycle, use the managed provider instead. It creates versionless domains on the configured service and removes both the domain and TLS subscription on deletion. Classic domains are removed by cloning and activating their service version first. + +```php +use Utopia\Cdn\Certificates\Provider\Fastly; + +$fastlyCertificates = new Fastly( + apiToken: 'YOUR_API_TOKEN', + serviceId: 'YOUR_SERVICE_ID', +); +``` + ### Cloudflare certificates Cloudflare certificates use Cloudflare for SaaS custom hostnames, which must be enabled for the zone and plan. diff --git a/src/Cdn/Certificates/Provider/Fastly.php b/src/Cdn/Certificates/Provider/Fastly.php new file mode 100644 index 0000000..c55e6f5 --- /dev/null +++ b/src/Cdn/Certificates/Provider/Fastly.php @@ -0,0 +1,312 @@ +deploymentPollAttempts < 1) { + throw new \InvalidArgumentException('Deployment poll attempts must be at least one.'); + } + + if ($this->deploymentPollIntervalMilliseconds < 0) { + throw new \InvalidArgumentException('Deployment poll interval cannot be negative.'); + } + + $this->client = $client ?? new Client(new CurlAdapter()); + $this->tls = new FastlyTls( + apiToken: $this->apiToken, + tlsConfigurationId: '', + certificateAuthority: $certificateAuthority, + client: $this->client, + apiBase: $this->apiBase, + ); + } + + public function issueCertificate(string $certName, string $domain, ?string $domainType): ?string + { + $domain = Domain::validate($domain); + $domainInfo = $this->findDomain($domain); + + if ($domainInfo !== null) { + $existingServiceId = $domainInfo['service_id'] ?? null; + + if (!\is_string($existingServiceId) || $existingServiceId === '') { + // A classic domain cannot be moved without activating a new + // service version, so leave its existing certificate untouched. + return null; + } + + if ($existingServiceId !== $this->serviceId) { + $domainId = $domainInfo['id'] ?? null; + if (!\is_string($domainId) || $domainId === '') { + throw new \RuntimeException('Fastly domain response was missing its ID.'); + } + + // Finish the certificate lifecycle while ownership is still + // unchanged. A TLS failure must not move a live hostname. + $renewDate = $this->tls->issueCertificate($certName, $domain, $domainType); + $status = $this->tls->getCertificateStatus($domain, $domainType); + + if (!\in_array($status, [Status::ISSUED, Status::RENEWING], true)) { + return $renewDate; + } + + $result = $this->request( + 'PATCH', + '/domain-management/v1/domains/' . \rawurlencode($domainId), + ['service_id' => $this->serviceId], + ); + $this->assertSuccess('reassign Fastly domain', $result); + + return $renewDate; + } + } + + if ($domainInfo === null) { + $result = $this->request('POST', '/domain-management/v1/domains', [ + 'fqdn' => $domain, + 'service_id' => $this->serviceId, + ]); + $this->assertSuccess('add Fastly domain', $result, [201]); + } + + return $this->tls->issueCertificate($certName, $domain, $domainType); + } + + public function isInstantGeneration(string $domain, ?string $domainType): bool + { + return false; + } + + public function getCertificateStatus(string $domain, ?string $domainType): string + { + return $this->tls->getCertificateStatus(Domain::validate($domain), $domainType); + } + + public function isRenewRequired(string $domain, ?string $domainType): bool + { + return $this->tls->isRenewRequired(Domain::validate($domain), $domainType); + } + + public function deleteCertificate(string $domain, ?string $domainType = null): void + { + $domain = Domain::validate($domain); + $domainInfo = $this->findDomain($domain); + + if ($domainInfo === null) { + $this->tls->deleteCertificate($domain, $domainType); + return; + } + + $serviceId = $domainInfo['service_id'] ?? null; + if (!\is_string($serviceId) || $serviceId === '') { + $this->deleteClassicDomain($domain, $domainType); + return; + } + + if ($serviceId !== $this->serviceId) { + return; + } + + $this->deleteVersionlessDomain($domainInfo, $domainType); + } + + /** @return array|null */ + private function findDomain(string $domain): ?array + { + $query = \http_build_query(['fqdn' => $domain, 'limit' => 100]); + $result = $this->request('GET', '/domain-management/v1/domains?' . $query); + $this->assertSuccess('fetch Fastly domains', $result); + + if (!\is_array($result['response'])) { + throw new \RuntimeException('Fastly domains response was not valid JSON.'); + } + + $domains = $result['response']['data'] ?? null; + if (!\is_array($domains)) { + throw new \RuntimeException('Fastly domains response was missing its data list.'); + } + + foreach ($domains as $candidate) { + if (\is_array($candidate) && ($candidate['fqdn'] ?? null) === $domain) { + return $candidate; + } + } + + return null; + } + + /** @param array $domainInfo */ + private function deleteVersionlessDomain(array $domainInfo, ?string $domainType = null): void + { + $domainId = $domainInfo['id'] ?? null; + $domain = $domainInfo['fqdn'] ?? null; + + if (!\is_string($domainId) || $domainId === '' || !\is_string($domain) || $domain === '') { + throw new \RuntimeException('Fastly domain response was missing its ID or FQDN.'); + } + + $result = $this->request('DELETE', '/domain-management/v1/domains/' . \rawurlencode($domainId)); + $this->assertSuccess('delete Fastly domain', $result, [204]); + + $this->tls->deleteCertificate($domain, $domainType); + } + + private function deleteClassicDomain(string $domain, ?string $domainType): void + { + $result = $this->request('GET', '/service/' . \rawurlencode($this->serviceId) . '/details'); + $this->assertSuccess('fetch Fastly service details', $result); + + if (!\is_array($result['response'])) { + throw new \RuntimeException('Fastly service details response was not valid JSON.'); + } + + $activeVersion = $result['response']['active_version'] ?? null; + if (!\is_array($activeVersion)) { + throw new \RuntimeException('Fastly service details response was missing its active version.'); + } + + $domains = $activeVersion['domains'] ?? []; + $containsDomain = \is_array($domains) && \array_any( + $domains, + static fn (mixed $candidate): bool => \is_array($candidate) && ($candidate['name'] ?? null) === $domain, + ); + + if (!$containsDomain) { + // Classic domain records do not identify their service. An + // account-wide FQDN match that is absent from this service may + // belong to another service, whose TLS must remain untouched. + return; + } + + $currentVersion = $activeVersion['number'] ?? null; + if (!\is_int($currentVersion)) { + throw new \RuntimeException('Fastly active service version was missing its number.'); + } + + $servicePath = '/service/' . \rawurlencode($this->serviceId) . '/version/'; + $result = $this->request('PUT', $servicePath . $currentVersion . '/clone'); + $this->assertSuccess('clone Fastly service version', $result); + + if (!\is_array($result['response']) || !\is_int($result['response']['number'] ?? null)) { + throw new \RuntimeException('Fastly cloned service version was missing its number.'); + } + $newVersion = $result['response']['number']; + + $result = $this->request('DELETE', $servicePath . $newVersion . '/domain/' . \rawurlencode($domain)); + $this->assertSuccess('remove classic Fastly domain', $result, [200]); + + $result = $this->request('PUT', $servicePath . $newVersion . '/activate'); + $this->assertSuccess('activate Fastly service version', $result); + + $this->waitForDeployment($newVersion); + $this->tls->deleteCertificate($domain, $domainType); + } + + private function waitForDeployment(int $version): void + { + $path = '/service/' . \rawurlencode($this->serviceId) . '/version/' . $version; + + for ($attempt = 1; $attempt <= $this->deploymentPollAttempts; $attempt++) { + $result = $this->request('GET', $path); + $this->assertSuccess('fetch Fastly service version', $result); + + if (\is_array($result['response']) && ($result['response']['active'] ?? false) === true) { + return; + } + + if ($attempt < $this->deploymentPollAttempts && $this->deploymentPollIntervalMilliseconds > 0) { + \usleep($this->deploymentPollIntervalMilliseconds * 1000); + } + } + + throw new \RuntimeException('Fastly service version was not deployed after ' . $this->deploymentPollAttempts . ' attempts.'); + } + + /** + * @param array|null $body + * @return array{statusCode:int,response:array|string|null,error:string|null} + */ + private function request(string $method, string $path, ?array $body = null): array + { + $factory = new RequestFactory(); + $request = $body === null + ? $factory->createRequest($method, $this->apiBase . $path) + : $factory->json($method, $this->apiBase . $path, $body); + $request = $request + ->withHeader(Header::USER_AGENT, 'Utopia CDN Fastly Certificates Provider') + ->withHeader('Fastly-Key', $this->apiToken) + ->withHeader(Header::ACCEPT, 'application/json'); + + try { + $response = $this->client->sendRequest($request); + } catch (ClientExceptionInterface $error) { + return ['statusCode' => 0, 'response' => null, 'error' => $error->getMessage()]; + } + + $contents = (string) $response->getBody(); + + try { + $decoded = \json_decode($contents, true, flags: JSON_THROW_ON_ERROR); + } catch (\JsonException) { + $decoded = $contents; + } + + return ['statusCode' => $response->getStatusCode(), 'response' => $decoded, 'error' => null]; + } + + /** + * @param array{statusCode:int,response:array|string|null,error:string|null} $result + * @param array|null $expectedStatuses + */ + private function assertSuccess(string $operation, array $result, ?array $expectedStatuses = null): void + { + $success = $expectedStatuses === null + ? $result['statusCode'] >= 200 && $result['statusCode'] < 300 + : \in_array($result['statusCode'], $expectedStatuses, true); + + if ($success) { + return; + } + + $message = $result['error']; + if (\is_array($result['response'])) { + $message ??= $result['response']['errors'][0]['detail'] + ?? $result['response']['errors'][0]['title'] + ?? $result['response']['msg'] + ?? null; + } + + throw new \RuntimeException('Failed to ' . $operation . ' with status ' . $result['statusCode'] . ': ' . ($message ?? 'Unknown Fastly error')); + } +} diff --git a/src/Cdn/Certificates/Provider/FastlyTls.php b/src/Cdn/Certificates/Provider/FastlyTls.php index e901c7b..c3a3f3c 100644 --- a/src/Cdn/Certificates/Provider/FastlyTls.php +++ b/src/Cdn/Certificates/Provider/FastlyTls.php @@ -75,7 +75,7 @@ public function deleteCertificate(string $domain, ?string $domainType = null): v $result = $this->request( 'DELETE', - '/tls/subscriptions/' . $subscription['resource']['id'] + '/tls/subscriptions/' . $subscription['resource']['id'] . '?force=true' ); if ($result['statusCode'] < 200 || $result['statusCode'] >= 300) { @@ -131,32 +131,37 @@ private function findSubscription(string $domain): ?array */ private function createSubscription(string $domain): array { + $relationships = [ + 'tls_domains' => [ + 'data' => [[ + 'type' => 'tls_domain', + 'id' => $domain, + ]], + ], + ]; + + if ($this->tlsConfigurationId !== '') { + $relationships['common_name'] = [ + 'data' => [ + 'type' => 'tls_domain', + 'id' => $domain, + ], + ]; + $relationships['tls_configuration'] = [ + 'data' => [ + 'type' => 'tls_configuration', + 'id' => $this->tlsConfigurationId, + ], + ]; + } + $result = $this->request('POST', '/tls/subscriptions', [ 'data' => [ 'type' => 'tls_subscription', 'attributes' => [ 'certificate_authority' => $this->certificateAuthority, ], - 'relationships' => [ - 'common_name' => [ - 'data' => [ - 'type' => 'tls_domain', - 'id' => $domain, - ], - ], - 'tls_configuration' => [ - 'data' => [ - 'type' => 'tls_configuration', - 'id' => $this->tlsConfigurationId, - ], - ], - 'tls_domains' => [ - 'data' => [[ - 'type' => 'tls_domain', - 'id' => $domain, - ]], - ], - ], + 'relationships' => $relationships, ], ]); diff --git a/tests/Cdn/Certificates/Provider/FastlyTest.php b/tests/Cdn/Certificates/Provider/FastlyTest.php new file mode 100644 index 0000000..edc7d6f --- /dev/null +++ b/tests/Cdn/Certificates/Provider/FastlyTest.php @@ -0,0 +1,235 @@ +json('{"data":[]}'), + $this->json('{}', 201), + $this->json('{"data":[]}'), + $this->json('{"data":{"id":"sub_1","attributes":{"state":"pending"}}}', 201), + ]); + + $provider = new Fastly('token', 'service_1', client: $client); + $this->assertNull($provider->issueCertificate('cert', 'example.com', null)); + + $this->assertSame('POST', $client->calls[1]['method']); + $this->assertSame('https://api.fastly.com/domain-management/v1/domains', $client->calls[1]['url']); + $this->assertSame(['fqdn' => 'example.com', 'service_id' => 'service_1'], $client->calls[1]['body']); + $this->assertSame('POST', $client->calls[3]['method']); + $this->assertSame('example.com', $client->calls[3]['body']['data']['relationships']['tls_domains']['data'][0]['id']); + } + + public function testIssueReassignsVersionlessDomainFromAnotherService(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com","service_id":"old_service"}]}'), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"issued"}}]}'), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"issued"}}]}'), + $this->json('{"id":"domain_1","fqdn":"example.com","service_id":"new_service"}'), + ]); + + (new Fastly('token', 'new_service', client: $client))->issueCertificate('cert', 'example.com', null); + + $this->assertCount(4, $client->calls); + $this->assertStringStartsWith('https://api.fastly.com/tls/subscriptions?', $client->calls[1]['url']); + $this->assertStringStartsWith('https://api.fastly.com/tls/subscriptions?', $client->calls[2]['url']); + $this->assertSame('PATCH', $client->calls[3]['method']); + $this->assertSame('https://api.fastly.com/domain-management/v1/domains/domain_1', $client->calls[3]['url']); + $this->assertSame(['service_id' => 'new_service'], $client->calls[3]['body']); + } + + public function testPendingTlsDoesNotReassignVersionlessDomain(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com","service_id":"old_service"}]}'), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"pending"}}]}'), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"pending"}}]}'), + ]); + + $this->assertNull((new Fastly('token', 'new_service', client: $client))->issueCertificate('cert', 'example.com', null)); + + $this->assertCount(3, $client->calls); + $this->assertSame('GET', $client->calls[2]['method']); + $this->assertStringStartsWith('https://api.fastly.com/tls/subscriptions?', $client->calls[2]['url']); + } + + public function testFailedVersionlessReassignmentLeavesDomainAndTlsUntouched(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com","service_id":"old_service"}]}'), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"issued"}}]}'), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"issued"}}]}'), + $this->json('{"msg":"service unavailable"}', 503), + ]); + + try { + (new Fastly('token', 'new_service', client: $client))->issueCertificate('cert', 'example.com', null); + $this->fail('Expected domain reassignment to fail.'); + } catch (\RuntimeException $error) { + $this->assertStringContainsString('reassign Fastly domain', $error->getMessage()); + } + + $this->assertCount(4, $client->calls); + $this->assertStringStartsWith('https://api.fastly.com/tls/subscriptions?', $client->calls[1]['url']); + $this->assertStringStartsWith('https://api.fastly.com/tls/subscriptions?', $client->calls[2]['url']); + $this->assertSame('PATCH', $client->calls[3]['method']); + } + + public function testTlsFailureStopsBeforeVersionlessDomainReassignment(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com","service_id":"old_service"}]}'), + $this->json('{"msg":"TLS unavailable"}', 503), + ]); + + try { + (new Fastly('token', 'new_service', client: $client))->issueCertificate('cert', 'example.com', null); + $this->fail('Expected TLS issuance to fail.'); + } catch (\RuntimeException $error) { + $this->assertStringContainsString('fetch Fastly TLS subscriptions', $error->getMessage()); + } + + $this->assertCount(2, $client->calls); + $this->assertStringStartsWith('https://api.fastly.com/tls/subscriptions?', $client->calls[1]['url']); + } + + public function testDeleteRemovesVersionlessSubscriptionAndDomain(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com","service_id":"service_1"}]}'), + new Response(204), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"issued"}}]}'), + new Response(204), + ]); + + (new Fastly('token', 'service_1', client: $client))->deleteCertificate('example.com'); + + $this->assertSame('DELETE', $client->calls[1]['method']); + $this->assertSame('https://api.fastly.com/domain-management/v1/domains/domain_1', $client->calls[1]['url']); + $this->assertSame('DELETE', $client->calls[3]['method']); + $this->assertSame('https://api.fastly.com/tls/subscriptions/sub_1?force=true', $client->calls[3]['url']); + } + + public function testFailedVersionlessDomainDeletionLeavesTlsSubscriptionUntouched(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com","service_id":"service_1"}]}'), + $this->json('{"msg":"domain is still active"}', 409), + ]); + + try { + (new Fastly('token', 'service_1', client: $client))->deleteCertificate('example.com'); + $this->fail('Expected domain deletion to fail.'); + } catch (\RuntimeException $error) { + $this->assertStringContainsString('delete Fastly domain', $error->getMessage()); + } + + $this->assertCount(2, $client->calls); + $this->assertSame('https://api.fastly.com/domain-management/v1/domains/domain_1', $client->calls[1]['url']); + } + + public function testVersionlessDomainOwnedByAnotherServiceIsNotDeleted(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com","service_id":"other_service"}]}'), + ]); + + (new Fastly('token', 'service_1', client: $client))->deleteCertificate('example.com'); + + $this->assertCount(1, $client->calls); + $this->assertStringContainsString('/domain-management/v1/domains?', $client->calls[0]['url']); + } + + public function testDeleteActivatesClassicServiceWithoutDomainBeforeRemovingTls(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com"}]}'), + $this->json('{"active_version":{"number":3,"domains":[{"name":"example.com"}]}}'), + $this->json('{"number":4}'), + $this->json('{}'), + $this->json('{}'), + $this->json('{"active":false}'), + $this->json('{"active":true}'), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"issued"}}]}'), + new Response(204), + ]); + + $provider = new Fastly( + 'token', + 'service_1', + client: $client, + deploymentPollAttempts: 2, + deploymentPollIntervalMilliseconds: 0, + ); + $provider->deleteCertificate('example.com'); + + $this->assertSame('PUT', $client->calls[2]['method']); + $this->assertSame('https://api.fastly.com/service/service_1/version/3/clone', $client->calls[2]['url']); + $this->assertSame('https://api.fastly.com/service/service_1/version/4/domain/example.com', $client->calls[3]['url']); + $this->assertSame('https://api.fastly.com/service/service_1/version/4/activate', $client->calls[4]['url']); + $this->assertSame('https://api.fastly.com/tls/subscriptions/sub_1?force=true', $client->calls[8]['url']); + } + + public function testClassicDomainConflictStopsBeforeActivationAndTlsDeletion(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com"}]}'), + $this->json('{"active_version":{"number":3,"domains":[{"name":"example.com"}]}}'), + $this->json('{"number":4}'), + $this->json('{"msg":"version is locked"}', 409), + ]); + + try { + (new Fastly('token', 'service_1', client: $client))->deleteCertificate('example.com'); + $this->fail('Expected classic domain deletion to fail.'); + } catch (\RuntimeException $error) { + $this->assertStringContainsString('remove classic Fastly domain', $error->getMessage()); + } + + $this->assertCount(4, $client->calls); + $this->assertSame('DELETE', $client->calls[3]['method']); + $this->assertSame('https://api.fastly.com/service/service_1/version/4/domain/example.com', $client->calls[3]['url']); + } + + public function testClassicDomainOwnedByAnotherServiceLeavesTlsUntouched(): void + { + $client = new TestClient([ + $this->json('{"data":[{"id":"domain_1","fqdn":"example.com"}]}'), + $this->json('{"active_version":{"number":3,"domains":[{"name":"other.example.com"}]}}'), + ]); + + (new Fastly('token', 'service_1', client: $client))->deleteCertificate('example.com'); + + $this->assertCount(2, $client->calls); + $this->assertSame('https://api.fastly.com/service/service_1/details', $client->calls[1]['url']); + } + + public function testDeleteStillRemovesOrphanedTlsSubscription(): void + { + $client = new TestClient([ + $this->json('{"data":[]}'), + $this->json('{"data":[{"id":"sub_1","attributes":{"state":"issued"}}]}'), + new Response(204), + ]); + + (new Fastly('token', 'service_1', client: $client))->deleteCertificate('example.com'); + + $this->assertCount(3, $client->calls); + $this->assertSame('https://api.fastly.com/tls/subscriptions/sub_1?force=true', $client->calls[2]['url']); + } + + private function json(string $body, int $status = 200): Response + { + return new Response($status, body: new Stream($body)); + } +} diff --git a/tests/Cdn/Certificates/Provider/FastlyTlsTest.php b/tests/Cdn/Certificates/Provider/FastlyTlsTest.php index f6e41c8..904c3b9 100644 --- a/tests/Cdn/Certificates/Provider/FastlyTlsTest.php +++ b/tests/Cdn/Certificates/Provider/FastlyTlsTest.php @@ -29,6 +29,21 @@ public function testIssueCertificateCreatesSubscriptionWhenMissing(): void $this->assertSame('tls-config-id', $client->calls[1]['body']['data']['relationships']['tls_configuration']['data']['id']); } + public function testIssueCertificateCanUseFastlyDomainManagementWithoutAConfiguration(): void + { + $client = new TestClient([ + new Response(200, body: new Stream('{"data":[]}')), + new Response(201, body: new Stream('{"data":{"id":"sub_123","attributes":{"state":"pending"}}}')), + ]); + + (new FastlyTls('token', '', 'certainly', $client))->issueCertificate('cert', 'example.com', null); + + $relationships = $client->calls[1]['body']['data']['relationships']; + $this->assertSame('example.com', $relationships['tls_domains']['data'][0]['id']); + $this->assertArrayNotHasKey('common_name', $relationships); + $this->assertArrayNotHasKey('tls_configuration', $relationships); + } + public function testGetCertificateStatusMapsFastlyState(): void { $client = new TestClient([ @@ -54,7 +69,7 @@ public function testDeleteCertificateRemovesSubscription(): void $this->assertCount(2, $client->calls); $this->assertSame('DELETE', $client->calls[1]['method']); - $this->assertSame('https://api.fastly.com/tls/subscriptions/sub_123', $client->calls[1]['url']); + $this->assertSame('https://api.fastly.com/tls/subscriptions/sub_123?force=true', $client->calls[1]['url']); } public function testIssueCertificateReturnsRenewDateFromIncludedCertificate(): void