diff --git a/README.md b/README.md index 7fa5fafa..46e16754 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,23 @@ op read "op://vault/stripe/api-key" | cloud secret:create --name=STRIPE_KEY -n | `cloud domain:delete` | Delete a domain | | `cloud domain:verify` | Verify domain DNS | +### Webhooks + +| Command | Description | +| -------------------------------------- | ------------------------------------------------- | +| `cloud webhook-endpoint:list` | List an environment's webhook endpoints | +| `cloud webhook-endpoint:get` | Get webhook endpoint details | +| `cloud webhook-endpoint:create` | Create a webhook endpoint for deployment events | +| `cloud webhook-endpoint:update` | Update a webhook endpoint's URL, events, or state | +| `cloud webhook-endpoint:delete` | Delete a webhook endpoint | +| `cloud webhook-endpoint:test` | Send a `ping` and show the delivery | +| `cloud webhook-endpoint:deliveries` | List the last 50 deliveries | +| `cloud webhook-endpoint:rotate-secret` | Generate a new signing secret | + +Cloud sends a signed `POST` to the endpoint for each deployment event it subscribes to: `deployment.live`, `deployment.succeeded`, `deployment.failed`, and `deployment.post_deploy_failed`. Pass `--events` once per event or as a comma-separated list. An environment can have up to five endpoints. + +The signing secret is returned only by `webhook-endpoint:create` and `webhook-endpoint:rotate-secret`. Both show it to a person; JSON output masks it unless you pass `--show-sensitive`. Rotating stops the old secret working immediately, so it asks for confirmation (or `--force`). `webhook-endpoint:test` exits non-zero when the ping fails or is blocked. Endpoints can be given by ID or by URL. + ### Email (Resend) | Command | Description | diff --git a/app/Client/Connector.php b/app/Client/Connector.php index 748e41f6..7ffa41df 100644 --- a/app/Client/Connector.php +++ b/app/Client/Connector.php @@ -26,6 +26,7 @@ use App\Client\Resources\ScheduledCommandsResource; use App\Client\Resources\SecretsResource; use App\Client\Resources\UsageResource; +use App\Client\Resources\WebhookEndpointsResource; use App\Client\Resources\WebSocketApplicationsResource; use App\Client\Resources\WebSocketClustersResource; use App\Cloud; @@ -272,6 +273,11 @@ public function usage(): UsageResource return new UsageResource($this); } + public function webhookEndpoints(): WebhookEndpointsResource + { + return new WebhookEndpointsResource($this); + } + public function cliAuth(): CliAuthResource { return new CliAuthResource(self::unauthenticated()); diff --git a/app/Client/README.md b/app/Client/README.md index 919d5670..baad472a 100644 --- a/app/Client/README.md +++ b/app/Client/README.md @@ -157,6 +157,16 @@ $data = $response->json(); - `UpdateWebSocketApplicationRequest` - Update an application - `DeleteWebSocketApplicationRequest` - Delete an application +#### Webhook Endpoints +- `ListWebhookEndpointsRequest` - List webhook endpoints for an environment +- `GetWebhookEndpointRequest` - Get a specific webhook endpoint +- `CreateWebhookEndpointRequest` - Create a webhook endpoint (the response holds its only copy of the signing secret) +- `UpdateWebhookEndpointRequest` - Update a webhook endpoint's URL, events, or enabled state +- `DeleteWebhookEndpointRequest` - Delete a webhook endpoint +- `TestWebhookEndpointRequest` - Send a `ping` event and return the delivery +- `ListWebhookDeliveriesRequest` - List the last 50 deliveries to a webhook endpoint +- `RotateWebhookEndpointSecretRequest` - Generate a new signing secret (the old one stops working immediately) + #### Meta - `GetOrganizationRequest` - Get the authenticated organization - `ListRegionsRequest` - List available regions diff --git a/app/Client/Requests/CreateWebhookEndpointRequestData.php b/app/Client/Requests/CreateWebhookEndpointRequestData.php new file mode 100644 index 00000000..2189b000 --- /dev/null +++ b/app/Client/Requests/CreateWebhookEndpointRequestData.php @@ -0,0 +1,27 @@ + $events + */ + public function __construct( + public readonly string $environmentId, + public readonly string $url, + public readonly array $events, + public readonly ?bool $enabled = null, + ) { + // + } + + public function toRequestData(): array + { + return $this->filter([ + 'url' => $this->url, + 'events' => $this->events, + 'enabled' => $this->enabled, + ]); + } +} diff --git a/app/Client/Requests/UpdateWebhookEndpointRequestData.php b/app/Client/Requests/UpdateWebhookEndpointRequestData.php new file mode 100644 index 00000000..c26970b8 --- /dev/null +++ b/app/Client/Requests/UpdateWebhookEndpointRequestData.php @@ -0,0 +1,27 @@ +|null $events + */ + public function __construct( + public readonly string $webhookEndpointId, + public readonly ?string $url = null, + public readonly ?array $events = null, + public readonly ?bool $enabled = null, + ) { + // + } + + public function toRequestData(): array + { + return $this->filter([ + 'url' => $this->url, + 'events' => $this->events, + 'enabled' => $this->enabled, + ]); + } +} diff --git a/app/Client/Resources/WebhookEndpoints/CreateWebhookEndpointRequest.php b/app/Client/Resources/WebhookEndpoints/CreateWebhookEndpointRequest.php new file mode 100644 index 00000000..7683cbca --- /dev/null +++ b/app/Client/Resources/WebhookEndpoints/CreateWebhookEndpointRequest.php @@ -0,0 +1,39 @@ +data->environmentId}/webhook-endpoints"; + } + + protected function defaultBody(): array + { + return $this->data->toRequestData(); + } + + public function createDtoFromResponse(Response $response): mixed + { + return WebhookEndpoint::createFromResponse($response->json()); + } +} diff --git a/app/Client/Resources/WebhookEndpoints/DeleteWebhookEndpointRequest.php b/app/Client/Resources/WebhookEndpoints/DeleteWebhookEndpointRequest.php new file mode 100644 index 00000000..db098b7d --- /dev/null +++ b/app/Client/Resources/WebhookEndpoints/DeleteWebhookEndpointRequest.php @@ -0,0 +1,22 @@ +webhookEndpointId}"; + } +} diff --git a/app/Client/Resources/WebhookEndpoints/GetWebhookEndpointRequest.php b/app/Client/Resources/WebhookEndpoints/GetWebhookEndpointRequest.php new file mode 100644 index 00000000..b65d1f01 --- /dev/null +++ b/app/Client/Resources/WebhookEndpoints/GetWebhookEndpointRequest.php @@ -0,0 +1,32 @@ +webhookEndpointId}"; + } + + public function createDtoFromResponse(Response $response): mixed + { + return WebhookEndpoint::createFromResponse($response->json()); + } +} diff --git a/app/Client/Resources/WebhookEndpoints/ListWebhookDeliveriesRequest.php b/app/Client/Resources/WebhookEndpoints/ListWebhookDeliveriesRequest.php new file mode 100644 index 00000000..3a280ef1 --- /dev/null +++ b/app/Client/Resources/WebhookEndpoints/ListWebhookDeliveriesRequest.php @@ -0,0 +1,33 @@ +webhookEndpointId}/deliveries"; + } + + public function createDtoFromResponse(Response $response): mixed + { + return array_map( + fn ($delivery) => WebhookDelivery::createFromResponse(['data' => $delivery]), + $response->json('data'), + ); + } +} diff --git a/app/Client/Resources/WebhookEndpoints/ListWebhookEndpointsRequest.php b/app/Client/Resources/WebhookEndpoints/ListWebhookEndpointsRequest.php new file mode 100644 index 00000000..bc70ccfb --- /dev/null +++ b/app/Client/Resources/WebhookEndpoints/ListWebhookEndpointsRequest.php @@ -0,0 +1,36 @@ +environmentId}/webhook-endpoints"; + } + + public function createDtoFromResponse(Response $response): mixed + { + return array_map(fn ($endpoint) => WebhookEndpoint::createFromResponse([ + 'data' => $endpoint, + 'included' => $response->json('included', []), + ]), $response->json('data')); + } +} diff --git a/app/Client/Resources/WebhookEndpoints/RotateWebhookEndpointSecretRequest.php b/app/Client/Resources/WebhookEndpoints/RotateWebhookEndpointSecretRequest.php new file mode 100644 index 00000000..16af2739 --- /dev/null +++ b/app/Client/Resources/WebhookEndpoints/RotateWebhookEndpointSecretRequest.php @@ -0,0 +1,29 @@ +webhookEndpointId}/secret"; + } + + public function createDtoFromResponse(Response $response): mixed + { + return WebhookEndpoint::createFromResponse($response->json()); + } +} diff --git a/app/Client/Resources/WebhookEndpoints/TestWebhookEndpointRequest.php b/app/Client/Resources/WebhookEndpoints/TestWebhookEndpointRequest.php new file mode 100644 index 00000000..b7653e17 --- /dev/null +++ b/app/Client/Resources/WebhookEndpoints/TestWebhookEndpointRequest.php @@ -0,0 +1,29 @@ +webhookEndpointId}/test"; + } + + public function createDtoFromResponse(Response $response): mixed + { + return WebhookDelivery::createFromResponse($response->json()); + } +} diff --git a/app/Client/Resources/WebhookEndpoints/UpdateWebhookEndpointRequest.php b/app/Client/Resources/WebhookEndpoints/UpdateWebhookEndpointRequest.php new file mode 100644 index 00000000..f4c60c49 --- /dev/null +++ b/app/Client/Resources/WebhookEndpoints/UpdateWebhookEndpointRequest.php @@ -0,0 +1,39 @@ +data->webhookEndpointId}"; + } + + protected function defaultBody(): array + { + return $this->data->toRequestData(); + } + + public function createDtoFromResponse(Response $response): mixed + { + return WebhookEndpoint::createFromResponse($response->json()); + } +} diff --git a/app/Client/Resources/WebhookEndpointsResource.php b/app/Client/Resources/WebhookEndpointsResource.php new file mode 100644 index 00000000..ebe3414d --- /dev/null +++ b/app/Client/Resources/WebhookEndpointsResource.php @@ -0,0 +1,75 @@ +paginate(new ListWebhookEndpointsRequest($environmentId)); + } + + public function get(string $webhookEndpointId): WebhookEndpoint + { + $request = new GetWebhookEndpointRequest($webhookEndpointId); + $response = $this->send($request); + + return $request->createDtoFromResponse($response); + } + + public function create(CreateWebhookEndpointRequestData $data): WebhookEndpoint + { + $request = new CreateWebhookEndpointRequest($data); + $response = $this->send($request); + + return $request->createDtoFromResponse($response); + } + + public function update(UpdateWebhookEndpointRequestData $data): WebhookEndpoint + { + $request = new UpdateWebhookEndpointRequest($data); + $response = $this->send($request); + + return $request->createDtoFromResponse($response); + } + + public function delete(string $webhookEndpointId): void + { + $this->send(new DeleteWebhookEndpointRequest($webhookEndpointId)); + } + + public function test(string $webhookEndpointId): WebhookDelivery + { + $request = new TestWebhookEndpointRequest($webhookEndpointId); + $response = $this->send($request); + + return $request->createDtoFromResponse($response); + } + + public function deliveries(string $webhookEndpointId): Paginator + { + return $this->paginate(new ListWebhookDeliveriesRequest($webhookEndpointId)); + } + + public function rotateSecret(string $webhookEndpointId): WebhookEndpoint + { + $request = new RotateWebhookEndpointSecretRequest($webhookEndpointId); + $response = $this->send($request); + + return $request->createDtoFromResponse($response); + } +} diff --git a/app/Commands/WebhookEndpointCreate.php b/app/Commands/WebhookEndpointCreate.php new file mode 100644 index 00000000..bf7c6a6f --- /dev/null +++ b/app/Commands/WebhookEndpointCreate.php @@ -0,0 +1,67 @@ +ensureClient(); + + intro('Creating Webhook Endpoint'); + + $environment = $this->resolvers()->environment()->from($this->argument('environment')); + + $endpoint = $this->loopUntilValid(fn () => $this->createEndpoint($environment)); + + $this->warnIfSigningSecretMasked('Pass --show-sensitive when creating an endpoint to include it, or run `cloud webhook-endpoint:rotate-secret` for a new one.'); + + $this->outputJsonIfWanted($endpoint); + + success("Webhook endpoint `{$endpoint->url}` created."); + + $this->showSigningSecret($endpoint); + } + + protected function createEndpoint(Environment $environment): WebhookEndpoint + { + $this->defineUrlField(); + $this->form()->prompt('url'); + + $this->defineEventsField(); + $this->form()->prompt('events'); + + return spin( + fn () => $this->client->webhookEndpoints()->create( + new CreateWebhookEndpointRequestData( + environmentId: $environment->id, + url: $this->form()->get('url'), + events: array_values($this->form()->get('events')), + // The API enables new endpoints by default, so only a request to disable is sent. + enabled: $this->option('disabled') ? false : null, + ), + ), + 'Creating webhook endpoint...', + ); + } +} diff --git a/app/Commands/WebhookEndpointDelete.php b/app/Commands/WebhookEndpointDelete.php new file mode 100644 index 00000000..76d2fb64 --- /dev/null +++ b/app/Commands/WebhookEndpointDelete.php @@ -0,0 +1,35 @@ +ensureClient(); + + intro('Deleting Webhook Endpoint'); + + $endpoint = $this->resolvers()->webhookEndpoint()->from($this->argument('webhook-endpoint')); + + $this->confirmDestructive("Delete webhook endpoint `{$endpoint->url}`? Cloud will stop sending it events."); + + spin( + fn () => $this->client->webhookEndpoints()->delete($endpoint->id), + 'Deleting webhook endpoint...', + ); + + $this->outputJsonIfWanted('Webhook endpoint deleted.'); + + success("Webhook endpoint `{$endpoint->url}` deleted."); + } +} diff --git a/app/Commands/WebhookEndpointDeliveries.php b/app/Commands/WebhookEndpointDeliveries.php new file mode 100644 index 00000000..eb700b74 --- /dev/null +++ b/app/Commands/WebhookEndpointDeliveries.php @@ -0,0 +1,55 @@ +ensureClient(); + + intro('Webhook Deliveries'); + + $endpoint = $this->resolvers()->webhookEndpoint()->from($this->argument('webhook-endpoint')); + + $items = $this->fetchList( + fn () => $this->client->webhookEndpoints()->deliveries($endpoint->id), + 'Fetching webhook deliveries...', + ); + + $this->outputJsonIfWanted($items); + + if ($items->isEmpty()) { + warning('No webhook deliveries found.'); + + return self::SUCCESS; + } + + dataTable( + headers: ['ID', 'Event', 'Attempt', 'Outcome', 'Status Code', 'Duration (ms)', 'Created At'], + rows: $items->map(fn (WebhookDelivery $delivery) => [ + $delivery->id, + $delivery->event, + (string) $delivery->attempt, + $delivery->outcomeLabel(), + (string) ($delivery->statusCode() ?? '—'), + (string) ($delivery->durationMs ?? '—'), + $delivery->createdAt?->toIso8601String() ?? '—', + ])->toArray(), + ); + } +} diff --git a/app/Commands/WebhookEndpointGet.php b/app/Commands/WebhookEndpointGet.php new file mode 100644 index 00000000..0b3d34de --- /dev/null +++ b/app/Commands/WebhookEndpointGet.php @@ -0,0 +1,38 @@ +ensureClient(); + + intro('Webhook Endpoint Details'); + + $endpoint = $this->resolvers()->webhookEndpoint()->from($this->argument('webhook-endpoint')); + + $this->outputJsonIfWanted($endpoint); + + dataList([ + 'ID' => $endpoint->id, + 'URL' => $endpoint->url, + 'Events' => $endpoint->eventLabels(), + 'Enabled' => $endpoint->enabled ? 'Yes' : 'No', + 'Last Delivery At' => $endpoint->lastDeliveryAt?->toIso8601String() ?? '—', + 'Last Outcome' => $endpoint->lastOutcomeLabel() ?? '—', + 'Created At' => $endpoint->createdAt?->toIso8601String() ?? '—', + ]); + } +} diff --git a/app/Commands/WebhookEndpointList.php b/app/Commands/WebhookEndpointList.php new file mode 100644 index 00000000..fb3675de --- /dev/null +++ b/app/Commands/WebhookEndpointList.php @@ -0,0 +1,61 @@ +ensureClient(); + + intro('Webhook Endpoints'); + + $environment = $this->resolvers()->environment()->from($this->argument('environment')); + + $items = $this->fetchList( + fn () => $this->client->webhookEndpoints()->list($environment->id), + 'Fetching webhook endpoints...', + ); + + $this->outputJsonIfWanted($items); + + if ($items->isEmpty()) { + warning('No webhook endpoints found.'); + + return self::SUCCESS; + } + + dataTable( + headers: ['ID', 'URL', 'Events', 'Enabled', 'Last Delivery', 'Last Outcome'], + rows: $items->map(fn (WebhookEndpoint $endpoint) => [ + $endpoint->id, + $endpoint->url, + implode(', ', $endpoint->events), + $endpoint->enabled ? 'Yes' : 'No', + $endpoint->lastDeliveryAt?->toIso8601String() ?? '—', + $endpoint->lastOutcomeLabel() ?? '—', + ])->toArray(), + actions: [ + Key::ENTER => [ + fn ($row) => $this->call('webhook-endpoint:get', ['webhook-endpoint' => $row[0]]), + 'View', + ], + ], + ); + } +} diff --git a/app/Commands/WebhookEndpointRotateSecret.php b/app/Commands/WebhookEndpointRotateSecret.php new file mode 100644 index 00000000..bb08b410 --- /dev/null +++ b/app/Commands/WebhookEndpointRotateSecret.php @@ -0,0 +1,46 @@ +ensureClient(); + + intro('Rotating Webhook Endpoint Secret'); + + $endpoint = $this->resolvers()->webhookEndpoint()->from($this->argument('webhook-endpoint')); + + $this->confirmDestructive("Rotate the signing secret of webhook endpoint `{$endpoint->url}`? The current secret stops working immediately."); + + $endpoint = spin( + fn () => $this->client->webhookEndpoints()->rotateSecret($endpoint->id), + 'Rotating signing secret...', + ); + + $this->warnIfSigningSecretMasked('Pass --show-sensitive to include it, or rotate again for a new one.'); + + $this->outputJsonIfWanted($endpoint); + + success("Signing secret of webhook endpoint `{$endpoint->url}` rotated."); + + $this->showSigningSecret($endpoint); + } +} diff --git a/app/Commands/WebhookEndpointTest.php b/app/Commands/WebhookEndpointTest.php new file mode 100644 index 00000000..048e8440 --- /dev/null +++ b/app/Commands/WebhookEndpointTest.php @@ -0,0 +1,64 @@ +ensureClient(); + + intro('Testing Webhook Endpoint'); + + $endpoint = $this->resolvers()->webhookEndpoint()->from($this->argument('webhook-endpoint')); + + $delivery = spin( + fn () => $this->client->webhookEndpoints()->test($endpoint->id), + 'Sending test delivery...', + ); + + // The request worked even when the delivery didn't, so a failed delivery still prints before exiting non-zero. + try { + $this->outputJsonIfWanted($delivery); + } catch (CommandExitException $e) { + throw $delivery->failed() ? new CommandExitException(self::FAILURE) : $e; + } + + dataList([ + 'Event' => $delivery->eventLabel(), + 'Outcome' => $delivery->outcomeLabel(), + 'Status Code' => (string) ($delivery->statusCode() ?? '—'), + 'Duration' => $delivery->durationMs === null ? '—' : "{$delivery->durationMs} ms", + 'Error' => $delivery->error ?? '—', + ]); + + if ($delivery->failed()) { + error("Test delivery to `{$endpoint->url}` {$delivery->outcome}."); + + return self::FAILURE; + } + + if ($delivery->outcome === 'pending') { + warning("Test delivery to `{$endpoint->url}` is still pending. Check it with `cloud webhook-endpoint:deliveries`."); + + return self::SUCCESS; + } + + success("Test delivery to `{$endpoint->url}` succeeded."); + } +} diff --git a/app/Commands/WebhookEndpointUpdate.php b/app/Commands/WebhookEndpointUpdate.php new file mode 100644 index 00000000..55c9e587 --- /dev/null +++ b/app/Commands/WebhookEndpointUpdate.php @@ -0,0 +1,107 @@ +ensureClient(); + + intro('Updating Webhook Endpoint'); + + $endpoint = $this->resolvers()->webhookEndpoint()->from($this->argument('webhook-endpoint')); + + $this->defineUrlField($endpoint); + $this->defineEventsField($endpoint); + $this->defineEnabledField($endpoint); + + foreach ($this->form()->filled() as $resolver) { + $this->reportChange( + $resolver->label(), + $resolver->previousValue(), + $this->describeValue($resolver->value()), + ); + } + + $updatedEndpoint = $this->runUpdate( + fn () => $this->updateEndpoint($endpoint), + fn () => $this->collectDataAndUpdate($endpoint), + ); + + $this->outputJsonIfWanted($updatedEndpoint); + + success("Webhook endpoint `{$updatedEndpoint->url}` updated."); + } + + protected function updateEndpoint(WebhookEndpoint $endpoint): WebhookEndpoint + { + $events = $this->form()->get('events'); + + return spin( + fn () => $this->client->webhookEndpoints()->update( + new UpdateWebhookEndpointRequestData( + webhookEndpointId: $endpoint->id, + url: $this->form()->get('url'), + events: $events === null ? null : array_values($events), + enabled: $this->form()->boolean('enabled'), + ), + ), + 'Updating webhook endpoint...', + ); + } + + protected function collectDataAndUpdate(WebhookEndpoint $endpoint): WebhookEndpoint + { + $selection = multiselect( + label: 'What do you want to update?', + options: collect($this->form()->defined()) + ->mapWithKeys(fn ($field) => [$field->key => $field->label()]) + ->toArray(), + ); + + if (empty($selection)) { + $this->outputErrorOrThrow('No fields to update. Select at least one option.'); + + throw new CommandExitException(self::FAILURE); + } + + foreach ($selection as $field) { + $this->form()->prompt($field); + } + + return $this->updateEndpoint($endpoint); + } + + protected function describeValue(mixed $value): ?string + { + return match (true) { + is_array($value) => implode(', ', $value), + is_bool($value) => $value ? 'true' : 'false', + default => $value, + }; + } +} diff --git a/app/Concerns/DefinesWebhookEndpointFields.php b/app/Concerns/DefinesWebhookEndpointFields.php new file mode 100644 index 00000000..9728bec4 --- /dev/null +++ b/app/Concerns/DefinesWebhookEndpointFields.php @@ -0,0 +1,134 @@ +form)) { + parent::form()->options([ + ...$this->options(), + 'events' => $this->eventsOption(), + 'enabled' => $this->enabledOption(), + ]); + } + + return $this->form; + } + + /** + * An array option that was never passed arrives as [], which Form would take as an answer. + * Each value may also be a comma-separated list. + * + * @return list|null + */ + protected function eventsOption(): ?array + { + if (! $this->hasOption('events')) { + return null; + } + + $events = collect($this->option('events')) + ->flatMap(fn (string $value) => explode(',', $value)) + ->map(fn (string $event) => trim($event)) + ->filter() + ->unique() + ->values() + ->all(); + + return $events === [] ? null : $events; + } + + protected function enabledOption(): ?bool + { + $enabled = $this->hasOption('enabled') && $this->option('enabled'); + $disabled = $this->hasOption('disabled') && $this->option('disabled'); + + if ($enabled && $disabled) { + $this->failAndExit('Pass either --enabled or --disabled, not both.'); + } + + return match (true) { + $enabled => true, + $disabled => false, + default => null, + }; + } + + protected function defineUrlField(?WebhookEndpoint $endpoint = null): void + { + $this->form()->define( + 'url', + fn ($resolver) => $resolver->fromInput( + fn (?string $value) => text( + label: 'URL', + placeholder: 'https://example.com/webhooks/cloud', + default: $value ?? $endpoint->url ?? '', + required: true, + hint: 'Cloud sends a signed POST request here for each event. It must use HTTPS.', + ), + ), + )->setLabel('URL')->setPreviousValue($endpoint?->url); + } + + protected function defineEventsField(?WebhookEndpoint $endpoint = null): void + { + $this->form()->define( + 'events', + fn ($resolver) => $resolver->fromInput( + fn (?array $value) => multiselect( + label: 'Events', + options: WebhookEventType::subscribableOptions(), + default: $value ?? $endpoint->events ?? [], + required: true, + ), + ), + )->setLabel('Events')->setPreviousValue($endpoint ? implode(', ', $endpoint->events) : null); + } + + protected function defineEnabledField(WebhookEndpoint $endpoint): void + { + $this->form()->define( + 'enabled', + fn ($resolver) => $resolver->fromInput( + fn (?bool $value) => confirm( + label: 'Send events to this endpoint?', + default: $value ?? $endpoint->enabled, + ), + ), + )->setLabel('Enabled')->setPreviousValue($endpoint->enabled ? 'true' : 'false'); + } + + /** + * --show-sensitive only governs JSON. Here a person is reading, and the API returns the secret only this once. + */ + protected function showSigningSecret(WebhookEndpoint $endpoint): void + { + dataList([ + 'ID' => $endpoint->id, + 'URL' => $endpoint->url, + 'Events' => $endpoint->eventLabels(), + 'Enabled' => $endpoint->enabled ? 'Yes' : 'No', + 'Signing Secret' => $endpoint->secret ?? '—', + ]); + + warning('Save this signing secret now. It will not be shown again.'); + } + + protected function warnIfSigningSecretMasked(string $howToGetAnother): void + { + if ($this->wantsJson() && ! $this->option('show-sensitive')) { + $this->outputWarning("The signing secret is masked and cannot be retrieved again. {$howToGetAnother}"); + } + } +} diff --git a/app/Dto/WebhookDelivery.php b/app/Dto/WebhookDelivery.php new file mode 100644 index 00000000..cd61a657 --- /dev/null +++ b/app/Dto/WebhookDelivery.php @@ -0,0 +1,72 @@ +, body?: string} $request + * @param array{status_code?: int, headers?: array, body?: string|null}|null $response + */ + public function __construct( + public readonly string $id, + public readonly string $event, + public readonly string $outcome, + public readonly ?string $eventId = null, + public readonly int $attempt = 1, + public readonly array $request = [], + public readonly ?array $response = null, + public readonly ?string $error = null, + public readonly ?int $durationMs = null, + #[WithCast(DateTimeInterfaceCast::class, type: CarbonImmutable::class)] + public readonly ?CarbonImmutable $createdAt = null, + ) { + // + } + + public function eventLabel(): string + { + return WebhookEventType::labelFor($this->event); + } + + public function outcomeLabel(): string + { + return WebhookDeliveryOutcome::labelFor($this->outcome) ?? $this->outcome; + } + + public function statusCode(): ?int + { + return $this->response['status_code'] ?? null; + } + + public function failed(): bool + { + return in_array($this->outcome, [WebhookDeliveryOutcome::FAILED->value, WebhookDeliveryOutcome::BLOCKED->value], true); + } + + public static function createFromResponse(array $response): self + { + $data = $response['data'] ?? []; + $attributes = $data['attributes'] ?? []; + + return self::from([ + 'id' => $data['id'], + 'event' => $attributes['event'] ?? '', + 'outcome' => $attributes['outcome'] ?? WebhookDeliveryOutcome::PENDING->value, + 'eventId' => $attributes['event_id'] ?? null, + 'attempt' => $attributes['attempt'] ?? 1, + 'request' => $attributes['request'] ?? [], + 'response' => $attributes['response'] ?? null, + 'error' => $attributes['error'] ?? null, + 'durationMs' => $attributes['duration_ms'] ?? null, + 'createdAt' => $attributes['created_at'] ?? null, + ]); + } +} diff --git a/app/Dto/WebhookEndpoint.php b/app/Dto/WebhookEndpoint.php new file mode 100644 index 00000000..e736082e --- /dev/null +++ b/app/Dto/WebhookEndpoint.php @@ -0,0 +1,61 @@ + $events + */ + public function __construct( + public readonly string $id, + public readonly string $url, + public readonly array $events = [], + public readonly bool $enabled = true, + #[WithCast(DateTimeInterfaceCast::class, type: CarbonImmutable::class)] + public readonly ?CarbonImmutable $lastDeliveryAt = null, + public readonly ?string $lastOutcome = null, + #[WithCast(DateTimeInterfaceCast::class, type: CarbonImmutable::class)] + public readonly ?CarbonImmutable $createdAt = null, + #[WithTransformer(MaskSensitiveValue::class)] + public readonly ?string $secret = null, + ) { + // + } + + public function eventLabels(): string + { + return collect($this->events)->map(fn (string $event) => WebhookEventType::labelFor($event))->join(', ') ?: '—'; + } + + public function lastOutcomeLabel(): ?string + { + return WebhookDeliveryOutcome::labelFor($this->lastOutcome); + } + + public static function createFromResponse(array $response): self + { + $data = $response['data'] ?? []; + $attributes = $data['attributes'] ?? []; + + return self::from([ + 'id' => $data['id'], + 'url' => $attributes['url'] ?? '', + 'events' => array_values($attributes['events'] ?? []), + 'enabled' => (bool) ($attributes['enabled'] ?? true), + 'lastDeliveryAt' => $attributes['last_delivery_at'] ?? null, + 'lastOutcome' => $attributes['last_outcome'] ?? null, + 'createdAt' => $attributes['created_at'] ?? null, + 'secret' => $attributes['secret'] ?? null, + ]); + } +} diff --git a/app/Enums/WebhookDeliveryOutcome.php b/app/Enums/WebhookDeliveryOutcome.php new file mode 100644 index 00000000..9d680684 --- /dev/null +++ b/app/Enums/WebhookDeliveryOutcome.php @@ -0,0 +1,30 @@ + 'Pending', + self::SUCCEEDED => 'Succeeded', + self::FAILED => 'Failed', + self::BLOCKED => 'Blocked', + }; + } + + public static function labelFor(?string $outcome): ?string + { + if ($outcome === null) { + return null; + } + + return self::tryFrom($outcome)?->label() ?? $outcome; + } +} diff --git a/app/Enums/WebhookEventType.php b/app/Enums/WebhookEventType.php new file mode 100644 index 00000000..7fa29de2 --- /dev/null +++ b/app/Enums/WebhookEventType.php @@ -0,0 +1,41 @@ + 'Deployment live', + self::DEPLOYMENT_SUCCEEDED => 'Deployment succeeded', + self::DEPLOYMENT_FAILED => 'Deployment failed', + self::DEPLOYMENT_POST_DEPLOY_FAILED => 'Post-deploy command failed', + self::PING => 'Ping', + }; + } + + /** + * The events an endpoint can subscribe to. Cloud sends a ping only when asked to test an endpoint. + * + * @return array + */ + public static function subscribableOptions(): array + { + return collect(self::cases()) + ->reject(fn (self $case) => $case === self::PING) + ->mapWithKeys(fn (self $case) => [$case->value => $case->label()]) + ->toArray(); + } + + public static function labelFor(string $event): string + { + return self::tryFrom($event)?->label() ?? $event; + } +} diff --git a/app/Resolvers/Resolvers.php b/app/Resolvers/Resolvers.php index 3bc9e680..dc99c33e 100644 --- a/app/Resolvers/Resolvers.php +++ b/app/Resolvers/Resolvers.php @@ -110,6 +110,11 @@ public function websocketApplication(): WebSocketApplicationResolver return $this->make(WebSocketApplicationResolver::class); } + public function webhookEndpoint(): WebhookEndpointResolver + { + return $this->make(WebhookEndpointResolver::class); + } + /** * @template T of Resolver * diff --git a/app/Resolvers/WebhookEndpointResolver.php b/app/Resolvers/WebhookEndpointResolver.php new file mode 100644 index 00000000..d4d2c971 --- /dev/null +++ b/app/Resolvers/WebhookEndpointResolver.php @@ -0,0 +1,123 @@ +fromIdentifier($idOrUrl) : null) + ?? ($idOrUrl ? null : $this->fromInput()); + + if (! $endpoint) { + $this->failAndExit('Unable to resolve webhook endpoint: '.($idOrUrl ?? 'Provide a valid webhook endpoint ID or URL.').'. Run `cloud webhook-endpoint:list --json` to see available webhook endpoints.'); + } + + $this->displayResolved('Webhook endpoint', $endpoint->url, $endpoint->id); + + return $endpoint; + } + + /** + * Endpoint IDs have no documented prefix, so anything that isn't a URL is tried as an ID first. + */ + public function fromIdentifier(string $identifier): ?WebhookEndpoint + { + if (! str_contains($identifier, '://')) { + $endpoint = $this->fetchById($identifier); + + if ($endpoint) { + return $endpoint; + } + } + + return $this->fromUrl($identifier); + } + + public function fromInput(): ?WebhookEndpoint + { + $environment = $this->environment(); + $endpoints = $this->fetchAll($environment); + + if ($endpoints->isEmpty()) { + $this->failAndExit("No webhook endpoints found for environment {$environment->name}. Create one with `cloud webhook-endpoint:create`."); + } + + if ($endpoints->hasSole()) { + return $endpoints->first(); + } + + $options = $endpoints->mapWithKeys(fn (WebhookEndpoint $endpoint) => [$endpoint->id => $endpoint->url])->toArray(); + + $this->ensureInteractive('Multiple webhook endpoints found. Provide a webhook endpoint ID or URL.', ['options' => $options]); + + $selected = select( + label: 'Webhook endpoint', + options: $options, + info: fn ($id) => $id, + ); + + $this->displayResolved = false; + + return $endpoints->firstWhere('id', $selected); + } + + protected function fetchById(string $id): ?WebhookEndpoint + { + // Only a 404 means "not an ID"; anything else (an expired token, an outage) must surface as itself. + try { + return spin( + fn () => $this->client->webhookEndpoints()->get($id), + 'Fetching webhook endpoint...', + ); + } catch (NotFoundException) { + return null; + } + } + + protected function fromUrl(string $url): ?WebhookEndpoint + { + $normalize = fn (string $value) => rtrim($value, '/'); + + return $this->fetchAll($this->environment()) + ->first(fn (WebhookEndpoint $endpoint) => $normalize($endpoint->url) === $normalize($url)); + } + + /** + * @return Collection + */ + protected function fetchAll(Environment $environment): Collection + { + return spin( + fn () => $this->client->webhookEndpoints()->list($environment->id)->collect()->collect(), + 'Fetching webhook endpoints...', + ); + } + + protected function environment(): Environment + { + return $this->environment ??= $this->resolvers() + ->environment() + ->withApplication($this->application()) + ->resolve(); + } + + protected function idPrefix(): callable + { + // The API documents no ID prefix, so identifiers are tried by ID in fromIdentifier() instead. + return fn () => false; + } +} diff --git a/skills/deploying-to-cloud/SKILL.md b/skills/deploying-to-cloud/SKILL.md index ac3577f9..34124992 100644 --- a/skills/deploying-to-cloud/SKILL.md +++ b/skills/deploying-to-cloud/SKILL.md @@ -69,11 +69,11 @@ If a project-local installation is not available, install the CLI globally with Commands follow a CRUD pattern: `resource:list`, `resource:get`, `resource:create`, `resource:update`, `resource:delete`. -Available resources: `application`, `environment`, `instance`, `database-cluster`, `database`, `database-user`, `cache`, `bucket`, `domain`, `websocket-cluster`, `background-process`, `scheduled-command`, `secret`, `command`, `deployment`. +Available resources: `application`, `environment`, `instance`, `database-cluster`, `database`, `database-user`, `cache`, `bucket`, `domain`, `webhook-endpoint`, `websocket-cluster`, `background-process`, `scheduled-command`, `secret`, `command`, `deployment`. Some resources have additional commands (e.g., `domain:verify`, `database:open`, `instance:sizes`, `cache:types`, `database:types`, `:metrics`). Discover these via `cloud -h`. -`database-user:create` returns the new user's password once and never again. JSON output masks it unless you pass `--show-sensitive`, so pass it when the password is needed. +`database-user:create` returns the new user's password once and never again. JSON output masks it unless you pass `--show-sensitive`, so pass it when the password is needed. The same goes for the signing secret from `webhook-endpoint:create` and `webhook-endpoint:rotate-secret`. Never hardcode command signatures. Always run `cloud -h` to discover options at runtime. @@ -119,6 +119,8 @@ Determine the task and follow the matching path: - Apex (`example.com`): ask the user whether www redirects to the root (`www_to_root`) or the reverse (`root_to_www`). - Leave `--wildcard-enabled` off unless the user asks for wildcard subdomains. +- Deployment webhooks: `cloud webhook-endpoint:create {environment} --url=https://... --events=deployment.succeeded,deployment.failed --show-sensitive --json -n` returns the signing secret once; store it where the receiving app reads it. Check the endpoint with `cloud webhook-endpoint:test {endpoint} --json -n` (non-zero exit when the ping fails) and past attempts with `cloud webhook-endpoint:deliveries {endpoint} --json -n`. `webhook-endpoint:rotate-secret` stops the old secret working at once, so it needs `--force` with `-n`; confirm with the user first. + - Edge cache: `cloud environment:purge-edge-cache {environment} -n` purges everything; pass one of `--path=/blog/post`, `--prefix=/blog/`, or `--tag=` to purge less. Tags need a dedicated edge network. - Laravel Cloud domain: `cloud environment:vanity-domain {environment} --name= --deploy -n --force`. Pass only the first part of the domain. The new domain takes effect on the next deploy, which `--deploy` starts and monitors. It can change only once every 30 minutes, so confirm with the user first. diff --git a/tests/Feature/WebhookEndpointCommandsTest.php b/tests/Feature/WebhookEndpointCommandsTest.php new file mode 100644 index 00000000..b5c510bd --- /dev/null +++ b/tests/Feature/WebhookEndpointCommandsTest.php @@ -0,0 +1,512 @@ +mockConfig = Mockery::mock(ConfigRepository::class); + $this->mockConfig->shouldReceive('apiTokens')->andReturn(collect(['test-api-token'])); + $this->app->instance(ConfigRepository::class, $this->mockConfig); + + $this->mockGit = Mockery::mock(Git::class); + $this->mockGit->shouldReceive('remoteRepo')->andReturn('')->byDefault(); + $this->mockGit->shouldReceive('currentBranch')->andReturn('main')->byDefault(); + $this->app->instance(Git::class, $this->mockGit); + + $this->localConfig = Mockery::mock(LocalConfig::class); + $this->localConfig->shouldReceive('get')->with('organization_id')->andReturn(null)->byDefault(); + $this->localConfig->shouldReceive('applicationId')->andReturn(null)->byDefault(); + $this->localConfig->shouldReceive('environmentId')->andReturn(null)->byDefault(); + $this->localConfig->shouldReceive('path')->andReturn('/project/.cloud/config.json')->byDefault(); + $this->app->instance(LocalConfig::class, $this->localConfig); +}); + +afterEach(function () { + MockClient::destroyGlobal(); +}); + +/** + * @param list|null $endpoints + * @return stdClass Holds the body of the last create or update request, once one is sent. + */ +function setupWebhookEndpointMocks(?array $endpoints = null, array $delivery = []): stdClass +{ + $sent = new stdClass; + $sent->body = null; + + $endpoints ??= [webhookEndpointResponse()]; + $environment = createEnvironmentResponse(['attributes' => ['branch' => 'main']]); + + MockClient::global([ + GetOrganizationRequest::class => MockResponse::make(organizationResponse(), 200), + ListApplicationsRequest::class => MockResponse::make([ + 'data' => [createApplicationResponse()], + 'included' => [organizationResponse()['data'], $environment], + 'links' => ['next' => null], + ], 200), + ListEnvironmentsRequest::class => MockResponse::make(['data' => [$environment], 'links' => ['next' => null]], 200), + GetEnvironmentRequest::class => MockResponse::make(['data' => $environment], 200), + ListWebhookEndpointsRequest::class => MockResponse::make(['data' => $endpoints, 'links' => ['next' => null]], 200), + GetWebhookEndpointRequest::class => function (PendingRequest $request) use ($endpoints) { + $endpoint = collect($endpoints)->first(fn (array $endpoint) => str_ends_with($request->getUrl(), '/webhook-endpoints/'.$endpoint['id'])); + + return $endpoint + ? MockResponse::make(['data' => $endpoint], 200) + : MockResponse::make(['message' => 'Not found.'], 404); + }, + CreateWebhookEndpointRequest::class => function (PendingRequest $request) use ($sent) { + $sent->body = $request->body()->all(); + + return MockResponse::make(['data' => webhookEndpointResponse([ + 'id' => 'whe-new', + 'attributes' => [ + 'url' => $sent->body['url'], + 'events' => $sent->body['events'], + 'enabled' => $sent->body['enabled'] ?? true, + 'last_delivery_at' => null, + 'last_outcome' => null, + 'secret' => 'whsec_one-time-secret', + ], + ])], 201); + }, + UpdateWebhookEndpointRequest::class => function (PendingRequest $request) use ($sent) { + $sent->body = $request->body()->all(); + + return MockResponse::make(['data' => webhookEndpointResponse(['attributes' => $sent->body])], 200); + }, + DeleteWebhookEndpointRequest::class => MockResponse::make([], 204), + TestWebhookEndpointRequest::class => MockResponse::make(['data' => webhookDeliveryResponse(array_replace_recursive([ + 'attributes' => ['event' => 'ping', 'attempt' => 1], + ], $delivery))], 201), + ListWebhookDeliveriesRequest::class => MockResponse::make([ + 'data' => [ + webhookDeliveryResponse(['id' => 'whd-2', 'attributes' => ['outcome' => 'failed', 'response' => null, 'error' => 'Timed out', 'duration_ms' => null]]), + webhookDeliveryResponse(), + ], + 'links' => ['next' => null], + ], 200), + RotateWebhookEndpointSecretRequest::class => MockResponse::make(['data' => webhookEndpointResponse([ + 'attributes' => ['secret' => 'whsec_rotated-secret'], + ])], 200), + ]); + + return $sent; +} + +it('maps an endpoint and a delivery from the API', function () { + $endpoint = WebhookEndpoint::createFromResponse(['data' => webhookEndpointResponse(['attributes' => ['secret' => 'whsec_x']])]); + $delivery = WebhookDelivery::createFromResponse(['data' => webhookDeliveryResponse()]); + + expect($endpoint->id)->toBe('whe-1') + ->and($endpoint->url)->toBe('https://example.com/webhooks/cloud') + ->and($endpoint->events)->toBe(['deployment.succeeded', 'deployment.failed']) + ->and($endpoint->eventLabels())->toBe('Deployment succeeded, Deployment failed') + ->and($endpoint->enabled)->toBeTrue() + ->and($endpoint->lastOutcomeLabel())->toBe('Succeeded') + ->and($endpoint->secret)->toBe('whsec_x') + ->and($delivery->eventId)->toBe('evt-1') + ->and($delivery->statusCode())->toBe(200) + ->and($delivery->durationMs)->toBe(142) + ->and($delivery->failed())->toBeFalse(); +}); + +it('lists the endpoints of an environment', function () { + setupWebhookEndpointMocks(); + + Artisan::call('webhook-endpoint:list', ['environment' => 'env-1', '--json' => true]); + + $endpoints = json_decode(Artisan::output(), true); + + expect($endpoints)->toHaveCount(1) + ->and($endpoints[0])->toMatchArray([ + 'id' => 'whe-1', + 'url' => 'https://example.com/webhooks/cloud', + 'events' => ['deployment.succeeded', 'deployment.failed'], + 'enabled' => true, + 'lastOutcome' => 'succeeded', + 'secret' => null, + ]); + + MockClient::global()->assertSent(fn ($request) => $request instanceof ListWebhookEndpointsRequest + && $request->resolveEndpoint() === '/environments/env-1/webhook-endpoints'); +}); + +it('lists no endpoints', function () { + setupWebhookEndpointMocks([]); + + Artisan::call('webhook-endpoint:list', ['environment' => 'env-1', '--json' => true]); + + expect(json_decode(Artisan::output(), true))->toBe([]); +}); + +it('gets an endpoint by ID', function () { + setupWebhookEndpointMocks(); + + Artisan::call('webhook-endpoint:get', ['webhook-endpoint' => 'whe-1', '--json' => true]); + + expect(json_decode(Artisan::output(), true))->toMatchArray(['id' => 'whe-1', 'url' => 'https://example.com/webhooks/cloud']); + + MockClient::global()->assertSent(fn ($request) => $request instanceof GetWebhookEndpointRequest + && $request->resolveEndpoint() === '/webhook-endpoints/whe-1'); + MockClient::global()->assertNotSent(ListWebhookEndpointsRequest::class); +}); + +it('gets an endpoint by URL from the environment without trying it as an ID', function () { + setupWebhookEndpointMocks([ + webhookEndpointResponse(), + webhookEndpointResponse(['id' => 'whe-2', 'attributes' => ['url' => 'https://hooks.example.com/deploys']]), + ]); + + Artisan::call('webhook-endpoint:get', ['webhook-endpoint' => 'https://hooks.example.com/deploys', '--json' => true]); + + expect(json_decode(Artisan::output(), true))->toMatchArray(['id' => 'whe-2']); + + MockClient::global()->assertNotSent(GetWebhookEndpointRequest::class); + MockClient::global()->assertSent(fn ($request) => $request instanceof ListWebhookEndpointsRequest + && $request->resolveEndpoint() === '/environments/env-1/webhook-endpoints'); +}); + +it('fails when the identifier is neither an ID nor a URL in the environment', function () { + setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:get', ['webhook-endpoint' => 'whe-missing', '--json' => true])->assertFailed(); + + MockClient::global()->assertSent(GetWebhookEndpointRequest::class); + MockClient::global()->assertSent(ListWebhookEndpointsRequest::class); +}); + +it('reports an API failure instead of treating it as not found', function () { + setupWebhookEndpointMocks(); + + MockClient::global()->addResponse(MockResponse::make(['message' => 'Server error'], 500), GetWebhookEndpointRequest::class); + + expect(fn () => Artisan::call('webhook-endpoint:get', ['webhook-endpoint' => 'whe-1', '--json' => true])) + ->toThrow(InternalServerErrorException::class); + + MockClient::global()->assertNotSent(ListWebhookEndpointsRequest::class); +}); + +it('picks the only endpoint of the environment when none is given', function () { + setupWebhookEndpointMocks(); + + Artisan::call('webhook-endpoint:get', ['--json' => true]); + + expect(json_decode(Artisan::output(), true))->toMatchArray(['id' => 'whe-1']); +}); + +it('asks for an endpoint headlessly when the environment has several', function () { + setupWebhookEndpointMocks([ + webhookEndpointResponse(), + webhookEndpointResponse(['id' => 'whe-2', 'attributes' => ['url' => 'https://hooks.example.com/deploys']]), + ]); + + $this->artisan('webhook-endpoint:get', ['--json' => true])->assertFailed(); +}); + +it('creates an endpoint headlessly with repeated and comma-separated events', function () { + $sent = setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:create', [ + 'environment' => 'env-1', + '--url' => 'https://example.com/hooks', + '--events' => ['deployment.live,deployment.failed', 'deployment.post_deploy_failed'], + '--json' => true, + ])->assertSuccessful(); + + expect($sent->body)->toBe([ + 'url' => 'https://example.com/hooks', + 'events' => ['deployment.live', 'deployment.failed', 'deployment.post_deploy_failed'], + ]); + + MockClient::global()->assertSent(fn ($request) => $request instanceof CreateWebhookEndpointRequest + && $request->resolveEndpoint() === '/environments/env-1/webhook-endpoints'); +}); + +it('creates a disabled endpoint with --disabled', function () { + $sent = setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:create', [ + 'environment' => 'env-1', + '--url' => 'https://example.com/hooks', + '--events' => ['deployment.live'], + '--disabled' => true, + '--json' => true, + ])->assertSuccessful(); + + expect($sent->body)->toBe([ + 'url' => 'https://example.com/hooks', + 'events' => ['deployment.live'], + 'enabled' => false, + ]); +}); + +it('requires a URL and events when creating headlessly', function (array $options) { + setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:create', ['environment' => 'env-1', '--json' => true, ...$options])->assertFailed(); + + MockClient::global()->assertNotSent(CreateWebhookEndpointRequest::class); +})->with([ + 'no URL' => [['--events' => ['deployment.live']]], + 'no events' => [['--url' => 'https://example.com/hooks']], +]); + +it('fails headlessly when the API rejects the endpoint', function () { + setupWebhookEndpointMocks(); + + MockClient::global()->addResponse(MockResponse::make([ + 'message' => 'The url field must start with https://.', + 'errors' => ['url' => ['The url field must start with https://.']], + ], 422), CreateWebhookEndpointRequest::class); + + $this->artisan('webhook-endpoint:create', [ + 'environment' => 'env-1', + '--url' => 'http://example.com/hooks', + '--events' => ['deployment.live'], + '--json' => true, + ])->assertFailed(); +}); + +it('masks the signing secret in json by default', function () { + setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:create', [ + 'environment' => 'env-1', + '--url' => 'https://example.com/hooks', + '--events' => ['deployment.live'], + '--json' => true, + ]) + ->assertSuccessful() + ->doesntExpectOutputToContain('whsec_one-time-secret') + ->expectsOutputToContain('"secret":"*****"'); +}); + +it('reveals the signing secret in json with --show-sensitive', function () { + setupWebhookEndpointMocks(); + + Artisan::call('webhook-endpoint:create', [ + 'environment' => 'env-1', + '--url' => 'https://example.com/hooks', + '--events' => ['deployment.live'], + '--json' => true, + '--show-sensitive' => true, + ]); + + expect(json_decode(Artisan::output(), true))->toMatchArray([ + 'id' => 'whe-new', + 'secret' => 'whsec_one-time-secret', + ]); +}); + +it('creates an endpoint interactively and shows the signing secret to a person', function () { + Artisan::registerCommand(new InteractiveWebhookEndpointCreateCommand); + + $sent = setupWebhookEndpointMocks(); + + Prompt::fake([ + ...str_split('https://example.com/hooks'), + Key::ENTER, + // Events: tick "Deployment live" and "Deployment failed". + Key::SPACE, + Key::DOWN, + Key::DOWN, + Key::SPACE, + Key::ENTER, + ]); + + $suppressed = Renderer::$suppressOutput; + + try { + $this->artisan('test:interactive-webhook-endpoint-create', ['environment' => 'env-1']) + ->assertSuccessful() + ->expectsOutputToContain('whsec_one-time-secret') + ->expectsOutputToContain('It will not be shown again.'); + } finally { + Renderer::$suppressOutput = $suppressed; + } + + expect($sent->body)->toBe([ + 'url' => 'https://example.com/hooks', + 'events' => ['deployment.live', 'deployment.failed'], + ]); +}); + +it('updates only the fields that were passed', function (array $options, array $body) { + $sent = setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:update', [ + 'webhook-endpoint' => 'whe-1', + '--json' => true, + ...$options, + ])->assertSuccessful(); + + expect($sent->body)->toBe($body); + + MockClient::global()->assertSent(fn ($request) => $request instanceof UpdateWebhookEndpointRequest + && $request->resolveEndpoint() === '/webhook-endpoints/whe-1'); +})->with([ + 'url' => [['--url' => 'https://example.com/new'], ['url' => 'https://example.com/new']], + 'events' => [['--events' => ['deployment.live,deployment.succeeded']], ['events' => ['deployment.live', 'deployment.succeeded']]], + 'disabled' => [['--disabled' => true], ['enabled' => false]], + 'enabled' => [['--enabled' => true], ['enabled' => true]], +]); + +it('refuses --enabled together with --disabled', function () { + setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:update', [ + 'webhook-endpoint' => 'whe-1', + '--enabled' => true, + '--disabled' => true, + '--json' => true, + ])->assertFailed(); + + MockClient::global()->assertNotSent(UpdateWebhookEndpointRequest::class); +}); + +it('fails headlessly when there is nothing to update', function () { + setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:update', ['webhook-endpoint' => 'whe-1', '--json' => true])->assertFailed(); + + MockClient::global()->assertNotSent(UpdateWebhookEndpointRequest::class); +}); + +it('picks what to update interactively', function () { + Artisan::registerCommand(new InteractiveWebhookEndpointUpdateCommand); + + $sent = setupWebhookEndpointMocks(); + + Prompt::fake([ + // What to update: tick Enabled only. + Key::DOWN, + Key::DOWN, + Key::SPACE, + Key::ENTER, + // Send events to this endpoint? Move from yes to no. + Key::LEFT, + Key::ENTER, + ]); + + $this->artisan('test:interactive-webhook-endpoint-update', ['webhook-endpoint' => 'whe-1'])->assertSuccessful(); + + expect($sent->body)->toBe(['enabled' => false]); +}); + +it('requires --force to delete headlessly', function () { + setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:delete', ['webhook-endpoint' => 'whe-1', '--no-interaction' => true])->assertFailed(); + + MockClient::global()->assertNotSent(DeleteWebhookEndpointRequest::class); +}); + +it('deletes an endpoint', function () { + setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:delete', [ + 'webhook-endpoint' => 'whe-1', + '--force' => true, + '--no-interaction' => true, + ])->assertSuccessful(); + + MockClient::global()->assertSent(fn ($request) => $request instanceof DeleteWebhookEndpointRequest + && $request->resolveEndpoint() === '/webhook-endpoints/whe-1'); +}); + +it('sends a test delivery and returns it', function () { + setupWebhookEndpointMocks(); + + Artisan::call('webhook-endpoint:test', ['webhook-endpoint' => 'whe-1', '--json' => true]); + + expect(json_decode(Artisan::output(), true))->toMatchArray([ + 'id' => 'whd-1', + 'event' => 'ping', + 'outcome' => 'succeeded', + 'durationMs' => 142, + ]); + + MockClient::global()->assertSent(fn ($request) => $request instanceof TestWebhookEndpointRequest + && $request->resolveEndpoint() === '/webhook-endpoints/whe-1/test'); +}); + +it('exits non-zero but still returns the delivery when the test delivery fails', function (string $outcome) { + setupWebhookEndpointMocks(delivery: ['attributes' => ['outcome' => $outcome, 'response' => null, 'error' => 'Connection refused']]); + + $exitCode = Artisan::call('webhook-endpoint:test', ['webhook-endpoint' => 'whe-1', '--json' => true]); + + expect($exitCode)->toBe(1) + ->and(json_decode(Artisan::output(), true))->toMatchArray([ + 'outcome' => $outcome, + 'response' => null, + 'error' => 'Connection refused', + ]); +})->with(['failed', 'blocked']); + +it('lists deliveries with their requests and responses', function () { + setupWebhookEndpointMocks(); + + Artisan::call('webhook-endpoint:deliveries', ['webhook-endpoint' => 'whe-1', '--json' => true]); + + $deliveries = json_decode(Artisan::output(), true); + + expect($deliveries)->toHaveCount(2) + ->and($deliveries[0])->toMatchArray(['id' => 'whd-2', 'outcome' => 'failed', 'response' => null, 'error' => 'Timed out']) + ->and($deliveries[1]['request']['headers'])->toHaveKey('X-Cloud-Signature') + ->and($deliveries[1]['response'])->toMatchArray(['status_code' => 200, 'body' => 'OK']); + + MockClient::global()->assertSent(fn ($request) => $request instanceof ListWebhookDeliveriesRequest + && $request->resolveEndpoint() === '/webhook-endpoints/whe-1/deliveries'); +}); + +it('requires --force to rotate the secret headlessly', function () { + setupWebhookEndpointMocks(); + + $this->artisan('webhook-endpoint:rotate-secret', ['webhook-endpoint' => 'whe-1', '--json' => true])->assertFailed(); + + MockClient::global()->assertNotSent(RotateWebhookEndpointSecretRequest::class); +}); + +it('rotates the secret and masks it in json unless asked', function (bool $showSensitive, string $secret) { + setupWebhookEndpointMocks(); + + Artisan::call('webhook-endpoint:rotate-secret', [ + 'webhook-endpoint' => 'whe-1', + '--force' => true, + '--json' => true, + '--show-sensitive' => $showSensitive, + ]); + + expect(json_decode(Artisan::output(), true))->toMatchArray(['id' => 'whe-1', 'secret' => $secret]); + + MockClient::global()->assertSent(fn ($request) => $request instanceof RotateWebhookEndpointSecretRequest + && $request->resolveEndpoint() === '/webhook-endpoints/whe-1/secret'); +})->with([ + 'masked' => [false, '*****'], + 'revealed' => [true, 'whsec_rotated-secret'], +]); diff --git a/tests/Fixtures/InteractiveWebhookEndpointCreateCommand.php b/tests/Fixtures/InteractiveWebhookEndpointCreateCommand.php new file mode 100644 index 00000000..e1df5621 --- /dev/null +++ b/tests/Fixtures/InteractiveWebhookEndpointCreateCommand.php @@ -0,0 +1,36 @@ +signature = str_replace('webhook-endpoint:create', 'test:interactive-webhook-endpoint-create', $this->signature); + + parent::__construct(); + } + + protected function isInteractive(): bool + { + return true; + } + + protected function configurePrompts(InputInterface $input): void + { + // The test runner can look like an agent or CI, which hides the human output under test. + Renderer::$suppressOutput = false; + + parent::configurePrompts($input); + + Prompt::interactive(true); + } +} diff --git a/tests/Fixtures/InteractiveWebhookEndpointUpdateCommand.php b/tests/Fixtures/InteractiveWebhookEndpointUpdateCommand.php new file mode 100644 index 00000000..a775a310 --- /dev/null +++ b/tests/Fixtures/InteractiveWebhookEndpointUpdateCommand.php @@ -0,0 +1,36 @@ +signature = str_replace('webhook-endpoint:update', 'test:interactive-webhook-endpoint-update', $this->signature); + + parent::__construct(); + } + + protected function isInteractive(): bool + { + return true; + } + + protected function configurePrompts(InputInterface $input): void + { + // The test runner can look like an agent or CI, which hides the human output under test. + Renderer::$suppressOutput = false; + + parent::configurePrompts($input); + + Prompt::interactive(true); + } +} diff --git a/tests/Helpers.php b/tests/Helpers.php index 3d93c7ed..98058c7e 100644 --- a/tests/Helpers.php +++ b/tests/Helpers.php @@ -773,3 +773,46 @@ function updatableInstanceResponse(array $attributes = []): array 'relationships' => ['environment' => ['data' => ['id' => 'env-1', 'type' => 'environments']]], ], 'included' => [createEnvironmentResponse()]]; } + +function webhookEndpointResponse(array $overrides = []): array +{ + return [ + 'id' => $overrides['id'] ?? 'whe-1', + 'type' => 'webhook_endpoints', + 'attributes' => array_merge([ + 'url' => 'https://example.com/webhooks/cloud', + 'events' => ['deployment.succeeded', 'deployment.failed'], + 'enabled' => true, + 'last_delivery_at' => '2026-01-02T00:00:00.000000Z', + 'last_outcome' => 'succeeded', + 'created_at' => '2026-01-01T00:00:00.000000Z', + ], $overrides['attributes'] ?? []), + ]; +} + +function webhookDeliveryResponse(array $overrides = []): array +{ + return [ + 'id' => $overrides['id'] ?? 'whd-1', + 'type' => 'webhook_deliveries', + 'attributes' => array_merge([ + 'event_id' => 'evt-1', + 'event' => 'deployment.succeeded', + 'attempt' => 1, + 'outcome' => 'succeeded', + 'request' => [ + 'url' => 'https://example.com/webhooks/cloud', + 'headers' => ['X-Cloud-Event' => 'deployment.succeeded', 'X-Cloud-Signature' => 'sha256=abc'], + 'body' => '{"event":"deployment.succeeded"}', + ], + 'response' => [ + 'status_code' => 200, + 'headers' => ['Content-Type' => 'text/plain'], + 'body' => 'OK', + ], + 'error' => null, + 'duration_ms' => 142, + 'created_at' => '2026-01-02T00:00:00.000000Z', + ], $overrides['attributes'] ?? []), + ]; +}