From b5faee58444499a2bf8bbcd1ae34f9c32a41b7a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 11:56:00 +0000 Subject: [PATCH 1/4] feat(secrets): add launch:secrets:list and the secrets resource foundation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the secrets resource (SecretsApi over the REST secrets endpoint, error wording, presenter) wired through resources.ts, and a list command that prints KEY and UPDATED and never a value. #claude_code# šŸ¤– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EptZEi8nvDRpqxwsFu2SSa --- .talismanrc | 21 +++- README.md | 25 ++++ package.json | 4 + src/commands/launch/secrets/list.test.ts | 101 ++++++++++++++++ src/commands/launch/secrets/list.ts | 30 +++++ src/resources.test.ts | 3 + src/resources.ts | 3 + src/secrets/secrets.api.test.ts | 116 +++++++++++++++++++ src/secrets/secrets.api.ts | 44 +++++++ src/secrets/secrets.errors.ts | 19 ++++ src/secrets/secrets.presenter.test.ts | 27 +++++ src/secrets/secrets.presenter.ts | 14 +++ src/secrets/types.ts | 10 ++ test/guards/layering.test.ts | 1 + test/integration/secrets-list.test.ts | 139 +++++++++++++++++++++++ 15 files changed, 556 insertions(+), 1 deletion(-) create mode 100644 src/commands/launch/secrets/list.test.ts create mode 100644 src/commands/launch/secrets/list.ts create mode 100644 src/secrets/secrets.api.test.ts create mode 100644 src/secrets/secrets.api.ts create mode 100644 src/secrets/secrets.errors.ts create mode 100644 src/secrets/secrets.presenter.test.ts create mode 100644 src/secrets/secrets.presenter.ts create mode 100644 src/secrets/types.ts create mode 100644 test/integration/secrets-list.test.ts diff --git a/.talismanrc b/.talismanrc index c9fd18d3..3b1f0204 100644 --- a/.talismanrc +++ b/.talismanrc @@ -225,6 +225,7 @@ fileignoreconfig: allowed_patterns: - "FlagKey" - filename: src/resources.ts + checksum: 491bcb5d0bcb24ff6f7146d51941e5f364010e7f638e441b603604af53b6d55d allowed_patterns: - "FlagKey" - filename: src/resources.test.ts @@ -329,7 +330,7 @@ fileignoreconfig: - filename: src/commands/launch/env/update.test.ts checksum: 2da219594e7bdd589adc0eff9ff035252a75aaa51dfa20514b18fd3266d7b752 - filename: README.md - checksum: 8f1e4d97fa7e97a4c6a3bdb6bbf3d0f4d3735c3dfc23579a4d0a7c6d725bc8e4 + checksum: feece1f1f5a29902e0fc08fc0b294b1128c42fc46ab5ea37efbdde2e162a4eb7 allowed_patterns: - "password-protection" - "-p, --password" @@ -464,4 +465,22 @@ fileignoreconfig: checksum: d811a8b35d640708a9d0e7b03d006fcae4718192adee94c47f625ce7662ea715 - filename: src/deployments/commit.prompt.ts checksum: 6991eb373ee016ce44fc4f47044d559cfeefa1c411526d6fd88d77c568379041 +- filename: test/integration/secrets-list.test.ts + checksum: dd9bea8e47b53feeda24a6d328947dfc3d11f79ef5a5c78bb1b3245761cebb13 +- filename: src/secrets/secrets.api.ts + checksum: b490601876ce1d2fe28b91536c335f8a8b4713e784b718d4b9731739a907531a +- filename: src/secrets/secrets.presenter.ts + checksum: f395458a0858a7ad01831013f0327a20bfa3a7e0c239d0725141c6e5a8f29a10 +- filename: package.json + checksum: b025f6d4b75a67695b939e625ef06edfc5f32014a1d802e14c19705188b383ba +- filename: src/commands/launch/secrets/list.ts + checksum: 000fec691dd7d82e3f957f4ec4a2b85e59cf59726280c39f4fde43241371cefa +- filename: src/commands/launch/secrets/list.test.ts + checksum: 61ed1b9851aaeeea325cd06d81cef11d17435c87653d73f49f7c2794dbeda1da +- filename: src/secrets/secrets.api.test.ts + checksum: c729f4ce0fad75bdc6a88019019ecd1bf3c50d2eddd3f1f9c331faaf25af07a8 +- filename: src/secrets/secrets.errors.ts + checksum: fa39fbaa0434045a9eb3b5bbbffa0960eab7655a7184f23558c51ff68238b1ca +- filename: src/secrets/secrets.presenter.test.ts + checksum: 4b1e940cc470c3aa9c4e060944f7737dd212eef5da36f982a4cdd64230537164 version: "1.0" diff --git a/README.md b/README.md index bb845f8b..91012800 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ with exit code 2 and name their V2 replacements. `launch:functions:serve` is liv * [`csdx launch:projects:list`](#csdx-launchprojectslist) * [`csdx launch:projects:update`](#csdx-launchprojectsupdate) * [`csdx launch:rollback`](#csdx-launchrollback) +* [`csdx launch:secrets:list`](#csdx-launchsecretslist) * [`csdx launch:site:open`](#csdx-launchsiteopen) * [`csdx launch:variables:list`](#csdx-launchvariableslist) * [`csdx launch:variables:set`](#csdx-launchvariablesset) @@ -764,6 +765,30 @@ DESCRIPTION _See code: [src/commands/launch/rollback.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/rollback.ts)_ +## `csdx launch:secrets:list` + +List the secrets of an environment, with their keys and update times and never their values + +``` +USAGE + $ csdx launch:secrets:list [-c ] [-d ] [--org ] [--project ] [--env ] + +FLAGS + -c, --config= Path to the local '.cs-launch.json' file + -d, --data-dir= Current working directory + --env= Environment name or UID + --org= Organization UID + --project= Project name or UID + +DESCRIPTION + List the secrets of an environment, with their keys and update times and never their values + +EXAMPLES + $ csdx launch:secrets:list --org --project --env +``` + +_See code: [src/commands/launch/secrets/list.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/secrets/list.ts)_ + ## `csdx launch:site:open` Open an environment's live site in your browser, or print its URL when there is no terminal. On a terminal, when the environment has more than one domain, you choose which one to open; --deployment opens that deployment's preview URL without asking. diff --git a/package.json b/package.json index 196d6b27..b44d2d5c 100644 --- a/package.json +++ b/package.json @@ -85,6 +85,9 @@ "launch:logs": { "description": "Read Launch deployment, server and live logs" }, + "launch:secrets": { + "description": "List, set and remove the secrets of a Launch environment" + }, "launch:variables": { "description": "List, set and remove the environment variables of a Launch environment" }, @@ -183,6 +186,7 @@ "launch:projects:list": "LNCH-PRJ-LS", "launch:projects:update": "LNCH-PRJ-UPD", "launch:rollback": "LNCH-RLBK", + "launch:secrets:list": "LNCH-SEC-LS", "launch:site:open": "LNCH-SITE-OPN", "launch:variables:list": "LNCH-VAR-LS", "launch:variables:set": "LNCH-VAR-SET", diff --git a/src/commands/launch/secrets/list.test.ts b/src/commands/launch/secrets/list.test.ts new file mode 100644 index 00000000..3d68949e --- /dev/null +++ b/src/commands/launch/secrets/list.test.ts @@ -0,0 +1,101 @@ +import { randomUUID } from 'node:crypto'; + +import type { UxLike } from '../../../core/prompt'; +import SecretsList from './list'; + +const RESOLVED = { org: 'org1', project: 'proj1', env: 'env1' }; + +function commandUnderTest( + secrets: unknown, + answer: () => Promise = async () => secrets, +) { + const lines: string[] = []; + const ux: UxLike = { + print: (message: string) => { + lines.push(message); + }, + inquire: async () => undefined as never, + }; + const fetched: unknown[] = []; + const command = Object.create(SecretsList.prototype) as SecretsList; + + Object.assign(command, { + ux, + resolved: RESOLVED, + services: { + ux, + outputIsTTY: false, + api: { + secrets: { + list: async (params: unknown) => { + fetched.push(params); + return answer(); + }, + }, + }, + }, + }); + + return { command, lines, fetched }; +} + +describe('launch:secrets:list', () => { + it('lists each secret with its key and update time under KEY and UPDATED and nothing else', async () => { + const { command, lines, fetched } = commandUnderTest([ + { key: 'API_TOKEN', updatedAt: '2026-09-01' }, + { key: 'DB_URL', updatedAt: '2026-09-02' }, + ]); + + await command.run(); + + expect(fetched).toEqual([{ org: 'org1', project: 'proj1', environment: 'env1' }]); + expect(lines[1]).toBe('│ KEY │ UPDATED │'); + expect(lines[3]).toBe('│ API_TOKEN │ 2026-09-01 │'); + expect(lines[5]).toBe('│ DB_URL │ 2026-09-02 │'); + expect(lines).toHaveLength(7); + expect(lines.join('\n')).not.toMatch(/VALUE/i); + }); + + it('prints a value that the repository handed back in no table row', async () => { + const value = randomUUID(); + const { command, lines } = commandUnderTest([{ key: 'API_TOKEN', updatedAt: '2026-09-01', value }]); + + await command.run(); + + expect(lines.join('\n')).toContain('API_TOKEN'); + expect(lines.join('\n')).not.toContain(value); + }); + + it('prints only the empty-table placeholder for an environment with no secrets', async () => { + const { command, lines } = commandUnderTest([]); + + await command.run(); + + expect(lines).toEqual(['No records found.']); + }); + + it('renders a placeholder for a secret that carries no key or update time', async () => { + const { command, lines } = commandUnderTest([{}]); + + await command.run(); + + expect(lines[3]).toBe('│ - │ - │'); + }); + + it('propagates a failed secrets request', async () => { + const failure = new Error('list failed'); + const { command, lines } = commandUnderTest(undefined, async () => Promise.reject(failure)); + + await expect(command.run()).rejects.toBe(failure); + expect(lines).toEqual([]); + }); + + it('declares org, project and env as required and no other flag', () => { + expect(SecretsList.inputs).toEqual({ + org: { required: true }, + project: { required: true }, + env: { required: true }, + }); + expect(Object.keys(SecretsList.flags).sort()).toEqual(['env', 'org', 'project']); + }); +}); diff --git a/src/commands/launch/secrets/list.ts b/src/commands/launch/secrets/list.ts new file mode 100644 index 00000000..a2b5a039 --- /dev/null +++ b/src/commands/launch/secrets/list.ts @@ -0,0 +1,30 @@ +import { LaunchCommand } from '../../../core/launch-command'; +import { flagsFor, inputs } from '../../../core/inputs'; +import { renderTable } from '../../../core/render'; +import { secretColumns } from '../../../secrets/secrets.presenter'; + +const listInputs = inputs({ + org: { required: true }, + project: { required: true }, + env: { required: true }, +}); + +export default class SecretsList extends LaunchCommand { + static description = 'List the secrets of an environment, with their keys and update times and never their values'; + + static examples = ['$ csdx launch:secrets:list --org --project --env ']; + + static inputs = listInputs; + + static flags = flagsFor(listInputs); + + async run(): Promise { + const secrets = await this.services.api.secrets.list({ + org: this.resolved.org, + project: this.resolved.project, + environment: this.resolved.env, + }); + + renderTable(this.ux, secretColumns(), secrets, process.stdout.columns, undefined, this.services.outputIsTTY); + } +} diff --git a/src/resources.test.ts b/src/resources.test.ts index 68f9de40..41fe6a22 100644 --- a/src/resources.test.ts +++ b/src/resources.test.ts @@ -7,6 +7,7 @@ import { ServerLogsApi } from './logs/server-logs.api'; import { EnvironmentsApi } from './environments/environments.api'; import { UploadsApi } from './uploads/uploads.api'; import { CacheApi } from './cache/cache.api'; +import { SecretsApi } from './secrets/secrets.api'; import { GitApi } from './git/git.api'; import { ProjectsApi } from './projects/projects.api'; import type { UxLike } from './core/prompt'; @@ -202,6 +203,7 @@ describe('the api surface', () => { 'liveLogs', 'organizations', 'projects', + 'secrets', 'serverLogs', 'stacks', 'uploads', @@ -217,6 +219,7 @@ describe('the api surface', () => { expect(api.git).toBeInstanceOf(GitApi); expect(api.uploads).toBeInstanceOf(UploadsApi); expect(api.cache).toBeInstanceOf(CacheApi); + expect(api.secrets).toBeInstanceOf(SecretsApi); }); it('sends deployment and server log reads through the logs client and nothing else through it', async () => { diff --git a/src/resources.ts b/src/resources.ts index 51ce079c..f6f71c15 100644 --- a/src/resources.ts +++ b/src/resources.ts @@ -22,6 +22,7 @@ import { OrganizationsApi } from './organizations/organizations.api'; import { UploadsApi } from './uploads/uploads.api'; import { StacksApi } from './stacks/stacks.api'; import { VariablesApi } from './variables/variables.api'; +import { SecretsApi } from './secrets/secrets.api'; import { CacheApi } from './cache/cache.api'; import type { CmaSession } from './transport/cma-client'; import type { EventStreamClient } from './transport/event-stream'; @@ -78,6 +79,7 @@ export interface ApiSurface { uploads: UploadsApi; stacks: StacksApi; variables: VariablesApi; + secrets: SecretsApi; cache: CacheApi; } @@ -99,6 +101,7 @@ export function buildApi( uploads: new UploadsApi(client), stacks: new StacksApi(cma), variables: new VariablesApi(client), + secrets: new SecretsApi(client), cache: new CacheApi(client), }; } diff --git a/src/secrets/secrets.api.test.ts b/src/secrets/secrets.api.test.ts new file mode 100644 index 00000000..f8d870b0 --- /dev/null +++ b/src/secrets/secrets.api.test.ts @@ -0,0 +1,116 @@ +import { randomUUID } from 'node:crypto'; + +import { MALFORMED_CODE } from '../transport/envelope'; +import { LaunchApiError } from '../transport/errors'; +import type { RestApiClient, RestRequest } from '../transport/rest-client'; +import { SECRETS_ERROR_MESSAGES } from './secrets.errors'; +import { SecretsApi } from './secrets.api'; + +const SCOPE = { org: 'org1', project: 'proj1', environment: 'env1' }; +const LIST_PATH = '/projects/proj1/environments/env1/secrets'; + +function fakeRestClient(result: unknown) { + const requests: RestRequest[] = []; + const messages: unknown[] = []; + const client = { + request: async (req: RestRequest, errorMessages: unknown) => { + requests.push(req); + messages.push(errorMessages); + return result; + }, + } as unknown as RestApiClient; + + return { client, requests, messages }; +} + +function failingRestClient(failure: unknown) { + return { + request: async () => Promise.reject(failure), + } as unknown as RestApiClient; +} + +describe('secrets api list', () => { + it('reads the secrets of the environment with its scope headers and the secrets wording', async () => { + const { client, requests, messages } = fakeRestClient({ + secrets: [{ key: 'API_TOKEN', updatedAt: '2026-09-01T10:00:00.000Z' }], + count: 1, + }); + + const secrets = await new SecretsApi(client).list(SCOPE); + + expect(requests).toEqual([{ method: 'GET', path: LIST_PATH, orgUid: 'org1', projectUid: 'proj1' }]); + expect(messages).toEqual([SECRETS_ERROR_MESSAGES]); + expect(secrets).toEqual([{ key: 'API_TOKEN', updatedAt: '2026-09-01T10:00:00.000Z' }]); + }); + + it('keeps only the key and update time of an entry, so a value in the body never leaves the repository', async () => { + const value = randomUUID(); + const { client } = fakeRestClient({ + secrets: [{ key: 'API_TOKEN', updatedAt: '2026-09-01', value, encryptedValue: value }], + }); + + const secrets = await new SecretsApi(client).list(SCOPE); + + expect(secrets).toEqual([{ key: 'API_TOKEN', updatedAt: '2026-09-01' }]); + expect(JSON.stringify(secrets)).not.toContain(value); + }); + + it('returns an empty list for an environment with no secrets', async () => { + const { client } = fakeRestClient({ secrets: [], count: 0 }); + + await expect(new SecretsApi(client).list(SCOPE)).resolves.toEqual([]); + }); + + it('drops entries that are not objects and a key or time that is not text', async () => { + const { client } = fakeRestClient({ + secrets: [null, 'text', 5, [], { key: 7, updatedAt: false }, { key: 'A' }, { updatedAt: '2026-09-01' }], + }); + + await expect(new SecretsApi(client).list(SCOPE)).resolves.toEqual([ + { key: undefined, updatedAt: undefined }, + { key: 'A', updatedAt: undefined }, + { key: undefined, updatedAt: '2026-09-01' }, + ]); + }); + + it.each([[undefined], [null], [{}], [{ secrets: 'A' }], [{ secrets: { key: 'A' } }], [[{ key: 'A' }]]])( + 'raises a malformed-response error when the body has no secrets array (%p)', + async (body) => { + const { client } = fakeRestClient(body); + + const failure = await new SecretsApi(client).list(SCOPE).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchApiError); + expect((failure as LaunchApiError).code).toBe(MALFORMED_CODE); + expect((failure as LaunchApiError).message).toBe('The Launch API returned a secret list without a secrets array.'); + }, + ); + + it('rewords any 403 as the permission message whatever code the service sent', async () => { + const forbidden = new LaunchApiError(403, [{ code: 'launch.SOMETHING', message: 'raw server text' }]); + + const failure = await new SecretsApi(failingRestClient(forbidden)).list(SCOPE).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchApiError); + expect((failure as LaunchApiError).status).toBe(403); + expect((failure as LaunchApiError).message).toBe( + 'You do not have permission to manage the secrets of this environment.', + ); + }); + + it('passes any other API error through unchanged', async () => { + const missing = new LaunchApiError(404, [{ code: 'launch.ENVIRONMENT.NOT_FOUND', message: 'Environment not found.' }]); + + const failure = await new SecretsApi(failingRestClient(missing)).list(SCOPE).catch((error: unknown) => error); + + expect(failure).toBe(missing); + }); + + it('passes a failure that is not an API error through unchanged', async () => { + const network = new Error('socket hang up'); + + const failure = await new SecretsApi(failingRestClient(network)).list(SCOPE).catch((error: unknown) => error); + + expect(failure).toBe(network); + }); +}); diff --git a/src/secrets/secrets.api.ts b/src/secrets/secrets.api.ts new file mode 100644 index 00000000..6d6ef66f --- /dev/null +++ b/src/secrets/secrets.api.ts @@ -0,0 +1,44 @@ +import { isRecord } from '../core/values'; +import { assertArray } from '../transport/envelope'; +import type { RestApiClient, RestRequest } from '../transport/rest-client'; +import { SECRETS_ERROR_MESSAGES, asSecretsFailure } from './secrets.errors'; +import type { Secret, SecretsParams } from './types'; + +export * from './types'; + +function textOf(value: unknown): string | undefined { + return typeof value === 'string' ? value : undefined; +} + +function secretOf(entry: unknown): Secret[] { + return isRecord(entry) ? [{ key: textOf(entry.key), updatedAt: textOf(entry.updatedAt) }] : []; +} + +function secretsPath({ project, environment }: SecretsParams): string { + return `/projects/${project}/environments/${environment}/secrets`; +} + +export class SecretsApi { + constructor(private readonly client: RestApiClient) {} + + private async request(req: RestRequest): Promise { + try { + return await this.client.request(req, SECRETS_ERROR_MESSAGES); + } catch (error) { + throw asSecretsFailure(error); + } + } + + async list(params: SecretsParams): Promise { + const response = await this.request({ + method: 'GET', + path: secretsPath(params), + orgUid: params.org, + projectUid: params.project, + }); + + assertArray(response, 'secrets', 'secret list'); + + return (response as { secrets: unknown[] }).secrets.flatMap(secretOf); + } +} diff --git a/src/secrets/secrets.errors.ts b/src/secrets/secrets.errors.ts new file mode 100644 index 00000000..1e93fb20 --- /dev/null +++ b/src/secrets/secrets.errors.ts @@ -0,0 +1,19 @@ +import { LaunchApiError } from '../transport/errors'; +import type { ErrorMessages } from '../transport/errors'; + +const SECRETS_FORBIDDEN_CODE = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.FORBIDDEN'; + +export const SECRETS_FORBIDDEN_MESSAGE = 'You do not have permission to manage the secrets of this environment.'; + +export const SECRETS_ERROR_MESSAGES: ErrorMessages = { + [SECRETS_FORBIDDEN_CODE]: SECRETS_FORBIDDEN_MESSAGE, + 'launch.ENVIRONMENT.NOT_FOUND': 'No environment found with that name or UID.', +}; + +export function asSecretsFailure(error: unknown): unknown { + if (error instanceof LaunchApiError && error.status === 403) { + return new LaunchApiError(403, [{ code: SECRETS_FORBIDDEN_CODE }], SECRETS_ERROR_MESSAGES); + } + + return error; +} diff --git a/src/secrets/secrets.presenter.test.ts b/src/secrets/secrets.presenter.test.ts new file mode 100644 index 00000000..e4165157 --- /dev/null +++ b/src/secrets/secrets.presenter.test.ts @@ -0,0 +1,27 @@ +import { secretColumns } from './secrets.presenter'; + +describe('secrets presenter', () => { + it('has exactly a KEY and an UPDATED column and no column that could carry a value', () => { + const headers = secretColumns().map((column) => column.header); + + expect(headers).toEqual(['KEY', 'UPDATED']); + }); + + it('renders the key and the update time of a secret', () => { + const [key, updated] = secretColumns(); + const secret = { key: 'API_TOKEN', updatedAt: '2026-09-01T10:00:00.000Z' }; + + expect(key.value(secret)).toBe('API_TOKEN'); + expect(updated.value(secret)).toBe('2026-09-01T10:00:00.000Z'); + }); + + it.each([[{}], [{ key: '', updatedAt: '' }], [{ key: ' ', updatedAt: ' ' }]])( + 'falls back to a dash for an absent key and update time (%p)', + (secret) => { + const [key, updated] = secretColumns(); + + expect(key.value(secret)).toBe('-'); + expect(updated.value(secret)).toBe('-'); + }, + ); +}); diff --git a/src/secrets/secrets.presenter.ts b/src/secrets/secrets.presenter.ts new file mode 100644 index 00000000..8588aa62 --- /dev/null +++ b/src/secrets/secrets.presenter.ts @@ -0,0 +1,14 @@ +import type { TableColumn } from '../core/render'; +import { isAbsent } from '../core/values'; +import type { Secret } from './types'; + +function text(value: string | undefined): string { + return value === undefined || isAbsent(value) ? '-' : value; +} + +export function secretColumns(): TableColumn[] { + return [ + { header: 'KEY', value: (secret) => text(secret.key) }, + { header: 'UPDATED', value: (secret) => text(secret.updatedAt) }, + ]; +} diff --git a/src/secrets/types.ts b/src/secrets/types.ts new file mode 100644 index 00000000..ad23fdb7 --- /dev/null +++ b/src/secrets/types.ts @@ -0,0 +1,10 @@ +export interface Secret { + key?: string; + updatedAt?: string; +} + +export interface SecretsParams { + org: string; + project: string; + environment: string; +} diff --git a/test/guards/layering.test.ts b/test/guards/layering.test.ts index e4f9912a..fb69bf28 100644 --- a/test/guards/layering.test.ts +++ b/test/guards/layering.test.ts @@ -20,6 +20,7 @@ const RESOURCE_EDGES: Record = { stacks: [], variables: ['environments', 'stacks'], cache: [], + secrets: [], logs: ['deployments'], site: ['deployments', 'environments'], }; diff --git a/test/integration/secrets-list.test.ts b/test/integration/secrets-list.test.ts new file mode 100644 index 00000000..9f38e683 --- /dev/null +++ b/test/integration/secrets-list.test.ts @@ -0,0 +1,139 @@ +import { randomUUID } from 'node:crypto'; +import { tmpdir } from 'node:os'; + +import { authHandler, configHandler } from '@contentstack/cli-utilities'; +import type { Interfaces } from '@oclif/core'; +import { runCommand } from '@oclif/test'; +import nock from 'nock'; + +import { stdoutOfWidth } from '../support/terminal'; +import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; +import { projectOwnership } from '../support/project-ownership'; + +const LAUNCH_HUB_URL = 'https://launch-api.integration.test'; +const ORG_UID = 'blt4d9e2a7c1f6b3085'; +const PROJECT_UID = 'a1b2c3d4e5f60718293a4b5c'; +const ENV_UID = 'd4e5f60718293a4b5c6d7e8f'; +const SECRETS_PATH = `/manage/projects/${PROJECT_UID}/environments/${ENV_UID}/secrets`; +const DATA_DIR = tmpdir(); + +const CONFIG: Record = { + authorisationType: 'BASIC', + authtoken: 'test-authtoken', + email: 'cli-user@example.test', + region: { + name: 'integration', + cma: 'https://cma.integration.test', + cda: 'https://cda.integration.test', + uiHost: 'https://app.integration.test', + launchHubUrl: LAUNCH_HUB_URL, + }, +}; + +const LIST = ['launch:secrets:list', '--org', ORG_UID, '--project', PROJECT_UID, '--env', ENV_UID, '--data-dir', DATA_DIR]; + +let config: Interfaces.Config; +let unmatched: string[]; + +function recordUnmatched(): void { + unmatched = []; + nock.emitter.on('no match', (request: { method?: string; path?: string }) => { + unmatched.push(`${request.method ?? 'UNKNOWN'} ${request.path ?? ''}`); + }); +} + +function secretsOfEnvironment() { + return nock(LAUNCH_HUB_URL) + .matchHeader('x-organization-uid', ORG_UID) + .matchHeader('x-project-uid', PROJECT_UID) + .matchHeader('x-cs-api-version', '1.0') + .get(SECRETS_PATH); +} + +describe('integration: launch:secrets:list driven through oclif runCommand', () => { + beforeAll(async () => { + config = await loadCliConfig(); + nock.disableNetConnect(); + }); + + beforeEach(() => { + process.exitCode = 0; + routeConsoleLogToStdout(); + recordUnmatched(); + jest.spyOn(configHandler, 'get').mockImplementation((key: string) => CONFIG[key]); + jest.spyOn(authHandler, 'compareOAuthExpiry').mockResolvedValue(undefined); + projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID).persist(); + }); + + afterEach(() => { + process.exitCode = 0; + nock.emitter.removeAllListeners('no match'); + nock.cleanAll(); + }); + + afterAll(() => { + process.exitCode = 0; + nock.enableNetConnect(); + nock.restore(); + }); + + it('reads the secrets endpoint under the right scope headers and prints KEY and UPDATED with no value', async () => { + const restoreWidth = stdoutOfWidth(200); + const value = randomUUID(); + + try { + const scope = secretsOfEnvironment().reply(200, { + secrets: [{ key: 'API_TOKEN', updatedAt: '2026-09-01T10:00:00.000Z', value }], + count: 1, + }); + + const { error, stdout } = await runCommand(LIST, config); + + expect(error).toBeUndefined(); + expect(scope.isDone()).toBe(true); + expect(unmatched).toEqual([]); + expect(stdout).toContain('│ KEY │ UPDATED │'); + expect(stdout).toContain('│ API_TOKEN │ 2026-09-01T10:00:00.000Z │'); + expect(stdout).not.toMatch(/VALUE/i); + expect(stdout).not.toContain(value); + } finally { + restoreWidth(); + } + }); + + it('prints the empty placeholder and exits 0 for an environment with no secrets', async () => { + const scope = secretsOfEnvironment().reply(200, { secrets: [], count: 0 }); + + const { error, stdout } = await runCommand(LIST, config); + + expect(error).toBeUndefined(); + expect(scope.isDone()).toBe(true); + expect(stdout).toContain('No records found.'); + }); + + it('exits 1 with the permission message and none of the raw server text on a 403', async () => { + const scope = secretsOfEnvironment().reply(403, { + errors: [{ code: 'launch.AUTH.FORBIDDEN', message: 'raw-server-detail' }], + status: 403, + }); + + const { error, stdout } = await runCommand(LIST, config); + + expect(scope.isDone()).toBe(true); + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('You do not have permission to manage the secrets of this environment.'); + expect(error?.message).not.toContain('raw-server-detail'); + expect(stdout).not.toContain('raw-server-detail'); + }); + + it('exits 2 naming --env when it is missing and there is no terminal to prompt on', async () => { + const { error } = await runCommand( + ['launch:secrets:list', '--org', ORG_UID, '--project', PROJECT_UID, '--data-dir', DATA_DIR], + config, + ); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('Missing required value for --env'); + expect(unmatched).toEqual([]); + }); +}); From c6fae35cb75d6e0de5f306952b5497600e711fbb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 12:15:17 +0000 Subject: [PATCH 2/4] feat(secrets): add launch:secrets:set to add or refresh an environment secret MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The value is read from a masked prompt on a terminal or from stdin when piped, never from an argument. It adds, or refreshes through PUT when the key is already listed, after the confirm gate, and warns for client-exposed prefixes. #claude_code# šŸ¤– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EptZEi8nvDRpqxwsFu2SSa --- .talismanrc | 34 +- README.md | 31 ++ package.json | 1 + src/commands/launch/secrets/set.test.ts | 194 ++++++++++++ src/commands/launch/secrets/set.ts | 57 ++++ src/secrets/secrets.api.test.ts | 112 ++++++- src/secrets/secrets.api.ts | 37 ++- src/secrets/secrets.errors.test.ts | 46 +++ src/secrets/secrets.errors.ts | 21 ++ src/secrets/secrets.exposure.test.ts | 27 ++ src/secrets/secrets.exposure.ts | 12 + src/secrets/secrets.redact.test.ts | 62 ++++ src/secrets/secrets.redact.ts | 20 ++ src/secrets/secrets.set.test.ts | 245 +++++++++++++++ src/secrets/secrets.set.ts | 53 ++++ src/secrets/secrets.value.test.ts | 56 ++++ src/secrets/secrets.value.ts | 46 +++ test/integration/secrets-set.test.ts | 396 ++++++++++++++++++++++++ 18 files changed, 1439 insertions(+), 11 deletions(-) create mode 100644 src/commands/launch/secrets/set.test.ts create mode 100644 src/commands/launch/secrets/set.ts create mode 100644 src/secrets/secrets.errors.test.ts create mode 100644 src/secrets/secrets.exposure.test.ts create mode 100644 src/secrets/secrets.exposure.ts create mode 100644 src/secrets/secrets.redact.test.ts create mode 100644 src/secrets/secrets.redact.ts create mode 100644 src/secrets/secrets.set.test.ts create mode 100644 src/secrets/secrets.set.ts create mode 100644 src/secrets/secrets.value.test.ts create mode 100644 src/secrets/secrets.value.ts create mode 100644 test/integration/secrets-set.test.ts diff --git a/.talismanrc b/.talismanrc index 3b1f0204..6b6e7700 100644 --- a/.talismanrc +++ b/.talismanrc @@ -330,7 +330,7 @@ fileignoreconfig: - filename: src/commands/launch/env/update.test.ts checksum: 2da219594e7bdd589adc0eff9ff035252a75aaa51dfa20514b18fd3266d7b752 - filename: README.md - checksum: feece1f1f5a29902e0fc08fc0b294b1128c42fc46ab5ea37efbdde2e162a4eb7 + checksum: 64778264c69e20d97e59ab6f90acc656fb944e1b37cf8adc04e9745428831996 allowed_patterns: - "password-protection" - "-p, --password" @@ -468,19 +468,43 @@ fileignoreconfig: - filename: test/integration/secrets-list.test.ts checksum: dd9bea8e47b53feeda24a6d328947dfc3d11f79ef5a5c78bb1b3245761cebb13 - filename: src/secrets/secrets.api.ts - checksum: b490601876ce1d2fe28b91536c335f8a8b4713e784b718d4b9731739a907531a + checksum: dde72f524817a6803dddeffba209354cc4b87a27e030154e03cc2276b00ffe70 - filename: src/secrets/secrets.presenter.ts checksum: f395458a0858a7ad01831013f0327a20bfa3a7e0c239d0725141c6e5a8f29a10 - filename: package.json - checksum: b025f6d4b75a67695b939e625ef06edfc5f32014a1d802e14c19705188b383ba + checksum: f7d4888fb27df1a3fcbe155af38f412b8a44d21ad3195eeb0fe976c19346be3d - filename: src/commands/launch/secrets/list.ts checksum: 000fec691dd7d82e3f957f4ec4a2b85e59cf59726280c39f4fde43241371cefa - filename: src/commands/launch/secrets/list.test.ts checksum: 61ed1b9851aaeeea325cd06d81cef11d17435c87653d73f49f7c2794dbeda1da - filename: src/secrets/secrets.api.test.ts - checksum: c729f4ce0fad75bdc6a88019019ecd1bf3c50d2eddd3f1f9c331faaf25af07a8 + checksum: 1bf3c331ff2df44dc29aa3fd96909154b092869c1ddcf743c4dda5598873409d - filename: src/secrets/secrets.errors.ts - checksum: fa39fbaa0434045a9eb3b5bbbffa0960eab7655a7184f23558c51ff68238b1ca + checksum: d3c18246c353f0f4feacbf9a55657c05e6f91aa1f1ecf52f65bd1529c7753c0b - filename: src/secrets/secrets.presenter.test.ts checksum: 4b1e940cc470c3aa9c4e060944f7737dd212eef5da36f982a4cdd64230537164 +- filename: src/commands/launch/secrets/set.test.ts + checksum: b30e6341b7ef18380f4368c389436e279089b6fb4c58027f710a470efdf6c84e +- filename: src/commands/launch/secrets/set.ts + checksum: 1a9ed82a799bef4512a4b3ba6b393fb1fc2ef8df004578fa49086946907f5ca0 +- filename: src/secrets/secrets.errors.test.ts + checksum: 51d453005edec01862879e067a9bfcb54f863553af37628295f534cd876e678a +- filename: src/secrets/secrets.exposure.test.ts + checksum: 0682812d0bd23e592db3677dea13248c06fa3ac76a10451b24ac8962f280ad07 +- filename: src/secrets/secrets.exposure.ts + checksum: b4b287be92004dfecf60dd586d9298b0345080c1f6085189470b692987b6fecd +- filename: src/secrets/secrets.redact.test.ts + checksum: 38e5bcb49fc56c3ab7aeb107925806be54f26770a3d17b72fd99cbd70711baa4 +- filename: src/secrets/secrets.redact.ts + checksum: 9b3a512c54b38775b17eaac97ce980168a7e608746953c771abf955dfefa680d +- filename: src/secrets/secrets.set.test.ts + checksum: ef91bd478f158f993b961483ee9d6b683b3b725fc7f7b63c840680b64ce3df3d +- filename: src/secrets/secrets.set.ts + checksum: b68c33d70cbd2027ae6bdfd5db7ae7cd1d477bf42889458b9eac679a2b20734e +- filename: src/secrets/secrets.value.test.ts + checksum: f9d8b5e5f3ff4e46595dc1b042e2d237679c3d45d054198292a24f6813cab330 +- filename: src/secrets/secrets.value.ts + checksum: 3371b523f234175bc45f7e5f7a41ff2d492ada4da15abff200ec300e059e4f30 +- filename: test/integration/secrets-set.test.ts + checksum: 132510384c8196bbff286292bc77a16e2fee687f0ec4d685a3bac728feb0f020 version: "1.0" diff --git a/README.md b/README.md index 91012800..e55e9ef3 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ with exit code 2 and name their V2 replacements. `launch:functions:serve` is liv * [`csdx launch:projects:update`](#csdx-launchprojectsupdate) * [`csdx launch:rollback`](#csdx-launchrollback) * [`csdx launch:secrets:list`](#csdx-launchsecretslist) +* [`csdx launch:secrets:set`](#csdx-launchsecretsset) * [`csdx launch:site:open`](#csdx-launchsiteopen) * [`csdx launch:variables:list`](#csdx-launchvariableslist) * [`csdx launch:variables:set`](#csdx-launchvariablesset) @@ -789,6 +790,36 @@ EXAMPLES _See code: [src/commands/launch/secrets/list.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/secrets/list.ts)_ +## `csdx launch:secrets:set` + +Add a secret to an environment, or refresh it when the key already exists. The value comes from a masked prompt, or from stdin when piped, and is never taken from an argument + +``` +USAGE + $ csdx launch:secrets:set --key ... [-c ] [-d ] [--org ] [--project ] [--env ] + [-y] + +FLAGS + -c, --config= Path to the local '.cs-launch.json' file + -d, --data-dir= Current working directory + -y, --yes Skip the confirmation prompt + --env= Environment name or UID + --key=... (required) Environment variable key, repeatable + --org= Organization UID + --project= Project name or UID + +DESCRIPTION + Add a secret to an environment, or refresh it when the key already exists. The value comes from a masked prompt, or + from stdin when piped, and is never taken from an argument + +EXAMPLES + $ csdx launch:secrets:set --org --project --env --key API_TOKEN + + $ printf '%s' "$TOKEN" | csdx launch:secrets:set --org --project --env --key API_TOKEN --yes +``` + +_See code: [src/commands/launch/secrets/set.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/secrets/set.ts)_ + ## `csdx launch:site:open` Open an environment's live site in your browser, or print its URL when there is no terminal. On a terminal, when the environment has more than one domain, you choose which one to open; --deployment opens that deployment's preview URL without asking. diff --git a/package.json b/package.json index b44d2d5c..d7ef9547 100644 --- a/package.json +++ b/package.json @@ -187,6 +187,7 @@ "launch:projects:update": "LNCH-PRJ-UPD", "launch:rollback": "LNCH-RLBK", "launch:secrets:list": "LNCH-SEC-LS", + "launch:secrets:set": "LNCH-SEC-SET", "launch:site:open": "LNCH-SITE-OPN", "launch:variables:list": "LNCH-VAR-LS", "launch:variables:set": "LNCH-VAR-SET", diff --git a/src/commands/launch/secrets/set.test.ts b/src/commands/launch/secrets/set.test.ts new file mode 100644 index 00000000..41fa09a6 --- /dev/null +++ b/src/commands/launch/secrets/set.test.ts @@ -0,0 +1,194 @@ +import { randomUUID } from 'node:crypto'; + +import { UsageError } from '../../../core/errors'; +import type { UxLike } from '../../../core/prompt'; +import { LaunchCommand } from '../../../core/launch-command'; +import { GENERIC_ARGUMENTS_MESSAGE } from '../../../secrets/secrets.redact'; +import SecretsSet from './set'; + +interface Harness { + key?: string[]; + yes?: boolean; + isTTY?: boolean; + answer?: unknown; + existing?: unknown[]; +} + +function commandUnderTest(harness: Harness = {}) { + const lines: string[] = []; + const inquired: Record[] = []; + const mutations: string[] = []; + const sent: unknown[][] = []; + const ux: UxLike = { + print: (message: string) => { + lines.push(message); + }, + inquire: async (payload: unknown) => { + inquired.push(payload as Record); + return harness.answer as never; + }, + }; + const command = Object.create(SecretsSet.prototype) as SecretsSet; + + Object.assign(command, { + ux, + resolved: { + org: 'org1', + project: 'proj1', + env: 'env1', + yes: harness.yes ?? false, + key: harness.key ?? ['API_TOKEN'], + }, + services: { + ux, + isTTY: harness.isTTY ?? true, + outputIsTTY: false, + api: { + secrets: { + list: async () => harness.existing ?? [], + add: async (...args: unknown[]) => { + mutations.push('add'); + sent.push(args); + return {}; + }, + refresh: async (...args: unknown[]) => { + mutations.push('refresh'); + sent.push(args); + return {}; + }, + }, + }, + }, + }); + + return { command, lines, inquired, mutations, sent }; +} + +describe('launch:secrets:set', () => { + it('asks for a masked value then a confirmation on a terminal and adds the secret', async () => { + const value = randomUUID(); + const answers = [value, true]; + const { command, inquired, mutations, sent, lines } = commandUnderTest(); + const original = command['ux'].inquire; + command['ux'].inquire = async (payload: unknown) => { + await original(payload); + return answers.shift() as never; + }; + + await command.run(); + + expect(inquired.map((payload) => payload.type)).toEqual(['password', 'confirm']); + expect(inquired[1].message).toBe('Add the secret API_TOKEN to this environment?'); + expect(mutations).toEqual(['add']); + expect(sent).toEqual([[{ org: 'org1', project: 'proj1', environment: 'env1' }, 'API_TOKEN', value]]); + expect(lines).toEqual(['āœ” Secret API_TOKEN added.']); + expect(JSON.stringify(inquired[1])).not.toContain(value); + }); + + it('skips the confirmation with --yes and refreshes an existing key', async () => { + const value = randomUUID(); + const { command, inquired, mutations } = commandUnderTest({ + yes: true, + answer: value, + existing: [{ key: 'API_TOKEN' }], + }); + + await command.run(); + + expect(inquired.map((payload) => payload.type)).toEqual(['password']); + expect(mutations).toEqual(['refresh']); + }); + + it('says the secret was not changed and exits 3 without sending when the user declines', async () => { + const answers = [randomUUID(), false]; + const { command, lines, mutations } = commandUnderTest(); + command['ux'].inquire = async () => answers.shift() as never; + + const error = (await command.run().catch((thrown: unknown) => thrown)) as { oclif?: { exit?: number } }; + + expect(error.oclif?.exit).toBe(3); + expect(mutations).toEqual([]); + expect(lines).toEqual(['Secret not changed.']); + }); + + it('reads the value from stdin and exits 2 naming --yes without a terminal, sending nothing', async () => { + const value = randomUUID(); + const reads: number[] = []; + const { command, mutations, inquired } = commandUnderTest({ isTTY: false }); + Object.assign(command, { + readStdin: async () => { + reads.push(1); + return value; + }, + }); + + const error = (await command.run().catch((thrown: unknown) => thrown)) as UsageError; + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe( + 'Add the secret API_TOKEN to this environment? Pass --yes to confirm without an interactive terminal.', + ); + expect(error.message).not.toContain(value); + expect(reads).toEqual([1]); + expect(inquired).toEqual([]); + expect(mutations).toEqual([]); + }); + + it('adds a piped value without asking anything when --yes was passed', async () => { + const value = randomUUID(); + const { command, inquired, sent } = commandUnderTest({ isTTY: false, yes: true }); + Object.assign(command, { readStdin: async () => value }); + + await command.run(); + + expect(inquired).toEqual([]); + expect(sent).toEqual([[{ org: 'org1', project: 'proj1', environment: 'env1' }, 'API_TOKEN', value]]); + }); + + it.each([[[]], [['A', 'B']]])('exits 2 asking for exactly one --key when given %p', async (key) => { + const { command, mutations, inquired } = commandUnderTest({ key }); + + const error = (await command.run().catch((thrown: unknown) => thrown)) as UsageError; + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe('Pass exactly one --key.'); + expect(mutations).toEqual([]); + expect(inquired).toEqual([]); + }); + + it('hands every failure on with a --flag=value pair and an unexpected argument scrubbed of the value', async () => { + const value = randomUUID(); + const handed: Error[] = []; + jest + .spyOn(LaunchCommand.prototype as unknown as { catch: (err: Error) => Promise }, 'catch') + .mockImplementation(async (err) => { + handed.push(err); + return 'handled'; + }); + const { command } = commandUnderTest(); + const flagged = new Error(`Nonexistent flag: --value=${value}`); + const positional = new Error(`Unexpected argument: ${value}`); + + const results = [ + await (command as unknown as { catch: (err: Error) => Promise }).catch(flagged), + await (command as unknown as { catch: (err: Error) => Promise }).catch(positional), + ]; + + expect(results).toEqual(['handled', 'handled']); + expect(handed).toEqual([flagged, positional]); + expect(handed.map((error) => error.message)).toEqual(['Nonexistent flag: --value', GENERIC_ARGUMENTS_MESSAGE]); + }); + + it('declares org, project, env, key and yes, and has no value flag', () => { + expect(SecretsSet.inputs).toEqual({ + org: { required: true }, + project: { required: true }, + env: { required: true }, + key: { required: true }, + yes: {}, + }); + expect(Object.keys(SecretsSet.flags).sort()).toEqual(['env', 'key', 'org', 'project', 'yes']); + }); +}); diff --git a/src/commands/launch/secrets/set.ts b/src/commands/launch/secrets/set.ts new file mode 100644 index 00000000..549e8761 --- /dev/null +++ b/src/commands/launch/secrets/set.ts @@ -0,0 +1,57 @@ +import { EXIT_CANCELLED } from '../../../core/constants'; +import { UsageError } from '../../../core/errors'; +import { flagsFor, inputs } from '../../../core/inputs'; +import { LaunchCommand } from '../../../core/launch-command'; +import { styled } from '../../../core/style'; +import { withoutArgumentValues } from '../../../secrets/secrets.redact'; +import { SecretSetter } from '../../../secrets/secrets.set'; +import { readSecretValue } from '../../../secrets/secrets.value'; + +const setInputs = inputs({ + org: { required: true }, + project: { required: true }, + env: { required: true }, + key: { required: true }, + yes: {}, +}); + +export default class SecretsSet extends LaunchCommand { + static description = + 'Add a secret to an environment, or refresh it when the key already exists. ' + + 'The value comes from a masked prompt, or from stdin when piped, and is never taken from an argument'; + + static examples = [ + '$ csdx launch:secrets:set --org --project --env --key API_TOKEN', + '$ printf \'%s\' "$TOKEN" | csdx launch:secrets:set --org --project ' + + '--env --key API_TOKEN --yes', + ]; + + static inputs = setInputs; + + static flags = flagsFor(setInputs); + + protected readStdin: () => Promise = () => readSecretValue(); + + async run(): Promise { + const [key, ...others] = this.resolved.key; + + if (key === undefined || others.length > 0) { + throw new UsageError('Pass exactly one --key.'); + } + + const outcome = await new SecretSetter( + this.services, + (question) => this.confirm(question), + () => this.readStdin(), + ).set({ org: this.resolved.org, project: this.resolved.project, environment: this.resolved.env, key }); + + if (outcome === 'declined') { + this.ux.print(styled('Secret not changed.', 'yellow', this.services.outputIsTTY === true)); + this.exit(EXIT_CANCELLED); + } + } + + protected async catch(err: Error & { exitCode?: number }): Promise { + return super.catch(withoutArgumentValues(err)); + } +} diff --git a/src/secrets/secrets.api.test.ts b/src/secrets/secrets.api.test.ts index f8d870b0..4024bdda 100644 --- a/src/secrets/secrets.api.test.ts +++ b/src/secrets/secrets.api.test.ts @@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto'; import { MALFORMED_CODE } from '../transport/envelope'; import { LaunchApiError } from '../transport/errors'; import type { RestApiClient, RestRequest } from '../transport/rest-client'; -import { SECRETS_ERROR_MESSAGES } from './secrets.errors'; +import { SECRETS_ERROR_MESSAGES, secretKeyMessages } from './secrets.errors'; import { SecretsApi } from './secrets.api'; const SCOPE = { org: 'org1', project: 'proj1', environment: 'env1' }; @@ -82,7 +82,9 @@ describe('secrets api list', () => { expect(failure).toBeInstanceOf(LaunchApiError); expect((failure as LaunchApiError).code).toBe(MALFORMED_CODE); - expect((failure as LaunchApiError).message).toBe('The Launch API returned a secret list without a secrets array.'); + expect((failure as LaunchApiError).message).toBe( + 'The Launch API returned a secret list without a secrets array.', + ); }, ); @@ -99,7 +101,9 @@ describe('secrets api list', () => { }); it('passes any other API error through unchanged', async () => { - const missing = new LaunchApiError(404, [{ code: 'launch.ENVIRONMENT.NOT_FOUND', message: 'Environment not found.' }]); + const missing = new LaunchApiError(404, [ + { code: 'launch.ENVIRONMENT.NOT_FOUND', message: 'Environment not found.' }, + ]); const failure = await new SecretsApi(failingRestClient(missing)).list(SCOPE).catch((error: unknown) => error); @@ -114,3 +118,105 @@ describe('secrets api list', () => { expect(failure).toBe(network); }); }); + +describe('secrets api add', () => { + it('posts the key and value to the secrets collection under the scope headers and the key wording', async () => { + const value = randomUUID(); + const { client, requests, messages } = fakeRestClient({ + key: 'API_TOKEN', + updatedAt: '2026-09-01T10:00:00.000Z', + value, + }); + + const secret = await new SecretsApi(client).add(SCOPE, 'API_TOKEN', value); + + expect(requests).toEqual([ + { method: 'POST', path: LIST_PATH, orgUid: 'org1', projectUid: 'proj1', body: { key: 'API_TOKEN', value } }, + ]); + expect(messages).toEqual([secretKeyMessages('API_TOKEN')]); + expect(secret).toEqual({ key: 'API_TOKEN', updatedAt: '2026-09-01T10:00:00.000Z' }); + }); + + it.each([[undefined], [null], ['text'], [[]]])( + 'returns an empty secret when the answer is not an object (%p)', + async (body) => { + const { client } = fakeRestClient(body); + + await expect(new SecretsApi(client).add(SCOPE, 'API_TOKEN', randomUUID())).resolves.toEqual({}); + }, + ); + + it('rewords a 403 and names the key on a 409 conflict, without the value in either', async () => { + const value = randomUUID(); + const conflict = new LaunchApiError( + 409, + [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT' }], + secretKeyMessages('DB_URL'), + ); + const forbidden = new LaunchApiError(403, [{ code: 'launch.X', message: 'raw' }]); + + const first = await new SecretsApi(failingRestClient(forbidden)) + .add(SCOPE, 'DB_URL', value) + .catch((error: unknown) => error); + const second = await new SecretsApi(failingRestClient(conflict)) + .add(SCOPE, 'DB_URL', value) + .catch((error: unknown) => error); + + expect((first as LaunchApiError).message).toBe( + 'You do not have permission to manage the secrets of this environment.', + ); + expect(second).toBe(conflict); + expect((second as LaunchApiError).message).not.toContain(value); + }); +}); + +describe('secrets api refresh', () => { + it('puts only the value to the secret named in the path, with the key wording', async () => { + const value = randomUUID(); + const { client, requests, messages } = fakeRestClient({ key: 'API_TOKEN', updatedAt: '2026-09-02' }); + + const secret = await new SecretsApi(client).refresh(SCOPE, 'API_TOKEN', value); + + expect(requests).toEqual([ + { method: 'PUT', path: `${LIST_PATH}/API_TOKEN`, orgUid: 'org1', projectUid: 'proj1', body: { value } }, + ]); + expect(messages).toEqual([secretKeyMessages('API_TOKEN')]); + expect(secret).toEqual({ key: 'API_TOKEN', updatedAt: '2026-09-02' }); + }); + + it.each([[undefined], [null], ['text']])( + 'returns an empty secret when the answer is not an object (%p)', + async (body) => { + const { client } = fakeRestClient(body); + + await expect(new SecretsApi(client).refresh(SCOPE, 'API_TOKEN', randomUUID())).resolves.toEqual({}); + }, + ); + + it('encodes a key that is not path-safe', async () => { + const { client, requests } = fakeRestClient({}); + + await new SecretsApi(client).refresh(SCOPE, 'A/B ?', randomUUID()); + + expect(requests[0].path).toBe(`${LIST_PATH}/A%2FB%20%3F`); + }); + + it('rewords a 403 and passes a 404 through', async () => { + const forbidden = new LaunchApiError(403, [{ code: 'launch.X', message: 'raw' }]); + const missing = new LaunchApiError( + 404, + [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND' }], + secretKeyMessages('A'), + ); + + const first = await new SecretsApi(failingRestClient(forbidden)) + .refresh(SCOPE, 'A', 'v') + .catch((error: unknown) => error); + const second = await new SecretsApi(failingRestClient(missing)) + .refresh(SCOPE, 'A', 'v') + .catch((error: unknown) => error); + + expect((first as LaunchApiError).status).toBe(403); + expect(second).toBe(missing); + }); +}); diff --git a/src/secrets/secrets.api.ts b/src/secrets/secrets.api.ts index 6d6ef66f..ea658319 100644 --- a/src/secrets/secrets.api.ts +++ b/src/secrets/secrets.api.ts @@ -1,7 +1,8 @@ import { isRecord } from '../core/values'; import { assertArray } from '../transport/envelope'; import type { RestApiClient, RestRequest } from '../transport/rest-client'; -import { SECRETS_ERROR_MESSAGES, asSecretsFailure } from './secrets.errors'; +import type { ErrorMessages } from '../transport/errors'; +import { SECRETS_ERROR_MESSAGES, asSecretsFailure, secretKeyMessages } from './secrets.errors'; import type { Secret, SecretsParams } from './types'; export * from './types'; @@ -21,9 +22,9 @@ function secretsPath({ project, environment }: SecretsParams): string { export class SecretsApi { constructor(private readonly client: RestApiClient) {} - private async request(req: RestRequest): Promise { + private async request(req: RestRequest, messages: ErrorMessages = SECRETS_ERROR_MESSAGES): Promise { try { - return await this.client.request(req, SECRETS_ERROR_MESSAGES); + return await this.client.request(req, messages); } catch (error) { throw asSecretsFailure(error); } @@ -41,4 +42,34 @@ export class SecretsApi { return (response as { secrets: unknown[] }).secrets.flatMap(secretOf); } + + async add(params: SecretsParams, key: string, value: string): Promise { + const response = await this.request( + { + method: 'POST', + path: secretsPath(params), + orgUid: params.org, + projectUid: params.project, + body: { key, value }, + }, + secretKeyMessages(key), + ); + + return secretOf(response)[0] ?? {}; + } + + async refresh(params: SecretsParams, key: string, value: string): Promise { + const response = await this.request( + { + method: 'PUT', + path: `${secretsPath(params)}/${encodeURIComponent(key)}`, + orgUid: params.org, + projectUid: params.project, + body: { value }, + }, + secretKeyMessages(key), + ); + + return secretOf(response)[0] ?? {}; + } } diff --git a/src/secrets/secrets.errors.test.ts b/src/secrets/secrets.errors.test.ts new file mode 100644 index 00000000..3040dfdc --- /dev/null +++ b/src/secrets/secrets.errors.test.ts @@ -0,0 +1,46 @@ +import { LaunchApiError } from '../transport/errors'; +import { SECRETS_ERROR_MESSAGES, secretKeyMessages } from './secrets.errors'; + +const PREFIX = 'launch.ENVIRONMENT.'; + +describe('secrets error wording', () => { + it.each([ + [ + 409, + `${PREFIX}ENVIRONMENT_SECRETS.KEY.CONFLICT`, + 'The key DB_URL is already used by a variable or a secret in this environment.', + ], + [ + 409, + `${PREFIX}ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE`, + 'The environment was changed by another request at the same moment. Run the command again.', + ], + [400, `${PREFIX}ENVIRONMENT_SECRETS.VALUE.MULTILINE`, 'Invalid value: a secret value cannot contain line breaks.'], + [400, `${PREFIX}ENVIRONMENT_VARIABLES.KEY.NOT_EMPTY`, 'Invalid key: the key cannot be empty.'], + [400, `${PREFIX}ENVIRONMENT_VARIABLES.KEY.NOT_STRING`, 'Invalid key: the key must be text.'], + [400, `${PREFIX}ENVIRONMENT_VARIABLES.KEY.TOO_LONG`, 'Invalid key: the key is too long.'], + [400, `${PREFIX}ENVIRONMENT_VARIABLES.VALUE.NOT_EMPTY`, 'Invalid value: the value cannot be empty.'], + [400, `${PREFIX}ENVIRONMENT_VARIABLES.VALUE.NOT_STRING`, 'Invalid value: the value must be text.'], + [400, `${PREFIX}ENVIRONMENT_VARIABLES.VALUE.TOO_LONG`, 'Invalid value: the value is too long.'], + [404, `${PREFIX}ENVIRONMENT_SECRETS.KEY.NOT_FOUND`, 'The secret DB_URL was not found in this environment.'], + [404, `${PREFIX}NOT_FOUND`, 'No environment found with that name or UID.'], + ])('words %i %s as a distinct message naming the key', (status, code, message) => { + const failure = new LaunchApiError(status, [{ code, message: 'raw server text' }], secretKeyMessages('DB_URL')); + + expect(failure.message).toBe(message); + }); + + it('keeps the server wording for a code it does not reword', () => { + const failure = new LaunchApiError( + 400, + [{ code: 'launch.SOMETHING.NEW', message: 'raw server text' }], + secretKeyMessages('DB_URL'), + ); + + expect(failure.message).toBe('raw server text'); + }); + + it('keeps the read-context messages free of any key', () => { + expect(Object.values(SECRETS_ERROR_MESSAGES).join(' ')).not.toContain('DB_URL'); + }); +}); diff --git a/src/secrets/secrets.errors.ts b/src/secrets/secrets.errors.ts index 1e93fb20..4ac39900 100644 --- a/src/secrets/secrets.errors.ts +++ b/src/secrets/secrets.errors.ts @@ -10,6 +10,27 @@ export const SECRETS_ERROR_MESSAGES: ErrorMessages = { 'launch.ENVIRONMENT.NOT_FOUND': 'No environment found with that name or UID.', }; +const CODE = 'launch.ENVIRONMENT.'; + +export function secretKeyMessages(key: string): ErrorMessages { + const taken = `The key ${key} is already used by a variable or a secret in this environment.`; + + return { + ...SECRETS_ERROR_MESSAGES, + [`${CODE}ENVIRONMENT_SECRETS.KEY.CONFLICT`]: taken, + [`${CODE}ENVIRONMENT_SECRETS.KEY.NOT_FOUND`]: `The secret ${key} was not found in this environment.`, + [`${CODE}ENVIRONMENT_SECRETS.VALUE.MULTILINE`]: 'Invalid value: a secret value cannot contain line breaks.', + [`${CODE}ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE`]: + 'The environment was changed by another request at the same moment. Run the command again.', + [`${CODE}ENVIRONMENT_VARIABLES.KEY.NOT_EMPTY`]: 'Invalid key: the key cannot be empty.', + [`${CODE}ENVIRONMENT_VARIABLES.KEY.NOT_STRING`]: 'Invalid key: the key must be text.', + [`${CODE}ENVIRONMENT_VARIABLES.KEY.TOO_LONG`]: 'Invalid key: the key is too long.', + [`${CODE}ENVIRONMENT_VARIABLES.VALUE.NOT_EMPTY`]: 'Invalid value: the value cannot be empty.', + [`${CODE}ENVIRONMENT_VARIABLES.VALUE.NOT_STRING`]: 'Invalid value: the value must be text.', + [`${CODE}ENVIRONMENT_VARIABLES.VALUE.TOO_LONG`]: 'Invalid value: the value is too long.', + }; +} + export function asSecretsFailure(error: unknown): unknown { if (error instanceof LaunchApiError && error.status === 403) { return new LaunchApiError(403, [{ code: SECRETS_FORBIDDEN_CODE }], SECRETS_ERROR_MESSAGES); diff --git a/src/secrets/secrets.exposure.test.ts b/src/secrets/secrets.exposure.test.ts new file mode 100644 index 00000000..ce6df01a --- /dev/null +++ b/src/secrets/secrets.exposure.test.ts @@ -0,0 +1,27 @@ +import { CLIENT_EXPOSED_PREFIXES, clientExposedWarning, isClientExposedKey } from './secrets.exposure'; + +describe('client-exposed secret keys', () => { + it('lists the five public prefixes', () => { + expect(CLIENT_EXPOSED_PREFIXES).toEqual(['NEXT_PUBLIC_', 'NUXT_PUBLIC_', 'VITE_', 'GATSBY_', 'PUBLIC_']); + }); + + it.each(['NEXT_PUBLIC_', 'NUXT_PUBLIC_', 'VITE_', 'GATSBY_', 'PUBLIC_'])( + 'treats a key starting with %s as client-exposed and warns about it by name', + (prefix) => { + const key = `${prefix}API_URL`; + + expect(isClientExposedKey(key)).toBe(true); + expect(clientExposedWarning(key)).toBe( + `Warning: ${key} starts with a client-exposed prefix, so its value is inlined into client JavaScript ` + + 'at build time and is visible to anyone who loads your site.', + ); + }, + ); + + it.each(['API_TOKEN', 'MY_NEXT_PUBLIC_X', 'next_public_x', 'PUBLIC', 'VITEX'])( + 'does not treat %s as client-exposed', + (key) => { + expect(isClientExposedKey(key)).toBe(false); + }, + ); +}); diff --git a/src/secrets/secrets.exposure.ts b/src/secrets/secrets.exposure.ts new file mode 100644 index 00000000..bcd05923 --- /dev/null +++ b/src/secrets/secrets.exposure.ts @@ -0,0 +1,12 @@ +export const CLIENT_EXPOSED_PREFIXES = ['NEXT_PUBLIC_', 'NUXT_PUBLIC_', 'VITE_', 'GATSBY_', 'PUBLIC_']; + +export function isClientExposedKey(key: string): boolean { + return CLIENT_EXPOSED_PREFIXES.some((prefix) => key.startsWith(prefix)); +} + +export function clientExposedWarning(key: string): string { + return ( + `Warning: ${key} starts with a client-exposed prefix, so its value is inlined into client JavaScript ` + + 'at build time and is visible to anyone who loads your site.' + ); +} diff --git a/src/secrets/secrets.redact.test.ts b/src/secrets/secrets.redact.test.ts new file mode 100644 index 00000000..71db7280 --- /dev/null +++ b/src/secrets/secrets.redact.test.ts @@ -0,0 +1,62 @@ +import { randomUUID } from 'node:crypto'; + +import { GENERIC_ARGUMENTS_MESSAGE, withoutArgumentValues } from './secrets.redact'; + +function failure(message: string): Error { + const error = new Error(message); + error.stack = `Error: ${message}\n at somewhere (file.ts:1:1)`; + return error; +} + +describe('withoutArgumentValues', () => { + it('drops the value of a --flag=value pair from the message and the stack', () => { + const value = randomUUID(); + + const error = withoutArgumentValues(failure(`Nonexistent flag: --value=${value}\nSee more help with --help`)); + + expect(error.message).toBe('Nonexistent flag: --value\nSee more help with --help'); + expect(error.stack).toBe( + 'Error: Nonexistent flag: --value\nSee more help with --help\n at somewhere (file.ts:1:1)', + ); + expect(`${error.message}${error.stack}`).not.toContain(value); + }); + + it('drops a short flag value too, whatever it contains', () => { + const error = withoutArgumentValues(failure('Nonexistent flag: -v=a b=c d')); + + expect(error.message).toBe('Nonexistent flag: -v'); + }); + + it.each([['Unexpected argument: VALUE'], ['Unexpected arguments: A, B']])( + 'replaces %p with the generic invalid-arguments message', + (line) => { + const error = withoutArgumentValues(failure(`${line}\nSee more help with --help`)); + + expect(error.message).toBe(`${GENERIC_ARGUMENTS_MESSAGE}\nSee more help with --help`); + expect(error.stack).toContain(GENERIC_ARGUMENTS_MESSAGE); + expect(error.stack).not.toContain('VALUE'); + }, + ); + + it('leaves a message with no argument value untouched, and returns the same error', () => { + const original = failure('Nonexistent flag: --value\nSee more help with --help'); + + const error = withoutArgumentValues(original); + + expect(error).toBe(original); + expect(error.message).toBe('Nonexistent flag: --value\nSee more help with --help'); + }); + + it('leaves a hyphenated word that is not a flag assignment alone', () => { + const error = withoutArgumentValues(failure('a well-known=thing')); + + expect(error.message).toBe('a well-known=thing'); + }); + + it('keeps an error with no stack free of one', () => { + const original = new Error('Nonexistent flag: --value=x'); + original.stack = undefined; + + expect(withoutArgumentValues(original).stack).toBeUndefined(); + }); +}); diff --git a/src/secrets/secrets.redact.ts b/src/secrets/secrets.redact.ts new file mode 100644 index 00000000..9c27c3a8 --- /dev/null +++ b/src/secrets/secrets.redact.ts @@ -0,0 +1,20 @@ +export const GENERIC_ARGUMENTS_MESSAGE = + 'Invalid arguments. A secret value is never taken from the command line: ' + + 'type it at the prompt, or pipe it in on stdin.'; + +const FLAG_ASSIGNMENT = /(?(error: E): E { + error.message = scrubbed(error.message); + + if (error.stack !== undefined) { + error.stack = scrubbed(error.stack); + } + + return error; +} diff --git a/src/secrets/secrets.set.test.ts b/src/secrets/secrets.set.test.ts new file mode 100644 index 00000000..01f3b860 --- /dev/null +++ b/src/secrets/secrets.set.test.ts @@ -0,0 +1,245 @@ +import { randomUUID } from 'node:crypto'; + +import type { ServiceContext } from '../core/service-context'; +import { LaunchApiError } from '../transport/errors'; +import { NoValueError } from './secrets.value'; +import { SecretSetter } from './secrets.set'; +import type { Secret } from './types'; + +const REQUEST = { org: 'org1', project: 'proj1', environment: 'env1', key: 'API_TOKEN' }; + +interface Harness { + isTTY?: boolean; + existing?: Secret[]; + typed?: unknown; + piped?: string | Error; + confirmed?: boolean; + confirmFails?: Error; + mutationFails?: Error; + listFails?: Error; +} + +function setterUnderTest(harness: Harness = {}) { + const calls: string[] = []; + const lines: string[] = []; + const prompts: Record[] = []; + const questions: string[] = []; + const listed: unknown[] = []; + const added: unknown[][] = []; + const refreshed: unknown[][] = []; + const stdinReads: number[] = []; + + const services = { + isTTY: harness.isTTY ?? false, + outputIsTTY: false, + ux: { + print: (line: string) => { + lines.push(line); + }, + inquire: async (payload: unknown) => { + calls.push('prompt'); + prompts.push(payload as Record); + return harness.typed as never; + }, + }, + api: { + secrets: { + list: async (params: unknown) => { + calls.push('list'); + listed.push(params); + + if (harness.listFails) { + throw harness.listFails; + } + + return harness.existing ?? []; + }, + add: async (...args: unknown[]) => { + calls.push('add'); + added.push(args); + + if (harness.mutationFails) { + throw harness.mutationFails; + } + + return {}; + }, + refresh: async (...args: unknown[]) => { + calls.push('refresh'); + refreshed.push(args); + + if (harness.mutationFails) { + throw harness.mutationFails; + } + + return {}; + }, + }, + }, + } as unknown as ServiceContext; + + const setter = new SecretSetter( + services, + async (question) => { + calls.push('confirm'); + questions.push(question); + + if (harness.confirmFails) { + throw harness.confirmFails; + } + + return harness.confirmed ?? true; + }, + async () => { + calls.push('stdin'); + stdinReads.push(1); + + if (harness.piped instanceof Error) { + throw harness.piped; + } + + return harness.piped ?? ''; + }, + ); + + return { setter, calls, lines, prompts, questions, listed, added, refreshed, stdinReads }; +} + +describe('SecretSetter', () => { + it('adds a new secret from piped stdin after listing and confirming, never prompting for the value', async () => { + const value = randomUUID(); + const run = setterUnderTest({ piped: value }); + + const outcome = await run.setter.set(REQUEST); + + expect(outcome).toBe('added'); + expect(run.calls).toEqual(['list', 'stdin', 'confirm', 'add']); + expect(run.listed).toEqual([{ org: 'org1', project: 'proj1', environment: 'env1' }]); + expect(run.added).toEqual([[{ org: 'org1', project: 'proj1', environment: 'env1' }, 'API_TOKEN', value]]); + expect(run.refreshed).toEqual([]); + expect(run.prompts).toEqual([]); + expect(run.questions).toEqual(['Add the secret API_TOKEN to this environment?']); + expect(run.lines).toEqual(['āœ” Secret API_TOKEN added.']); + expect(run.lines.join('\n')).not.toContain(value); + }); + + it('asks for the value with a masked prompt on a terminal and never reads stdin', async () => { + const value = randomUUID(); + const run = setterUnderTest({ isTTY: true, typed: value }); + + await run.setter.set(REQUEST); + + expect(run.calls).toEqual(['list', 'prompt', 'confirm', 'add']); + expect(run.prompts).toHaveLength(1); + expect(run.prompts[0]).toMatchObject({ type: 'password', message: 'Value for API_TOKEN', mask: '*' }); + expect(run.added[0][2]).toBe(value); + expect(run.stdinReads).toEqual([]); + }); + + it('refreshes instead of adding when the key is already listed, and sends no add', async () => { + const value = randomUUID(); + const run = setterUnderTest({ piped: value, existing: [{ key: 'OTHER' }, { key: 'API_TOKEN' }] }); + + const outcome = await run.setter.set(REQUEST); + + expect(outcome).toBe('refreshed'); + expect(run.refreshed).toEqual([[{ org: 'org1', project: 'proj1', environment: 'env1' }, 'API_TOKEN', value]]); + expect(run.added).toEqual([]); + expect(run.questions).toEqual([ + 'Refresh the secret API_TOKEN in this environment? Its current value will be replaced.', + ]); + expect(run.lines).toEqual(['āœ” Secret API_TOKEN refreshed.']); + }); + + it('adds when only a key that differs in case or by prefix is listed', async () => { + const run = setterUnderTest({ piped: 'v', existing: [{ key: 'api_token' }, { key: 'API_TOKEN_2' }, {}] }); + + await expect(run.setter.set(REQUEST)).resolves.toBe('added'); + expect(run.refreshed).toEqual([]); + }); + + it('sends nothing and reports a decline when the confirmation is refused', async () => { + const run = setterUnderTest({ piped: randomUUID(), confirmed: false }); + + const outcome = await run.setter.set(REQUEST); + + expect(outcome).toBe('declined'); + expect(run.calls).toEqual(['list', 'stdin', 'confirm']); + expect(run.added).toEqual([]); + expect(run.refreshed).toEqual([]); + expect(run.lines).toEqual([]); + }); + + it('refuses an empty pipe before confirming or sending anything', async () => { + const run = setterUnderTest({ piped: new NoValueError() }); + + await expect(run.setter.set(REQUEST)).rejects.toBeInstanceOf(NoValueError); + expect(run.calls).toEqual(['list', 'stdin']); + expect(run.added).toEqual([]); + }); + + it.each(['NEXT_PUBLIC_API_URL', 'NUXT_PUBLIC_X', 'VITE_X', 'GATSBY_X', 'PUBLIC_X'])( + 'warns that %s is exposed to the client and still sends it', + async (key) => { + const run = setterUnderTest({ piped: 'v' }); + + await run.setter.set({ ...REQUEST, key }); + + expect(run.lines[0]).toContain(`Warning: ${key} starts with a client-exposed prefix`); + expect(run.lines).toHaveLength(2); + expect(run.calls).toEqual(['list', 'stdin', 'confirm', 'add']); + }, + ); + + it.each(['API_TOKEN', 'MY_NEXT_PUBLIC_X'])('prints no exposure warning for %s', async (key) => { + const run = setterUnderTest({ piped: 'v' }); + + await run.setter.set({ ...REQUEST, key }); + + expect(run.lines).toEqual([`āœ” Secret ${key} added.`]); + }); + + it('prints the exposure warning before the value is read, and also when the user then declines', async () => { + const run = setterUnderTest({ piped: 'v', confirmed: false }); + + await run.setter.set({ ...REQUEST, key: 'VITE_X' }); + + expect(run.lines).toHaveLength(1); + expect(run.lines[0]).toContain('VITE_X'); + }); + + it('keeps a value out of a failed mutation, and prints nothing as a success', async () => { + const value = 'line1\nline2'; + const failure = new LaunchApiError(400, [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.VALUE.MULTILINE' }]); + const run = setterUnderTest({ piped: value, mutationFails: failure }); + + await expect(run.setter.set(REQUEST)).rejects.toBe(failure); + expect(run.lines).toEqual([]); + expect(run.lines.join('\n')).not.toContain('line1'); + expect(run.questions.join('\n')).not.toContain('line1'); + }); + + it('propagates a failed list before asking for a value', async () => { + const failure = new Error('list failed'); + const run = setterUnderTest({ listFails: failure, isTTY: true }); + + await expect(run.setter.set(REQUEST)).rejects.toBe(failure); + expect(run.calls).toEqual(['list']); + }); + + it('propagates a failed prompt', async () => { + const run = setterUnderTest({ isTTY: true, typed: undefined }); + + await expect(run.setter.set(REQUEST)).rejects.toThrow('Cancelled'); + expect(run.calls).toEqual(['list', 'prompt']); + }); + + it('propagates a failed confirm without sending', async () => { + const failure = new Error('no terminal'); + const run = setterUnderTest({ piped: 'v', confirmFails: failure }); + + await expect(run.setter.set(REQUEST)).rejects.toBe(failure); + expect(run.added).toEqual([]); + expect(run.refreshed).toEqual([]); + }); +}); diff --git a/src/secrets/secrets.set.ts b/src/secrets/secrets.set.ts new file mode 100644 index 00000000..90ef942a --- /dev/null +++ b/src/secrets/secrets.set.ts @@ -0,0 +1,53 @@ +import { askSecret } from '../core/prompt'; +import type { ServiceContext } from '../core/service-context'; +import { styled } from '../core/style'; +import { clientExposedWarning, isClientExposedKey } from './secrets.exposure'; +import type { SecretsParams } from './types'; + +export interface SetSecretRequest extends SecretsParams { + key: string; +} + +export type SetSecretOutcome = 'added' | 'refreshed' | 'declined'; + +export type Confirm = (question: string) => Promise; + +export class SecretSetter { + constructor( + private readonly services: ServiceContext, + private readonly confirm: Confirm, + private readonly readStdin: () => Promise, + ) {} + + async set({ key, ...scope }: SetSecretRequest): Promise { + const colour = this.services.outputIsTTY === true; + + if (isClientExposedKey(key)) { + this.services.ux.print(styled(clientExposedWarning(key), 'yellow', colour)); + } + + const listed = await this.services.api.secrets.list(scope); + const exists = listed.some((secret) => secret.key === key); + const value = this.services.isTTY ? await askSecret(this.services.ux, `Value for ${key}`) : await this.readStdin(); + + const question = exists + ? `Refresh the secret ${key} in this environment? Its current value will be replaced.` + : `Add the secret ${key} to this environment?`; + + if (!(await this.confirm(question))) { + return 'declined'; + } + + if (exists) { + await this.services.api.secrets.refresh(scope, key, value); + } else { + await this.services.api.secrets.add(scope, key, value); + } + + const outcome = exists ? 'refreshed' : 'added'; + + this.services.ux.print(styled(`āœ” Secret ${key} ${outcome}.`, 'green', colour)); + + return outcome; + } +} diff --git a/src/secrets/secrets.value.test.ts b/src/secrets/secrets.value.test.ts new file mode 100644 index 00000000..c3cf44f7 --- /dev/null +++ b/src/secrets/secrets.value.test.ts @@ -0,0 +1,56 @@ +import { randomUUID } from 'node:crypto'; +import { Readable } from 'node:stream'; + +import { EXIT_RUNTIME } from '../core/constants'; +import { NoValueError, STDIN_TIMEOUT_MS, readSecretValue } from './secrets.value'; + +function hanging(): AsyncIterable { + return { + [Symbol.asyncIterator]: () => ({ next: () => new Promise>(() => undefined) }), + }; +} + +describe('reading a secret value from stdin', () => { + it('bounds the read at thirty seconds', () => { + expect(STDIN_TIMEOUT_MS).toBe(30000); + }); + + it('joins every chunk and drops one trailing line break', async () => { + const value = randomUUID(); + + await expect( + readSecretValue(Readable.from([value.slice(0, 10), Buffer.from(`${value.slice(10)}\n`)])), + ).resolves.toBe(value); + await expect(readSecretValue(Readable.from([`${value}\r\n`]))).resolves.toBe(value); + await expect(readSecretValue(Readable.from([`${value}\n\n`]))).resolves.toBe(`${value}\n`); + }); + + it('keeps the whitespace inside and around the value', async () => { + await expect(readSecretValue(Readable.from([' a b ']))).resolves.toBe(' a b '); + }); + + it.each([[[]], [['']], [['\n']], [['\r\n']]])('raises the no-value error for %p', async (chunks) => { + const failure = await readSecretValue(Readable.from(chunks)).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(NoValueError); + expect((failure as NoValueError).exitCode).toBe(EXIT_RUNTIME); + expect((failure as NoValueError).message).toBe( + 'No value received on stdin; pipe the value in, for example: ' + + 'printf %s "$TOKEN" | csdx launch:secrets:set --key API_TOKEN, ' + + 'or run the command in a terminal to enter it at the prompt.', + ); + }); + + it('gives up on a stream that never ends and says no value was received', async () => { + const failure = await readSecretValue(hanging(), 20).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(NoValueError); + expect((failure as NoValueError).message).toContain('No value received on stdin'); + }); + + it('propagates a stream that fails', async () => { + const broken = new Readable({ read: () => broken.destroy(new Error('stdin failed')) }); + + await expect(readSecretValue(broken)).rejects.toThrow('stdin failed'); + }); +}); diff --git a/src/secrets/secrets.value.ts b/src/secrets/secrets.value.ts new file mode 100644 index 00000000..d3fcc37c --- /dev/null +++ b/src/secrets/secrets.value.ts @@ -0,0 +1,46 @@ +import { EXIT_RUNTIME } from '../core/constants'; +import { LaunchError } from '../core/errors'; +import { readPipedInput } from '../core/piped-input'; + +export const STDIN_TIMEOUT_MS = 30000; + +export class NoValueError extends LaunchError { + readonly exitCode = EXIT_RUNTIME; + + constructor() { + super( + 'No value received on stdin; pipe the value in, for example: ' + + 'printf %s "$TOKEN" | csdx launch:secrets:set --key API_TOKEN, ' + + 'or run the command in a terminal to enter it at the prompt.', + ); + this.name = 'NoValueError'; + } +} + +function silence(timeoutMs: number): { timeout: Promise; stop: () => void } { + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new NoValueError()), timeoutMs); + }); + + return { timeout, stop: () => clearTimeout(timer) }; +} + +export async function readSecretValue( + stream: AsyncIterable = process.stdin, + timeoutMs: number = STDIN_TIMEOUT_MS, +): Promise { + const { timeout, stop } = silence(timeoutMs); + + try { + const value = (await Promise.race([readPipedInput(stream), timeout])).replace(/\r?\n$/, ''); + + if (value === '') { + throw new NoValueError(); + } + + return value; + } finally { + stop(); + } +} diff --git a/test/integration/secrets-set.test.ts b/test/integration/secrets-set.test.ts new file mode 100644 index 00000000..aa160608 --- /dev/null +++ b/test/integration/secrets-set.test.ts @@ -0,0 +1,396 @@ +import { randomUUID } from 'node:crypto'; +import { Readable } from 'node:stream'; +import { tmpdir } from 'node:os'; + +import { authHandler, configHandler } from '@contentstack/cli-utilities'; +import type { Interfaces } from '@oclif/core'; +import { runCommand } from '@oclif/test'; +import nock from 'nock'; + +import { answerPrompts, onTerminal } from '../support/terminal'; +import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; +import { GENERIC_ARGUMENTS_MESSAGE } from '../../src/secrets/secrets.redact'; +import { projectOwnership } from '../support/project-ownership'; + +const LAUNCH_HUB_URL = 'https://launch-api.integration.test'; +const ORG_UID = 'blt4d9e2a7c1f6b3085'; +const PROJECT_UID = 'a1b2c3d4e5f60718293a4b5c'; +const ENV_UID = 'd4e5f60718293a4b5c6d7e8f'; +const SECRETS_PATH = `/manage/projects/${PROJECT_UID}/environments/${ENV_UID}/secrets`; +const DATA_DIR = tmpdir(); + +const CONFIG: Record = { + authorisationType: 'BASIC', + authtoken: 'test-authtoken', + email: 'cli-user@example.test', + region: { + name: 'integration', + cma: 'https://cma.integration.test', + cda: 'https://cda.integration.test', + uiHost: 'https://app.integration.test', + launchHubUrl: LAUNCH_HUB_URL, + }, +}; + +const SET_BASE = [ + 'launch:secrets:set', + '--org', + ORG_UID, + '--project', + PROJECT_UID, + '--env', + ENV_UID, + '--data-dir', + DATA_DIR, +]; +const SET = [...SET_BASE, '--key', 'API_TOKEN']; +const CONFLICT_CODE = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT'; + +let config: Interfaces.Config; +let unmatched: string[]; +let restoreStdin: (() => void) | undefined; + +function recordUnmatched(): void { + unmatched = []; + nock.emitter.on('no match', (request: { method?: string; path?: string }) => { + unmatched.push(`${request.method ?? 'UNKNOWN'} ${request.path ?? ''}`); + }); +} + +function hub() { + return nock(LAUNCH_HUB_URL) + .matchHeader('x-organization-uid', ORG_UID) + .matchHeader('x-project-uid', PROJECT_UID) + .matchHeader('x-cs-api-version', '1.0'); +} + +function existing(keys: string[]): nock.Scope { + return hub() + .get(SECRETS_PATH) + .reply(200, { secrets: keys.map((key) => ({ key, updatedAt: '2026-09-01T10:00:00.000Z' })), count: keys.length }); +} + +function pipe(text: string): void { + const original = Object.getOwnPropertyDescriptor(process, 'stdin') as PropertyDescriptor; + + Object.defineProperty(process, 'stdin', { value: Readable.from([text]), configurable: true }); + restoreStdin = () => Object.defineProperty(process, 'stdin', original); +} + +describe('integration: launch:secrets:set driven through oclif runCommand', () => { + beforeAll(async () => { + config = await loadCliConfig(); + nock.disableNetConnect(); + }); + + beforeEach(() => { + process.exitCode = 0; + routeConsoleLogToStdout(); + recordUnmatched(); + jest.spyOn(configHandler, 'get').mockImplementation((key: string) => CONFIG[key]); + jest.spyOn(authHandler, 'compareOAuthExpiry').mockResolvedValue(undefined); + projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID).persist(); + }); + + afterEach(() => { + restoreStdin?.(); + restoreStdin = undefined; + process.exitCode = 0; + nock.emitter.removeAllListeners('no match'); + nock.cleanAll(); + }); + + afterAll(() => { + process.exitCode = 0; + nock.enableNetConnect(); + nock.restore(); + }); + + it('T13: adds a piped value after reading the list, with the key and value in the POST body and no prompt', async () => { + const value = randomUUID(); + const sent: unknown[] = []; + const prompts = answerPrompts({}); + pipe(`${value}\n`); + const list = existing([]); + const post = hub() + .post(SECRETS_PATH, (body) => { + sent.push(body); + return true; + }) + .reply(201, { key: 'API_TOKEN', updatedAt: '2026-09-02T10:00:00.000Z' }); + + const { error, stdout } = await runCommand([...SET, '--yes'], config); + + expect(error).toBeUndefined(); + expect(list.isDone()).toBe(true); + expect(post.isDone()).toBe(true); + expect(sent).toEqual([{ key: 'API_TOKEN', value }]); + expect(prompts.messages).toEqual([]); + expect(unmatched).toEqual([]); + expect(stdout).toBe('āœ” Secret API_TOKEN added.\n'); + }); + + it('T14: on a terminal asks for the value then the confirmation, and refreshes with a PUT because the key exists', async () => { + const value = randomUUID(); + const sent: unknown[] = []; + const prompts = answerPrompts({ + 'Value for API_TOKEN': value, + 'Refresh the secret API_TOKEN in this environment? Its current value will be replaced.': true, + }); + existing(['API_TOKEN']); + const put = hub() + .put(`${SECRETS_PATH}/API_TOKEN`, (body) => { + sent.push(body); + return true; + }) + .reply(200, { key: 'API_TOKEN', updatedAt: '2026-09-02T10:00:00.000Z' }); + + const { error, stdout } = await onTerminal(() => runCommand(SET, config)); + + expect(error).toBeUndefined(); + expect(put.isDone()).toBe(true); + expect(sent).toEqual([{ value }]); + expect(prompts.payloads.map((payload) => payload.type)).toEqual(['password', 'confirm']); + expect(prompts.payloads[0]).toMatchObject({ mask: '*' }); + expect(unmatched).toEqual([]); + expect(stdout).toBe('āœ” Secret API_TOKEN refreshed.\n'); + expect(stdout).not.toContain(value); + }); + + it('sends nothing and exits 3 when the confirmation is declined', async () => { + answerPrompts({ 'Value for API_TOKEN': randomUUID(), 'Add the secret API_TOKEN to this environment?': false }); + existing([]); + + const { error, stdout } = await onTerminal(() => runCommand(SET, config)); + + expect(error?.oclif?.exit).toBe(3); + expect(stdout).toBe('Secret not changed.\n'); + expect(unmatched).toEqual([]); + }); + + it('exits 2 naming --yes without a terminal and never sends the POST', async () => { + const value = randomUUID(); + pipe(value); + existing([]); + + const { error, stdout } = await runCommand(SET, config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe( + 'Add the secret API_TOKEN to this environment? Pass --yes to confirm without an interactive terminal.', + ); + expect(error?.message).not.toContain(value); + expect(stdout).not.toContain(value); + expect(unmatched).toEqual([]); + }); + + it('exits 1 saying no value was received on an empty pipe, and sends nothing', async () => { + pipe(''); + existing([]); + + const { error } = await runCommand([...SET, '--yes'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toContain('No value received on stdin'); + expect(unmatched).toEqual([]); + }); + + it('T15: refuses --value as a separate argument without echoing the value or sending anything', async () => { + const value = randomUUID(); + + const { error, stdout } = await runCommand([...SET, '--value', value, '--yes'], config); + + expect(error?.message).toBe('Nonexistent flag: --value\nSee more help with --help'); + expect(error?.oclif?.exit).toBeGreaterThan(0); + expect(`${error?.message}${stdout}`).not.toContain(value); + expect(unmatched).toEqual([]); + }); + + it('T16: refuses --value= without echoing the value or sending anything', async () => { + const value = randomUUID(); + + const { error, stdout } = await runCommand([...SET, `--value=${value}`, '--yes'], config); + + expect(error?.message).toBe('Nonexistent flag: --value\nSee more help with --help'); + expect(error?.oclif?.exit).toBeGreaterThan(0); + expect(`${error?.message}${stdout}`).not.toContain(value); + expect(unmatched).toEqual([]); + }); + + it.each([ + ['before the flags', 2], + ['after --key', 2], + ['after --yes', 2], + ])('refuses a value given as a positional argument %s without echoing it', async (place, exit) => { + const value = randomUUID(); + const argv = { + 'before the flags': [SET[0], value, ...SET.slice(1), '--yes'], + 'after --key': [...SET, value, '--yes'], + 'after --yes': [...SET, '--yes', value], + }[place] as string[]; + + const { error, stdout } = await runCommand(argv, config); + + expect(error?.oclif?.exit).toBe(exit); + expect(`${error?.message}${stdout}`).not.toContain(value); + expect(unmatched).toEqual([]); + }); + + it('words an unexpected positional argument with the generic invalid-arguments message', async () => { + const { error } = await runCommand([SET[0], randomUUID(), ...SET.slice(1), '--yes'], config); + + expect(error?.message).toBe(`${GENERIC_ARGUMENTS_MESSAGE}\nSee more help with --help`); + }); + + it('T17: exits 2 naming --key when it is missing, and sends nothing', async () => { + const { error } = await runCommand([...SET_BASE, '--yes'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('Missing required value for --key'); + expect(unmatched).toEqual([]); + }); + + it('exits 2 asking for exactly one key when --key is repeated, and sends nothing', async () => { + const { error } = await runCommand([...SET, '--key', 'OTHER', '--yes'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('Pass exactly one --key.'); + expect(unmatched).toEqual([]); + }); + + it('prints the client-exposed warning for a public prefix and still adds the secret', async () => { + pipe(randomUUID()); + existing([]); + const post = hub().post(SECRETS_PATH).reply(201, { key: 'NEXT_PUBLIC_API_URL' }); + + const { error, stdout } = await runCommand([...SET_BASE, '--key', 'NEXT_PUBLIC_API_URL', '--yes'], config); + + expect(error).toBeUndefined(); + expect(post.isDone()).toBe(true); + expect(stdout).toBe( + 'Warning: NEXT_PUBLIC_API_URL starts with a client-exposed prefix, so its value is inlined into client ' + + 'JavaScript at build time and is visible to anyone who loads your site.\n' + + 'āœ” Secret NEXT_PUBLIC_API_URL added.\n', + ); + }); + + it('T21: exits 1 naming the key when the API answers 409 because a variable already uses it', async () => { + const value = randomUUID(); + pipe(value); + existing([]); + hub() + .post(SECRETS_PATH) + .reply(409, { errors: [{ code: CONFLICT_CODE, message: 'raw conflict' }], status: 409 }); + + const { error, stdout } = await runCommand([...SET_BASE, '--key', 'DB_URL', '--yes'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('The key DB_URL is already used by a variable or a secret in this environment.'); + expect(`${error?.message}${stdout}`).not.toContain(value); + }); + + it('exits 1 with the concurrent-update advice on a 409 CONCURRENT_UPDATE', async () => { + pipe(randomUUID()); + existing([]); + hub() + .post(SECRETS_PATH) + .reply(409, { errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE' }], status: 409 }); + + const { error } = await runCommand([...SET, '--yes'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe( + 'The environment was changed by another request at the same moment. Run the command again.', + ); + }); + + it('exits 1 with the multi-line message on a 400 and never echoes the lines', async () => { + pipe('line1\nline2'); + existing([]); + hub() + .post(SECRETS_PATH) + .reply(400, { errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.VALUE.MULTILINE' }], status: 400 }); + + const { error, stdout } = await runCommand([...SET, '--yes'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('Invalid value: a secret value cannot contain line breaks.'); + expect(`${error?.message}${stdout}`).not.toContain('line1'); + }); + + it('exits 1 with the invalid-key message on a 400 key validation code', async () => { + pipe(randomUUID()); + existing([]); + hub() + .post(SECRETS_PATH) + .reply(400, { + errors: [{ key: { code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.TOO_LONG', message: 'Bad request' } }], + status: 400, + }); + + const { error } = await runCommand([...SET, '--yes'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('Invalid key: the key is too long.'); + }); + + it('exits 1 with the permission message on a 403 from the list, before asking for a value', async () => { + const prompts = answerPrompts({}); + hub() + .get(SECRETS_PATH) + .reply(403, { errors: [{ code: 'launch.AUTH.FORBIDDEN', message: 'raw' }], status: 403 }); + + const { error } = await onTerminal(() => runCommand(SET, config)); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('You do not have permission to manage the secrets of this environment.'); + expect(prompts.messages).toEqual([]); + }); + + it('exits 1 naming the secret on a 404 from the refresh', async () => { + pipe(randomUUID()); + existing(['API_TOKEN']); + hub() + .put(`${SECRETS_PATH}/API_TOKEN`) + .reply(404, { errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND' }], status: 404 }); + + const { error } = await runCommand([...SET, '--yes'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('The secret API_TOKEN was not found in this environment.'); + }); + + it('T23: puts the value in no output on success or on a 400, and in none of the console calls', async () => { + const value = randomUUID(); + const logged: string[] = []; + jest.spyOn(console, 'log').mockImplementation((...args: unknown[]) => void logged.push(args.join(' '))); + jest.spyOn(console, 'error').mockImplementation((...args: unknown[]) => void logged.push(args.join(' '))); + pipe(value); + existing([]); + hub().post(SECRETS_PATH).reply(201, { key: 'API_TOKEN', updatedAt: '2026-09-02' }); + + const success = await runCommand([...SET, '--yes'], config); + + restoreStdin?.(); + pipe(value); + existing([]); + hub() + .post(SECRETS_PATH) + .reply(400, { errors: [{ code: 'launch.SOMETHING.NEW', message: 'rejected' }], status: 400 }); + + const failure = await runCommand([...SET, '--yes'], config); + + expect(success.error).toBeUndefined(); + expect(failure.error?.oclif?.exit).toBe(1); + for (const text of [ + success.stdout, + success.stderr, + failure.stdout, + failure.stderr, + failure.error?.message, + ...logged, + ]) { + expect(text ?? '').not.toContain(value); + } + }); +}); From d6c1a2bd01d48c62b169761298328baa493d8f18 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 12:22:10 +0000 Subject: [PATCH 3/4] feat(secrets): add launch:secrets:unset to delete environment secrets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Repeatable --key deletes each secret with a DELETE per key in order, behind the confirm gate; the first failure stops the run, keys already removed keep their success line. Adds SecretsApi.delete and the unset short name. #claude_code# šŸ¤– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EptZEi8nvDRpqxwsFu2SSa --- .talismanrc | 18 +- README.md | 37 +++- package.json | 1 + src/commands/launch/secrets/unset.test.ts | 145 ++++++++++++++ src/commands/launch/secrets/unset.ts | 48 +++++ src/secrets/secrets.api.test.ts | 39 ++++ src/secrets/secrets.api.ts | 12 ++ src/secrets/secrets.unset.test.ts | 106 +++++++++++ src/secrets/secrets.unset.ts | 35 ++++ test/integration/secrets-unset.test.ts | 219 ++++++++++++++++++++++ 10 files changed, 653 insertions(+), 7 deletions(-) create mode 100644 src/commands/launch/secrets/unset.test.ts create mode 100644 src/commands/launch/secrets/unset.ts create mode 100644 src/secrets/secrets.unset.test.ts create mode 100644 src/secrets/secrets.unset.ts create mode 100644 test/integration/secrets-unset.test.ts diff --git a/.talismanrc b/.talismanrc index 6b6e7700..c073b62c 100644 --- a/.talismanrc +++ b/.talismanrc @@ -330,7 +330,7 @@ fileignoreconfig: - filename: src/commands/launch/env/update.test.ts checksum: 2da219594e7bdd589adc0eff9ff035252a75aaa51dfa20514b18fd3266d7b752 - filename: README.md - checksum: 64778264c69e20d97e59ab6f90acc656fb944e1b37cf8adc04e9745428831996 + checksum: 7dd83c3cc6c7dbd60f5fe1317ff762ccd8b5ab0d62009912ae890af036b5da23 allowed_patterns: - "password-protection" - "-p, --password" @@ -468,17 +468,17 @@ fileignoreconfig: - filename: test/integration/secrets-list.test.ts checksum: dd9bea8e47b53feeda24a6d328947dfc3d11f79ef5a5c78bb1b3245761cebb13 - filename: src/secrets/secrets.api.ts - checksum: dde72f524817a6803dddeffba209354cc4b87a27e030154e03cc2276b00ffe70 + checksum: 526a2571b04092cc17cf185ae4a72ae89b654fbd855a1993f57bdd8c75dcad1b - filename: src/secrets/secrets.presenter.ts checksum: f395458a0858a7ad01831013f0327a20bfa3a7e0c239d0725141c6e5a8f29a10 - filename: package.json - checksum: f7d4888fb27df1a3fcbe155af38f412b8a44d21ad3195eeb0fe976c19346be3d + checksum: 0b379192f02930eddbcfedf5ee44560e901b500a9cec989c85d4ad2d999fe23d - filename: src/commands/launch/secrets/list.ts checksum: 000fec691dd7d82e3f957f4ec4a2b85e59cf59726280c39f4fde43241371cefa - filename: src/commands/launch/secrets/list.test.ts checksum: 61ed1b9851aaeeea325cd06d81cef11d17435c87653d73f49f7c2794dbeda1da - filename: src/secrets/secrets.api.test.ts - checksum: 1bf3c331ff2df44dc29aa3fd96909154b092869c1ddcf743c4dda5598873409d + checksum: 5b8bd33a74b92ec67e13525564b609b837903785598e19d35dcf5045cd7202c1 - filename: src/secrets/secrets.errors.ts checksum: d3c18246c353f0f4feacbf9a55657c05e6f91aa1f1ecf52f65bd1529c7753c0b - filename: src/secrets/secrets.presenter.test.ts @@ -507,4 +507,14 @@ fileignoreconfig: checksum: 3371b523f234175bc45f7e5f7a41ff2d492ada4da15abff200ec300e059e4f30 - filename: test/integration/secrets-set.test.ts checksum: 132510384c8196bbff286292bc77a16e2fee687f0ec4d685a3bac728feb0f020 +- filename: src/secrets/secrets.unset.ts + checksum: 7d8edbbb92a5fed456b46aeb80e9f5771cdc94122943d5e4cce9e8646490607a +- filename: src/secrets/secrets.unset.test.ts + checksum: 19b92b8ce558ce8a9781dd5d7aaa030e866121fd62bc299fc21d9db7d580bcc8 +- filename: src/commands/launch/secrets/unset.ts + checksum: 757c99b0a7205c2e9a47c47f264e7649181d60c41eb7cedab0e4999c71cbdd61 +- filename: src/commands/launch/secrets/unset.test.ts + checksum: 7d14875cfe1a20ef577c3c825c92b7d084acb207d5b435c35e9b521b3f55ee89 +- filename: test/integration/secrets-unset.test.ts + checksum: ee4c835c560ec86fbffff1f73a4b284ff89de962ae03554ffaae98417c700107 version: "1.0" diff --git a/README.md b/README.md index e55e9ef3..0c0d06bc 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ with exit code 2 and name their V2 replacements. `launch:functions:serve` is liv * [`csdx launch:rollback`](#csdx-launchrollback) * [`csdx launch:secrets:list`](#csdx-launchsecretslist) * [`csdx launch:secrets:set`](#csdx-launchsecretsset) +* [`csdx launch:secrets:unset`](#csdx-launchsecretsunset) * [`csdx launch:site:open`](#csdx-launchsiteopen) * [`csdx launch:variables:list`](#csdx-launchvariableslist) * [`csdx launch:variables:set`](#csdx-launchvariablesset) @@ -796,15 +797,15 @@ Add a secret to an environment, or refresh it when the key already exists. The v ``` USAGE - $ csdx launch:secrets:set --key ... [-c ] [-d ] [--org ] [--project ] [--env ] - [-y] + $ csdx launch:secrets:set [-c ] [-d ] [--org ] [--project ] [--env ] [--key + ...] [-y] FLAGS -c, --config= Path to the local '.cs-launch.json' file -d, --data-dir= Current working directory -y, --yes Skip the confirmation prompt --env= Environment name or UID - --key=... (required) Environment variable key, repeatable + --key=... Environment variable key, repeatable --org= Organization UID --project= Project name or UID @@ -820,6 +821,36 @@ EXAMPLES _See code: [src/commands/launch/secrets/set.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/secrets/set.ts)_ +## `csdx launch:secrets:unset` + +Remove secrets from an environment, after asking for confirmation. Repeat --key to remove several; the first failure stops the run and the keys already removed are listed + +``` +USAGE + $ csdx launch:secrets:unset [-c ] [-d ] [--org ] [--project ] [--env ] [--key + ...] [-y] + +FLAGS + -c, --config= Path to the local '.cs-launch.json' file + -d, --data-dir= Current working directory + -y, --yes Skip the confirmation prompt + --env= Environment name or UID + --key=... Environment variable key, repeatable + --org= Organization UID + --project= Project name or UID + +DESCRIPTION + Remove secrets from an environment, after asking for confirmation. Repeat --key to remove several; the first failure + stops the run and the keys already removed are listed + +EXAMPLES + $ csdx launch:secrets:unset --org --project --env --key API_TOKEN + + $ csdx launch:secrets:unset --org --project --env --key API_TOKEN --key DB_URL --yes +``` + +_See code: [src/commands/launch/secrets/unset.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/secrets/unset.ts)_ + ## `csdx launch:site:open` Open an environment's live site in your browser, or print its URL when there is no terminal. On a terminal, when the environment has more than one domain, you choose which one to open; --deployment opens that deployment's preview URL without asking. diff --git a/package.json b/package.json index d7ef9547..764c7067 100644 --- a/package.json +++ b/package.json @@ -188,6 +188,7 @@ "launch:rollback": "LNCH-RLBK", "launch:secrets:list": "LNCH-SEC-LS", "launch:secrets:set": "LNCH-SEC-SET", + "launch:secrets:unset": "LNCH-SEC-UNSET", "launch:site:open": "LNCH-SITE-OPN", "launch:variables:list": "LNCH-VAR-LS", "launch:variables:set": "LNCH-VAR-SET", diff --git a/src/commands/launch/secrets/unset.test.ts b/src/commands/launch/secrets/unset.test.ts new file mode 100644 index 00000000..d630ad87 --- /dev/null +++ b/src/commands/launch/secrets/unset.test.ts @@ -0,0 +1,145 @@ +import { randomUUID } from 'node:crypto'; + +import { LaunchCommand } from '../../../core/launch-command'; +import type { UxLike } from '../../../core/prompt'; +import { GENERIC_ARGUMENTS_MESSAGE } from '../../../secrets/secrets.redact'; +import { SECRETS_ERROR_MESSAGES, SECRETS_FORBIDDEN_MESSAGE } from '../../../secrets/secrets.errors'; +import { LaunchApiError } from '../../../transport/errors'; +import SecretsUnset from './unset'; + +interface Harness { + key?: string[]; + yes?: boolean; + isTTY?: boolean; + answer?: unknown; + failure?: Error; +} + +function commandUnderTest(harness: Harness = {}) { + const lines: string[] = []; + const inquired: Record[] = []; + const deleted: unknown[][] = []; + const ux: UxLike = { + print: (message: string) => { + lines.push(message); + }, + inquire: async (payload: unknown) => { + inquired.push(payload as Record); + return (harness.answer ?? true) as never; + }, + }; + const command = Object.create(SecretsUnset.prototype) as SecretsUnset; + + Object.assign(command, { + ux, + resolved: { + org: 'org1', + project: 'proj1', + env: 'env1', + yes: harness.yes ?? false, + key: harness.key ?? ['API_TOKEN'], + }, + services: { + ux, + isTTY: harness.isTTY ?? true, + outputIsTTY: false, + api: { + secrets: { + delete: async (...args: unknown[]) => { + deleted.push(args); + + if (harness.failure) { + throw harness.failure; + } + }, + }, + }, + }, + }); + + return { command, lines, inquired, deleted }; +} + +const SCOPE = { org: 'org1', project: 'proj1', environment: 'env1' }; + +describe('launch:secrets:unset', () => { + it('deletes every key in order without asking when --yes was passed, with one success line per key', async () => { + const { command, inquired, deleted, lines } = commandUnderTest({ yes: true, key: ['API_TOKEN', 'DB_URL'] }); + + await command.run(); + + expect(inquired).toEqual([]); + expect(deleted).toEqual([ + [SCOPE, 'API_TOKEN'], + [SCOPE, 'DB_URL'], + ]); + expect(lines).toEqual(['āœ” Secret API_TOKEN removed.', 'āœ” Secret DB_URL removed.']); + }); + + it('asks on a terminal and deletes when the answer is yes', async () => { + const { command, inquired, deleted } = commandUnderTest({ answer: true }); + + await command.run(); + + expect(inquired.map((payload) => payload.type)).toEqual(['confirm']); + expect(inquired[0].message).toBe('Remove the secret API_TOKEN from this environment? This cannot be undone.'); + expect(deleted).toEqual([[SCOPE, 'API_TOKEN']]); + }); + + it('says the secrets were not removed and exits 3 without sending when the user declines', async () => { + const { command, lines, deleted } = commandUnderTest({ answer: false }); + + const error = (await command.run().catch((thrown: unknown) => thrown)) as { oclif?: { exit?: number } }; + + expect(error.oclif?.exit).toBe(3); + expect(deleted).toEqual([]); + expect(lines).toEqual(['Secrets not removed.']); + }); + + it('lets an API failure propagate with its own message and the exit code it carries', async () => { + const failure = new LaunchApiError( + 403, + [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.FORBIDDEN' }], + SECRETS_ERROR_MESSAGES, + ); + const { command, lines } = commandUnderTest({ yes: true, failure }); + + const error = (await command.run().catch((thrown: unknown) => thrown)) as LaunchApiError; + + expect(error).toBe(failure); + expect(error.message).toBe(SECRETS_FORBIDDEN_MESSAGE); + expect(error.exitCode).toBe(1); + expect(lines).toEqual([]); + }); + + it('hands every failure on with a --flag=value pair and an unexpected argument scrubbed of the value', async () => { + const handed: Error[] = []; + jest + .spyOn(LaunchCommand.prototype as unknown as { catch: (err: Error) => Promise }, 'catch') + .mockImplementation(async (err) => { + handed.push(err); + return 'handled'; + }); + const { command } = commandUnderTest(); + const value = randomUUID(); + const flagged = new Error(`Nonexistent flag: --value=${value}`); + const positional = new Error(`Unexpected argument: ${value}`); + const call = (err: Error) => (command as unknown as { catch: (err: Error) => Promise }).catch(err); + + const results = [await call(flagged), await call(positional)]; + + expect(results).toEqual(['handled', 'handled']); + expect(handed.map((error) => error.message)).toEqual(['Nonexistent flag: --value', GENERIC_ARGUMENTS_MESSAGE]); + }); + + it('declares org, project, env, a required key and yes, and has no value flag', () => { + expect(SecretsUnset.inputs).toEqual({ + org: { required: true }, + project: { required: true }, + env: { required: true }, + key: { required: true }, + yes: {}, + }); + expect(Object.keys(SecretsUnset.flags).sort()).toEqual(['env', 'key', 'org', 'project', 'yes']); + }); +}); diff --git a/src/commands/launch/secrets/unset.ts b/src/commands/launch/secrets/unset.ts new file mode 100644 index 00000000..082545b2 --- /dev/null +++ b/src/commands/launch/secrets/unset.ts @@ -0,0 +1,48 @@ +import { EXIT_CANCELLED } from '../../../core/constants'; +import { flagsFor, inputs } from '../../../core/inputs'; +import { LaunchCommand } from '../../../core/launch-command'; +import { styled } from '../../../core/style'; +import { withoutArgumentValues } from '../../../secrets/secrets.redact'; +import { SecretRemover } from '../../../secrets/secrets.unset'; + +const unsetInputs = inputs({ + org: { required: true }, + project: { required: true }, + env: { required: true }, + key: { required: true }, + yes: {}, +}); + +export default class SecretsUnset extends LaunchCommand { + static description = + 'Remove secrets from an environment, after asking for confirmation. ' + + 'Repeat --key to remove several; the first failure stops the run and the keys already removed are listed'; + + static examples = [ + '$ csdx launch:secrets:unset --org --project --env --key API_TOKEN', + '$ csdx launch:secrets:unset --org --project --env ' + + '--key API_TOKEN --key DB_URL --yes', + ]; + + static inputs = unsetInputs; + + static flags = flagsFor(unsetInputs); + + async run(): Promise { + const removed = await new SecretRemover(this.services, (question) => this.confirm(question)).remove({ + org: this.resolved.org, + project: this.resolved.project, + environment: this.resolved.env, + keys: this.resolved.key, + }); + + if (!removed) { + this.ux.print(styled('Secrets not removed.', 'yellow', this.services.outputIsTTY === true)); + this.exit(EXIT_CANCELLED); + } + } + + protected async catch(err: Error & { exitCode?: number }): Promise { + return super.catch(withoutArgumentValues(err)); + } +} diff --git a/src/secrets/secrets.api.test.ts b/src/secrets/secrets.api.test.ts index 4024bdda..c2c1a41d 100644 --- a/src/secrets/secrets.api.test.ts +++ b/src/secrets/secrets.api.test.ts @@ -220,3 +220,42 @@ describe('secrets api refresh', () => { expect(second).toBe(missing); }); }); + +describe('secrets api delete', () => { + it('deletes the secret named in the path under the scope headers, with the key wording and no body', async () => { + const { client, requests, messages } = fakeRestClient(undefined); + + await new SecretsApi(client).delete(SCOPE, 'API_TOKEN'); + + expect(requests).toEqual([ + { method: 'DELETE', path: `${LIST_PATH}/API_TOKEN`, orgUid: 'org1', projectUid: 'proj1' }, + ]); + expect(messages).toEqual([secretKeyMessages('API_TOKEN')]); + }); + + it('encodes a key that is not path-safe', async () => { + const { client, requests } = fakeRestClient(undefined); + + await new SecretsApi(client).delete(SCOPE, 'A/B ?'); + + expect(requests[0].path).toBe(`${LIST_PATH}/A%2FB%20%3F`); + }); + + it('rewords a 403 and passes a 404 that names the key through unchanged', async () => { + const missing = new LaunchApiError( + 404, + [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND' }], + secretKeyMessages('GONE'), + ); + const forbidden = new LaunchApiError(403, [{ code: 'launch.X', message: 'raw' }]); + + const first = await new SecretsApi(failingRestClient(forbidden)).delete(SCOPE, 'GONE').catch((e: unknown) => e); + const second = await new SecretsApi(failingRestClient(missing)).delete(SCOPE, 'GONE').catch((e: unknown) => e); + + expect((first as LaunchApiError).message).toBe( + 'You do not have permission to manage the secrets of this environment.', + ); + expect(second).toBe(missing); + expect((second as LaunchApiError).message).toBe('The secret GONE was not found in this environment.'); + }); +}); diff --git a/src/secrets/secrets.api.ts b/src/secrets/secrets.api.ts index ea658319..3ae209c0 100644 --- a/src/secrets/secrets.api.ts +++ b/src/secrets/secrets.api.ts @@ -72,4 +72,16 @@ export class SecretsApi { return secretOf(response)[0] ?? {}; } + + async delete(params: SecretsParams, key: string): Promise { + await this.request( + { + method: 'DELETE', + path: `${secretsPath(params)}/${encodeURIComponent(key)}`, + orgUid: params.org, + projectUid: params.project, + }, + secretKeyMessages(key), + ); + } } diff --git a/src/secrets/secrets.unset.test.ts b/src/secrets/secrets.unset.test.ts new file mode 100644 index 00000000..99e45acc --- /dev/null +++ b/src/secrets/secrets.unset.test.ts @@ -0,0 +1,106 @@ +import type { ServiceContext } from '../core/service-context'; +import { LaunchApiError } from '../transport/errors'; +import { SecretRemover } from './secrets.unset'; + +const REQUEST = { org: 'org1', project: 'proj1', environment: 'env1', keys: ['API_TOKEN'] }; +const SCOPE = { org: 'org1', project: 'proj1', environment: 'env1' }; + +interface Harness { + confirmed?: boolean; + failOn?: string; + failure?: Error; +} + +function removerUnderTest(harness: Harness = {}) { + const calls: string[] = []; + const lines: string[] = []; + const questions: string[] = []; + const deleted: unknown[][] = []; + const services = { + outputIsTTY: false, + ux: { + print: (line: string) => { + calls.push('print'); + lines.push(line); + }, + }, + api: { + secrets: { + delete: async (...args: unknown[]) => { + calls.push(`delete ${String(args[1])}`); + deleted.push(args); + + if (args[1] === harness.failOn) { + throw harness.failure; + } + }, + }, + }, + } as unknown as ServiceContext; + const confirm = async (question: string) => { + calls.push('confirm'); + questions.push(question); + return harness.confirmed ?? true; + }; + + return { remover: new SecretRemover(services, confirm), calls, lines, questions, deleted }; +} + +describe('SecretRemover', () => { + it('confirms once before the first delete, deletes each key in order and prints one line per key', async () => { + const { remover, calls, lines, questions, deleted } = removerUnderTest(); + + const removed = await remover.remove({ ...REQUEST, keys: ['API_TOKEN', 'DB_URL'] }); + + expect(removed).toBe(true); + expect(questions).toEqual(['Remove the secrets API_TOKEN, DB_URL from this environment? This cannot be undone.']); + expect(deleted).toEqual([ + [SCOPE, 'API_TOKEN'], + [SCOPE, 'DB_URL'], + ]); + expect(calls).toEqual(['confirm', 'delete API_TOKEN', 'print', 'delete DB_URL', 'print']); + expect(lines).toEqual(['āœ” Secret API_TOKEN removed.', 'āœ” Secret DB_URL removed.']); + }); + + it('sends nothing and prints nothing when the confirmation is declined', async () => { + const { remover, calls, lines, deleted } = removerUnderTest({ confirmed: false }); + + const removed = await remover.remove(REQUEST); + + expect(removed).toBe(false); + expect(calls).toEqual(['confirm']); + expect(deleted).toEqual([]); + expect(lines).toEqual([]); + }); + + it('words the question for a single key in the singular', async () => { + const { remover, questions } = removerUnderTest(); + + await remover.remove(REQUEST); + + expect(questions).toEqual(['Remove the secret API_TOKEN from this environment? This cannot be undone.']); + }); + + it('deletes a key given twice once', async () => { + const { remover, deleted, questions } = removerUnderTest(); + + await remover.remove({ ...REQUEST, keys: ['API_TOKEN', 'DB_URL', 'API_TOKEN'] }); + + expect(deleted).toEqual([ + [SCOPE, 'API_TOKEN'], + [SCOPE, 'DB_URL'], + ]); + expect(questions).toEqual(['Remove the secrets API_TOKEN, DB_URL from this environment? This cannot be undone.']); + }); + + it('stops at the first failure, keeps the lines for the keys already removed and attempts no later key', async () => { + const failure = new LaunchApiError(404, [{ code: 'x' }]); + const { remover, calls, lines } = removerUnderTest({ failOn: 'B', failure }); + + const thrown = await remover.remove({ ...REQUEST, keys: ['A', 'B', 'C'] }).catch((error: unknown) => error); + + expect(thrown).toBe(failure); + expect(calls).toEqual(['confirm', 'delete A', 'print', 'delete B']); + expect(lines).toEqual(['āœ” Secret A removed.']); + }); +}); diff --git a/src/secrets/secrets.unset.ts b/src/secrets/secrets.unset.ts new file mode 100644 index 00000000..662b0863 --- /dev/null +++ b/src/secrets/secrets.unset.ts @@ -0,0 +1,35 @@ +import type { ServiceContext } from '../core/service-context'; +import { styled } from '../core/style'; +import type { SecretsParams } from './types'; + +export interface RemoveSecretsRequest extends SecretsParams { + keys: string[]; +} + +export type Confirm = (question: string) => Promise; + +export class SecretRemover { + constructor( + private readonly services: ServiceContext, + private readonly confirm: Confirm, + ) {} + + async remove({ keys: requested, ...scope }: RemoveSecretsRequest): Promise { + const keys = [...new Set(requested)]; + const colour = this.services.outputIsTTY === true; + const subject = keys.length === 1 ? 'secret' : 'secrets'; + + if ( + !(await this.confirm(`Remove the ${subject} ${keys.join(', ')} from this environment? This cannot be undone.`)) + ) { + return false; + } + + for (const key of keys) { + await this.services.api.secrets.delete(scope, key); + this.services.ux.print(styled(`āœ” Secret ${key} removed.`, 'green', colour)); + } + + return true; + } +} diff --git a/test/integration/secrets-unset.test.ts b/test/integration/secrets-unset.test.ts new file mode 100644 index 00000000..44b73ed1 --- /dev/null +++ b/test/integration/secrets-unset.test.ts @@ -0,0 +1,219 @@ +import { randomUUID } from 'node:crypto'; +import { tmpdir } from 'node:os'; + +import { authHandler, configHandler } from '@contentstack/cli-utilities'; +import type { Interfaces } from '@oclif/core'; +import { runCommand } from '@oclif/test'; +import nock from 'nock'; + +import { answerPrompts, onTerminal } from '../support/terminal'; +import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; +import { GENERIC_ARGUMENTS_MESSAGE } from '../../src/secrets/secrets.redact'; +import { projectOwnership } from '../support/project-ownership'; + +const LAUNCH_HUB_URL = 'https://launch-api.integration.test'; +const ORG_UID = 'blt4d9e2a7c1f6b3085'; +const PROJECT_UID = 'a1b2c3d4e5f60718293a4b5c'; +const ENV_UID = 'd4e5f60718293a4b5c6d7e8f'; +const SECRETS_PATH = `/manage/projects/${PROJECT_UID}/environments/${ENV_UID}/secrets`; +const DATA_DIR = tmpdir(); + +const CONFIG: Record = { + authorisationType: 'BASIC', + authtoken: 'test-authtoken', + email: 'cli-user@example.test', + region: { + name: 'integration', + cma: 'https://cma.integration.test', + cda: 'https://cda.integration.test', + uiHost: 'https://app.integration.test', + launchHubUrl: LAUNCH_HUB_URL, + }, +}; + +const UNSET_BASE = [ + 'launch:secrets:unset', + '--org', + ORG_UID, + '--project', + PROJECT_UID, + '--env', + ENV_UID, + '--data-dir', + DATA_DIR, +]; +const UNSET = [...UNSET_BASE, '--key', 'API_TOKEN']; +const NOT_FOUND_CODE = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND'; + +let config: Interfaces.Config; +let unmatched: string[]; + +function recordUnmatched(): void { + unmatched = []; + nock.emitter.on('no match', (request: { method?: string; path?: string }) => { + unmatched.push(`${request.method ?? 'UNKNOWN'} ${request.path ?? ''}`); + }); +} + +function hub() { + return nock(LAUNCH_HUB_URL) + .matchHeader('x-organization-uid', ORG_UID) + .matchHeader('x-project-uid', PROJECT_UID) + .matchHeader('x-cs-api-version', '1.0'); +} + +describe('integration: launch:secrets:unset driven through oclif runCommand', () => { + beforeAll(async () => { + config = await loadCliConfig(); + nock.disableNetConnect(); + }); + + beforeEach(() => { + process.exitCode = 0; + routeConsoleLogToStdout(); + recordUnmatched(); + jest.spyOn(configHandler, 'get').mockImplementation((key: string) => CONFIG[key]); + jest.spyOn(authHandler, 'compareOAuthExpiry').mockResolvedValue(undefined); + projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID).persist(); + }); + + afterEach(() => { + process.exitCode = 0; + nock.emitter.removeAllListeners('no match'); + nock.cleanAll(); + }); + + afterAll(() => { + process.exitCode = 0; + nock.enableNetConnect(); + nock.restore(); + }); + + it('T26: deletes two keys in order with --yes, one DELETE each, no body, no prompt and one line per key', async () => { + const order: string[] = []; + const prompts = answerPrompts({}); + const first = hub() + .delete(`${SECRETS_PATH}/API_TOKEN`) + .reply(204, () => { + order.push('API_TOKEN'); + }); + const second = hub() + .delete(`${SECRETS_PATH}/DB_URL`) + .reply(204, () => { + order.push('DB_URL'); + }); + + const { error, stdout } = await runCommand([...UNSET, '--key', 'DB_URL', '--yes'], config); + + expect(error).toBeUndefined(); + expect(first.isDone()).toBe(true); + expect(second.isDone()).toBe(true); + expect(order).toEqual(['API_TOKEN', 'DB_URL']); + expect(prompts.messages).toEqual([]); + expect(unmatched).toEqual([]); + expect(stdout).toBe('āœ” Secret API_TOKEN removed.\nāœ” Secret DB_URL removed.\n'); + }); + + it('percent-encodes a key that is not path-safe in the DELETE path', async () => { + const delete1 = hub().delete(`${SECRETS_PATH}/A%2FB`).reply(204); + + const { error } = await runCommand([...UNSET_BASE, '--key', 'A/B', '--yes'], config); + + expect(error).toBeUndefined(); + expect(delete1.isDone()).toBe(true); + expect(unmatched).toEqual([]); + }); + + it('asks on a terminal and deletes after a yes', async () => { + const prompts = answerPrompts({ + 'Remove the secret API_TOKEN from this environment? This cannot be undone.': true, + }); + const del = hub().delete(`${SECRETS_PATH}/API_TOKEN`).reply(204); + + const { error, stdout } = await onTerminal(() => runCommand(UNSET, config)); + + expect(error).toBeUndefined(); + expect(del.isDone()).toBe(true); + expect(prompts.payloads.map((payload) => payload.type)).toEqual(['confirm']); + expect(stdout).toBe('āœ” Secret API_TOKEN removed.\n'); + }); + + it('sends nothing and exits 3 when the confirmation is declined', async () => { + answerPrompts({ 'Remove the secret API_TOKEN from this environment? This cannot be undone.': false }); + + const { error, stdout } = await onTerminal(() => runCommand(UNSET, config)); + + expect(error?.oclif?.exit).toBe(3); + expect(stdout).toBe('Secrets not removed.\n'); + expect(unmatched).toEqual([]); + }); + + it('exits 2 naming --yes without a terminal and never sends the DELETE', async () => { + const { error } = await runCommand(UNSET, config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe( + 'Remove the secret API_TOKEN from this environment? This cannot be undone. ' + + 'Pass --yes to confirm without an interactive terminal.', + ); + expect(unmatched).toEqual([]); + }); + + it('T27: exits 1 naming the missing key on a 404 and stops before the keys after it', async () => { + hub().delete(`${SECRETS_PATH}/API_TOKEN`).reply(204); + hub() + .delete(`${SECRETS_PATH}/MISSING_KEY`) + .reply(404, { errors: [{ code: NOT_FOUND_CODE, message: 'raw' }], status: 404 }); + + const { error, stdout } = await runCommand( + [...UNSET, '--key', 'MISSING_KEY', '--key', 'NEVER_REACHED', '--yes'], + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('The secret MISSING_KEY was not found in this environment.'); + expect(stdout).toBe('āœ” Secret API_TOKEN removed.\n'); + expect(unmatched).toEqual([]); + }); + + it('exits 1 with the permission message on a 403', async () => { + hub() + .delete(`${SECRETS_PATH}/API_TOKEN`) + .reply(403, { errors: [{ code: 'launch.AUTH.FORBIDDEN', message: 'raw' }], status: 403 }); + + const { error, stdout } = await runCommand([...UNSET, '--yes'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('You do not have permission to manage the secrets of this environment.'); + expect(stdout).toBe(''); + }); + + it('T28: exits 2 naming --key when it is missing, and sends nothing', async () => { + const { error } = await runCommand([...UNSET_BASE, '--yes'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('Missing required value for --key'); + expect(unmatched).toEqual([]); + }); + + it('refuses --value as an unknown flag and does not echo it or send anything', async () => { + const value = randomUUID(); + + const { error, stdout } = await runCommand([...UNSET, `--value=${value}`, '--yes'], config); + + expect(error?.message).toBe('Nonexistent flag: --value\nSee more help with --help'); + expect(error?.oclif?.exit).toBeGreaterThan(0); + expect(`${error?.message}${stdout}`).not.toContain(value); + expect(unmatched).toEqual([]); + }); + + it('words a positional argument with the generic invalid-arguments message without echoing it', async () => { + const value = randomUUID(); + + const { error, stdout } = await runCommand([UNSET[0], value, ...UNSET.slice(1), '--yes'], config); + + expect(error?.message).toBe(`${GENERIC_ARGUMENTS_MESSAGE}\nSee more help with --help`); + expect(`${error?.message}${stdout}`).not.toContain(value); + expect(unmatched).toEqual([]); + }); +}); From e247ea3e8c7468998ef1486fc350c6c8dc5c4d7f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 12:25:38 +0000 Subject: [PATCH 4/4] chore(talisman): refresh checksums for src/resources.test.ts, src/secrets/secrets.redact.ts, src/secrets/secrets.redact.test.ts, test/guards/layering.test.ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four .talismanrc checksums were stale against the committed content of files changed on this branch; replaced only those values with fresh Talisman checksums. #claude_code# šŸ¤– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EptZEi8nvDRpqxwsFu2SSa --- .talismanrc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.talismanrc b/.talismanrc index c073b62c..80a9f3fb 100644 --- a/.talismanrc +++ b/.talismanrc @@ -229,7 +229,7 @@ fileignoreconfig: allowed_patterns: - "FlagKey" - filename: src/resources.test.ts - checksum: 05a4c54c69bfff1042fa0df038c46881830e3d7014777c87919c5c0739974f45 + checksum: b82772dc9691aa93b12766ecfe8eeb64c3adb1639e86ae3fc0a2321a5164c32f allowed_patterns: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" @@ -258,7 +258,7 @@ fileignoreconfig: - filename: src/git/local-repository.ts checksum: b9091ed135dfebdf590a5412bbfba2b2f96d4a177cf944a20909b93405268e9f - filename: test/guards/layering.test.ts - checksum: fa3a7ee934a03ff88618d02722273ea913b0fc1728d177e86a71d9e69236aa71 + checksum: 3e27ec0322a9966750ce641410172553e2e96c2100db69927f07bac3f1023827 - filename: src/commands/launch/projects/create.test.ts checksum: 9c40b4b6ed4f7d678ecb921a71f5af7284cd685c1337f47144456ae43a38b1ad - filename: src/commands/launch/projects/delete.test.ts @@ -494,9 +494,9 @@ fileignoreconfig: - filename: src/secrets/secrets.exposure.ts checksum: b4b287be92004dfecf60dd586d9298b0345080c1f6085189470b692987b6fecd - filename: src/secrets/secrets.redact.test.ts - checksum: 38e5bcb49fc56c3ab7aeb107925806be54f26770a3d17b72fd99cbd70711baa4 + checksum: 9a59750943e8217d14d98867793b7f1d1389cc159bb6e36cb8b52ab36e3a4669 - filename: src/secrets/secrets.redact.ts - checksum: 9b3a512c54b38775b17eaac97ce980168a7e608746953c771abf955dfefa680d + checksum: 0b16cc9a526c56890a5cd77e2d247ecfae79aca32bd0efa9fae4eede9835ff51 - filename: src/secrets/secrets.set.test.ts checksum: ef91bd478f158f993b961483ee9d6b683b3b725fc7f7b63c840680b64ce3df3d - filename: src/secrets/secrets.set.ts