diff --git a/app/Client/Resources/EnvironmentsResource.php b/app/Client/Resources/EnvironmentsResource.php index e814f9d3..b41dc6f4 100644 --- a/app/Client/Resources/EnvironmentsResource.php +++ b/app/Client/Resources/EnvironmentsResource.php @@ -172,6 +172,7 @@ public function withDefaultIncludes(): static 'database', 'cache', 'websocketApplication', + 'buckets', ); } } diff --git a/app/Commands/EnvironmentUpdate.php b/app/Commands/EnvironmentUpdate.php index cc2758da..bd5b6d80 100644 --- a/app/Commands/EnvironmentUpdate.php +++ b/app/Commands/EnvironmentUpdate.php @@ -3,9 +3,11 @@ namespace App\Commands; use App\Client\Requests\UpdateEnvironmentRequestData; +use App\Dto\BucketKey; use App\Dto\Cache; use App\Dto\Database; use App\Dto\Environment; +use App\Dto\ObjectStorageBucket; use App\Dto\WebsocketApplication; use App\Dto\WebsocketCluster; use App\Enums\EnvironmentColor; @@ -61,6 +63,7 @@ class EnvironmentUpdate extends BaseCommand {--database-id= : Database ID to attach (empty string to detach)} {--cache-id= : Cache ID to attach (empty string to detach)} {--websocket-application-id= : WebSocket application ID to attach (empty string to detach)} + {--bucket-keys= : Bucket keys to attach as comma-separated KEY_ID:DISK entries, with :default on at most one (fk-1:local:default,fk-2:public). Replaces every attached bucket; empty string to detach all} {--force : Force update without confirmation}'; protected $description = 'Update an environment'; @@ -97,6 +100,8 @@ public function handle() protected function updateEnvironment(Environment $environment): Environment { + $filesystemKeys = $this->filesystemKeys($environment); + // The API turns basic auth on only alongside a password, so one option covers both: a password turns it on, empty turns it off. $httpBasicAuthPassword = $this->form()->get('http_basic_auth_password'); @@ -134,6 +139,7 @@ protected function updateEnvironment(Environment $environment): Environment responseHeadersHsts: $this->hsts($environment), firewallBlockPath: $this->form()->boolean('firewall_block_path'), firewallBrowserIntegrityCheck: $this->form()->boolean('firewall_browser_integrity_check'), + filesystemKeys: $filesystemKeys, usesHttpBasicAuth: $httpBasicAuthPassword === null ? null : filled($httpBasicAuthPassword), httpBasicAuthPassword: filled($httpBasicAuthPassword) ? $httpBasicAuthPassword : null, ), @@ -144,6 +150,56 @@ protected function updateEnvironment(Environment $environment): Environment return $this->client->environments()->get($environment->id); } + /** + * The API takes the attached buckets as one list and replaces it, so the option names every bucket the environment should end up with. + * + * @return array|null + */ + protected function filesystemKeys(Environment $environment): ?array + { + $value = $this->form()->get('filesystem_keys'); + + if ($value === null) { + return null; + } + + $keys = $this->parseBucketKeys($value); + + if ($environment->bucketIds !== []) { + $this->confirmDestructive($keys === [] + ? "Detach every bucket from {$environment->name}?" + : "Replace the buckets attached to {$environment->name}? Any attached bucket not listed will be detached."); + } + + return $keys; + } + + /** + * @return array + */ + protected function parseBucketKeys(string $value): array + { + if (trim($value) === '') { + return []; + } + + $keys = collect(explode(',', $value))->map(function (string $entry) { + $parts = array_map(trim(...), explode(':', $entry)); + + if (count($parts) < 2 || count($parts) > 3 || $parts[0] === '' || $parts[1] === '' || (isset($parts[2]) && $parts[2] !== 'default')) { + $this->failAndExit("Invalid bucket key entry: {$entry}. Use KEY_ID:DISK, or KEY_ID:DISK:default for the default disk."); + } + + return ['id' => $parts[0], 'disk' => $parts[1], 'is_default_disk' => isset($parts[2])]; + }); + + if ($keys->where('is_default_disk', true)->count() > 1) { + $this->failAndExit('Only one bucket can be the default disk.'); + } + + return $keys->values()->all(); + } + protected function clearableInteger(string $key): int|string|null { $value = $this->form()->get($key); @@ -376,6 +432,15 @@ protected function defineFields(Environment $environment): void ), 'websocket-application-id', )->setPreviousValue($environment->websocketApplicationId ?? ''); + + // Named after the API field so a validation error on filesystem_keys.* asks for the buckets again. + $this->form()->define( + 'filesystem_keys', + fn ($resolver) => $resolver->fromInput( + fn ($value) => $this->selectBucketKeys(), + ), + 'bucket-keys', + )->setLabel('Buckets'); } /** @@ -562,6 +627,65 @@ protected function selectWebsocketApplication(?string $value, ?string $currentId ); } + protected function selectBucketKeys(): string + { + $buckets = spin( + fn () => $this->client->objectStorageBuckets()->list()->collect(), + 'Fetching buckets...', + ); + + if ($buckets->isEmpty()) { + $this->failAndExit('No buckets found. Create one with `cloud bucket:create`.'); + } + + $entries = []; + $hasDefault = false; + + do { + $bucketId = (string) select( + label: $entries === [] ? 'Bucket' : 'Another bucket', + options: ($entries === [] ? ['' => '— Detach all —'] : []) + $buckets->mapWithKeys( + fn (ObjectStorageBucket $bucket) => [$bucket->id => $bucket->name], + )->all(), + ); + + if ($bucketId === '') { + return ''; + } + + $keys = spin( + fn () => $this->client->bucketKeys()->list($bucketId)->collect(), + 'Fetching bucket keys...', + ); + + if ($keys->isEmpty()) { + $this->failAndExit('That bucket has no keys. Create one with `cloud bucket-key:create`.'); + } + + $keyId = (string) select( + label: 'Bucket key', + options: $keys->mapWithKeys(fn (BucketKey $key) => [$key->id => "{$key->name} ({$key->permission})"])->all(), + ); + + // The API's own rule, which also keeps out the ':' and ',' the entries are joined with. + $disk = text( + label: 'Disk name', + placeholder: 'public', + required: true, + validate: fn (string $name) => preg_match('/^[A-Za-z0-9 _-]{1,40}$/', $name) + ? null + : 'Use up to 40 letters, numbers, spaces, dashes, or underscores.', + ); + + $isDefault = ! $hasDefault && confirm(label: 'Make it the default disk?', default: false); + $hasDefault = $hasDefault || $isDefault; + + $entries[] = $isDefault ? "{$keyId}:{$disk}:default" : "{$keyId}:{$disk}"; + } while (confirm(label: 'Attach another bucket?', default: false)); + + return implode(',', $entries); + } + protected function collectDataAndUpdate(Environment $environment): Environment { $selection = multiselect( diff --git a/app/Dto/Environment.php b/app/Dto/Environment.php index eb26616b..fa4ee0b3 100644 --- a/app/Dto/Environment.php +++ b/app/Dto/Environment.php @@ -51,6 +51,8 @@ public function __construct( public readonly ?string $databaseSchemaId = null, public readonly ?string $cacheId = null, public readonly ?string $websocketApplicationId = null, + /** IDs of the attached buckets. The API does not say which key or disk each one uses. */ + public readonly array $bucketIds = [], #[DataCollectionOf(Secret::class)] public readonly array $secrets = [], public readonly ?EnvironmentResend $resend = null, @@ -161,6 +163,10 @@ public static function createFromResponse(array $response): self $transformed['websocketApplicationId'] = $relationships['websocketApplication']['data']['id']; } + if (isset($relationships['buckets']['data'])) { + $transformed['bucketIds'] = array_column($relationships['buckets']['data'], 'id'); + } + if (isset($relationships['secrets']['data'])) { $secretIds = array_column($relationships['secrets']['data'], 'id'); diff --git a/skills/deploying-to-cloud/SKILL.md b/skills/deploying-to-cloud/SKILL.md index e62d7b8f..ac3577f9 100644 --- a/skills/deploying-to-cloud/SKILL.md +++ b/skills/deploying-to-cloud/SKILL.md @@ -106,6 +106,8 @@ Determine the task and follow the matching path: - Secrets: `echo "$VALUE" | cloud secret:create --name=NAME --json -n`, then `cloud environment-secret:attach` +- Buckets: `cloud environment:update {environment} --bucket-keys=KEY_ID:DISK:default,KEY_ID:public --json -n --force` attaches bucket keys, read from `cloud bucket-key:list {bucket} --json -n`. It replaces every attached bucket, so list all of them; `--force` is needed when buckets are already attached + - Provision infrastructure: `cloud :create --json -n` - Brand new project (no code yet): `cloud new --starter-kit= --repository=/ --path= -n` creates a private GitHub repository from the starter kit, deploys it (with a database for Laravel kits), and clones it to ``. The repository must not exist yet. Run `cloud new -h` for the kits. diff --git a/skills/deploying-to-cloud/reference/checklists.md b/skills/deploying-to-cloud/reference/checklists.md index 5ddc94c2..f9fd9c3b 100644 --- a/skills/deploying-to-cloud/reference/checklists.md +++ b/skills/deploying-to-cloud/reference/checklists.md @@ -9,6 +9,7 @@ Use these checklists when performing complex setups. Copy the relevant checklist - [ ] Create the environment - [ ] Provision the database (`database-cluster:create` then `database:create`) - [ ] Provision the cache (`cache:create`) +- [ ] Create and attach any buckets (`bucket:create`, then `environment:update --bucket-keys`) - [ ] Set environment variables (`environment:variables`) - [ ] Create and attach any secrets (`secret:create` then `environment-secret:attach`) - [ ] Attach custom domain (`domain:create` then `domain:verify`) diff --git a/tests/Feature/EnvironmentRelationshipsTest.php b/tests/Feature/EnvironmentRelationshipsTest.php index 10ee19e5..f6674f08 100644 --- a/tests/Feature/EnvironmentRelationshipsTest.php +++ b/tests/Feature/EnvironmentRelationshipsTest.php @@ -1,14 +1,20 @@ mockGit = Mockery::mock(Git::class); @@ -30,7 +36,7 @@ * The API returns a relationship only when the request asked to include it, so * the fake has to drop anything the caller did not request. */ -function attachedEnvironmentResponse(?string $include): array +function attachedEnvironmentResponse(?string $include, array $bucketIds = []): array { $requested = explode(',', $include ?? ''); @@ -39,6 +45,7 @@ function attachedEnvironmentResponse(?string $include): array 'database' => ['data' => ['id' => '65634813', 'type' => 'databaseSchemas']], 'cache' => ['data' => null], 'websocketApplication' => ['data' => null], + 'buckets' => ['data' => array_map(fn (string $id) => ['id' => $id, 'type' => 'filesystems'], $bucketIds)], ], fn ($key) => in_array($key, $requested, true), ARRAY_FILTER_USE_KEY); return [ @@ -120,3 +127,186 @@ function captureEnvironmentIncludes(): Closure expect($sentDatabaseSchemaId->value)->toBe('65634813'); }); + +it('reads the attached bucket ids from the environment relationships', function () { + MockClient::global([ + GetOrganizationRequest::class => MockResponse::make(organizationResponse(), 200), + GetApplicationRequest::class => MockResponse::make(['data' => createApplicationResponse()], 200), + GetEnvironmentRequest::class => fn (PendingRequest $request) => MockResponse::make( + attachedEnvironmentResponse($request->query()->get('include'), ['fs-1']), + 200, + ), + ]); + + $this->artisan('environment:get', [ + 'environment' => 'env-1', + '--json' => true, + '--fields' => 'bucketIds', + '--no-interaction' => true, + ])->assertSuccessful() + ->expectsOutputToContain('"bucketIds":["fs-1"]'); +}); + +/** + * @return stdClass whose `body` holds the update request body, or stays unset when no update was sent + */ +function captureBucketUpdate(array $attachedBucketIds): stdClass +{ + $sent = new stdClass; + + MockClient::global([ + GetOrganizationRequest::class => MockResponse::make(organizationResponse(), 200), + GetApplicationRequest::class => MockResponse::make(['data' => createApplicationResponse()], 200), + GetEnvironmentRequest::class => fn (PendingRequest $request) => MockResponse::make( + attachedEnvironmentResponse($request->query()->get('include'), $attachedBucketIds), + 200, + ), + UpdateEnvironmentRequest::class => function (PendingRequest $request) use ($sent) { + $sent->body = $request->body()->all(); + + return MockResponse::make(attachedEnvironmentResponse(null), 200); + }, + ]); + + return $sent; +} + +it('attaches several bucket keys with their disks', function () { + $sent = captureBucketUpdate([]); + + $this->artisan('environment:update', [ + 'environment' => 'env-1', + '--bucket-keys' => 'fk-1:local:default,fk-2:public', + '--json' => true, + '--no-interaction' => true, + ])->assertSuccessful(); + + expect($sent->body['filesystem_keys'])->toBe([ + ['id' => 'fk-1', 'disk' => 'local', 'is_default_disk' => true], + ['id' => 'fk-2', 'disk' => 'public', 'is_default_disk' => false], + ]); +}); + +it('refuses to replace attached buckets without --force', function () { + $sent = captureBucketUpdate(['fs-existing']); + + $this->artisan('environment:update', [ + 'environment' => 'env-1', + '--bucket-keys' => 'fk-1:local', + '--json' => true, + '--no-interaction' => true, + ])->assertFailed(); + + expect(isset($sent->body))->toBeFalse(); +}); + +it('replaces attached buckets with --force', function () { + $sent = captureBucketUpdate(['fs-existing']); + + $this->artisan('environment:update', [ + 'environment' => 'env-1', + '--bucket-keys' => 'fk-1:local', + '--force' => true, + '--json' => true, + '--no-interaction' => true, + ])->assertSuccessful(); + + expect($sent->body['filesystem_keys'])->toBe([['id' => 'fk-1', 'disk' => 'local', 'is_default_disk' => false]]); +}); + +it('detaches every bucket when given an empty list', function () { + $sent = captureBucketUpdate(['fs-existing']); + + $this->artisan('environment:update', [ + 'environment' => 'env-1', + '--bucket-keys' => '', + '--force' => true, + '--json' => true, + '--no-interaction' => true, + ])->assertSuccessful(); + + expect($sent->body)->toHaveKey('filesystem_keys') + ->and($sent->body['filesystem_keys'])->toBe([]); +}); + +it('rejects bucket key entries without a disk or with two default disks', function (string $value) { + $sent = captureBucketUpdate([]); + + $this->artisan('environment:update', [ + 'environment' => 'env-1', + '--bucket-keys' => $value, + '--json' => true, + '--no-interaction' => true, + ])->assertFailed(); + + expect(isset($sent->body))->toBeFalse(); +})->with([ + 'missing disk' => 'fk-1', + 'unknown suffix' => 'fk-1:local:primary', + 'two defaults' => 'fk-1:local:default,fk-2:public:default', +]); + +it('asks for the buckets again when the API rejects an attached bucket', function () { + $bodies = []; + + MockClient::global([ + GetOrganizationRequest::class => MockResponse::make(organizationResponse(), 200), + GetApplicationRequest::class => MockResponse::make(['data' => createApplicationResponse()], 200), + GetEnvironmentRequest::class => fn (PendingRequest $request) => MockResponse::make( + attachedEnvironmentResponse($request->query()->get('include')), + 200, + ), + ListObjectStorageBucketsRequest::class => MockResponse::make(['data' => [bucketResponse()], 'links' => ['next' => null]], 200), + ListBucketKeysRequest::class => MockResponse::make(['data' => [bucketKeyResponse()], 'links' => ['next' => null]], 200), + UpdateEnvironmentRequest::class => function (PendingRequest $request) use (&$bodies) { + $bodies[] = $request->body()->all(); + + return count($bodies) === 1 + ? MockResponse::make(['message' => 'Invalid.', 'errors' => ['filesystem_keys.0.disk' => ['The disk has already been taken.']]], 422) + : MockResponse::make(attachedEnvironmentResponse(null), 200); + }, + ]); + + Artisan::registerCommand(new InteractiveEnvironmentUpdateCommand); + + Prompt::fake([ + // Choose Buckets, the last field. + Key::UP, Key::SPACE, Key::ENTER, + // The bucket, its only key, a disk name the API rejects, not the default, no more buckets. + Key::DOWN, Key::ENTER, Key::ENTER, 't', 'a', 'k', 'e', 'n', Key::ENTER, Key::ENTER, Key::ENTER, + // Asked for the buckets again. + Key::DOWN, Key::ENTER, Key::ENTER, 'f', 'i', 'l', 'e', 's', Key::ENTER, Key::ENTER, Key::ENTER, + ]); + + $this->artisan('test:interactive-environment-update', ['environment' => 'env-1'])->assertSuccessful(); + + expect($bodies)->toHaveCount(2) + ->and($bodies[0]['filesystem_keys'])->toBe([['id' => 'flsk-1', 'disk' => 'taken', 'is_default_disk' => false]]) + ->and($bodies[1]['filesystem_keys'])->toBe([['id' => 'flsk-1', 'disk' => 'files', 'is_default_disk' => false]]); +}); + +it('refuses a disk name the bucket list cannot carry when choosing buckets interactively', function () { + $sent = captureBucketUpdate([]); + + MockClient::global()->addResponses([ + ListObjectStorageBucketsRequest::class => MockResponse::make(['data' => [bucketResponse()], 'links' => ['next' => null]], 200), + ListBucketKeysRequest::class => MockResponse::make(['data' => [bucketKeyResponse()], 'links' => ['next' => null]], 200), + ]); + + Artisan::registerCommand(new InteractiveEnvironmentUpdateCommand); + + Prompt::fake([ + // Choose Buckets, the last field, then the bucket and its only key. + Key::UP, Key::SPACE, Key::ENTER, + Key::DOWN, Key::ENTER, Key::ENTER, + // A colon would read back as the default-disk marker, so the prompt refuses it. + 'l', 'o', 'c', 'a', 'l', ':', 'd', 'e', 'f', 'a', 'u', 'l', 't', Key::ENTER, + Key::BACKSPACE, Key::BACKSPACE, Key::BACKSPACE, Key::BACKSPACE, Key::BACKSPACE, Key::BACKSPACE, Key::BACKSPACE, Key::BACKSPACE, Key::ENTER, + // Not the default disk, no more buckets. + Key::ENTER, Key::ENTER, + ]); + + $this->artisan('test:interactive-environment-update', ['environment' => 'env-1'])->assertSuccessful(); + + expect($sent->body['filesystem_keys'])->toBe([['id' => 'flsk-1', 'disk' => 'local', 'is_default_disk' => false]]); +});