From f643c2c730e4dfc1410b9478bae87ae6d5fba5c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 06:18:40 +0000 Subject: [PATCH 1/3] refactor(secrets): bring back the secrets API, errors and rules that --secret reuses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restores the parts of the reverted secrets module that the variables commands build on: SecretsApi (list and remove), the secret error wording, the key rules, the secret input pieces, the glued-value test helper, the secrets entry in the api surface and its layering edge. None of the launch:secrets commands come back. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 23 ++- src/core/secret-input.test.ts | 233 ++++++++++++++++++++++ src/core/secret-input.ts | 146 ++++++++++++++ src/resources.test.ts | 20 ++ src/resources.ts | 3 + src/secrets/secret.rules.test.ts | 28 +++ src/secrets/secret.rules.ts | 13 ++ src/secrets/secrets.api.test.ts | 220 ++++++++++++++++++++ src/secrets/secrets.api.ts | 63 ++++++ src/secrets/secrets.errors.test.ts | 310 +++++++++++++++++++++++++++++ src/secrets/secrets.errors.ts | 98 +++++++++ src/secrets/types.ts | 10 + test/guards/layering.test.ts | 1 + test/support/glued-value.ts | 5 + 14 files changed, 1171 insertions(+), 2 deletions(-) create mode 100644 src/core/secret-input.test.ts create mode 100644 src/core/secret-input.ts create mode 100644 src/secrets/secret.rules.test.ts create mode 100644 src/secrets/secret.rules.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.test.ts create mode 100644 src/secrets/secrets.errors.ts create mode 100644 src/secrets/types.ts create mode 100644 test/support/glued-value.ts diff --git a/.talismanrc b/.talismanrc index 278b95a3..af6ec8f0 100644 --- a/.talismanrc +++ b/.talismanrc @@ -231,10 +231,11 @@ fileignoreconfig: allowed_patterns: - "FlagKey" - filename: src/resources.ts + checksum: 527cbaf7a41201c1b739f635b309c48d1bf5cff87d0643975ede990612ba6d51 allowed_patterns: - "FlagKey" - filename: src/resources.test.ts - checksum: 4574756938e66ba1f2379c096bef5c50947cc60059c7dd9615c0f5104f8ac775 + checksum: 6c2a0938d406767bbc80890aece988fbef1b01f809bd4b488403946aaef2ad37 allowed_patterns: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" @@ -260,7 +261,7 @@ fileignoreconfig: - filename: src/git/local-repository.ts checksum: b9091ed135dfebdf590a5412bbfba2b2f96d4a177cf944a20909b93405268e9f - filename: test/guards/layering.test.ts - checksum: e75b5dbe065e8061cba9c92d7b27ed0297e8ec2aace7beda6657ac9767d77040 + checksum: 7bac022f4db5bd85e05cc8949bd60a90ff53edeee9cc9246fe7bf9124d8356cf - filename: src/commands/launch/projects/create.test.ts checksum: fc7097703f1068e125596daebf6db539ed15643f75e1d240da8e059b4fe5e8a4 - filename: src/commands/launch/projects/delete.test.ts @@ -491,4 +492,22 @@ fileignoreconfig: checksum: b71ca5a072dc5a1ecc18ba9f2460fe33285404a7e10c19d454c0697d0fc91d3d - filename: src/variables/variable.files.ts checksum: 2a8df02d571a14f88fc9127eef0359dbbf5e8c61331466bb22143dfd4745d7ce +- filename: src/secrets/secrets.api.ts + checksum: 97726c06d37466fc18eddf8581e814ca9f981af507cb31b8065a4fe6e89ffc6d +- filename: src/secrets/secret.rules.test.ts + checksum: 97684adae48270c9b8d06292d622c654138351d5db7c76e6a033da70a9b0e0be +- filename: src/secrets/secret.rules.ts + checksum: 1b80dd54bd4ace1b312175c0a461e0c9faf6bbb4bc6963b2b41cf1b82b64236b +- filename: src/secrets/types.ts + checksum: 4d146539c1e02afb6d1bd6eb5ccd04a53c387802daeac6d6e2eafe7dbb43a322 +- filename: src/secrets/secrets.errors.ts + checksum: ecdd6bf2233cf14312238aca6d8863a4621641b3ed465c0dd0c49e93c5b345e9 +- filename: src/core/secret-input.ts + checksum: 72b3b0d121ad9e0fc0ef84dc2a85fe90f308835eabadf013732e2e71ffaaf9ab +- filename: src/secrets/secrets.api.test.ts + checksum: 0490d8a5bc12139a44503cf92f4568ca45f1de8a36d78cd90791d76ead1dab93 +- filename: src/core/secret-input.test.ts + checksum: e9b9179635cc4848923d37c153eb1515ca260f4bf8d92e326709c749315c3d26 +- filename: src/secrets/secrets.errors.test.ts + checksum: c116485896375f3317e1d1e57bf9f3ccfdbb3ccbe759eff4ac1c3bf79cc19a89 version: "1.0" diff --git a/src/core/secret-input.test.ts b/src/core/secret-input.test.ts new file mode 100644 index 00000000..dc76606a --- /dev/null +++ b/src/core/secret-input.test.ts @@ -0,0 +1,233 @@ +import { randomUUID } from 'node:crypto'; +import { Readable } from 'node:stream'; + +import { UsageError } from './errors'; +import type { SecretValueIo } from './secret-input'; +import { + CLIENT_EXPOSED_PREFIXES, + DEFAULT_SECRET_IO, + STDIN_TIMEOUT_MS, + RemovalFailedError, + SecretInputTimeoutError, + SecretsRemovalStoppedError, + clientExposedPrefix, + clientExposedWarning, + emptyValueError, + readWithin, +} from './secret-input'; + +function ioOf(read: () => Promise, stdinTimeoutMs = 1000) { + const closed: string[] = []; + const io: SecretValueIo = { + readStdin: read, + closeStdin: () => { + closed.push('closed'); + }, + stdinTimeoutMs, + }; + + return { io, closed }; +} + +describe('readWithin', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('answers with what was read and leaves no timer running', async () => { + const { io, closed } = ioOf(async () => 'abc'); + + await expect(readWithin(io)).resolves.toBe('abc'); + expect(jest.getTimerCount()).toBe(0); + expect(closed).toEqual([]); + }); + + it('propagates a read failure and leaves no timer running', async () => { + const failure = new Error('stdin broke'); + const { io, closed } = ioOf(async () => Promise.reject(failure)); + + await expect(readWithin(io)).rejects.toBe(failure); + expect(jest.getTimerCount()).toBe(0); + expect(closed).toEqual([]); + }); + + it('ends with a timeout error at exactly the limit, not a millisecond before, and closes stdin', async () => { + const { io, closed } = ioOf(() => new Promise(() => undefined), 2500); + const outcome = readWithin(io).catch((error: unknown) => error); + let settled = false; + void outcome.then(() => { + settled = true; + }); + + await jest.advanceTimersByTimeAsync(2499); + expect(settled).toBe(false); + expect(closed).toEqual([]); + + await jest.advanceTimersByTimeAsync(1); + const error = await outcome; + + expect(error).toBeInstanceOf(SecretInputTimeoutError); + expect((error as Error).message).toContain('within 3 seconds'); + expect(closed).toEqual(['closed']); + }); + + it('names one second in the singular when the limit is one', async () => { + const { io } = ioOf(() => new Promise(() => undefined), 1000); + const outcome = readWithin(io).catch((error: unknown) => error); + + await jest.advanceTimersByTimeAsync(1000); + + expect(((await outcome) as Error).message).toContain('within 1 second,'); + }); + + it('words the timeout for a dotenv stream when told the stream is a dotenv', async () => { + const { io } = ioOf(() => new Promise(() => undefined), 1000); + const outcome = readWithin(io, 'dotenv').catch((error: unknown) => error); + + await jest.advanceTimersByTimeAsync(1000); + + expect(await outcome).toEqual(new SecretInputTimeoutError(1, 'dotenv')); + expect(((await outcome) as Error).message).toContain('No dotenv text arrived'); + }); + + it('ignores a read that fails after the timeout has already ended it', async () => { + let fail: (error: Error) => void = () => undefined; + const { io } = ioOf( + () => + new Promise((_resolve, reject) => { + fail = reject; + }), + 10, + ); + const outcome = readWithin(io).catch((error: unknown) => error); + + await jest.advanceTimersByTimeAsync(10); + fail(new Error('premature close')); + await Promise.resolve(); + + expect(await outcome).toBeInstanceOf(SecretInputTimeoutError); + }); +}); + +describe('DEFAULT_SECRET_IO', () => { + it('waits 30 seconds for standard input', () => { + expect(STDIN_TIMEOUT_MS).toBe(30_000); + expect(DEFAULT_SECRET_IO.stdinTimeoutMs).toBe(STDIN_TIMEOUT_MS); + }); + + it('reads the piped stream of the process', async () => { + const value = randomUUID(); + const stream = Readable.from([`${value}\n`]); + const original = Object.getOwnPropertyDescriptor(process, 'stdin'); + + Object.defineProperty(process, 'stdin', { value: stream, configurable: true }); + + try { + await expect(DEFAULT_SECRET_IO.readStdin()).resolves.toBe(`${value}\n`); + } finally { + Object.defineProperty(process, 'stdin', original as PropertyDescriptor); + } + }); + + it('closes the stream of the process by destroying it', () => { + const destroyed: string[] = []; + const original = Object.getOwnPropertyDescriptor(process, 'stdin'); + const stream = { destroy: () => destroyed.push('destroyed') }; + + Object.defineProperty(process, 'stdin', { value: stream, configurable: true }); + + try { + DEFAULT_SECRET_IO.closeStdin(); + } finally { + Object.defineProperty(process, 'stdin', original as PropertyDescriptor); + } + + expect(destroyed).toEqual(['destroyed']); + }); +}); + +describe('CLIENT_EXPOSED_PREFIXES', () => { + it('lists the five public prefixes the story names, in order', () => { + expect([...CLIENT_EXPOSED_PREFIXES]).toEqual(['NEXT_PUBLIC_', 'NUXT_PUBLIC_', 'VITE_', 'GATSBY_', 'PUBLIC_']); + }); +}); + +describe('clientExposedPrefix', () => { + it.each(CLIENT_EXPOSED_PREFIXES.map((prefix) => [prefix]))('finds %s at the start of a key', (prefix) => { + expect(clientExposedPrefix(`${prefix}TOKEN`)).toBe(prefix); + expect(clientExposedPrefix(prefix)).toBe(prefix); + }); + + it.each([ + ['API_TOKEN'], + ['MY_NEXT_PUBLIC_X'], + ['NEXT_PUBLIC'], + ['next_public_x'], + ['VITE'], + ['XPUBLIC_X'], + [''], + ])('finds none in %p', (key) => { + expect(clientExposedPrefix(key)).toBeUndefined(); + }); +}); + +describe('clientExposedWarning', () => { + it.each(CLIENT_EXPOSED_PREFIXES.map((prefix) => [prefix]))( + 'names the key and the prefix and says the value is inlined into client JavaScript at build time for %s', + (prefix) => { + const key = `${prefix}ANALYTICS`; + + expect(clientExposedWarning(key)).toBe( + `Warning: ${key} starts with ${prefix}, so its value is inlined into client JavaScript at build time ` + + 'and is readable by anyone who loads the site. Do not keep a credential under this name.', + ); + }, + ); + + it.each([['API_TOKEN'], ['MY_NEXT_PUBLIC_X']])('is undefined for %s', (key) => { + expect(clientExposedWarning(key)).toBeUndefined(); + }); +}); + +describe('emptyValueError', () => { + it('is a usage error that names the key and says nothing was changed', () => { + const error = emptyValueError('API_TOKEN'); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe('The value for API_TOKEN is empty. A secret needs a non-empty value; nothing was changed.'); + }); +}); + +describe('removal errors', () => { + it('words a combined failure from the cause message, or from the text of a cause that is not an Error', () => { + const fromError = new RemovalFailedError(['A', 'B'], ['C'], new Error('refused')); + const fromText = new RemovalFailedError(['A'], ['C', 'D'], 'plain failure'); + + expect(fromError.exitCode).toBe(1); + expect(fromError.message).toBe( + 'Some keys were not removed. Variables left in place: A, B (refused). Secrets left in place: C.', + ); + expect(fromText.message).toBe( + 'Some keys were not removed. Variables left in place: A (plain failure). Secrets left in place: C, D.', + ); + expect(fromText.cause).toBe('plain failure'); + }); + + it('words a stopped run from the text of a cause that is not an Error', () => { + const stopped = new SecretsRemovalStoppedError({ + removed: [], + failed: ['A'], + notAttempted: ['B'], + cause: 'plain failure', + }); + + expect(stopped.message).toBe( + 'Stopped at secret A: plain failure\nRemoved: none.\nFailed: A.\nNot attempted: B.', + ); + }); +}); diff --git a/src/core/secret-input.ts b/src/core/secret-input.ts new file mode 100644 index 00000000..21061aed --- /dev/null +++ b/src/core/secret-input.ts @@ -0,0 +1,146 @@ +import { EXIT_RUNTIME } from './constants'; +import { LaunchError, UsageError } from './errors'; +import { readPipedInput } from './piped-input'; + +export const STDIN_TIMEOUT_MS = 30_000; + +export const CLIENT_EXPOSED_PREFIXES = ['NEXT_PUBLIC_', 'NUXT_PUBLIC_', 'VITE_', 'GATSBY_', 'PUBLIC_'] as const; + +export type StdinContent = 'value' | 'dotenv'; + +const TIMEOUT_WORDING: Record = { + value: { + arrived: 'No value arrived', + hint: 'Pipe the value in, for example: printf \'%s\' "$TOKEN" | csdx launch:variables:set --secret ', + }, + dotenv: { + arrived: 'No dotenv text arrived', + hint: + 'Pipe KEY=value lines in, for example: printf \'STRIPE_KEY=%s\\n\' "$STRIPE_KEY" | ' + + 'csdx launch:variables:set --secret STRIPE_KEY --dotenv -', + }, +}; + +export class SecretInputTimeoutError extends LaunchError { + readonly exitCode = EXIT_RUNTIME; + + constructor(seconds: number, content: StdinContent = 'value') { + const { arrived, hint } = TIMEOUT_WORDING[content]; + + super( + `${arrived} on standard input within ${seconds} ${seconds === 1 ? 'second' : 'seconds'}, ` + + `so nothing was changed. ${hint}`, + ); + this.name = 'SecretInputTimeoutError'; + } +} + +export interface SecretValueIo { + readStdin(): Promise; + closeStdin(): void; + stdinTimeoutMs: number; +} + +function destroy(stream: { destroy(): unknown }): void { + stream.destroy(); +} + +export const DEFAULT_SECRET_IO: SecretValueIo = { + readStdin: () => readPipedInput(), + closeStdin: () => destroy(process.stdin), + stdinTimeoutMs: STDIN_TIMEOUT_MS, +}; + +const MS_PER_SECOND = 1000; + +export function readWithin(io: SecretValueIo, content: StdinContent = 'value'): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + io.closeStdin(); + reject(new SecretInputTimeoutError(Math.ceil(io.stdinTimeoutMs / MS_PER_SECOND), content)); + }, io.stdinTimeoutMs); + + io.readStdin().then( + (text) => { + clearTimeout(timer); + resolve(text); + }, + (error: unknown) => { + clearTimeout(timer); + reject(error); + }, + ); + }); +} + +export function clientExposedPrefix(key: string): string | undefined { + return CLIENT_EXPOSED_PREFIXES.find((prefix) => key.startsWith(prefix)); +} + +export function clientExposedWarning(key: string): string | undefined { + const prefix = clientExposedPrefix(key); + + return prefix === undefined + ? undefined + : `Warning: ${key} starts with ${prefix}, so its value is inlined into client JavaScript at build time ` + + 'and is readable by anyone who loads the site. Do not keep a credential under this name.'; +} + +export function emptyValueError(key: string): UsageError { + return new UsageError(`The value for ${key} is empty. A secret needs a non-empty value; nothing was changed.`); +} + +export class SecretsNotRemovedError extends LaunchError { + readonly exitCode = EXIT_RUNTIME; + + constructor(keys: string[], total: number) { + super(`${keys.length} of ${total} ${total === 1 ? 'secret was' : 'secrets were'} not removed: ${keys.join(', ')}.`); + this.name = 'SecretsNotRemovedError'; + } +} + +export class RemovalFailedError extends LaunchError { + readonly exitCode = EXIT_RUNTIME; + readonly cause: unknown; + + constructor(variables: string[], secrets: string[], cause: unknown) { + const reason = cause instanceof Error ? cause.message : String(cause); + + super( + 'Some keys were not removed. ' + + `Variables left in place: ${variables.join(', ')} (${reason}). ` + + `Secrets left in place: ${secrets.join(', ')}.`, + ); + this.name = 'RemovalFailedError'; + this.cause = cause; + } +} + +export interface RemovalStop { + removed: string[]; + failed: string[]; + notAttempted: string[]; + cause: unknown; + at?: 'variables'; +} + +function named(keys: string[]): string { + return keys.length === 0 ? 'none' : keys.join(', '); +} + +export class SecretsRemovalStoppedError extends LaunchError { + readonly exitCode = EXIT_RUNTIME; + readonly cause: unknown; + + constructor({ removed, failed, notAttempted, cause, at }: RemovalStop) { + const reason = cause instanceof Error ? cause.message : String(cause); + const where = at === 'variables' ? 'the variables' : `secret ${failed[failed.length - 1]}`; + + super( + `Stopped at ${where}: ${reason}\n` + + `Removed: ${named(removed)}.\nFailed: ${named(failed)}.\nNot attempted: ${named(notAttempted)}.`, + ); + this.name = 'SecretsRemovalStoppedError'; + this.cause = cause; + } +} diff --git a/src/resources.test.ts b/src/resources.test.ts index 5bfc13a4..e5934fd6 100644 --- a/src/resources.test.ts +++ b/src/resources.test.ts @@ -8,6 +8,7 @@ import { EnvironmentsApi } from './environments/environments.api'; import { UploadsApi } from './uploads/uploads.api'; import { CacheApi } from './cache/cache.api'; import { GitApi } from './git/git.api'; +import { SecretsApi } from './secrets/secrets.api'; import { ProjectsApi } from './projects/projects.api'; import type { UxLike } from './core/prompt'; import * as prompt from './projects/project.prompt'; @@ -203,6 +204,7 @@ describe('the api surface', () => { 'liveLogs', 'organizations', 'projects', + 'secrets', 'serverLogs', 'stacks', 'uploads', @@ -218,6 +220,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 () => { @@ -248,6 +251,23 @@ describe('the api surface', () => { expect(sent.manage.map((req) => req.path)).toEqual(['/projects/p1/environments/e1/deployments/d1']); }); + it('reads secrets through the manage client and never through the logs client', async () => { + const sent = { manage: [] as RestRequest[], logs: [] as RestRequest[] }; + const recording = (into: RestRequest[]) => + ({ + request: async (req: RestRequest) => { + into.push(req); + return { secrets: [], count: 0 }; + }, + }) as unknown as RestApiClient; + const api = buildApi(recording(sent.manage), UNUSED_CMA, recording(sent.logs), {} as never); + + await api.secrets.list({ org: 'o1', project: 'p1', environment: 'e1' }); + + expect(sent.manage.map((req) => req.path)).toEqual(['/projects/p1/environments/e1/secrets']); + expect(sent.logs).toEqual([]); + }); + it('T84: opens the live route through the stream client and not through either rest client', async () => { const opened: unknown[] = []; const sent: RestRequest[] = []; diff --git a/src/resources.ts b/src/resources.ts index 51ce079c..0494ea68 100644 --- a/src/resources.ts +++ b/src/resources.ts @@ -21,6 +21,7 @@ import { GitApi } from './git/git.api'; import { OrganizationsApi } from './organizations/organizations.api'; import { UploadsApi } from './uploads/uploads.api'; import { StacksApi } from './stacks/stacks.api'; +import { SecretsApi } from './secrets/secrets.api'; import { VariablesApi } from './variables/variables.api'; import { CacheApi } from './cache/cache.api'; import type { CmaSession } from './transport/cma-client'; @@ -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/secret.rules.test.ts b/src/secrets/secret.rules.test.ts new file mode 100644 index 00000000..5c037f49 --- /dev/null +++ b/src/secrets/secret.rules.test.ts @@ -0,0 +1,28 @@ +import { UsageError } from '../core/errors'; +import { assertSecretKey, invalidKeyError } from './secret.rules'; + +describe('assertSecretKey', () => { + it.each([['.'], ['..']])('refuses %j with a usage error naming the key', (key) => { + const thrown = ((): UsageError | undefined => { + try { + assertSecretKey(key); + } catch (error) { + return error as UsageError; + } + + return undefined; + })(); + + expect(thrown).toBeInstanceOf(UsageError); + expect(thrown?.exitCode).toBe(2); + expect(thrown?.message).toBe(invalidKeyError(key).message); + expect(thrown?.message).toContain(`"${key}"`); + }); + + it.each([['API_TOKEN'], ['...'], ['.env'], ['a.b'], ['a..'], [' . '], ['%2e%2e'], ['a/b'], ['']])( + 'accepts %j', + (key) => { + expect(() => assertSecretKey(key)).not.toThrow(); + }, + ); +}); diff --git a/src/secrets/secret.rules.ts b/src/secrets/secret.rules.ts new file mode 100644 index 00000000..a8f42aa9 --- /dev/null +++ b/src/secrets/secret.rules.ts @@ -0,0 +1,13 @@ +import { UsageError } from '../core/errors'; + +export function invalidKeyError(key: string): UsageError { + return new UsageError( + `"${key}" cannot be used as a secret key: "." and ".." are path segments, not names. Nothing was changed.`, + ); +} + +export function assertSecretKey(key: string): void { + if (key === '.' || key === '..') { + throw invalidKeyError(key); + } +} diff --git a/src/secrets/secrets.api.test.ts b/src/secrets/secrets.api.test.ts new file mode 100644 index 00000000..999b1509 --- /dev/null +++ b/src/secrets/secrets.api.test.ts @@ -0,0 +1,220 @@ +import { randomBytes, randomUUID } from 'node:crypto'; + +import { UsageError } from '../core/errors'; +import { LaunchApiError, parseErrorEnvelope } from '../transport/errors'; +import type { RestApiClient, RestRequest } from '../transport/rest-client'; +import { SECRETS_ERROR_MESSAGES } from './secrets.errors'; +import { SecretsApi, secretsPath } from './secrets.api'; + +const ORG = randomBytes(9).toString('hex'); +const PROJECT = randomBytes(12).toString('hex'); +const ENVIRONMENT = randomBytes(12).toString('hex'); +const SCOPE = { org: ORG, project: PROJECT, environment: ENVIRONMENT }; + +function fakeRestClient(answer: () => Promise) { + const requests: RestRequest[] = []; + const messages: unknown[] = []; + const client = { + request: async (req: RestRequest, errorMessages: unknown) => { + requests.push(req); + messages.push(errorMessages); + return answer(); + }, + } as unknown as RestApiClient; + + return { client, requests, messages }; +} + +describe('secretsPath', () => { + it('addresses the secrets of one environment', () => { + expect(secretsPath(SCOPE)).toBe(`/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets`); + }); + + it('addresses one secret by its key and encodes the key as a single path segment', () => { + expect(secretsPath(SCOPE, 'A/B C?d=1#e%f')).toBe( + `/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets/A%2FB%20C%3Fd%3D1%23e%25f`, + ); + }); + + it.each([['.'], ['..']])('refuses the dot segment %j, which a URL resolves out of the secrets prefix', (key) => { + expect(() => secretsPath(SCOPE, key)).toThrow(UsageError); + expect(() => secretsPath(SCOPE, key)).toThrow(`"${key}"`); + }); + + it('keeps a percent-encoded dot segment inside the prefix, where it stays one literal segment', () => { + const path = secretsPath(SCOPE, '%2e%2e'); + const resolved = new URL(path, 'https://launch.example.test').pathname; + + expect(path).toBe(`/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets/%252e%252e`); + expect(resolved).toBe(path); + expect(resolved.startsWith(`/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets/`)).toBe(true); + }); + + it.each([['API_TOKEN'], ['a.b'], ['...'], ['.env']])('keeps the ordinary key %j inside the prefix after URL resolution', (key) => { + const path = secretsPath(SCOPE, key); + + expect(new URL(path, 'https://launch.example.test').pathname).toBe( + `/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets/${encodeURIComponent(key)}`, + ); + }); + + it('turns a slash in a key into %2F so it cannot open a second segment', () => { + const path = secretsPath(SCOPE, 'a/../b'); + + expect(path).toBe(`/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets/a%2F..%2Fb`); + expect(new URL(path, 'https://launch.example.test').pathname).toBe(path); + }); + + it('keeps an empty key as a segment rather than dropping it', () => { + expect(secretsPath(SCOPE, '')).toBe(`/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets/`); + }); +}); + +describe('SecretsApi.list', () => { + it('reads the secrets with a scoped GET and the secrets wording, keeping only key and updatedAt', async () => { + const leaked = randomUUID(); + const { client, requests, messages } = fakeRestClient(async () => ({ + secrets: [ + { key: 'API_TOKEN', updatedAt: '2026-09-01T10:00:00.000Z', value: leaked, _id: 'x' }, + { key: 'DB_PASSWORD', updatedAt: '2026-09-02T10:00:00.000Z' }, + ], + count: 2, + })); + + const secrets = await new SecretsApi(client).list(SCOPE); + + expect(requests).toEqual([ + { + method: 'GET', + path: `/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets`, + orgUid: ORG, + projectUid: PROJECT, + }, + ]); + expect(messages).toEqual([SECRETS_ERROR_MESSAGES]); + expect(secrets).toEqual([ + { key: 'API_TOKEN', updatedAt: '2026-09-01T10:00:00.000Z' }, + { key: 'DB_PASSWORD', updatedAt: '2026-09-02T10:00:00.000Z' }, + ]); + expect(JSON.stringify(secrets)).not.toContain(leaked); + }); + + it('returns an empty list for a response with no secrets', async () => { + const { client } = fakeRestClient(async () => ({ secrets: [], count: 0 })); + + await expect(new SecretsApi(client).list(SCOPE)).resolves.toEqual([]); + }); + + it.each([ + ['a key that is not text', { key: 7, updatedAt: '2026-09-01' }, { key: undefined, updatedAt: '2026-09-01' }], + ['a blank key', { key: ' ', updatedAt: '2026-09-01' }, { key: undefined, updatedAt: '2026-09-01' }], + ['no updatedAt', { key: 'A' }, { key: 'A', updatedAt: undefined }], + ['an updatedAt that is not text', { key: 'A', updatedAt: 5 }, { key: 'A', updatedAt: undefined }], + ['a blank updatedAt', { key: 'A', updatedAt: ' ' }, { key: 'A', updatedAt: undefined }], + ])('keeps an entry with %s and leaves the missing field undefined', async (_label, entry, expected) => { + const { client } = fakeRestClient(async () => ({ secrets: [entry], count: 1 })); + + await expect(new SecretsApi(client).list(SCOPE)).resolves.toEqual([expected]); + }); + + it.each([[null], ['text'], [3], [[]]])('drops a list entry that is not an object (%p)', async (entry) => { + const { client } = fakeRestClient(async () => ({ secrets: [entry, { key: 'KEPT' }], count: 2 })); + + await expect(new SecretsApi(client).list(SCOPE)).resolves.toEqual([{ key: 'KEPT', updatedAt: undefined }]); + }); + + it.each([[undefined], [null], [{}], [{ secrets: null }], [{ secrets: {} }], [[]], ['text']])( + 'raises a malformed-response error when the answer has no secrets array (%p)', + async (answer) => { + const { client } = fakeRestClient(async () => answer); + + const failure = await new SecretsApi(client).list(SCOPE).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchApiError); + expect((failure as LaunchApiError).message).toBe( + 'Launch returned an unexpected response. Try again; if it keeps happening, update the CLI or contact support.', + ); + }, + ); + + it.each([ + [403, 'Permission is needed to view the secrets of this environment.'], + [404, 'The project or environment was not found.'], + [400, 'The secrets of this environment could not be listed. Try again.'], + ])('rewords a %i from the read in read-context wording', async (status, message) => { + const { client } = fakeRestClient(async () => { + throw parseErrorEnvelope(status, { errors: [{ code: 'launch.X', message: 'raw text' }] }, SECRETS_ERROR_MESSAGES); + }); + + const failure = await new SecretsApi(client).list(SCOPE).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchApiError); + expect((failure as LaunchApiError).status).toBe(status); + expect((failure as LaunchApiError).message).toBe(message); + }); + + it('lets a failure that is not an API error propagate as it is', async () => { + const failure = new Error('socket closed'); + const { client } = fakeRestClient(async () => Promise.reject(failure)); + + await expect(new SecretsApi(client).list(SCOPE)).rejects.toBe(failure); + }); +}); + +describe('SecretsApi.remove', () => { + it('DELETEs the encoded key path with the scope headers, no body and the secrets wording', async () => { + const { client, requests, messages } = fakeRestClient(async () => undefined); + + await expect(new SecretsApi(client).remove({ ...SCOPE, key: 'A/B C' })).resolves.toBeUndefined(); + + expect(requests).toEqual([ + { + method: 'DELETE', + path: `/projects/${PROJECT}/environments/${ENVIRONMENT}/secrets/A%2FB%20C`, + orgUid: ORG, + projectUid: PROJECT, + }, + ]); + expect(requests[0]).not.toHaveProperty('body'); + expect(messages).toEqual([SECRETS_ERROR_MESSAGES]); + }); + + it.each([ + [404, 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND', 'No secret with that key exists in this environment.'], + [404, 'launch.SOMETHING.ELSE', 'The project, the environment or the secret was not found.'], + [403, 'launch.RBAC.FORBIDDEN', 'Permission is needed to change the secrets of this environment.'], + [ + 409, + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE', + "Another change to this environment's variables and secrets landed at the same moment, so nothing was changed. Run the command again.", + ], + ])('words a %i with code %s in write context', async (status, code, message) => { + const { client } = fakeRestClient(async () => { + throw parseErrorEnvelope(status, { errors: [{ code, message: 'raw' }] }, SECRETS_ERROR_MESSAGES); + }); + + const failure = await new SecretsApi(client).remove({ ...SCOPE, key: 'A' }).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchApiError); + expect((failure as LaunchApiError).status).toBe(status); + expect((failure as LaunchApiError).message).toBe(message); + }); + + it('lets a plain failure propagate with its message untouched', async () => { + const { client } = fakeRestClient(async () => Promise.reject(new Error('socket closed'))); + + await expect(new SecretsApi(client).remove({ ...SCOPE, key: 'A' })).rejects.toThrow('socket closed'); + }); +}); + +describe('SecretsApi with a dot-segment key', () => { + it.each([['.'], ['..']])('sends no request to remove the key %j', async (key) => { + const { client, requests } = fakeRestClient(async () => undefined); + const api = new SecretsApi(client); + + const removed = await api.remove({ ...SCOPE, key }).catch((error: unknown) => error); + + expect(removed).toBeInstanceOf(UsageError); + expect(requests).toEqual([]); + }); +}); diff --git a/src/secrets/secrets.api.ts b/src/secrets/secrets.api.ts new file mode 100644 index 00000000..3ee35581 --- /dev/null +++ b/src/secrets/secrets.api.ts @@ -0,0 +1,63 @@ +import { isRecord } from '../core/values'; +import type { EnvironmentParams } from '../environments/environments.api'; +import { assertArray } from '../transport/envelope'; +import type { RestApiClient, RestRequest } from '../transport/rest-client'; +import { assertSecretKey } from './secret.rules'; +import { SECRETS_ERROR_MESSAGES, asReadFailure, asWriteFailure } from './secrets.errors'; +import type { SecretKeyParams, SecretSummary } from './types'; + +export * from './types'; + +export function secretsPath({ project, environment }: EnvironmentParams, key?: string): string { + const base = `/projects/${project}/environments/${environment}/secrets`; + + if (key === undefined) { + return base; + } + + assertSecretKey(key); + + return `${base}/${encodeURIComponent(key)}`; +} + +function textOf(value: unknown): string | undefined { + return typeof value === 'string' && value.trim() !== '' ? value : undefined; +} + +function summaryOf(entry: unknown): SecretSummary[] { + return isRecord(entry) ? [{ key: textOf(entry.key), updatedAt: textOf(entry.updatedAt) }] : []; +} + +export class SecretsApi { + constructor(private readonly client: RestApiClient) {} + + private request(req: RestRequest): Promise { + return this.client.request(req, SECRETS_ERROR_MESSAGES); + } + + async list(params: EnvironmentParams): Promise { + const response = await this.request({ + method: 'GET', + path: secretsPath(params), + orgUid: params.org, + projectUid: params.project, + }).catch((error: unknown) => { + throw asReadFailure(error); + }); + + assertArray(response, 'secrets', 'secret list'); + + return (response as { secrets: unknown[] }).secrets.flatMap(summaryOf); + } + + async remove({ org, project, environment, key }: SecretKeyParams): Promise { + await this.request({ + method: 'DELETE', + path: secretsPath({ org, project, environment }, key), + orgUid: org, + projectUid: project, + }).catch((error: unknown) => { + throw asWriteFailure(error, ''); + }); + } +} diff --git a/src/secrets/secrets.errors.test.ts b/src/secrets/secrets.errors.test.ts new file mode 100644 index 00000000..25be649b --- /dev/null +++ b/src/secrets/secrets.errors.test.ts @@ -0,0 +1,310 @@ +import { randomUUID } from 'node:crypto'; + +import { EXIT_RUNTIME } from '../core/constants'; +import { SessionExpiredError } from '../core/errors'; +import { SecretInputTimeoutError, SecretsNotRemovedError, SecretsRemovalStoppedError } from '../core/secret-input'; +import { LaunchApiError, LaunchNetworkError, parseErrorEnvelope } from '../transport/errors'; +import { SECRETS_ERROR_MESSAGES, asReadFailure, asWriteFailure } from './secrets.errors'; + +const PREFIX = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS'; + +function failure(status: number, body: unknown): LaunchApiError { + return parseErrorEnvelope(status, body, SECRETS_ERROR_MESSAGES); +} + +describe('SECRETS_ERROR_MESSAGES', () => { + it.each([ + [`${PREFIX}.KEY.CONFLICT`, 'A secret or a variable with that key already exists in this environment.'], + [`${PREFIX}.KEY.NOT_FOUND`, 'No secret with that key exists in this environment.'], + [`${PREFIX}.VALUE.MULTILINE`, 'A secret value must be a single line.'], + [ + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE', + "Another change to this environment's variables and secrets landed at the same moment, so nothing was changed. Run the command again.", + ], + ['launch.ENVIRONMENT.NOT_FOUND', 'The project or environment was not found.'], + ['launch.PROJECT.NOT_FOUND', 'The project or environment was not found.'], + ])('words %s in the CLI own words, whatever text the API sent', (code, message) => { + const error = failure(409, { errors: [{ code, message: 'text from the API' }] }); + + expect(error.message).toBe(message); + expect(error.code).toBe(code); + expect(error.exitCode).toBe(EXIT_RUNTIME); + }); +}); + +describe('asReadFailure', () => { + it('passes a failure that is not an API error through untouched', () => { + const error = new Error('socket closed'); + + expect(asReadFailure(error)).toBe(error); + }); + + it.each([ + ['an empty body', {}], + ['an unrelated code', { errors: [{ code: 'launch.UNKNOWN_403', message: 'Forbidden' }] }], + ['no code', { errors: [{ message: 'Forbidden' }] }], + ])('words a 403 as needing permission to view the environment for %s', (_label, body) => { + const error = asReadFailure(failure(403, body)) as LaunchApiError; + + expect(error).toBeInstanceOf(LaunchApiError); + expect(error.status).toBe(403); + expect(error.message).toBe('Permission is needed to view the secrets of this environment.'); + expect(error.exitCode).toBe(EXIT_RUNTIME); + }); + + it.each([ + ['an environment code', { errors: [{ code: 'launch.ENVIRONMENT.NOT_FOUND', message: 'Environment not found.' }] }], + ['a secret key code', { errors: [{ code: `${PREFIX}.KEY.NOT_FOUND`, message: 'Key not found.' }] }], + ['an empty body', {}], + ['no code', { errors: [{ message: 'Not found.' }] }], + ])('words a 404 as a missing project or environment, never as a missing secret, for %s', (_label, body) => { + const error = asReadFailure(failure(404, body)) as LaunchApiError; + + expect(error).toBeInstanceOf(LaunchApiError); + expect(error.status).toBe(404); + expect(error.message).toBe('The project or environment was not found.'); + expect(error.message).not.toContain('secret'); + expect(error.exitCode).toBe(EXIT_RUNTIME); + }); + + it.each([ + ['an empty body', {}], + ['a validation entry', { errors: [{ code: 'launch.ENVIRONMENT.UID.INVALID', message: 'uid echo 123' }] }], + ])('words a 400 as a rejected read without repeating the API text for %s', (_label, body) => { + const error = asReadFailure(failure(400, body)) as LaunchApiError; + + expect(error).toBeInstanceOf(LaunchApiError); + expect(error.status).toBe(400); + expect(error.message).toBe('The secrets of this environment could not be listed. Try again.'); + expect(error.exitCode).toBe(EXIT_RUNTIME); + }); + + it.each([401, 429, 500, 502])('leaves a %i as the API error it already is', (status) => { + const error = failure(status, { errors: [{ code: 'launch.SOMETHING', message: 'text' }] }); + + expect(asReadFailure(error)).toBe(error); + }); +}); + +describe('asWriteFailure', () => { + it.each([ + ['a 409 conflict', 409, `${PREFIX}.KEY.CONFLICT`, 'A secret or a variable with that key already exists in this environment.'], + [ + 'a 409 concurrent update', + 409, + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE', + "Another change to this environment's variables and secrets landed at the same moment, so nothing was changed. Run the command again.", + ], + ['a 400 multiline value', 400, `${PREFIX}.VALUE.MULTILINE`, 'A secret value must be a single line.'], + ['a 404 secret not found', 404, `${PREFIX}.KEY.NOT_FOUND`, 'No secret with that key exists in this environment.'], + ['a 404 environment not found', 404, 'launch.ENVIRONMENT.NOT_FOUND', 'The project or environment was not found.'], + ])('keeps the catalog wording and the code for %s', (_label, status, code, message) => { + const error = asWriteFailure(failure(status, { errors: [{ code, message: 'text from the API' }] }), randomUUID()); + + expect(error).toBeInstanceOf(LaunchApiError); + expect((error as LaunchApiError).status).toBe(status); + expect((error as LaunchApiError).code).toBe(code); + expect((error as LaunchApiError).message).toBe(message); + expect((error as LaunchApiError).exitCode).toBe(EXIT_RUNTIME); + }); + + it.each([ + ['an unrelated code', { errors: [{ code: 'launch.RBAC.FORBIDDEN', message: 'raw forbidden text' }] }], + ['an empty body', {}], + ])('words a 403 as needing permission to change the secrets, not to view them, for %s', (_label, body) => { + const error = asWriteFailure(failure(403, body), randomUUID()) as LaunchApiError; + + expect(error.status).toBe(403); + expect(error.message).toBe('Permission is needed to change the secrets of this environment.'); + expect(error.message).not.toContain('view'); + }); + + it.each([ + ['an unrelated code', { errors: [{ code: 'launch.SOMETHING', message: 'Not found.' }] }], + ['an empty body', {}], + ])('words a 404 with no catalog code as a missing project, environment or secret for %s', (_label, body) => { + const error = asWriteFailure(failure(404, body), randomUUID()) as LaunchApiError; + + expect(error.status).toBe(404); + expect(error.message).toBe('The project, the environment or the secret was not found.'); + }); + + it('shows the API wording of a 400 validation entry that is not in the catalog', () => { + const error = asWriteFailure( + failure(400, { errors: [{ code: 'launch.ENVIRONMENT.KEY.INVALID', message: 'key must be a valid name' }] }), + randomUUID(), + ) as LaunchApiError; + + expect(error.status).toBe(400); + expect(error.code).toBe('launch.ENVIRONMENT.KEY.INVALID'); + expect(error.message).toBe('key must be a valid name'); + }); + + it('words a field-named 400 from its field and code, as the read path does', () => { + const error = asWriteFailure( + failure(400, { errors: [{ value: { code: 'launch.ENVIRONMENT.VALUE.TOO_LONG', message: 'Bad request' } }] }), + randomUUID(), + ) as LaunchApiError; + + expect(error.message).toBe('The request was not accepted: value: launch.ENVIRONMENT.VALUE.TOO_LONG'); + }); + + it('strips the value, and its trimmed form, from every API text an error carries', () => { + const secret = randomUUID(); + const padded = ` ${secret} `; + const error = asWriteFailure( + failure(400, { + errors: [ + { code: 'launch.X.ONE', message: `value ${padded} is bad and ${secret} again` }, + { code: 'launch.X.TWO' }, + ], + }), + padded, + ) as LaunchApiError; + + expect(error.message).toBe('value •••••• is bad and •••••• again'); + expect(error.errors).toEqual([{ code: 'launch.X.ONE', message: 'value •••••• is bad and •••••• again' }, { code: 'launch.X.TWO' }]); + expect(JSON.stringify(error.errors)).not.toContain(secret); + }); + + it('does not touch the text of an error when the value is empty', () => { + const error = asWriteFailure(failure(400, { errors: [{ code: 'launch.X', message: 'plain text' }] }), '') as LaunchApiError; + + expect(error.message).toBe('plain text'); + }); + + it('keeps the fixed catalog wording even when the value is a piece of it', () => { + const error = asWriteFailure( + failure(409, { errors: [{ code: `${PREFIX}.KEY.CONFLICT`, message: 'x' }] }), + 'secret', + ) as LaunchApiError; + + expect(error.message).toBe('A secret or a variable with that key already exists in this environment.'); + }); + + it('rebuilds a network error without its cause and with the value stripped from its message', () => { + const secret = randomUUID(); + const cause = new Error(`request body ${secret}`); + const error = asWriteFailure(new LaunchNetworkError(`Could not send ${secret}`, cause, true), secret) as LaunchNetworkError; + + expect(error).toBeInstanceOf(LaunchNetworkError); + expect(error.message).toBe('Could not send ••••••'); + expect(error.cause).toBeUndefined(); + expect(error.retryable).toBe(true); + }); + + it('keeps a network error that was not retryable not retryable', () => { + const error = asWriteFailure(new LaunchNetworkError('proxy down', new Error('x')), randomUUID()) as LaunchNetworkError; + + expect(error.retryable).toBe(false); + }); + + it('passes another CLI error, which carries only CLI wording, through untouched', () => { + const error = new SessionExpiredError(); + + expect(asWriteFailure(error, randomUUID())).toBe(error); + }); + + it('replaces a plain error by one with the value stripped and no cause or stack from the original', () => { + const secret = randomUUID(); + const original = Object.assign(new Error(`boom ${secret}`), { cause: secret }); + const error = asWriteFailure(original, secret) as Error; + + expect(error).not.toBe(original); + expect(error.message).toBe('boom ••••••'); + expect((error as Error & { cause?: unknown }).cause).toBeUndefined(); + expect(error.stack).not.toContain(secret); + }); + + it('returns a thrown value that is not an error as it is', () => { + expect(asWriteFailure('text', randomUUID())).toBe('text'); + }); +}); + +describe('SecretInputTimeoutError', () => { + it('uses the singular for one second', () => { + expect(new SecretInputTimeoutError(1).message).toContain('within 1 second, so'); + }); + + it('says how long it waited and that nothing changed, exiting 1', () => { + const error = new SecretInputTimeoutError(30); + + expect(error.name).toBe('SecretInputTimeoutError'); + expect(error.exitCode).toBe(EXIT_RUNTIME); + expect(error.message).toBe( + 'No value arrived on standard input within 30 seconds, so nothing was changed. ' + + 'Pipe the value in, for example: printf \'%s\' "$TOKEN" | csdx launch:variables:set --secret ', + ); + }); + + it('gives a dotenv stream its own hint, not the single-value one', () => { + const error = new SecretInputTimeoutError(30, 'dotenv'); + + expect(error.exitCode).toBe(EXIT_RUNTIME); + expect(error.message).toBe( + 'No dotenv text arrived on standard input within 30 seconds, so nothing was changed. ' + + 'Pipe KEY=value lines in, for example: printf \'STRIPE_KEY=%s\\n\' "$STRIPE_KEY" | ' + + 'csdx launch:variables:set --secret STRIPE_KEY --dotenv -', + ); + expect(error.message).not.toContain('"$TOKEN"'); + }); +}); + +describe('SecretsNotRemovedError', () => { + it.each([ + [['A'], 1, '1 of 1 secret was not removed: A.'], + [['A', 'B'], 2, '2 of 2 secrets were not removed: A, B.'], + [['B'], 3, '1 of 3 secrets were not removed: B.'], + ])('names the keys that stayed and counts them against the request (%p of %i)', (keys, total, message) => { + const error = new SecretsNotRemovedError(keys, total); + + expect(error.name).toBe('SecretsNotRemovedError'); + expect(error.exitCode).toBe(EXIT_RUNTIME); + expect(error.message).toBe(message); + }); +}); + +describe('SecretsRemovalStoppedError', () => { + it('names the cause, the keys removed, the keys that failed and the keys never attempted', () => { + const cause = new LaunchNetworkError('cannot reach the Launch API', undefined); + + const error = new SecretsRemovalStoppedError({ removed: ['A', 'B'], failed: ['C'], notAttempted: ['D', 'E'], cause }); + + expect(error.name).toBe('SecretsRemovalStoppedError'); + expect(error.exitCode).toBe(EXIT_RUNTIME); + expect(error.cause).toBe(cause); + expect(error.message).toBe( + 'Stopped at secret C: cannot reach the Launch API\nRemoved: A, B.\nFailed: C.\nNot attempted: D, E.', + ); + }); + + it('says none for an empty group and counts earlier API failures with the key it stopped on', () => { + const error = new SecretsRemovalStoppedError({ + removed: [], + failed: ['A', 'B'], + notAttempted: [], + cause: new Error('boom'), + }); + + expect(error.message).toBe('Stopped at secret B: boom\nRemoved: none.\nFailed: A, B.\nNot attempted: none.'); + }); + + it('says it stopped at the variables when the variables patch is where it stopped', () => { + const error = new SecretsRemovalStoppedError({ + removed: [], + failed: ['A', 'B'], + notAttempted: ['C'], + cause: new Error('boom'), + at: 'variables', + }); + + expect(error.message).toBe('Stopped at the variables: boom\nRemoved: none.\nFailed: A, B.\nNot attempted: C.'); + }); + + it('words a cause that is not an error from its text', () => { + const error = new SecretsRemovalStoppedError({ removed: ['A'], failed: ['B'], notAttempted: [], cause: 'socket closed' }); + + expect(error.message).toBe('Stopped at secret B: socket closed\nRemoved: A.\nFailed: B.\nNot attempted: none.'); + expect(error.cause).toBe('socket closed'); + }); +}); diff --git a/src/secrets/secrets.errors.ts b/src/secrets/secrets.errors.ts new file mode 100644 index 00000000..d8720ee5 --- /dev/null +++ b/src/secrets/secrets.errors.ts @@ -0,0 +1,98 @@ +import { LaunchError } from '../core/errors'; +import { REDACTED } from '../core/redact'; +import { LaunchApiError, LaunchNetworkError } from '../transport/errors'; +import type { ApiErrorEntry, ErrorMessages } from '../transport/errors'; + +const ERROR_CODE_NAMESPACE = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS'; + +const SCOPE_NOT_FOUND_MESSAGE = 'The project or environment was not found.'; + +const READ_FORBIDDEN_CODE = `${ERROR_CODE_NAMESPACE}.READ_FORBIDDEN`; +const READ_REJECTED_CODE = `${ERROR_CODE_NAMESPACE}.READ_REJECTED`; +const SCOPE_NOT_FOUND_CODE = 'launch.ENVIRONMENT.NOT_FOUND'; + +export const SECRETS_ERROR_MESSAGES: ErrorMessages = { + [`${ERROR_CODE_NAMESPACE}.KEY.CONFLICT`]: 'A secret or a variable with that key already exists in this environment.', + [`${ERROR_CODE_NAMESPACE}.KEY.NOT_FOUND`]: 'No secret with that key exists in this environment.', + [`${ERROR_CODE_NAMESPACE}.VALUE.MULTILINE`]: 'A secret value must be a single line.', + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE': + "Another change to this environment's variables and secrets landed at the same moment, so nothing was changed. " + + 'Run the command again.', + [SCOPE_NOT_FOUND_CODE]: SCOPE_NOT_FOUND_MESSAGE, + 'launch.PROJECT.NOT_FOUND': SCOPE_NOT_FOUND_MESSAGE, + [READ_FORBIDDEN_CODE]: 'Permission is needed to view the secrets of this environment.', + [READ_REJECTED_CODE]: 'The secrets of this environment could not be listed. Try again.', +}; + +export function asReadFailure(error: unknown): unknown { + if (!(error instanceof LaunchApiError)) { + return error; + } + + if (error.status === 403) { + return new LaunchApiError(403, [{ code: READ_FORBIDDEN_CODE }], SECRETS_ERROR_MESSAGES); + } + + if (error.status === 404) { + return new LaunchApiError(404, [{ code: SCOPE_NOT_FOUND_CODE }], SECRETS_ERROR_MESSAGES); + } + + if (error.status === 400) { + return new LaunchApiError(400, [{ code: READ_REJECTED_CODE }], SECRETS_ERROR_MESSAGES); + } + + return error; +} + +const WRITE_FORBIDDEN_CODE = `${ERROR_CODE_NAMESPACE}.WRITE_FORBIDDEN`; +const WRITE_NOT_FOUND_CODE = `${ERROR_CODE_NAMESPACE}.WRITE_NOT_FOUND`; + +const WRITE_MESSAGES: ErrorMessages = { + ...SECRETS_ERROR_MESSAGES, + [WRITE_FORBIDDEN_CODE]: 'Permission is needed to change the secrets of this environment.', + [WRITE_NOT_FOUND_CODE]: 'The project, the environment or the secret was not found.', +}; + +function withoutValue(text: string, value: string): string { + return [value, value.trim()] + .filter((form) => form !== '') + .reduce((redacted, form) => redacted.split(form).join(REDACTED), text); +} + +function redactedEntry(entry: ApiErrorEntry, value: string): ApiErrorEntry { + return entry.message === undefined ? entry : { ...entry, message: withoutValue(entry.message, value) }; +} + +function reworded(error: LaunchApiError): LaunchApiError { + if (error.status === 403) { + return new LaunchApiError(403, [{ code: WRITE_FORBIDDEN_CODE }], WRITE_MESSAGES); + } + + if (error.status === 404 && !(error.code in WRITE_MESSAGES)) { + return new LaunchApiError(404, [{ code: WRITE_NOT_FOUND_CODE }], WRITE_MESSAGES); + } + + return error; +} + +export function asWriteFailure(error: unknown, value: string): unknown { + if (error instanceof LaunchApiError) { + const { status, errors } = reworded(error); + + return new LaunchApiError( + status, + errors.map((entry) => redactedEntry(entry, value)), + WRITE_MESSAGES, + ); + } + + if (error instanceof LaunchNetworkError) { + return new LaunchNetworkError(withoutValue(error.message, value), undefined, error.retryable); + } + + if (error instanceof LaunchError) { + return error; + } + + return error instanceof Error ? new Error(withoutValue(error.message, value)) : error; +} diff --git a/src/secrets/types.ts b/src/secrets/types.ts new file mode 100644 index 00000000..3eb117fd --- /dev/null +++ b/src/secrets/types.ts @@ -0,0 +1,10 @@ +import type { EnvironmentParams } from '../environments/environments.api'; + +export interface SecretSummary { + key: string | undefined; + updatedAt: string | undefined; +} + +export interface SecretKeyParams extends EnvironmentParams { + key: string; +} diff --git a/test/guards/layering.test.ts b/test/guards/layering.test.ts index 2d2c9e2f..5add337f 100644 --- a/test/guards/layering.test.ts +++ b/test/guards/layering.test.ts @@ -19,6 +19,7 @@ const RESOURCE_EDGES: Record = { uploads: [], stacks: [], variables: ['environments', 'stacks'], + secrets: ['environments'], cache: [], logs: ['deployments'], site: ['deployments', 'environments'], diff --git a/test/support/glued-value.ts b/test/support/glued-value.ts new file mode 100644 index 00000000..c017395c --- /dev/null +++ b/test/support/glued-value.ts @@ -0,0 +1,5 @@ +import { randomInt, randomUUID } from 'node:crypto'; + +export function gluedValue(): string { + return `${randomInt(10)}${randomUUID()}`; +} From a2ea5bef7d121112d897776ecea4592cccef3510 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 06:19:25 +0000 Subject: [PATCH 2/3] feat(variables): manage secrets with --secret on the variables commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit variables:set takes --secret KEY and sends variables and secrets in one PATCH, variables:list shows both in one table, and variables:unset removes either kind. The launch:secrets commands stay removed; the README and AGENTS.md describe the new flow. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 66 +- AGENTS.md | 50 +- README.md | 51 +- src/commands/launch/variables/list.test.ts | 128 ++- src/commands/launch/variables/list.ts | 39 +- src/commands/launch/variables/set.test.ts | 20 +- src/commands/launch/variables/set.ts | 16 +- src/commands/launch/variables/unset.test.ts | 41 +- src/commands/launch/variables/unset.ts | 6 +- src/variables/variable.dotenv.ts | 2 +- src/variables/variable.errors.ts | 59 +- src/variables/variable.inputs.test.ts | 53 +- src/variables/variable.inputs.ts | 20 +- src/variables/variable.page.test.ts | 71 +- src/variables/variable.page.ts | 24 +- src/variables/variable.presenter.test.ts | 38 +- src/variables/variable.presenter.ts | 17 +- src/variables/variable.rules.test.ts | 53 +- src/variables/variable.rules.ts | 30 + src/variables/variable.secrets.ts | 172 ++++ src/variables/variable.set.test.ts | 992 +++++++++++++++++++ src/variables/variable.set.ts | 160 ++- src/variables/variable.summary.test.ts | 35 +- src/variables/variable.summary.ts | 24 + src/variables/variable.unset.test.ts | 378 ++++++- src/variables/variable.unset.ts | 101 +- src/variables/variable.values.ts | 2 +- src/variables/variable.writer.test.ts | 302 +++++- src/variables/variable.writer.ts | 114 ++- src/variables/variables.api.test.ts | 258 ++++- src/variables/variables.api.ts | 66 +- test/integration/retired-commands.test.ts | 24 + test/integration/variables-list.test.ts | 88 +- test/integration/variables-set-unset.test.ts | 853 +++++++++++++++- 34 files changed, 4123 insertions(+), 230 deletions(-) create mode 100644 src/variables/variable.secrets.ts diff --git a/.talismanrc b/.talismanrc index af6ec8f0..8bd31ce6 100644 --- a/.talismanrc +++ b/.talismanrc @@ -14,7 +14,7 @@ fileignoreconfig: - filename: src/core/failure.test.ts checksum: 98ce2e3fbb4f6730cd7e295ec753d083f8483ff2c47bbde148f69dcc10771327 - filename: test/integration/retired-commands.test.ts - checksum: c1019c8477b25323206b675d883818452220477131369cd5e37ffceff088128b + checksum: 4833da1a6c90aefd1022a83f9e3d2eb067652efdd77c7d2adec73a3f54207b25 - filename: test/integration/manage-base-path.test.ts checksum: 79eb9ad420ea47d5bee8045d812c45b010bbeeafcaf5f85d11653140b0cd0db1 - filename: src/transport/rest-client.ts @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 3a255c9a11a4529ae420edc57565ef7e73355b83f3341c6ca7d21866ba0b2f8a + checksum: 23b61b685f217c801a2f6e233ecf8b9a104f38f722d5772e7416a6e2dd8003fd allowed_patterns: - "Do not add an exemption to a guard to make a new file pass" - "passes its own error wording to `client.request\\(req, MESSAGES\\)`" @@ -337,7 +337,7 @@ fileignoreconfig: - filename: src/commands/launch/env/update.test.ts checksum: 82c76af721bfdfd8eb7cf49494ffbe15d98b988e98bca1015b9d34b42b5226bd - filename: README.md - checksum: 47317e2767ecf41a22f3ba728f2c5a8098f8d17879af095199504e4eab54081f + checksum: 1fc59d9fd97816c9c1784f5a28cf4982161136ca4abc87ee0d0ab082f7c2ead8 allowed_patterns: - "password-protection" - "-p, --password" @@ -345,13 +345,13 @@ fileignoreconfig: - filename: test/integration/environments-create.test.ts checksum: b2bae2f96095ceb5b345339550f0af5dcf9e30b3fce2f98aca51a6e791d710cb - filename: src/commands/launch/variables/list.test.ts - checksum: 87ccb762f4931326fc50bca1c01aeb4a16d552e4dfa141d00370fdfafa4363be + checksum: b0f70fc2d9c60307ad4e2212c88ecc3f829d92f2bd09ee1de513c06a4a6b7e13 - filename: src/commands/launch/variables/set.test.ts - checksum: 72688fdf094918b8b0c68c7cca57960c2badb635cbb5df15688e9da900c786c8 + checksum: 43afa41270573dc7d081159389d607ba1bbf4c983e1f5cccca07fdbe81dbb06a - filename: src/commands/launch/variables/unset.test.ts - checksum: bf2a359e57fdb0146dad160962f8ae01596450460c604794026ddcb697f74c68 + checksum: 216cdf0e44419d55bf18e325acdd47d213faf716a372e9fd10878042b18690a9 - filename: src/commands/launch/variables/unset.ts - checksum: 233c50867eb28f61275ea58535f2839fda3d023b678cd38a9f9e853925de9719 + checksum: 38d2c9bad2b1d5099cf23e79c01e6e284881b362cd8dcefe0b8eb25974d9a6c7 - filename: src/environments/environment.errors.test.ts checksum: 33ae71db0a46173c903659438a77d1d441797a8296e0591dbaa48512f32a4cab - filename: src/stacks/stacks.api.test.ts @@ -365,31 +365,31 @@ fileignoreconfig: - filename: src/variables/variable.dotenv.test.ts checksum: 052f2825b778402e199e64ec887dc13f8fc2748535b8d176eb73dc6528f14824 - filename: src/variables/variable.dotenv.ts - checksum: 9dae58ca744cf45332d054387fa0707169d01c1b57754af5133898c0c0efeb8c + checksum: 6f5c1557d332820862ff4c83d9a25e6f26bd7d1c1debf2c2c0e63a11482aa5ca - filename: src/variables/variable.errors.ts - checksum: f66b960365b83561f70b5fcef521bcc8a00d99b4415fb6a5df5bcf752a91d480 + checksum: cd95d75b6f1b8a7887197fc9ee5e0575d6ab59e5012bfb5ea765752dd83e5186 - filename: src/variables/variable.files.test.ts checksum: 301bc761c194453c0ec6fe073bf83960712e8f298f2fb6b782c1eadafd5089f5 - filename: src/variables/variable.inputs.test.ts - checksum: 11f41a57e57d9fec46afddd9f8a62df76eaf6fec4afbccf39fe4bce23a978eaf + checksum: a8da4cc9157b94d9cb4fa4f5c211f785e3889b58b2ad78023b2e20ecf67e35ce - filename: src/variables/variable.inputs.ts - checksum: b29fcc7fdddc938507d060ff3590d1d0705f5e8f173b232a488fa09d4c96c177 + checksum: 1d44e6482f6d3bbe34f82c0c81ea57a3e4bd099f9ea90c680eccb908035a0f00 - filename: src/variables/variable.merge.test.ts checksum: 581a5cc5d9d23223643bd461525c6755205ebf16f33ae7388c8e88de19461fbf - filename: src/variables/variable.merge.ts checksum: f096c83e4894e6d96b620873815bc0f85c2a79c73b353c1a518bb870ca48976b - filename: src/variables/variable.page.test.ts - checksum: 9a4e63c0dbfd35b499149a98ce5642787097e9491746b4b874b2eda88f1d2b50 + checksum: 0fe41bd944b6af04e2c9f824b43ef11cd8ab993a842b2d759ac394118d6350a2 - filename: src/variables/variable.parse.test.ts checksum: 8cfcd7f3b0784f525238ab09d8cbe8b8d8fb3a90eb164cb5bd4cdf15a8740e86 - filename: src/variables/variable.parse.ts checksum: 912ef100eaec7e08ffef90100f8559a224aed709bd4527dcf15653f8b4131287 - filename: src/variables/variable.presenter.test.ts - checksum: 62e8b0eff16ed4408d929092ce6808aeabea001a6cc15780d46c4ac4226eec3d + checksum: 2b52d2638ca8eea42b14be3c498a7c86d171423ad1bf5240c35931befdf08841 - filename: src/variables/variable.presenter.ts - checksum: ee8e4dcf75ad7e849d1e8e64ce6a6549d13fc62dc9aa322d96eb2e725d629db5 + checksum: c2bc7c96e29e681d7c9338216c4d878fdfa076ddec9f1209151f3b920ef46180 - filename: src/variables/variable.set.test.ts - checksum: f3571146c4b5b605efc85e0f9c9a8968273a4b5c856c00c9617dfae94000a3f6 + checksum: 7a4dda6e582c37b4e1752a80e756b1f3e5cff4fddc5459572c3a2d7e44084934 - filename: src/variables/variable.sources.test.ts checksum: 92c0365b05a8aa16be74da225cb49b85612358acbaaa5c79688183254b160059 - filename: src/variables/variable.sources.ts @@ -399,31 +399,31 @@ fileignoreconfig: - filename: src/variables/variable.stack.ts checksum: 9d4bd5b72063e0d3951e01696794ec7409294a64ff65693b8dc910fe0a2d2c2d - filename: src/variables/variable.summary.test.ts - checksum: 8b214a1f1f43ac1a76434b75e4ff1ffd73a9e73dc2a0d6bae9ca43fd678182e5 + checksum: 81289639b2d44d04844860a03b3d52cb4b1f5ac41b90d3b4a2feccf9dda84c03 - filename: src/variables/variable.summary.ts - checksum: 0da287557a5c4280074d1a26aeff4f7d95b205e4266ff47c18b62665134f5bdc + checksum: 8f8fbe30dccf5a19d609e7456612e09bedfc8d3d3f4525a8b7cd403cadcc5318 - filename: src/variables/variable.unset.test.ts - checksum: 8797c7aa2960fc0328d5cab8cfdddf674ac624ace95f79338520851a2c7b732a + checksum: a7cc82fccd133f00dec6bf6048095cbaff4020c892228b39a54152b820e6e2b4 - filename: src/variables/variable.unset.ts - checksum: 4050a023edd3c6db1507eb2d0f2815d8c0c03622b2810b4977a8fba6e83818fe + checksum: 81dc12abdd102f5bf1002df27cac9f70ac1e0b1707de392f29feb72baf35d241 - filename: src/variables/variable.values.test.ts checksum: cdedaa03735077efdfac3cfdc8a05e7f13e1fc3f1bc2274b8ed9f493f496d43c - filename: src/variables/variable.values.ts - checksum: 9e078c80c9dd18d9cc9db43c58c702bf9e14d60bbd4d1d2efc41227e754c0fbc + checksum: a79563b50ab061e446550ddb673624678c29407d0ecf504ec506d4795dd10912 - filename: src/variables/variable.writer.test.ts - checksum: 7991a4ba0c58f187dfebf01092642459ce89b297f453159ca8e0953a2ee7e2b8 + checksum: f30f00af216c5912ac3d795465e7209af9b3ee2c2c0a179c781a79318952e873 - filename: src/variables/variable.writer.ts - checksum: 11acfccfad30b66a44954e97127d2a7bcebdb80f92299da6d645ac847c97192a + checksum: 108c73c5a4b6f5266d33de103b214502c309027d89ea1fd15e3a2027ee6e83b4 - filename: src/variables/variables.api.test.ts - checksum: b6d455927d0b40b6b211ae979a4eba8298aa842cb2f7e7cbc79743641f0182f2 + checksum: 25a5e54b304075622aebfc7fcb89cd000485ab979d168c05859fad8245e7b49b - filename: src/variables/variables.api.ts - checksum: 85ea6db36b1e588b0435155fd20f4ed8d2aafa790c6ed02bf1ceef366e6e9b8e + checksum: edd5a9f96f4ded0683a5f68f6642efc700962abc67db15e40ed6e03cc89f28d2 - filename: test/fixtures/cms-environment-variables.json checksum: cb2cbb2d1d858b1cf2115c218a0ecca04ce04baf054fe11fe6123589c1afce27 - filename: test/integration/variables-list.test.ts - checksum: 5ea6a0fcd331496ca19773e90dab81e09eb5290b8f22a1880bffc7916f3778b2 + checksum: e4b28ea1deed65b6d9bbcbd147b07afd009a7ae5f4f82dcf61c03b80f0d01fe2 - filename: test/integration/variables-set-unset.test.ts - checksum: a8718e81d0e743f935eac40884a556a3a80bb55f66d339cef36916b33c57c2f7 + checksum: 32943eb4167f93810577356a8a83b6ce5bdf077099b42fc2fbd0db8c3954fe8b - filename: test/fixtures/deployments-list.json checksum: 2f10f24dc0ceb8e85f5201b7c1530c0c540c044ef50b732cc29e07289112316e - filename: test/integration/deployments-get.test.ts @@ -510,4 +510,18 @@ fileignoreconfig: checksum: e9b9179635cc4848923d37c153eb1515ca260f4bf8d92e326709c749315c3d26 - filename: src/secrets/secrets.errors.test.ts checksum: c116485896375f3317e1d1e57bf9f3ccfdbb3ccbe759eff4ac1c3bf79cc19a89 +- filename: src/commands/launch/variables/set.ts + checksum: 72281bb3dc2d665fd614082692a0f6e2ab09394e86295a6542c89f0f1294cc28 +- filename: src/variables/variable.rules.test.ts + checksum: 88e5e98a79584302390e97d65369616644653bbb9f74f6c6ddb38eaf7783b9af +- filename: src/variables/variable.rules.ts + checksum: f87e18ed22a3eef31c997e0b3daf49547a56cea35dc3e278c000e7d5f6402cf0 +- filename: src/variables/variable.secrets.ts + checksum: 852c10918a9a0386e9567838ef0b40b0f5b4f0fbbbf28a9a327bac6aae9cd007 +- filename: src/variables/variable.set.ts + checksum: 0a08a0da82e37383345100f4f3d32f5c39734a84fd3b32a4d51326420c040f22 +- filename: src/commands/launch/variables/list.ts + checksum: a359e01ff4f7ef687df3e3c42672d5f794aa84ce8ebd4b33f84b43384617e76f +- filename: src/variables/variable.page.ts + checksum: 20bb11e438d6d94aae9f4e100f810dc4dfed772685e29cc2c8e9364b5df4cb29 version: "1.0" diff --git a/AGENTS.md b/AGENTS.md index cc582c3e..f7e71719 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -151,11 +151,15 @@ src/ stacks/ the Contentstack stack and delivery-token lookups behind --from-stack, through the CmaSession (no Launch endpoint) variables/ the shared variable-source resolver (--var, --dotenv, --from-stack, a detected .env file), the - writer behind launch:variables:set / :unset, and the masked presenter behind :list. Its - VariablesApi owns the per-variable PATCH and the stack template read; the - pre-confirmation read for unset and the list read go through environments. + writer behind launch:variables:set / :unset, and the presenter behind :list (variables and + secrets in one table). Its VariablesApi owns the per-variable PATCH and the stack template + read; the reads for unset and list go through environments and the shared api surface's + secrets list. EnvironmentBuilder calls back into it for the create commands, so the two folders each name the other in the layering allow-list + secrets/ SecretsApi (list and remove one secret) and the wording of the secret errors, reached through the + api surface by variables:list and variables:unset. It has no commands of its own: launch:secrets:* + was removed and answers as an unknown command, with no alias deployments/ the deployment repository, the status classification, the wait/stream loop and LogTail that projects:create, deployments:create and logs:get all drive, the DeploymentFollower that watches one @@ -341,8 +345,10 @@ the green `✔ Project deleted successfully.`, matching `projects:update`. `PATCH .../environments/:uid/variables` (`VariablesApi.patch`, CL-7179) with a body of `{set: [{key, value}]}` or `{unset: [key]}`, never both, so the CLI no longer reads the environment to merge and cannot overwrite a concurrent change to another key. The server merges under a compare-and-swap and its response carries keys -only, which the CLI ignores. `unset` still reads the environment once, before it asks, to name it in the -question and to refuse a key that is not set with exit 2 before any prompt; a key that disappears after that +only, which the CLI ignores. `unset` reads the environment once, before it asks, to name it in the +question and to work out whether each `--key` is a variable or a secret, and reads `GET .../secrets` only when at least one +`--key` is not a held variable (a variables-only unset makes no secrets read, so a refused or missing secrets route cannot block it), +and refuses a key that is neither with exit 2 before any prompt; a key that disappears after that read comes back as 404 `KEY.NOT_FOUND`, which `VariablesApi.patch` rewords to the same not-set usage error (`variable.errors.ts`). A 409 `CONCURRENT_UPDATE` (the server gave up after its retries) exits 1 with advice to run the command again; `PATCH_EMPTY` and `CONFLICTING_KEYS` cannot be sent by this CLI and read as a CLI bug. A PUT or @@ -357,12 +363,44 @@ prints a yellow `Skipped adding variables.` and sends nothing (sources that supp under `--data-dir`, always printing the file it chose, and fails with exit 2 when there is none. A bare `--var KEY` is a hidden prompt on a terminal, a stdin read for exactly one bare key without one, and exit 2 naming `--var =` and `--dotenv ` for two or more. The API refuses an empty value, so `KEY=` is a usage error naming the key, and an empty value inside a dotenv file is skipped with its key reported. No value reaches stdout, a -prompt message, a confirmation or an error: `list` masks through `redactedColumn`, and a failed `PATCH` is worded from +prompt message, a confirmation or an error: `list` masks through `REDACTED` and shows a secret as `(write-only)`, and a failed `PATCH` is worded from `ENVIRONMENT_ERROR_MESSAGES`. A code with no entry there falls back to the API's own message, which the service words from keys at most, never from a value (CL-7179). The stack and delivery-token lookups behind `--from-stack` walk the Management API 100 per page and raise `CmaScanLimitError` after `MAX_PAGES` pages rather than return a truncated list. +`set --secret KEY` (repeatable, or `--secret A,B`; one key per occurrence, so a value typed after it is a stray argument, +exit 2) marks keys write-only and still sends **one** `PATCH .../variables` with `set` for the variables and `secrets` +for every secret with a value, so all of it is saved or none of it. `--secret` counts as a given source: no source +chooser, no `.env` auto-detection, no `Using variables from` line. `VariableSetter.setWithSecrets` takes a key's value +from `--dotenv `, `--dotenv -` (the dotenv text on standard input, read only when `--secret` is given; without it `-` +is a file named `-`) or `--from-stack`, else a masked `Value for KEY (1/2)` prompt on a terminal, else one piped value +(`readWithin`, 30 s). Every check runs before the first write and, where possible, before the first prompt, in +`src/variables/variable.secrets.ts`: a key twice, a key in both `--var` and `--secret`, a bare `--var KEY` or a second key that needs +standard input without a terminal (each exit 2), a `--secret` key that is a held variable (`KEY is a variable.`), an empty or +multi-line value, the combined 128 entries and, per request, 14336 bytes of the keys and values this run sends (the +server stays the authority on the environment-wide size). With `--dotenv -`, any key of the stream that `--secret` does not name is a +usage error naming the keys, since it would otherwise be saved as a readable variable; a `--dotenv ` or `--from-stack` keeps +sending its other keys as variables. The client-exposed-prefix warning for a `--secret` key prints once the key checks have passed, +before the first prompt or standard input read, and there is no confirmation or `--yes`. A 409 `KEY.CONFLICT` names each `set` key that is +a held secret (`KEY is a secret.`), else each `--secret` key that has become a variable (`KEY is a variable.`), else shows the API's own +message. A `--secret` run reads the environment and `GET .../secrets` first; a run without +`--secret` reads nothing. The summary is one line per kind (`1 variable set`, `1 secret added`, `1 secret updated`), never a +value. `src/core/secret-input.ts` holds the secret input pieces `variables` uses (`readWithin`, the stdin timeout error, whose +hint names `launch:variables:set --secret `, the empty-value error and the client-exposed-prefix warning) because +`variables` may not import `secrets`. + +`variables:list` fetches the environment and `GET .../secrets` and prints one `KEY | TYPE | VALUE | UPDATED` table: a +variable row is `variable`, masked, with the environment's `updatedAt`; a secret row is `secret`, `(write-only)`, with the +secret's own `updatedAt` (`-` when absent). `pageOfVariables` pages both lists in memory together, variables first, so +`--limit`/`--skip` and the `Showing a-b of n` footer count both; a secrets read the API answers with an error (403, 404) still prints the +variables table, then a yellow warning line with the read-failure wording and exit 0. `variables:unset --key` sends the variable keys in one `PATCH .../variables {unset}` (none when there are +none) and each secret key as its own `DELETE .../secrets/`, one result line per key. A secret delete the API refuses +is reported and the rest are still attempted (`SecretsNotRemovedError`, exit 1); when the variables PATCH was refused as well, one +`RemovalFailedError` (exit 1) names the variables and the secrets left in place; a delete that fails without an API answer +stops the run (`SecretsRemovalStoppedError`, which also lists the variables already removed). These error classes live in +`src/core/secret-input.ts` because `variables` may not import `secrets`. + `projects:create` and `env:create` take `--var` and `--dotenv` and reach the same resolver through `EnvironmentBuilder`, which asks last - after Contentstack Authentication, where V1 asked - with no auto-detection. With neither flag it offers a checkbox over the sources plus `Skip adding environment variables`, which cannot be diff --git a/README.md b/README.md index 8b57d48e..cff6f119 100644 --- a/README.md +++ b/README.md @@ -323,7 +323,8 @@ FLAGS --build-cmd= Build command --config= Path to the local '.cs-launch.json' file --cs-auth= Contentstack Authentication (enable | disable) - --dotenv=... Path to a dotenv file, absolute or relative to the current folder + --dotenv=... Path to a dotenv file, absolute or relative to the current folder. On + launch:variables:set with --secret, - reads the dotenv text from standard input --framework= Framework preset (Gatsby | NextJs | CRA | CSR | Analog | Angular | Nuxt | Astro | VueJs | Remix | Other) --from-stack Import the variables of a Contentstack stack. Asks for the stack and a delivery token on a @@ -334,8 +335,8 @@ FLAGS --project= Project name or UID --res-mode= Response mode (buffered | streaming) --server-cmd= Server command - --var=... Environment variable as KEY=VALUE, repeatable. A KEY with no value is asked at a hidden - prompt, or read from standard input when piped + --var=... Environment variable as KEY=VALUE, repeatable: a variable, the value can be read in the UI. + A KEY with no value is asked at a hidden prompt, or read from standard input when piped DESCRIPTION Create an environment in a Launch project and follow its first deployment @@ -620,7 +621,8 @@ FLAGS --config= Path to the local '.cs-launch.json' file --cs-auth= Contentstack Authentication (enable | disable) --description= Project description (255 characters or fewer) - --dotenv=... Path to a dotenv file, absolute or relative to the current folder + --dotenv=... Path to a dotenv file, absolute or relative to the current folder. On + launch:variables:set with --secret, - reads the dotenv text from standard input --env-name= Name of the environment created with the project (200 characters or fewer) --framework= Framework preset (Gatsby | NextJs | CRA | CSR | Analog | Angular | Nuxt | Astro | VueJs | Remix | Other) @@ -632,8 +634,8 @@ FLAGS --res-mode= Response mode (buffered | streaming) --server-cmd= Server command --type= Project type (GitHub | FileUpload) - --var=... Environment variable as KEY=VALUE, repeatable. A KEY with no value is asked at a hidden - prompt, or read from standard input when piped + --var=... Environment variable as KEY=VALUE, repeatable: a variable, the value can be read in the UI. + A KEY with no value is asked at a hidden prompt, or read from standard input when piped DESCRIPTION Create a Launch project, its first environment, and its first deployment @@ -794,7 +796,7 @@ _See code: [src/commands/launch/site/open.ts](https://github.com/contentstack/la ## `csdx launch:variables:list` -List the environment variables of an environment, with their values masked +List the variables and secrets of an environment in one table. Variable values are masked and a secret shows (write-only); a value is never printed ``` USAGE @@ -811,39 +813,46 @@ FLAGS --skip= Number of records to skip DESCRIPTION - List the environment variables of an environment, with their values masked + List the variables and secrets of an environment in one table. Variable values are masked and a secret shows (write-only); a value is never printed EXAMPLES $ csdx launch:variables:list --org --project --env + + $ csdx launch:variables:list --org --project --env --limit 20 --skip 20 ``` _See code: [src/commands/launch/variables/list.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/variables/list.ts)_ ## `csdx launch:variables:set` -Add or change environment variables from --var, --dotenv or a detected .env file; later sources win +Add or change environment variables from --var, --dotenv or a detected .env file; later sources win. Mark a key as a secret with --secret KEY: its value is write-only and is never a flag ``` USAGE $ csdx launch:variables:set [--config ] [-d ] [--org ] [--project ] [--env ] [--var - ...] [--dotenv ...] [--from-stack] [-a ] + ...] [--secret ...] [--dotenv ...] [--from-stack] [-a ] FLAGS -a, --alias= Alias of a delivery token saved with csdx auth:tokens:add, used with --from-stack without a prompt -d, --data-dir= Current working directory --config= Path to the local '.cs-launch.json' file - --dotenv=... Path to a dotenv file, absolute or relative to the current folder + --dotenv=... Path to a dotenv file, absolute or relative to the current folder. On launch:variables:set + with --secret, - reads the dotenv text from standard input --env= Environment name or UID --from-stack Import the variables of a Contentstack stack. Asks for the stack and a delivery token on a terminal --org= Organization UID --project= Project name or UID - --var=... Environment variable as KEY=VALUE, repeatable. A KEY with no value is asked at a hidden - prompt, or read from standard input when piped + --secret=... Secret KEY, repeatable or as A,B: write-only, the value can't be read back. Replaces the + value if KEY is already a secret. The value is never a flag: it comes from --dotenv or + --from-stack, else a hidden prompt, else standard input when piped + --var=... Environment variable as KEY=VALUE, repeatable: a variable, the value can be read in the UI. + A KEY with no value is asked at a hidden prompt, or read from standard input when piped DESCRIPTION - Add or change environment variables from --var, --dotenv or a detected .env file; later sources win + Add or change environment variables from --var, --dotenv or a detected .env file; later sources win. Mark a key as a + secret with --secret KEY: its value is write-only and is never a flag EXAMPLES $ csdx launch:variables:set --org --project --env --var API_URL=https://example.test DEBUG=true @@ -851,13 +860,19 @@ EXAMPLES $ csdx launch:variables:set --org --project --env --dotenv .env.staging $ printf '%s' "$TOKEN" | csdx launch:variables:set --org --project --env --var API_TOKEN + + $ csdx launch:variables:set --org --project --env --var API_URL=https://example.test --secret STRIPE_KEY,DB_PASSWORD + + $ printf '%s' "$STRIPE_KEY" | csdx launch:variables:set --org --project --env --secret STRIPE_KEY + + $ printf 'STRIPE_KEY=%s\nDB_PASSWORD=%s\n' "$STRIPE_KEY" "$DB_PASSWORD" | csdx launch:variables:set --org --project --env --dotenv - --secret STRIPE_KEY,DB_PASSWORD ``` _See code: [src/commands/launch/variables/set.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/variables/set.ts)_ ## `csdx launch:variables:unset` -Remove environment variables from an environment, after asking for confirmation +Remove variables and secrets from an environment, after asking for confirmation. Each --key may name a variable or a secret; the command works out which ``` USAGE @@ -868,18 +883,20 @@ FLAGS -d, --data-dir= Current working directory --config= Path to the local '.cs-launch.json' file --env= Environment name or UID - --key=... Environment variable key, repeatable + --key=... Key of a variable or a secret to remove, repeatable --org= Organization UID --project= Project name or UID --yes Skip the confirmation prompt DESCRIPTION - Remove environment variables from an environment, after asking for confirmation + Remove variables and secrets from an environment, after asking for confirmation. Each --key may name a variable or a secret; the command works out which EXAMPLES $ csdx launch:variables:unset --org --project --env --key API_KEY $ csdx launch:variables:unset --org --project --env --key API_KEY --key DEBUG --yes + + $ csdx launch:variables:unset --org --project --env --key DEBUG --key DB_PASSWORD ``` _See code: [src/commands/launch/variables/unset.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/variables/unset.ts)_ diff --git a/src/commands/launch/variables/list.test.ts b/src/commands/launch/variables/list.test.ts index 34f22f29..c9af583f 100644 --- a/src/commands/launch/variables/list.test.ts +++ b/src/commands/launch/variables/list.test.ts @@ -1,13 +1,25 @@ import { REDACTED } from '../../../core/redact'; import type { UxLike } from '../../../core/prompt'; +import { LaunchApiError } from '../../../transport/errors'; import VariablesList from './list'; +function refused(status: number, message: string): LaunchApiError { + const code = `launch.TEST.${status}`; + + return new LaunchApiError(status, [{ code }], { [code]: message }); +} + +const FORBIDDEN = 'Permission is needed to view the secrets of this environment.'; +const NOT_FOUND = 'The project or environment was not found.'; + const RESOLVED = { org: 'org1', project: 'proj1', env: 'env1', limit: 100, skip: 0 }; function commandUnderTest( environment: unknown, resolved: Record = RESOLVED, answer: () => Promise = async () => environment, + secrets: () => Promise = async () => [], + outputIsTTY = false, ) { const lines: string[] = []; const ux: UxLike = { @@ -17,6 +29,7 @@ function commandUnderTest( inquire: async () => undefined as never, }; const fetched: unknown[] = []; + const fetchedSecrets: unknown[] = []; const command = Object.create(VariablesList.prototype) as VariablesList; Object.assign(command, { @@ -24,7 +37,7 @@ function commandUnderTest( resolved, services: { ux, - outputIsTTY: false, + outputIsTTY, api: { environments: { get: async (params: unknown) => { @@ -32,16 +45,22 @@ function commandUnderTest( return answer(); }, }, + secrets: { + list: async (params: unknown) => { + fetchedSecrets.push(params); + return secrets(); + }, + }, }, }, }); - return { command, lines, fetched }; + return { command, lines, fetched, fetchedSecrets }; } describe('launch:variables:list', () => { it('lists each key with a masked value and the environment update time, never a value', async () => { - const { command, lines, fetched } = commandUnderTest({ + const { command, lines, fetched, fetchedSecrets } = commandUnderTest({ uid: 'env1', updatedAt: '2026-09-01', environmentVariables: [ @@ -55,15 +74,110 @@ describe('launch:variables:list', () => { const output = lines.join('\n'); expect(fetched).toEqual([{ org: 'org1', project: 'proj1', environment: 'env1' }]); - expect(lines[1]).toBe('│ KEY │ VALUE │ UPDATED │'); - expect(lines[3]).toBe(`│ API_KEY │ ${REDACTED} │ 2026-09-01 │`); - expect(lines[5]).toBe(`│ API_URL │ ${REDACTED} │ 2026-09-01 │`); + expect(fetchedSecrets).toEqual([{ org: 'org1', project: 'proj1', environment: 'env1' }]); + expect(lines[1]).toBe('│ KEY │ TYPE │ VALUE │ UPDATED │'); + expect(lines[3]).toBe(`│ API_KEY │ variable │ ${REDACTED} │ 2026-09-01 │`); + expect(lines[5]).toBe(`│ API_URL │ variable │ ${REDACTED} │ 2026-09-01 │`); expect(lines[lines.length - 1]).toBe('Showing 1-2 of 2'); expect(output).toContain('API_KEY'); expect(output).not.toContain('never-printed-abc'); expect(output).not.toContain('https://example.test'); }); + it('lists a secret after the variables as write-only with its own update time', async () => { + const { command, lines } = commandUnderTest( + { updatedAt: '2026-09-01', environmentVariables: [{ key: 'API_URL', value: 'never-printed-abc' }] }, + RESOLVED, + undefined, + async () => [ + { key: 'STRIPE_KEY', updatedAt: '2026-12-03' }, + { key: 'DB_PASSWORD', updatedAt: undefined }, + ], + ); + + await command.run(); + + expect(lines[3]).toBe(`│ API_URL │ variable │ ${REDACTED} │ 2026-09-01 │`); + expect(lines[5]).toBe('│ STRIPE_KEY │ secret │ (write-only) │ 2026-12-03 │'); + expect(lines[7]).toBe('│ DB_PASSWORD │ secret │ (write-only) │ - │'); + expect(lines[lines.length - 1]).toBe('Showing 1-3 of 3'); + expect(lines.join('\n')).not.toContain('never-printed-abc'); + }); + + it('pages the secrets after the variables with limit and skip', async () => { + const { command, lines } = commandUnderTest( + { environmentVariables: [{ key: 'A', value: 'a1' }] }, + { ...RESOLVED, limit: 1, skip: 1 }, + undefined, + async () => [{ key: 'S1', updatedAt: undefined }, { key: 'S2', updatedAt: undefined }], + ); + + await command.run(); + + expect(lines.join('\n')).toContain('S1'); + expect(lines.join('\n')).not.toContain('S2'); + expect(lines.join('\n')).not.toContain('│ A '); + expect(lines[lines.length - 1]).toBe('Showing 2-2 of 3'); + }); + + it('prints the variables table and then a yellow warning when the secrets are refused', async () => { + const { command, lines } = commandUnderTest( + { updatedAt: '2026-09-01', environmentVariables: [{ key: 'A', value: 'never-printed-abc' }] }, + undefined, + undefined, + async () => Promise.reject(refused(403, FORBIDDEN)), + true, + ); + + await expect(command.run()).resolves.toBeUndefined(); + + expect(lines[3]).toContain('A'); + expect(lines[lines.length - 2]).toBe('Showing 1-1 of 1'); + expect(lines[lines.length - 1]).toBe( + `\u001b[33m${FORBIDDEN}\u001b[39m`, + ); + expect(lines.join('\n')).not.toContain('never-printed-abc'); + }); + + it('prints the warning without colour off a terminal and for any answered failure of the secrets read', async () => { + const { command, lines } = commandUnderTest( + { environmentVariables: [{ key: 'A', value: 'a1' }] }, + undefined, + undefined, + async () => Promise.reject(refused(404, NOT_FOUND)), + ); + + await command.run(); + + expect(lines[lines.length - 1]).toBe(NOT_FOUND); + }); + + it('prints the empty placeholder and the warning when there are no variables and the secrets are refused', async () => { + const { command, lines } = commandUnderTest({}, undefined, undefined, async () => + Promise.reject(refused(403, FORBIDDEN)), + ); + + await command.run(); + + expect(lines).toEqual([ + 'No records found.', + FORBIDDEN, + ]); + }); + + it('fails when the secrets read fails without an API answer', async () => { + const failure = new Error('secrets failed'); + const { command, lines } = commandUnderTest( + { environmentVariables: [{ key: 'A', value: 'a1' }] }, + undefined, + undefined, + async () => Promise.reject(failure), + ); + + await expect(command.run()).rejects.toBe(failure); + expect(lines).toEqual([]); + }); + it('applies limit and skip to the variables and numbers the footer from skip', async () => { const { command, lines } = commandUnderTest( { environmentVariables: [{ key: 'A', value: 'a1' }, { key: 'B', value: 'b1' }, { key: 'C', value: 'c1' }] }, @@ -96,7 +210,7 @@ describe('launch:variables:list', () => { await command.run(); - expect(lines[3]).toBe(`│ - │ ${REDACTED} │ - │`); + expect(lines[3]).toBe(`│ - │ variable │ ${REDACTED} │ - │`); expect(lines.join('\n')).not.toContain('secret-value'); }); diff --git a/src/commands/launch/variables/list.ts b/src/commands/launch/variables/list.ts index dd44088f..9fe3b426 100644 --- a/src/commands/launch/variables/list.ts +++ b/src/commands/launch/variables/list.ts @@ -1,8 +1,10 @@ import { LaunchCommand } from '../../../core/launch-command'; import { flagsFor, inputs } from '../../../core/inputs'; import { renderPagination, renderTable } from '../../../core/render'; +import { styled } from '../../../core/style'; +import { LaunchApiError } from '../../../transport/errors'; import { pageOfVariables } from '../../../variables/variable.page'; -import { variableColumns } from '../../../variables/variable.presenter'; +import { listColumns } from '../../../variables/variable.presenter'; const listInputs = inputs({ org: { required: true }, @@ -13,10 +15,13 @@ const listInputs = inputs({ }); export default class VariablesList extends LaunchCommand { - static description = 'List the environment variables of an environment, with their values masked'; + static description = + 'List the variables and secrets of an environment in one table. ' + + 'Variable values are masked and a secret shows (write-only); a value is never printed'; static examples = [ '$ csdx launch:variables:list --org --project --env ', + '$ csdx launch:variables:list --org --project --env --limit 20 --skip 20', ]; static inputs = listInputs; @@ -24,20 +29,40 @@ export default class VariablesList extends LaunchCommand { static flags = flagsFor(listInputs); async run(): Promise { - const environment = await this.services.api.environments.get({ + const scope = { org: this.resolved.org, project: this.resolved.project, environment: this.resolved.env, + }; + const environment = await this.services.api.environments.get(scope); + let warning: string | undefined; + const secrets = await this.services.api.secrets.list(scope).catch((error: unknown) => { + if (!(error instanceof LaunchApiError)) { + throw error; + } + + warning = error.message; + + return []; }); - const page = pageOfVariables(environment.environmentVariables ?? [], this.resolved.limit, this.resolved.skip); + const page = pageOfVariables( + environment.environmentVariables ?? [], + secrets, + this.resolved.limit, + this.resolved.skip, + ); renderTable( this.ux, - variableColumns(environment.updatedAt), - page.variables, + listColumns(environment.updatedAt), + page.rows, process.stdout.columns, this.services.outputIsTTY, ); - renderPagination(this.ux, page.pagination, page.variables.length); + renderPagination(this.ux, page.pagination, page.rows.length); + + if (warning !== undefined) { + this.ux.print(styled(warning, 'yellow', this.services.outputIsTTY === true)); + } } } diff --git a/src/commands/launch/variables/set.test.ts b/src/commands/launch/variables/set.test.ts index dc0dfeb0..484b305c 100644 --- a/src/commands/launch/variables/set.test.ts +++ b/src/commands/launch/variables/set.test.ts @@ -1,5 +1,5 @@ import type { UxLike } from '../../../core/prompt'; -import { aliasRequiresFromStack, singleDotenv } from '../../../variables/variable.rules'; +import { aliasRequiresFromStack, secretTakesKeyOnly, singleDotenv } from '../../../variables/variable.rules'; import { VariableSetter } from '../../../variables/variable.set'; import VariablesSet from './set'; @@ -58,6 +58,7 @@ describe('launch:variables:set', () => { project: 'p', env: 'e', var: ['A=1'], + secret: ['STRIPE_KEY', 'DB_PASSWORD'], dotenv: ['a.env'], 'from-stack': true, alias: 'my-prod', @@ -71,6 +72,7 @@ describe('launch:variables:set', () => { project: 'p', environment: 'e', vars: ['A=1'], + secrets: ['STRIPE_KEY', 'DB_PASSWORD'], envFiles: ['a.env'], fromStack: true, alias: 'my-prod', @@ -86,18 +88,28 @@ describe('launch:variables:set', () => { expect(updates).toEqual([]); }); - it('declares org, project and env as required and the two source flags as optional', () => { + it('declares org, project and env as required and every source flag as optional', () => { expect(VariablesSet.inputs).toEqual({ org: { required: true }, project: { required: true }, env: { required: true }, var: {}, + secret: {}, dotenv: {}, 'from-stack': {}, alias: {}, }); - expect(Object.keys(VariablesSet.flags).sort()).toEqual(['alias', 'dotenv', 'env', 'from-stack', 'org', 'project', 'var']); - expect(VariablesSet.rules).toEqual([aliasRequiresFromStack, singleDotenv]); + expect(Object.keys(VariablesSet.flags).sort()).toEqual([ + 'alias', + 'dotenv', + 'env', + 'from-stack', + 'org', + 'project', + 'secret', + 'var', + ]); + expect(VariablesSet.rules).toEqual([aliasRequiresFromStack, secretTakesKeyOnly, singleDotenv]); expect(Object.keys(VariablesSet.flags).sort()).toEqual(Object.keys(VariablesSet.inputs).sort()); }); }); diff --git a/src/commands/launch/variables/set.ts b/src/commands/launch/variables/set.ts index 4416b4f9..bf9f77ca 100644 --- a/src/commands/launch/variables/set.ts +++ b/src/commands/launch/variables/set.ts @@ -1,6 +1,6 @@ import { LaunchCommand } from '../../../core/launch-command'; import { flagsFor, inputs } from '../../../core/inputs'; -import { aliasRequiresFromStack, singleDotenv } from '../../../variables/variable.rules'; +import { aliasRequiresFromStack, secretTakesKeyOnly, singleDotenv } from '../../../variables/variable.rules'; import { VariableSetter } from '../../../variables/variable.set'; const setInputs = inputs({ @@ -8,6 +8,7 @@ const setInputs = inputs({ project: { required: true }, env: { required: true }, var: {}, + secret: {}, dotenv: {}, 'from-stack': {}, alias: {}, @@ -15,7 +16,8 @@ const setInputs = inputs({ export default class VariablesSet extends LaunchCommand { static description = - 'Add or change environment variables from --var, --dotenv or a detected .env file; later sources win'; + 'Add or change environment variables from --var, --dotenv or a detected .env file; later sources win. ' + + 'Mark a key as a secret with --secret KEY: its value is write-only and is never a flag'; static examples = [ '$ csdx launch:variables:set --org --project --env ' + @@ -24,13 +26,20 @@ export default class VariablesSet extends LaunchCommand { '--dotenv .env.staging', '$ printf \'%s\' "$TOKEN" | csdx launch:variables:set --org --project ' + '--env --var API_TOKEN', + '$ csdx launch:variables:set --org --project --env ' + + '--var API_URL=https://example.test --secret STRIPE_KEY,DB_PASSWORD', + '$ printf \'%s\' "$STRIPE_KEY" | csdx launch:variables:set --org --project ' + + '--env --secret STRIPE_KEY', + '$ printf \'STRIPE_KEY=%s\\nDB_PASSWORD=%s\\n\' "$STRIPE_KEY" "$DB_PASSWORD" | ' + + 'csdx launch:variables:set --org --project --env ' + + '--dotenv - --secret STRIPE_KEY,DB_PASSWORD', ]; static inputs = setInputs; static flags = flagsFor(setInputs); - static rules = [aliasRequiresFromStack, singleDotenv]; + static rules = [aliasRequiresFromStack, secretTakesKeyOnly, singleDotenv]; async run(): Promise { await new VariableSetter(this.services).set({ @@ -38,6 +47,7 @@ export default class VariablesSet extends LaunchCommand { project: this.resolved.project, environment: this.resolved.env, vars: this.resolved.var, + secrets: this.resolved.secret, envFiles: this.resolved['dotenv'], fromStack: this.resolved['from-stack'], alias: this.resolved.alias, diff --git a/src/commands/launch/variables/unset.test.ts b/src/commands/launch/variables/unset.test.ts index 399bee1b..3d3d5d3c 100644 --- a/src/commands/launch/variables/unset.test.ts +++ b/src/commands/launch/variables/unset.test.ts @@ -10,6 +10,7 @@ interface Harness { yes?: boolean; key?: string[]; updateFails?: Error; + secrets?: string[]; } function commandUnderTest(harness: Harness) { @@ -17,6 +18,7 @@ function commandUnderTest(harness: Harness) { const inquired: unknown[] = []; const calls: string[] = []; const updates: unknown[] = []; + const removals: unknown[] = []; const ux: UxLike = { print: (message: string) => { lines.push(message); @@ -48,6 +50,16 @@ function commandUnderTest(harness: Harness) { return { name: 'staging', environmentVariables: [{ key: 'API_KEY', value: 'never-printed-value' }, { key: 'DEBUG', value: 'x' }] }; }, }, + secrets: { + list: async () => { + calls.push('list'); + return (harness.secrets ?? []).map((key) => ({ key, updatedAt: undefined })); + }, + remove: async (params: unknown) => { + calls.push('remove'); + removals.push(params); + }, + }, variables: { patch: async (params: unknown) => { calls.push('patch'); @@ -62,7 +74,7 @@ function commandUnderTest(harness: Harness) { }, }); - return { command, lines, inquired, calls, updates }; + return { command, lines, inquired, calls, updates, removals }; } describe('launch:variables:unset', () => { @@ -80,6 +92,33 @@ describe('launch:variables:unset', () => { expect(lines.join('')).not.toContain('never-printed-value'); }); + it('confirms once for a variable and a secret, patches the variable and deletes the secret', async () => { + const { command, lines, inquired, calls, updates, removals } = commandUnderTest({ + answer: true, + key: ['API_KEY', 'DB_PASSWORD'], + secrets: ['DB_PASSWORD'], + }); + + await command.run(); + + expect(inquired).toEqual([ + { + type: 'confirm', + name: 'confirm', + message: + 'Are you sure you want to remove the variable API_KEY and the secret DB_PASSWORD from the "staging" environment?', + default: false, + }, + ]); + expect(calls).toEqual(['get', 'list', 'patch', 'remove']); + expect(updates).toEqual([{ ...SCOPE, unset: ['API_KEY'] }]); + expect(removals).toEqual([{ ...SCOPE, key: 'DB_PASSWORD' }]); + expect(lines).toEqual([ + '✔ Variable API_KEY removed from the "staging" environment.', + '✔ Secret DB_PASSWORD removed from the "staging" environment.', + ]); + }); + it('skips the question when --yes was passed', async () => { const { command, inquired, calls, lines } = commandUnderTest({ yes: true }); diff --git a/src/commands/launch/variables/unset.ts b/src/commands/launch/variables/unset.ts index c0ec539d..616453b5 100644 --- a/src/commands/launch/variables/unset.ts +++ b/src/commands/launch/variables/unset.ts @@ -14,12 +14,16 @@ const unsetInputs = inputs({ }); export default class VariablesUnset extends LaunchCommand { - static description = 'Remove environment variables from an environment, after asking for confirmation'; + static description = + 'Remove variables and secrets from an environment, after asking for confirmation. ' + + 'Each --key may name a variable or a secret; the command works out which'; static examples = [ '$ csdx launch:variables:unset --org --project --env --key API_KEY', '$ csdx launch:variables:unset --org --project --env ' + '--key API_KEY --key DEBUG --yes', + '$ csdx launch:variables:unset --org --project --env ' + + '--key DEBUG --key DB_PASSWORD', ]; static inputs = unsetInputs; diff --git a/src/variables/variable.dotenv.ts b/src/variables/variable.dotenv.ts index ddf70f5e..94e3fe02 100644 --- a/src/variables/variable.dotenv.ts +++ b/src/variables/variable.dotenv.ts @@ -17,7 +17,7 @@ export class DotenvLineError extends Error { const INLINE_COMMENT = /[ \t]#/; const EXPORT_PREFIX = /^export[ \t]+/; -const VALID_KEY = /^[A-Za-z_][A-Za-z0-9_.-]*$/; +export const VALID_KEY = /^[A-Za-z_][A-Za-z0-9_.-]*$/; const QUOTES = ['"', "'", '`']; function findClosingQuote(text: string, quote: string): number { diff --git a/src/variables/variable.errors.ts b/src/variables/variable.errors.ts index 9789fb2c..1e2c4eb4 100644 --- a/src/variables/variable.errors.ts +++ b/src/variables/variable.errors.ts @@ -1,4 +1,9 @@ -import { UsageError } from '../core/errors'; +import { EXIT_RUNTIME } from '../core/constants'; +import { LaunchError, UsageError } from '../core/errors'; +import { REDACTED } from '../core/redact'; +import { LaunchApiError, LaunchNetworkError } from '../transport/errors'; +import type { ApiErrorEntry } from '../transport/errors'; +import type { ErrorMessages } from '../transport/errors'; export function notSetError(keys: string[]): UsageError { return new UsageError(`${keys.join(', ')} ${keys.length === 1 ? 'is' : 'are'} not set in this environment.`); @@ -9,3 +14,55 @@ export function someNotSetError(keys: string[]): UsageError { ? notSetError(keys) : new UsageError(`At least one of ${keys.join(', ')} is not set in this environment.`); } + +export function notVariablesError(keys: string[]): UsageError { + return new UsageError(keys.map((key) => `${key} is a variable.`).join('\n')); +} + +export class SecretKeyConflictError extends LaunchError { + readonly exitCode = EXIT_RUNTIME; + + constructor( + readonly keys: string[] = [], + readonly cause?: LaunchApiError, + ) { + super( + keys.length === 0 + ? 'A key you passed is a secret. Use --secret to replace its value.' + : keys.map((key) => `${key} is a secret. Use --secret ${key} to replace its value.`).join('\n'), + ); + this.name = 'SecretKeyConflictError'; + } +} + +function withoutValues(text: string, values: string[]): string { + return values + .flatMap((value) => [value, value.trim()]) + .filter((form) => form !== '') + .sort((longer, shorter) => shorter.length - longer.length) + .reduce((redacted, form) => redacted.split(form).join(REDACTED), text); +} + +function redactedEntry(entry: ApiErrorEntry, values: string[]): ApiErrorEntry { + return entry.message === undefined ? entry : { ...entry, message: withoutValues(entry.message, values) }; +} + +export function withoutSecretValues(error: unknown, values: string[], messages: ErrorMessages): unknown { + if (error instanceof LaunchApiError) { + return new LaunchApiError( + error.status, + error.errors.map((entry) => redactedEntry(entry, values)), + messages, + ); + } + + if (error instanceof LaunchNetworkError) { + return new LaunchNetworkError(withoutValues(error.message, values), undefined, error.retryable); + } + + if (error instanceof LaunchError || !(error instanceof Error)) { + return error; + } + + return new Error(withoutValues(error.message, values)); +} diff --git a/src/variables/variable.inputs.test.ts b/src/variables/variable.inputs.test.ts index 62ab84a2..c91164aa 100644 --- a/src/variables/variable.inputs.test.ts +++ b/src/variables/variable.inputs.test.ts @@ -1,18 +1,19 @@ import { Parser } from '@oclif/core'; import { catalog } from '../resources'; +import { gluedValue } from '../../test/support/glued-value'; import { variableFlags, variableResolution } from './variable.inputs'; describe('variable inputs', () => { it('names each flag as the Commands Details "All flags" tables name it', () => { - expect(Object.keys(variableFlags)).toEqual(['var', 'dotenv', 'key', 'from-stack', 'alias']); + expect(Object.keys(variableFlags)).toEqual(['var', 'secret', 'dotenv', 'key', 'from-stack', 'alias']); }); - it.each(['var', 'dotenv', 'key'] as const)('declares %s repeatable so each occurrence and each value is kept', (name) => { + it.each(['var', 'secret', 'dotenv', 'key'] as const)('declares %s repeatable so each occurrence and each value is kept', (name) => { expect(variableFlags[name].multiple).toBe(true); }); - it.each(['var', 'dotenv', 'key', 'from-stack', 'alias'] as const)('never marks %s required at parse time', (name) => { + it.each(['var', 'secret', 'dotenv', 'key', 'from-stack', 'alias'] as const)('never marks %s required at parse time', (name) => { expect(variableFlags[name].required).toBeFalsy(); }); @@ -76,4 +77,50 @@ describe('variable inputs', () => { expect(parsed.flags['dotenv']).toEqual(['a.env', 'b.env']); expect(parsed.flags.key).toEqual(['X', 'Y']); }); + + it('parses --secret A,B and repeated --secret occurrences to the same keys in order', async () => { + const joined = await Parser.parse(['--secret', 'A,B', '--secret', 'C'], { flags: { secret: variableFlags.secret } }); + const trailing = await Parser.parse(['--secret', 'A', '--secret', 'B,C'], { + flags: { secret: variableFlags.secret }, + }); + + expect(joined.flags.secret).toEqual(['A', 'B', 'C']); + expect(trailing.flags.secret).toEqual(['A', 'B', 'C']); + }); + + it('stops --secret at the next flag instead of swallowing it', async () => { + const parsed = await Parser.parse(['--secret', 'STRIPE_KEY', '--project', 'x'], { + flags: { secret: variableFlags.secret, project: catalog.project }, + }); + + expect(parsed.flags.secret).toEqual(['STRIPE_KEY']); + expect(parsed.flags.project).toBe('x'); + }); + + it('takes one key per --secret occurrence, so a value typed after the key is a stray argument and not a key', async () => { + const value = gluedValue(); + + await expect( + Parser.parse(['--secret', 'STRIPE_KEY', value], { flags: { secret: variableFlags.secret }, strict: true }), + ).rejects.toThrow('Unexpected argument'); + }); + + it('describes --var as a variable whose value can be read in the UI', () => { + expect(variableFlags.var.description).toContain('variable, the value can be read in the UI'); + }); + + it('describes --secret as write-only and replacing, without a move sentence', () => { + const description = variableFlags.secret.description ?? ''; + + expect(description).toContain("write-only, the value can't be read back. Replaces the value if KEY is already a secret."); + expect(description).not.toMatch(/moves?/i); + }); + + it('describes --key as naming a variable or a secret to remove', () => { + expect(variableFlags.key.description).toBe('Key of a variable or a secret to remove, repeatable'); + }); + + it('says --dotenv - reads standard input when --secret is given', () => { + expect(variableFlags.dotenv.description).toContain('with --secret, - reads the dotenv text from standard input'); + }); }); diff --git a/src/variables/variable.inputs.ts b/src/variables/variable.inputs.ts index 254f7395..9a8d6b8a 100644 --- a/src/variables/variable.inputs.ts +++ b/src/variables/variable.inputs.ts @@ -6,14 +6,25 @@ export const variableFlags = { var: Flags.string({ multiple: true, description: - 'Environment variable as KEY=VALUE, repeatable. A KEY with no value is asked at a hidden prompt, ' + - 'or read from standard input when piped', + 'Environment variable as KEY=VALUE, repeatable: a variable, the value can be read in the UI. ' + + 'A KEY with no value is asked at a hidden prompt, or read from standard input when piped', + }), + secret: Flags.string({ + multiple: true, + multipleNonGreedy: true, + delimiter: ',', + description: + 'Secret KEY, repeatable or as A,B: write-only, the value can\'t be read back. ' + + 'Replaces the value if KEY is already a secret. The value is never a flag: it comes from --dotenv or ' + + '--from-stack, else a hidden prompt, else standard input when piped', }), dotenv: Flags.string({ multiple: true, - description: 'Path to a dotenv file, absolute or relative to the current folder', + description: + 'Path to a dotenv file, absolute or relative to the current folder. ' + + 'On launch:variables:set with --secret, - reads the dotenv text from standard input', }), - key: Flags.string({ multiple: true, description: 'Environment variable key, repeatable' }), + key: Flags.string({ multiple: true, description: 'Key of a variable or a secret to remove, repeatable' }), 'from-stack': Flags.boolean({ description: 'Import the variables of a Contentstack stack. Asks for the stack and a delivery token on a terminal', }), @@ -25,6 +36,7 @@ export const variableFlags = { export const variableResolution = { var: {} satisfies ResolutionSpec, + secret: {} satisfies ResolutionSpec, dotenv: {} satisfies ResolutionSpec, key: {} satisfies ResolutionSpec, 'from-stack': {} satisfies ResolutionSpec, diff --git a/src/variables/variable.page.test.ts b/src/variables/variable.page.test.ts index 785a5420..62b82bb2 100644 --- a/src/variables/variable.page.test.ts +++ b/src/variables/variable.page.test.ts @@ -1,39 +1,78 @@ import { pageOfVariables } from './variable.page'; -const THREE = [{ key: 'A' }, { key: 'B' }, { key: 'C' }]; +const VARIABLES = [{ key: 'A', value: 'never-printed-a' }, { key: 'B', value: 'never-printed-b' }]; +const SECRETS = [ + { key: 'S1', updatedAt: '2026-12-03T07:53:26.577Z' }, + { key: 'S2', updatedAt: undefined }, + { key: 'S3', updatedAt: undefined }, +]; describe('variable page', () => { - it('returns the window starting at skip and holding at most limit variables with the total count', () => { - const page = pageOfVariables(THREE, 1, 1); + it('lists the variables first and then the secrets, counting both', () => { + const page = pageOfVariables(VARIABLES, SECRETS, 100, 0); - expect(page).toEqual({ variables: [{ key: 'B' }], pagination: { count: 3, limit: 1, skip: 1 } }); + expect(page.rows.map((row) => `${row.type}:${row.key}`)).toEqual([ + 'variable:A', + 'variable:B', + 'secret:S1', + 'secret:S2', + 'secret:S3', + ]); + expect(page.pagination).toEqual({ count: 5, limit: 100, skip: 0 }); }); - it('returns every variable when limit is exactly the number held', () => { - expect(pageOfVariables(THREE, 3, 0).variables).toEqual(THREE); + it('returns only the variables when the limit stops at the boundary', () => { + const page = pageOfVariables(VARIABLES, SECRETS, 2, 0); + + expect(page.rows).toEqual([{ type: 'variable', key: 'A' }, { type: 'variable', key: 'B' }]); + expect(page.pagination).toEqual({ count: 5, limit: 2, skip: 0 }); }); - it('returns the remainder when limit runs past the end', () => { - expect(pageOfVariables(THREE, 100, 2).variables).toEqual([{ key: 'C' }]); + it('crosses from the last variable into the first secret', () => { + const page = pageOfVariables(VARIABLES, SECRETS, 2, 1); + + expect(page.rows).toEqual([ + { type: 'variable', key: 'B' }, + { type: 'secret', key: 'S1', updatedAt: '2026-12-03T07:53:26.577Z' }, + ]); + expect(page.pagination).toEqual({ count: 5, limit: 2, skip: 1 }); + }); + + it('returns only secrets once skip passes every variable', () => { + const page = pageOfVariables(VARIABLES, SECRETS, 10, 2); + + expect(page.rows.map((row) => row.type)).toEqual(['secret', 'secret', 'secret']); + expect(page.pagination).toEqual({ count: 5, limit: 10, skip: 2 }); }); it('returns nothing when skip equals the number held, still reporting the total', () => { - expect(pageOfVariables(THREE, 10, 3)).toEqual({ variables: [], pagination: { count: 3, limit: 10, skip: 3 } }); + expect(pageOfVariables(VARIABLES, SECRETS, 10, 5)).toEqual({ + rows: [], + pagination: { count: 5, limit: 10, skip: 5 }, + }); }); it('returns nothing when skip is past the end', () => { - expect(pageOfVariables(THREE, 10, 99).variables).toEqual([]); + expect(pageOfVariables(VARIABLES, SECRETS, 10, 99).rows).toEqual([]); + }); + + it('pages variables alone and secrets alone', () => { + expect(pageOfVariables(VARIABLES, [], 1, 1).rows).toEqual([{ type: 'variable', key: 'B' }]); + expect(pageOfVariables([], SECRETS, 1, 2).rows).toEqual([{ type: 'secret', key: 'S3', updatedAt: undefined }]); }); - it('returns nothing and a zero count when the environment holds no variables', () => { - expect(pageOfVariables([], 100, 0)).toEqual({ variables: [], pagination: { count: 0, limit: 100, skip: 0 } }); + it('returns nothing and a zero count when the environment holds neither', () => { + expect(pageOfVariables([], [], 100, 0)).toEqual({ rows: [], pagination: { count: 0, limit: 100, skip: 0 } }); }); - it('does not alter the list it was given', () => { - const held = [...THREE]; + it('keeps a variable value out of its row and does not alter the lists it was given', () => { + const variables = [...VARIABLES]; + const secrets = [...SECRETS]; - pageOfVariables(held, 1, 1); + const page = pageOfVariables(variables, secrets, 100, 0); - expect(held).toEqual(THREE); + expect(JSON.stringify(page)).not.toContain('never-printed'); + expect(variables).toEqual(VARIABLES); + expect(secrets).toEqual(SECRETS); }); }); diff --git a/src/variables/variable.page.ts b/src/variables/variable.page.ts index df24f108..b699937b 100644 --- a/src/variables/variable.page.ts +++ b/src/variables/variable.page.ts @@ -1,14 +1,30 @@ import type { Pagination } from '../core/render'; import type { EnvironmentVariable } from '../environments/types'; +import type { VariableRow } from './variable.presenter'; + +export interface HeldSecret { + key: string | undefined; + updatedAt: string | undefined; +} export interface VariablePage { - variables: EnvironmentVariable[]; + rows: VariableRow[]; pagination: Pagination; } -export function pageOfVariables(held: EnvironmentVariable[], limit: number, skip: number): VariablePage { +export function pageOfVariables( + variables: EnvironmentVariable[], + secrets: HeldSecret[], + limit: number, + skip: number, +): VariablePage { + const rows: VariableRow[] = [ + ...variables.map(({ key }): VariableRow => ({ type: 'variable', key })), + ...secrets.map(({ key, updatedAt }): VariableRow => ({ type: 'secret', key, updatedAt })), + ]; + return { - variables: held.slice(skip, skip + limit), - pagination: { count: held.length, limit, skip }, + rows: rows.slice(skip, skip + limit), + pagination: { count: rows.length, limit, skip }, }; } diff --git a/src/variables/variable.presenter.test.ts b/src/variables/variable.presenter.test.ts index c5f0bd90..efbd081a 100644 --- a/src/variables/variable.presenter.test.ts +++ b/src/variables/variable.presenter.test.ts @@ -1,8 +1,12 @@ import { REDACTED } from '../core/redact'; -import { pairColumns, variableColumns } from './variable.presenter'; +import { pairColumns, listColumns, WRITE_ONLY } from './variable.presenter'; +import type { VariableRow } from './variable.presenter'; -function cells(variable: { key?: string; value?: string }, updatedAt?: string): string[] { - return variableColumns(updatedAt).map((column) => column.value(variable)); +const ENVIRONMENT_UPDATED_AT = '2025-11-06T07:39:53.582Z'; +const SECRET_UPDATED_AT = '2026-12-03T07:53:26.577Z'; + +function cells(row: VariableRow, updatedAt?: string): string[] { + return listColumns(updatedAt).map((column) => column.value(row)); } describe('variable presenter', () => { @@ -10,23 +14,29 @@ describe('variable presenter', () => { expect(pairColumns().map((column) => column.header)).toEqual(['KEY', 'VALUE']); }); - it('renders the key, a masked value and the environment update time', () => { - const row = cells({ key: 'API_KEY', value: 'never-printed-abc' }, '2026-09-01T10:00:00.000Z'); + it('renders variable and secret rows in one table with a type column, masking and never showing a value', () => { + const variable = cells({ type: 'variable', key: 'API_URL', value: 'never-printed-abc' }, ENVIRONMENT_UPDATED_AT); + const stripe = cells({ type: 'secret', key: 'STRIPE_KEY', updatedAt: SECRET_UPDATED_AT }, ENVIRONMENT_UPDATED_AT); + const password = cells({ type: 'secret', key: 'DB_PASSWORD' }, ENVIRONMENT_UPDATED_AT); - expect(variableColumns().map((column) => column.header)).toEqual(['KEY', 'VALUE', 'UPDATED']); - expect(row).toEqual(['API_KEY', REDACTED, '2026-09-01T10:00:00.000Z']); - expect(row.join(' ')).not.toContain('never-printed-abc'); + expect(listColumns().map((column) => column.header)).toEqual(['KEY', 'TYPE', 'VALUE', 'UPDATED']); + expect(variable).toEqual(['API_URL', 'variable', REDACTED, ENVIRONMENT_UPDATED_AT]); + expect(stripe).toEqual(['STRIPE_KEY', 'secret', WRITE_ONLY, SECRET_UPDATED_AT]); + expect(password).toEqual(['DB_PASSWORD', 'secret', WRITE_ONLY, '-']); + expect(variable.join(' ')).not.toContain('never-printed-abc'); }); - it.each([[undefined], [''], [' ']])('renders a placeholder for a key that is %p', (key) => { - const row = cells({ key, value: 'secret' }, '2026-09-01'); + it('never uses the environment update time for a secret row', () => { + expect(cells({ type: 'secret', key: 'STRIPE_KEY' }, ENVIRONMENT_UPDATED_AT)[3]).toBe('-'); + }); - expect(row).toEqual(['-', REDACTED, '2026-09-01']); + it.each([[undefined], [''], [' ']])('renders a placeholder for a key that is %p', (key) => { + expect(cells({ type: 'variable', key }, '2026-09-01')).toEqual(['-', 'variable', REDACTED, '2026-09-01']); + expect(cells({ type: 'secret', key }, '2026-09-01')).toEqual(['-', 'secret', WRITE_ONLY, '-']); }); it.each([[undefined], [''], [' ']])('renders a placeholder for an update time that is %p', (updatedAt) => { - const row = cells({ key: 'API_KEY' }, updatedAt); - - expect(row).toEqual(['API_KEY', REDACTED, '-']); + expect(cells({ type: 'variable', key: 'API_KEY' }, updatedAt)).toEqual(['API_KEY', 'variable', REDACTED, '-']); + expect(cells({ type: 'secret', key: 'STRIPE_KEY', updatedAt })).toEqual(['STRIPE_KEY', 'secret', WRITE_ONLY, '-']); }); }); diff --git a/src/variables/variable.presenter.ts b/src/variables/variable.presenter.ts index 6800d019..50e72b69 100644 --- a/src/variables/variable.presenter.ts +++ b/src/variables/variable.presenter.ts @@ -1,8 +1,14 @@ -import { redactedColumn } from '../core/redact'; +import { REDACTED, redactedColumn } from '../core/redact'; import type { TableColumn } from '../core/render'; import { isAbsent } from '../core/values'; import type { EnvironmentVariable } from '../environments/types'; +export const WRITE_ONLY = '(write-only)'; + +export type VariableRow = + | ({ type: 'variable' } & EnvironmentVariable) + | { type: 'secret'; key?: string; updatedAt?: string }; + function text(value: string | undefined): string { return value === undefined || isAbsent(value) ? '-' : value; } @@ -11,6 +17,11 @@ export function pairColumns(): TableColumn[] { return [{ header: 'KEY', value: (variable) => text(variable.key) }, redactedColumn('VALUE')]; } -export function variableColumns(updatedAt?: string): TableColumn[] { - return [...pairColumns(), { header: 'UPDATED', value: () => text(updatedAt) }]; +export function listColumns(environmentUpdatedAt?: string): TableColumn[] { + return [ + { header: 'KEY', value: (row) => text(row.key) }, + { header: 'TYPE', value: (row) => row.type }, + { header: 'VALUE', value: (row) => (row.type === 'secret' ? WRITE_ONLY : REDACTED) }, + { header: 'UPDATED', value: (row) => text(row.type === 'secret' ? row.updatedAt : environmentUpdatedAt) }, + ]; } diff --git a/src/variables/variable.rules.test.ts b/src/variables/variable.rules.test.ts index 5fbe3a89..a74e0c6c 100644 --- a/src/variables/variable.rules.test.ts +++ b/src/variables/variable.rules.test.ts @@ -1,5 +1,11 @@ import { UsageError } from '../core/errors'; -import { aliasRequiresFromStack, singleDotenv } from './variable.rules'; +import { gluedValue } from '../../test/support/glued-value'; +import { + aliasRequiresFromStack, + SECRET_KEY_INVALID_MESSAGE, + secretTakesKeyOnly, + singleDotenv, +} from './variable.rules'; describe('variable rules', () => { it('refuses --alias without --from-stack, naming both', () => { @@ -38,4 +44,49 @@ describe('variable rules', () => { it.each([[undefined], [[]], [['a.env']]])('accepts no --dotenv or a single one (%p)', (dotenv) => { expect(() => singleDotenv({ dotenv }, {})).not.toThrow(); }); + + it.each([['='], [':']])('refuses --secret KEY%svalue as a usage error that does not echo the value', (separator) => { + const value = gluedValue(); + const run = () => secretTakesKeyOnly({ secret: ['OK', `STRIPE_KEY${separator}${value}`] }, { secret: 'flag' }); + + expect(run).toThrow(UsageError); + expect(run).toThrow('--secret takes a key only. Give the value at the prompt, on standard input or with --dotenv.'); + expect(run).not.toThrow(value); + }); + + it.each([[' '], ['\t'], [' ']])( + 'refuses a --secret token with a value after whitespace as a usage error that does not echo it', + (gap) => { + const value = gluedValue(); + const run = () => secretTakesKeyOnly({ secret: ['OK', `DB_PASSWORD${gap}${value}`] }, { secret: 'flag' }); + + expect(run).toThrow(UsageError); + expect(run).toThrow(SECRET_KEY_INVALID_MESSAGE); + expect(run).not.toThrow(value); + expect(run).not.toThrow('DB_PASSWORD'); + }, + ); + + it.each([['1KEY'], ['-KEY'], ['.KEY'], ['KEY!'], ['KÉY'], [' KEY'], ['KEY ']])( + 'refuses --secret %p, which is not an environment variable key', + (key) => { + const run = () => secretTakesKeyOnly({ secret: [key] }, { secret: 'flag' }); + + expect(run).toThrow(UsageError); + expect(run).toThrow(SECRET_KEY_INVALID_MESSAGE); + }, + ); + + it.each([['A'], ['_A'], ['a_b'], ['A.B'], ['A-B'], ['A1']])('accepts --secret %p as an environment variable key', (key) => { + expect(() => secretTakesKeyOnly({ secret: [key] }, {})).not.toThrow(); + }); + + it.each([[['']], [[' ']], [['A', '']], [[42]]])('refuses a blank or non-text --secret key (%p)', (secret) => { + expect(() => secretTakesKeyOnly({ secret }, {})).toThrow(UsageError); + expect(() => secretTakesKeyOnly({ secret }, {})).toThrow('--secret needs a key. Pass --secret .'); + }); + + it.each([[undefined], [null], [[]], [['STRIPE_KEY', 'DB_PASSWORD']]])('accepts no --secret or plain keys (%p)', (secret) => { + expect(() => secretTakesKeyOnly({ secret }, {})).not.toThrow(); + }); }); diff --git a/src/variables/variable.rules.ts b/src/variables/variable.rules.ts index fac097ee..be3e6f3b 100644 --- a/src/variables/variable.rules.ts +++ b/src/variables/variable.rules.ts @@ -1,6 +1,7 @@ import { UsageError } from '../core/errors'; import type { Rule } from '../core/rules'; import { isAbsent } from '../core/values'; +import { VALID_KEY } from './variable.dotenv'; import { MULTIPLE_DOTENV_PATHS } from './variable.files'; export const aliasRequiresFromStack: Rule = (resolved) => { @@ -17,3 +18,32 @@ export const singleDotenv: Rule = (resolved) => { throw new UsageError(MULTIPLE_DOTENV_PATHS); } }; + +export const SECRET_KEY_ONLY_MESSAGE = + '--secret takes a key only. Give the value at the prompt, on standard input or with --dotenv.'; + +export const SECRET_KEY_INVALID_MESSAGE = + '--secret takes a key made of letters, digits, _, . and -, starting with a letter or _. ' + + 'Give the value at the prompt, on standard input or with --dotenv.'; + +export const SECRET_KEY_MISSING_MESSAGE = '--secret needs a key. Pass --secret .'; + +export const secretTakesKeyOnly: Rule = (resolved) => { + const keys = resolved.secret; + + if (!Array.isArray(keys)) { + return; + } + + if (keys.some((key) => typeof key !== 'string' || isAbsent(key))) { + throw new UsageError(SECRET_KEY_MISSING_MESSAGE); + } + + if (keys.some((key: string) => key.includes('=') || key.includes(':'))) { + throw new UsageError(SECRET_KEY_ONLY_MESSAGE); + } + + if (keys.some((key: string) => !VALID_KEY.test(key))) { + throw new UsageError(SECRET_KEY_INVALID_MESSAGE); + } +}; diff --git a/src/variables/variable.secrets.ts b/src/variables/variable.secrets.ts new file mode 100644 index 00000000..d9f8e420 --- /dev/null +++ b/src/variables/variable.secrets.ts @@ -0,0 +1,172 @@ +import { CancelledError, UsageError } from '../core/errors'; +import type { UxLike } from '../core/prompt'; +import type { ServiceContext } from '../core/service-context'; +import { emptyValueError } from '../core/secret-input'; +import { SecretKeyConflictError, notVariablesError } from './variable.errors'; +import type { Assignment } from './variable.parse'; + +export const MAX_ENTRIES = 128; + +export const MAX_BYTES = 14 * 1024; + +export const STDIN_PATH = '-'; + +function listed(keys: string[]): string { + return keys.join(', '); +} + +function isOrAre(keys: string[]): string { + return keys.length === 1 ? 'is' : 'are'; +} + +export function assertDistinctSecrets(keys: string[]): void { + const repeated = [...new Set(keys.filter((key, index) => keys.indexOf(key) !== index))]; + + if (repeated.length > 0) { + throw new UsageError( + `${listed(repeated)} ${repeated.length === 1 ? 'was' : 'were'} passed to --secret more than once. ` + + 'Pass each key once.', + ); + } +} + +export function assertNotAlsoVariable(assignments: Assignment[], keys: string[]): void { + const clashing = keys.filter((key) => assignments.some((assignment) => assignment.key === key)); + + if (clashing.length > 0) { + throw new UsageError( + `${listed(clashing)} ${isOrAre(clashing)} in both --var and --secret. ` + + 'A secret value never goes on the command line: remove it from --var.', + ); + } +} + +export function assertNoBareVariables(assignments: Assignment[], services: ServiceContext): void { + const bare = assignments.filter(({ value }) => value === undefined).map(({ key }) => key); + + if (bare.length > 0 && !services.isTTY) { + throw new UsageError( + `${listed(bare)} ${bare.length === 1 ? 'has' : 'have'} no value. ` + + 'With --secret, standard input is for the secret: pass --var =, or use --dotenv .', + ); + } +} + +export function assertPipedValues(lacking: string[], services: ServiceContext, dotenvOnStdin: boolean): void { + if (!services.isTTY && dotenvOnStdin && lacking.length > 0) { + throw new UsageError( + `No value for ${listed(lacking)} was found in the dotenv text on standard input. ` + + `Add ${lacking.map((key) => `${key}=`).join(', ')} to it.`, + ); + } + + if (!services.isTTY && lacking.length > 1) { + throw new UsageError( + `${listed(lacking)} each need a value, and only one value can be piped in. ` + + 'Pipe KEY=value lines into --dotenv - instead, or use --dotenv .', + ); + } +} + +export function assertStreamKeysNamed(streamKeys: string[], secretKeys: string[]): void { + const unnamed = streamKeys.filter((key) => !secretKeys.includes(key)); + + if (unnamed.length > 0) { + const one = unnamed.length === 1; + + throw new UsageError( + `The dotenv text on standard input holds ${listed(unnamed)}, ` + + `which ${one ? 'is' : 'are'} not named in --secret and would be saved as ` + + `${one ? 'a readable variable' : 'readable variables'}. ` + + `Name ${one ? 'it' : 'them'} in --secret, remove ${one ? 'it' : 'them'} from the input, ` + + 'or use --dotenv to set variables and secrets together.', + ); + } +} + +export function assertNoDotenvOnTerminal(envFiles: string[] | undefined, services: ServiceContext): void { + if (services.isTTY && (envFiles ?? []).includes(STDIN_PATH)) { + throw new UsageError( + '--dotenv - reads the dotenv text from standard input, and this is a terminal. ' + + 'Pipe it in, for example: printf \'STRIPE_KEY=%s\\n\' "$STRIPE_KEY" | ' + + 'csdx launch:variables:set --secret STRIPE_KEY --dotenv -, or use --dotenv .', + ); + } +} + +export function assertNotVariables(keys: string[], heldVariables: Set): void { + const variables = keys.filter((key) => heldVariables.has(key)); + + if (variables.length > 0) { + throw notVariablesError(variables); + } +} + +export function assertNotHeldSecrets(variableKeys: string[], heldSecrets: Set): void { + const secrets = [...new Set(variableKeys)].filter((key) => heldSecrets.has(key)); + + if (secrets.length > 0) { + throw new SecretKeyConflictError(secrets); + } +} + +export function assertSecretValue(key: string, value: string): void { + if (value.trim() === '') { + throw emptyValueError(key); + } + + if (/[\r\n]/.test(value)) { + throw new UsageError( + `The value for ${key} has more than one line. A secret value must be a single line; nothing was changed.`, + ); + } +} + +export interface Held { + variables: Set; + secrets: Set; +} + +export function assertEntryLimit(held: Held, variableKeys: string[], secretKeys: string[]): void { + const total = + new Set([...held.variables, ...variableKeys]).size + new Set([...held.secrets, ...secretKeys]).size; + + if (total > MAX_ENTRIES) { + throw new UsageError( + `This change would leave ${total} variables and secrets in the environment, ` + + `and the limit is ${MAX_ENTRIES}. Nothing was changed.`, + ); + } +} + +export function assertByteLimit(entries: { key: string; value: string }[]): void { + const total = entries.reduce((sum, { key, value }) => sum + Buffer.byteLength(key) + Buffer.byteLength(value), 0); + + if (total > MAX_BYTES) { + throw new UsageError( + `This request is ${total} bytes of keys and values, and one request is limited to ${MAX_BYTES} bytes (14 KB). ` + + 'Nothing was changed.', + ); + } +} + +export function withoutTrailingNewline(text: string): string { + return text.replace(/\r?\n$/, ''); +} + +export async function askSecretValue(ux: UxLike, message: string): Promise { + const validate = (value: string): true | string => (value.trim() === '' ? `${message} can't be empty.` : true); + const answer = await ux.inquire({ + type: 'password', + name: 'value', + message, + mask: '*', + validate, + }); + + if (typeof answer !== 'string') { + throw new CancelledError(); + } + + return answer; +} diff --git a/src/variables/variable.set.test.ts b/src/variables/variable.set.test.ts index fcb970dc..e1a9c414 100644 --- a/src/variables/variable.set.test.ts +++ b/src/variables/variable.set.test.ts @@ -4,9 +4,14 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Readable } from 'node:stream'; +import { gluedValue } from '../../test/support/glued-value'; +import { CancelledError, UsageError } from '../core/errors'; import type { UxLike } from '../core/prompt'; +import type { SecretValueIo } from '../core/secret-input'; +import { SecretInputTimeoutError } from '../core/secret-input'; import type { ServiceContext } from '../core/service-context'; import type { PatchVariablesParams } from './variables.api'; +import { SecretKeyConflictError } from './variable.errors'; import { DEFAULT_VARIABLE_IO } from './variable.io'; import { VariableSetter } from './variable.set'; import type { SavedToken } from './variable.stack'; @@ -213,6 +218,993 @@ describe('variable setter with --from-stack', () => { ).rejects.toThrow('--alias is required with --from-stack.'); expect(patches).toEqual([]); }); + + it('reads a --secret key from --from-stack and keeps the other stack keys as variables', async () => { + const token = gluedValue(); + const { setter, asked, patches } = secretSetter({ + terminal: {}, + stack: { + saved: { token, apiKey: 'blt9', environment: 'staging' }, + template: [{ key: 'CONTENTSTACK_API_HOST', value: 'api.example.test' }], + }, + }); + + await setter.set({ + ...SCOPE, + ...NO_SOURCES, + fromStack: true, + alias: 'prod', + secrets: ['CONTENTSTACK_DELIVERY_TOKEN'], + }); + + expect(asked).toEqual([]); + expect(patches).toEqual([ + { + ...SCOPE, + set: [ + { key: 'CONTENTSTACK_API_HOST', value: 'api.example.test' }, + { key: 'CONTENTSTACK_API_KEY', value: 'blt9' }, + { key: 'CONTENTSTACK_ENVIRONMENT', value: 'staging' }, + ], + secrets: [{ key: 'CONTENTSTACK_DELIVERY_TOKEN', value: token }], + }, + ]); + }); +}); + +interface SecretRun { + files?: Record; + terminal?: Record; + heldVariables?: (string | undefined)[]; + heldSecrets?: (string | undefined)[]; + dotenvStdin?: string; + keyStdin?: string; + stdinTimeoutMs?: number; + readsNeverEnd?: boolean; + dotenvReadsNeverEnd?: boolean; + fail?: { environment?: Error; secrets?: Error; patch?: Error; keyStdin?: Error }; + stack?: { saved: SavedToken; template: { key: string; value: string }[] }; +} + +function secretSetter(run: SecretRun = {}) { + const asked: { message: string; payload: Record }[] = []; + const events: string[] = []; + const patches: PatchVariablesParams[] = []; + const reads = { dotenvStdin: 0, keyStdin: 0, closed: 0 }; + const answers = run.terminal; + const ux: UxLike = { + print: (message: string) => { + events.push(`print:${message}`); + }, + inquire: (async (payload: { message: string }) => { + asked.push({ message: payload.message, payload: payload as unknown as Record }); + events.push(`ask:${payload.message}`); + return (answers ?? {})[payload.message]; + }) as UxLike['inquire'], + }; + const services = { + ux, + isTTY: answers !== undefined, + outputIsTTY: false, + api: { + environments: { + get: async () => { + events.push('get environment'); + if (run.fail?.environment) { + throw run.fail.environment; + } + return run.heldVariables === undefined + ? {} + : { environmentVariables: run.heldVariables.map((key) => ({ key })) }; + }, + }, + secrets: { + list: async () => { + events.push('list secrets'); + if (run.fail?.secrets) { + throw run.fail.secrets; + } + return (run.heldSecrets ?? []).map((key) => ({ key, updatedAt: '2026-12-03T07:53:26.577Z' })); + }, + }, + variables: { + stackTemplate: async () => run.stack?.template ?? [], + patch: async (params: PatchVariablesParams) => { + events.push('patch'); + patches.push(params); + if (run.fail?.patch) { + throw run.fail.patch; + } + return []; + }, + }, + }, + } as unknown as ServiceContext; + const files = run.files ?? {}; + const io = { + readFile: async (path: string) => { + events.push(`read:${path}`); + if (!(path in files)) { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); + } + return files[path]; + }, + exists: (path: string) => path in files, + readStdin: async () => { + reads.dotenvStdin += 1; + events.push('read stdin'); + if (run.dotenvReadsNeverEnd) { + return new Promise(() => undefined); + } + return run.dotenvStdin ?? ''; + }, + }; + const secretIo: SecretValueIo = { + readStdin: () => { + reads.keyStdin += 1; + events.push('read stdin'); + if (run.readsNeverEnd) { + return new Promise(() => undefined); + } + return run.fail?.keyStdin ? Promise.reject(run.fail.keyStdin) : Promise.resolve(run.keyStdin ?? ''); + }, + closeStdin: () => { + reads.closed += 1; + }, + stdinTimeoutMs: run.stdinTimeoutMs ?? 1000, + }; + const setter = new VariableSetter(services, io, () => run.stack?.saved, secretIo); + + return { setter, asked, events, patches, reads }; +} + +function messagesOf(asked: { message: string }[]): string[] { + return asked.map(({ message }) => message); +} + +function wire(events: string[]): string[] { + return events.filter((event) => !event.startsWith('print:') && !event.startsWith('ask:') && event !== 'read stdin'); +} + +const NO_SOURCES = { vars: undefined, envFiles: undefined, dataDir: '/work' }; + +describe('variable setter with --secret', () => { + it('takes a secret from --dotenv, asks one masked prompt unnumbered for the key the file lacks, and sends one patch', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + const { setter, asked, patches, reads, events } = secretSetter({ + files: { 'a.env': `API_URL=https://x\nSTRIPE_KEY=${stripe}` }, + terminal: { 'Value for DB_PASSWORD': password }, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['a.env'], secrets: ['STRIPE_KEY', 'DB_PASSWORD'] }); + + expect(messagesOf(asked)).toEqual(['Value for DB_PASSWORD']); + expect(asked[0].payload).toMatchObject({ type: 'password', mask: '*' }); + expect(reads).toEqual({ dotenvStdin: 0, keyStdin: 0, closed: 0 }); + expect(patches).toEqual([ + { + ...SCOPE, + set: [{ key: 'API_URL', value: 'https://x' }], + secrets: [ + { key: 'STRIPE_KEY', value: stripe }, + { key: 'DB_PASSWORD', value: password }, + ], + }, + ]); + expect(wire(events)).toEqual(['read:a.env', 'get environment', 'list secrets', 'patch']); + }); + + it('asks a numbered masked prompt per key when several are needed, never the source chooser, and reads no stdin', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + const { setter, asked, patches, reads } = secretSetter({ + terminal: { 'Value for STRIPE_KEY (1/2)': stripe, 'Value for DB_PASSWORD (2/2)': password }, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY', 'DB_PASSWORD'] }); + + expect(messagesOf(asked)).toEqual(['Value for STRIPE_KEY (1/2)', 'Value for DB_PASSWORD (2/2)']); + expect(asked.map(({ payload }) => payload.type)).toEqual(['password', 'password']); + expect(reads.dotenvStdin + reads.keyStdin).toBe(0); + expect(patches).toEqual([ + { + ...SCOPE, + secrets: [ + { key: 'STRIPE_KEY', value: stripe }, + { key: 'DB_PASSWORD', value: password }, + ], + }, + ]); + }); + + it('does not open the chooser, auto-detect .env.local or print Using variables from for --secret alone', async () => { + const value = gluedValue(); + const { setter, asked, events, patches } = secretSetter({ + files: { '/work/.env.local': 'API_URL=https://x' }, + terminal: { 'Value for STRIPE_KEY': value }, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }); + + expect(messagesOf(asked)).toEqual(['Value for STRIPE_KEY']); + expect(events.some((event) => event.startsWith('read:'))).toBe(false); + expect(events.some((event) => event.includes('Using variables from'))).toBe(false); + expect(patches).toEqual([{ ...SCOPE, secrets: [{ key: 'STRIPE_KEY', value }] }]); + }); + + it('succeeds with only --secret and no variable instead of printing No changes made', async () => { + const { setter, events } = secretSetter({ keyStdin: `${gluedValue()}\n` }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }); + + expect(events).not.toContain('print:No changes made.'); + expect(events).toContain('patch'); + }); + + it('reads the dotenv text from standard input for --dotenv - and takes every secret from it with no prompt', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + const { setter, patches, reads, asked, events } = secretSetter({ + dotenvStdin: `STRIPE_KEY=${stripe}\nDB_PASSWORD=${password}\n`, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['STRIPE_KEY', 'DB_PASSWORD'] }); + + expect(reads).toEqual({ dotenvStdin: 1, keyStdin: 0, closed: 0 }); + expect(asked).toEqual([]); + expect(events).not.toContain('read:-'); + expect(patches).toEqual([ + { + ...SCOPE, + secrets: [ + { key: 'STRIPE_KEY', value: stripe }, + { key: 'DB_PASSWORD', value: password }, + ], + }, + ]); + }); + + it('still reads --dotenv - as a file named - when no --secret is given', async () => { + const { setter, order } = fakes({ '-': 'A=1' }); + + await setter.set({ ...SCOPE, vars: undefined, envFiles: ['-'], dataDir: '/work' }); + + expect(order).toEqual(['read:-', 'patch']); + }); + + it('refuses a --dotenv - stream that lacks a --secret key without a terminal, naming the key and asking nothing', async () => { + const stripe = gluedValue(); + const { setter, reads, asked, patches } = secretSetter({ dotenvStdin: `STRIPE_KEY=${stripe}\n` }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['STRIPE_KEY', 'DB_PASSWORD'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe( + 'No value for DB_PASSWORD was found in the dotenv text on standard input. Add DB_PASSWORD= to it.', + ); + expect((failure as Error).message).not.toContain(stripe); + expect(reads).toEqual({ dotenvStdin: 1, keyStdin: 0, closed: 0 }); + expect(asked).toEqual([]); + expect(patches).toEqual([]); + }); + + it('refuses a --dotenv - stream that holds keys not named in --secret, naming them and never a value, before any request', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + const { setter, reads, asked, events, patches } = secretSetter({ + dotenvStdin: `STRIPE_KEY=${stripe}\nDB_PASSWORD=${password}\nEMPTY=\n`, + }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as UsageError).exitCode).toBe(2); + expect((failure as Error).message).toBe( + 'The dotenv text on standard input holds DB_PASSWORD, EMPTY, which are not named in --secret and would be ' + + 'saved as readable variables. Name them in --secret, remove them from the input, or use --dotenv ' + + 'to set variables and secrets together.', + ); + expect((failure as Error).message).not.toContain(stripe); + expect((failure as Error).message).not.toContain(password); + expect(reads).toEqual({ dotenvStdin: 1, keyStdin: 0, closed: 0 }); + expect(asked).toEqual([]); + expect(events).not.toContain('get environment'); + expect(events).not.toContain('list secrets'); + expect(patches).toEqual([]); + }); + + it('uses the singular for one key a --dotenv - stream holds beyond --secret', async () => { + const { setter } = secretSetter({ dotenvStdin: `STRIPE_KEY=${gluedValue()}\nAPI_URL=https://x\n` }); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['STRIPE_KEY'] })).rejects.toThrow( + 'The dotenv text on standard input holds API_URL, which is not named in --secret and would be saved as a ' + + 'readable variable.', + ); + }); + + it('still sends the other keys of a --dotenv file as variables beside --secret', async () => { + const stripe = gluedValue(); + const { setter, patches } = secretSetter({ + files: { 'ci.env': `STRIPE_KEY=${stripe}\nAPI_URL=https://x\nDB_HOST=db.example.test\n` }, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['ci.env'], secrets: ['STRIPE_KEY'] }); + + expect(patches).toEqual([ + { + ...SCOPE, + set: [ + { key: 'API_URL', value: 'https://x' }, + { key: 'DB_HOST', value: 'db.example.test' }, + ], + secrets: [{ key: 'STRIPE_KEY', value: stripe }], + }, + ]); + }); + + it('names every key a --dotenv - stream lacks', async () => { + const { setter } = secretSetter({ dotenvStdin: 'OTHER=1\n' }); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['A', 'B'] })).rejects.toThrow( + 'No value for A, B was found in the dotenv text on standard input. Add A=, B= to it.', + ); + }); + + it('reads one piped value for a single key without a terminal and drops its one trailing newline', async () => { + const value = gluedValue(); + const { setter, reads, asked, patches } = secretSetter({ keyStdin: `${value}\n` }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }); + + expect(reads).toEqual({ dotenvStdin: 0, keyStdin: 1, closed: 0 }); + expect(asked).toEqual([]); + expect(patches).toEqual([{ ...SCOPE, secrets: [{ key: 'STRIPE_KEY', value }] }]); + }); + + it('refuses a second key that needs stdin without a terminal, naming --dotenv -, before reading or sending anything', async () => { + const { setter, reads, events } = secretSetter({ keyStdin: `${gluedValue()}\n` }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY', 'DB_PASSWORD'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toContain('--dotenv -'); + expect((failure as Error).message).toContain('STRIPE_KEY, DB_PASSWORD'); + expect(reads).toEqual({ dotenvStdin: 0, keyStdin: 0, closed: 0 }); + expect(events).toEqual([]); + }); + + it('lets a --dotenv file supply one key so the other can read standard input', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + const { setter, patches, reads } = secretSetter({ + files: { 'a.env': `STRIPE_KEY=${stripe}` }, + keyStdin: `${password}\n`, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['a.env'], secrets: ['STRIPE_KEY', 'DB_PASSWORD'] }); + + expect(reads.keyStdin).toBe(1); + expect(patches[0].secrets).toEqual([ + { key: 'STRIPE_KEY', value: stripe }, + { key: 'DB_PASSWORD', value: password }, + ]); + }); + + it('refuses --dotenv - on a terminal, asking to pipe the dotenv text in, before reading or asking anything', async () => { + const { setter, reads, asked, events, patches } = secretSetter({ terminal: {} }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as UsageError).exitCode).toBe(2); + expect((failure as Error).message).toBe( + '--dotenv - reads the dotenv text from standard input, and this is a terminal. ' + + 'Pipe it in, for example: printf \'STRIPE_KEY=%s\\n\' "$STRIPE_KEY" | ' + + 'csdx launch:variables:set --secret STRIPE_KEY --dotenv -, or use --dotenv .', + ); + expect(reads).toEqual({ dotenvStdin: 0, keyStdin: 0, closed: 0 }); + expect(asked).toEqual([]); + expect(events).toEqual([]); + expect(patches).toEqual([]); + }); + + it('still reads a --dotenv file on a terminal beside --secret', async () => { + const value = gluedValue(); + const { setter, reads, patches } = secretSetter({ + terminal: {}, + files: { 'a.env': `STRIPE_KEY=${value}` }, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['a.env'], secrets: ['STRIPE_KEY'] }); + + expect(reads.dotenvStdin).toBe(0); + expect(patches).toEqual([{ ...SCOPE, secrets: [{ key: 'STRIPE_KEY', value }] }]); + }); + + it('words the timeout of a --dotenv - stream that never ends with the dotenv hint, closing stdin and sending nothing', async () => { + jest.useFakeTimers(); + + try { + const { setter, reads, patches } = secretSetter({ dotenvReadsNeverEnd: true, stdinTimeoutMs: 1000 }); + const outcome = setter + .set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + await jest.advanceTimersByTimeAsync(1000); + + const failure = await outcome; + + expect(failure).toBeInstanceOf(SecretInputTimeoutError); + expect((failure as Error).message).toContain('No dotenv text arrived on standard input within 1 second'); + expect((failure as Error).message).not.toContain('"$TOKEN"'); + expect(reads).toEqual({ dotenvStdin: 1, keyStdin: 0, closed: 1 }); + expect(patches).toEqual([]); + } finally { + jest.useRealTimers(); + } + }); + + it('refuses a bare --var KEY without a terminal when --secret is given, reading nothing', async () => { + const { setter, reads, events } = secretSetter({ keyStdin: `${gluedValue()}\n` }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, vars: ['API_TOKEN'], secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe( + 'API_TOKEN has no value. With --secret, standard input is for the secret: ' + + 'pass --var =, or use --dotenv .', + ); + expect(reads).toEqual({ dotenvStdin: 0, keyStdin: 0, closed: 0 }); + expect(events).toEqual([]); + }); + + it('names every bare --var key when several lack a value', async () => { + const { setter } = secretSetter(); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, vars: ['A', 'B'], secrets: ['S'] })).rejects.toThrow( + 'A, B have no value.', + ); + }); + + it('still asks for a bare --var KEY on a terminal beside a --secret key', async () => { + const token = gluedValue(); + const stripe = gluedValue(); + const { setter, asked, patches } = secretSetter({ + terminal: { 'Value for API_TOKEN': token, 'Value for STRIPE_KEY': stripe }, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, vars: ['API_TOKEN'], secrets: ['STRIPE_KEY'] }); + + expect(messagesOf(asked)).toEqual(['Value for API_TOKEN', 'Value for STRIPE_KEY']); + expect(patches).toEqual([ + { + ...SCOPE, + set: [{ key: 'API_TOKEN', value: token }], + secrets: [{ key: 'STRIPE_KEY', value: stripe }], + }, + ]); + }); + + it.each([ + ['on a terminal', { terminal: {} }], + ['without a terminal', {}], + ])('refuses a key in both --var KEY=value and --secret %s, naming the key and never the value', async (_label, run) => { + const value = gluedValue(); + const { setter, asked, events } = secretSetter(run); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, vars: [`STRIPE_KEY=${value}`], secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe( + 'STRIPE_KEY is in both --var and --secret. A secret value never goes on the command line: ' + + 'remove it from --var.', + ); + expect((failure as Error).message).not.toContain(value); + expect(asked).toEqual([]); + expect(events).toEqual([]); + }); + + it('names every key that is in both --var and --secret', async () => { + const { setter } = secretSetter(); + + await expect( + setter.set({ ...SCOPE, ...NO_SOURCES, vars: ['A=1', 'B=2'], secrets: ['A', 'B'] }), + ).rejects.toThrow('A, B are in both --var and --secret.'); + }); + + it('refuses the same --secret key twice before any prompt or read, naming it once', async () => { + const { setter, asked, events } = secretSetter({ terminal: {} }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY', 'STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe('STRIPE_KEY was passed to --secret more than once. Pass each key once.'); + expect(asked).toEqual([]); + expect(events).toEqual([]); + }); + + it('names every repeated --secret key once', async () => { + const { setter } = secretSetter({ terminal: {} }); + + await expect( + setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['A', 'B', 'A', 'B', 'A'] }), + ).rejects.toThrow('A, B were passed to --secret more than once.'); + }); + + it('refuses a --secret key that is a held variable before any prompt or write', async () => { + const { setter, asked, events } = secretSetter({ terminal: {}, heldVariables: ['API_URL', 'OTHER'] }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, secrets: ['API_URL'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe('API_URL is a variable.'); + expect(asked).toEqual([]); + expect(wire(events)).toEqual(['get environment', 'list secrets']); + }); + + it('names each --secret key that is a held variable on its own line', async () => { + const { setter } = secretSetter({ terminal: {}, heldVariables: ['A', 'B'] }); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['A', 'C', 'B'] })).rejects.toThrow( + 'A is a variable.\nB is a variable.', + ); + }); + + it.each([ + ['--var', { vars: ['STRIPE_KEY=https://x'] }, {}], + ['--dotenv', { envFiles: ['a.env'] }, { files: { 'a.env': 'STRIPE_KEY=https://x' } }], + ])( + 'refuses a %s variable that is a held secret before any prompt, with the Replace hint and exit 1', + async (_label, source, run) => { + const { setter, asked, events, patches } = secretSetter({ + ...run, + terminal: {}, + heldSecrets: ['STRIPE_KEY', 'OTHER'], + }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, ...source, secrets: ['DB_PASSWORD'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(SecretKeyConflictError); + expect((failure as SecretKeyConflictError).exitCode).toBe(1); + expect((failure as Error).message).toBe('STRIPE_KEY is a secret. Use --secret STRIPE_KEY to replace its value.'); + expect(asked).toEqual([]); + expect(wire(events).slice(-2)).toEqual(['get environment', 'list secrets']); + expect(patches).toEqual([]); + }, + ); + + it('refuses a --from-stack variable that is a held secret before any prompt', async () => { + const { setter, asked, patches } = secretSetter({ + terminal: {}, + heldSecrets: ['CONTENTSTACK_API_HOST'], + stack: { + saved: { token: gluedValue(), apiKey: 'blt9', environment: 'staging' }, + template: [{ key: 'CONTENTSTACK_API_HOST', value: 'api.example.test' }], + }, + }); + + await expect( + setter.set({ ...SCOPE, ...NO_SOURCES, fromStack: true, alias: 'prod', secrets: ['DB_PASSWORD'] }), + ).rejects.toThrow('CONTENTSTACK_API_HOST is a secret. Use --secret CONTENTSTACK_API_HOST to replace its value.'); + expect(asked).toEqual([]); + expect(patches).toEqual([]); + }); + + it('names each variable that is a held secret on its own line and does not count it twice towards the limit', async () => { + const { setter, asked, patches } = secretSetter({ + terminal: {}, + heldVariables: Array.from({ length: 100 }, (_, index) => `V${index}`), + heldSecrets: Array.from({ length: 28 }, (_, index) => `S${index}`), + }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, vars: ['S0=1', 'S1=2', 'V1=3'], secrets: ['S2'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(SecretKeyConflictError); + expect((failure as Error).message).toBe( + 'S0 is a secret. Use --secret S0 to replace its value.\nS1 is a secret. Use --secret S1 to replace its value.', + ); + expect(asked).toEqual([]); + expect(patches).toEqual([]); + }); + + it.each([ + ['an empty answer', ''], + ['a blank answer', ' '], + ])('refuses %s at the prompt as an empty value and sends nothing', async (_label, answer) => { + const { setter, patches } = secretSetter({ terminal: { 'Value for STRIPE_KEY': answer } }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe( + 'The value for STRIPE_KEY is empty. A secret needs a non-empty value; nothing was changed.', + ); + expect(patches).toEqual([]); + }); + + it('refuses a piped lone newline as an empty value and sends nothing', async () => { + const { setter, patches } = secretSetter({ keyStdin: '\n' }); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] })).rejects.toThrow( + 'The value for STRIPE_KEY is empty. A secret needs a non-empty value; nothing was changed.', + ); + expect(patches).toEqual([]); + }); + + it('sends a value padded with spaces unchanged', async () => { + const value = ` ${gluedValue()} `; + const { setter, patches } = secretSetter({ terminal: { 'Value for STRIPE_KEY': value } }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }); + + expect(patches[0].secrets).toEqual([{ key: 'STRIPE_KEY', value }]); + }); + + it('falls through to the prompt for a --secret key that is empty in the dotenv file', async () => { + const value = gluedValue(); + const { setter, asked, patches, events } = secretSetter({ + files: { 'a.env': 'STRIPE_KEY=\nAPI_URL=https://x' }, + terminal: { 'Value for STRIPE_KEY': value }, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['a.env'], secrets: ['STRIPE_KEY'] }); + + expect(messagesOf(asked)).toEqual(['Value for STRIPE_KEY']); + expect(events).toContain('print:Skipped 1 variable with an empty value in a.env: STRIPE_KEY.'); + expect(patches).toEqual([ + { + ...SCOPE, + set: [{ key: 'API_URL', value: 'https://x' }], + secrets: [{ key: 'STRIPE_KEY', value }], + }, + ]); + }); + + it('refuses a piped value with an inner line break, naming the key and neither line', async () => { + const first = gluedValue(); + const second = gluedValue(); + const { setter, patches } = secretSetter({ keyStdin: `${first}\n${second}\n` }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe( + 'The value for STRIPE_KEY has more than one line. A secret value must be a single line; nothing was changed.', + ); + expect((failure as Error).message).not.toContain(first); + expect((failure as Error).message).not.toContain(second); + expect(patches).toEqual([]); + }); + + it('refuses a piped value that ends in a lone carriage return, naming the key and not the value', async () => { + const value = gluedValue(); + const { setter, patches } = secretSetter({ keyStdin: `${value}\r` }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe( + 'The value for STRIPE_KEY has more than one line. A secret value must be a single line; nothing was changed.', + ); + expect((failure as Error).message).not.toContain(value); + expect(patches).toEqual([]); + }); + + it('refuses a dotenv stream value with an inner carriage return before any read of the environment', async () => { + const first = gluedValue(); + const second = gluedValue(); + const { setter, events, patches } = secretSetter({ dotenvStdin: `STRIPE_KEY="${first}\\r${second}"\n` }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toContain('A secret value must be a single line'); + expect((failure as Error).message).not.toContain(first); + expect((failure as Error).message).not.toContain(second); + expect(wire(events)).toEqual([]); + expect(patches).toEqual([]); + }); + + it('refuses a multi-line value from a dotenv file before any read of the environment', async () => { + const first = gluedValue(); + const second = gluedValue(); + const { setter, events } = secretSetter({ files: { 'a.env': `STRIPE_KEY="${first}\\n${second}"` } }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, envFiles: ['a.env'], secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toContain('A secret value must be a single line'); + expect((failure as Error).message).not.toContain(first); + expect((failure as Error).message).not.toContain(second); + expect(wire(events)).toEqual(['read:a.env']); + }); + + it('drops a trailing CRLF from a piped value and sends the rest', async () => { + const value = gluedValue(); + const { setter, patches } = secretSetter({ keyStdin: `${value}\r\n` }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }); + + expect(patches[0].secrets).toEqual([{ key: 'STRIPE_KEY', value }]); + }); + + it('allows a change that makes exactly 128 entries and counts a replaced secret once', async () => { + const held = Array.from({ length: 26 }, (_, index) => `S${index}`); + const { setter, patches } = secretSetter({ + terminal: { + 'Value for S0 (1/3)': gluedValue(), + 'Value for N1 (2/3)': gluedValue(), + 'Value for N2 (3/3)': gluedValue(), + }, + heldVariables: Array.from({ length: 100 }, (_, index) => `V${index}`), + heldSecrets: held, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['S0', 'N1', 'N2'] }); + + expect(patches).toHaveLength(1); + }); + + it('refuses the 129th entry before any prompt or write', async () => { + const { setter, asked, patches } = secretSetter({ + terminal: {}, + heldVariables: Array.from({ length: 100 }, (_, index) => `V${index}`), + heldSecrets: Array.from({ length: 26 }, (_, index) => `S${index}`), + }); + + const failure = await setter + .set({ ...SCOPE, ...NO_SOURCES, secrets: ['N1', 'N2', 'N3'] }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe( + 'This change would leave 129 variables and secrets in the environment, and the limit is 128. ' + + 'Nothing was changed.', + ); + expect(asked).toEqual([]); + expect(patches).toEqual([]); + }); + + it('counts a new variable of the same run and a held variable it sets again only once', async () => { + const heldVariables = Array.from({ length: 127 }, (_, index) => `V${index}`); + const allowed = secretSetter({ keyStdin: `${gluedValue()}\n`, heldVariables }); + const refused = secretSetter({ keyStdin: `${gluedValue()}\n`, heldVariables }); + + await allowed.setter.set({ ...SCOPE, ...NO_SOURCES, vars: ['V0=1'], secrets: ['S'] }); + await expect(refused.setter.set({ ...SCOPE, ...NO_SOURCES, vars: ['NEW=1'], secrets: ['S'] })).rejects.toThrow( + 'would leave 129 variables and secrets', + ); + + expect(allowed.patches).toHaveLength(1); + expect(refused.patches).toEqual([]); + }); + + it('allows keys and values of exactly 14 KB and refuses one byte more, naming no value', async () => { + const room = 14 * 1024 - Buffer.byteLength('STRIPE_KEY') - Buffer.byteLength('A') - Buffer.byteLength('1'); + const exact = 'x'.repeat(room); + const over = 'x'.repeat(room + 1); + const allowed = secretSetter({ terminal: { 'Value for STRIPE_KEY': exact } }); + const refused = secretSetter({ terminal: { 'Value for STRIPE_KEY': over } }); + + await allowed.setter.set({ ...SCOPE, ...NO_SOURCES, vars: ['A=1'], secrets: ['STRIPE_KEY'] }); + const failure = await refused.setter + .set({ ...SCOPE, ...NO_SOURCES, vars: ['A=1'], secrets: ['STRIPE_KEY'] }) + .catch((error: unknown) => error); + + expect(allowed.patches).toHaveLength(1); + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe( + 'This request is 14337 bytes of keys and values, and one request is limited to 14336 bytes (14 KB). ' + + 'Nothing was changed.', + ); + expect((failure as Error).message).not.toContain('xxxx'); + expect(refused.patches).toEqual([]); + }); + + it('measures the limit in UTF-8 bytes, not characters', async () => { + const value = 'é'.repeat(7168); + const { setter, patches } = secretSetter({ terminal: { 'Value for K': value } }); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['K'] })).rejects.toThrow('14337 bytes'); + expect(value.length).toBeLessThan(14 * 1024); + expect(patches).toEqual([]); + }); + + it('ends with the timeout error after exactly the limit when standard input never ends, closing it and sending nothing', async () => { + jest.useFakeTimers(); + + try { + const { setter, reads, patches } = secretSetter({ readsNeverEnd: true, stdinTimeoutMs: 1000 }); + const outcome = setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }).catch((error: unknown) => error); + let settled = false; + void outcome.then(() => { + settled = true; + }); + + await jest.advanceTimersByTimeAsync(999); + expect(settled).toBe(false); + expect(reads.closed).toBe(0); + + await jest.advanceTimersByTimeAsync(1); + + expect(await outcome).toBeInstanceOf(SecretInputTimeoutError); + expect(reads.closed).toBe(1); + expect(patches).toEqual([]); + } finally { + jest.useRealTimers(); + } + }); + + it('prints the client-exposed warning before the write, then one line per kind with keys only', async () => { + const value = gluedValue(); + const { setter, events } = secretSetter({ + terminal: { + 'Value for NEXT_PUBLIC_X (1/3)': value, + 'Value for STRIPE_KEY (2/3)': value, + 'Value for DB_PASSWORD (3/3)': value, + }, + heldSecrets: ['DB_PASSWORD'], + }); + + await setter.set({ + ...SCOPE, + ...NO_SOURCES, + vars: ['API_URL=https://x'], + secrets: ['NEXT_PUBLIC_X', 'STRIPE_KEY', 'DB_PASSWORD'], + }); + + expect(events.filter((event) => event.startsWith('print:') || event === 'patch')).toEqual([ + expect.stringContaining('print:Warning: NEXT_PUBLIC_X starts with NEXT_PUBLIC_'), + 'patch', + 'print:✔ 1 variable set: API_URL', + 'print:✔ 2 secrets added: NEXT_PUBLIC_X, STRIPE_KEY', + 'print:✔ 1 secret updated: DB_PASSWORD', + ]); + expect(events.join('\n')).not.toContain(value); + }); + + it('prints the client-exposed warning of every --secret key that has a prefix before the first prompt', async () => { + const value = gluedValue(); + const { setter, events } = secretSetter({ + terminal: { + 'Value for NEXT_PUBLIC_X (1/3)': value, + 'Value for VITE_Y (2/3)': value, + 'Value for DB_PASSWORD (3/3)': value, + }, + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['NEXT_PUBLIC_X', 'VITE_Y', 'DB_PASSWORD'] }); + + expect(events.filter((event) => event.startsWith('print:Warning') || event.startsWith('ask:'))).toEqual([ + expect.stringContaining('print:Warning: NEXT_PUBLIC_X starts with NEXT_PUBLIC_'), + expect.stringContaining('print:Warning: VITE_Y starts with VITE_'), + 'ask:Value for NEXT_PUBLIC_X (1/3)', + 'ask:Value for VITE_Y (2/3)', + 'ask:Value for DB_PASSWORD (3/3)', + ]); + expect(events.join('\n')).not.toContain(value); + }); + + it('prints the client-exposed warning before reading a piped value and before reading a --dotenv - stream', async () => { + const piped = secretSetter({ keyStdin: `${gluedValue()}\n` }); + const streamed = secretSetter({ dotenvStdin: `VITE_Y=${gluedValue()}\n` }); + + await piped.setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['NEXT_PUBLIC_X'] }); + await streamed.setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['-'], secrets: ['VITE_Y'] }); + + expect(piped.events.indexOf('read stdin')).toBeGreaterThan( + piped.events.findIndex((event) => event.startsWith('print:Warning: NEXT_PUBLIC_X')), + ); + expect(streamed.events.findIndex((event) => event.startsWith('print:Warning: VITE_Y'))).toBeGreaterThanOrEqual(0); + expect(streamed.events.indexOf('read stdin')).toBeGreaterThan( + streamed.events.findIndex((event) => event.startsWith('print:Warning: VITE_Y')), + ); + }); + + it('prints no client-exposed warning when a key check refuses the run first', async () => { + const { setter, events } = secretSetter({ terminal: {} }); + + await expect( + setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['NEXT_PUBLIC_X', 'NEXT_PUBLIC_X'] }), + ).rejects.toBeInstanceOf(UsageError); + expect(events).toEqual([]); + }); + + it('prints no summary when the write fails', async () => { + const { setter, events } = secretSetter({ + keyStdin: `${gluedValue()}\n`, + fail: { patch: new Error('patch failed') }, + }); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] })).rejects.toThrow('patch failed'); + expect(events.filter((event) => event.startsWith('print:'))).toEqual([]); + }); + + it.each([ + ['reading the environment', { environment: new Error('environment failed') }], + ['listing the secrets', { secrets: new Error('secrets failed') }], + ['reading standard input', { keyStdin: new Error('stdin failed') }], + ])('propagates a failure %s and sends nothing', async (_label, fail) => { + const { setter, patches } = secretSetter({ keyStdin: `${gluedValue()}\n`, fail }); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] })).rejects.toThrow( + /failed$/, + ); + expect(patches).toEqual([]); + }); + + it.each([[undefined], [null]])('cancels when the prompt answers %p and sends nothing', async (answer) => { + const { setter, patches } = secretSetter({ terminal: { 'Value for STRIPE_KEY': answer } }); + + await expect(setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] })).rejects.toBeInstanceOf( + CancelledError, + ); + expect(patches).toEqual([]); + }); + + it('refuses a blank answer at the masked prompt itself, naming the prompt and echoing nothing', async () => { + const { setter, asked } = secretSetter({ terminal: { 'Value for STRIPE_KEY': gluedValue() } }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }); + const validate = asked[0].payload.validate as (value: string) => true | string; + + expect(validate('')).toBe("Value for STRIPE_KEY can't be empty."); + expect(validate(' ')).toBe("Value for STRIPE_KEY can't be empty."); + expect(validate('x')).toBe(true); + }); + + it('skips a held variable or secret the service listed without a key when counting and checking', async () => { + const value = gluedValue(); + const { setter, patches } = secretSetter({ + terminal: { 'Value for STRIPE_KEY': value }, + heldVariables: [undefined, 'API_URL'], + heldSecrets: [undefined, 'OTHER'], + }); + + await setter.set({ ...SCOPE, ...NO_SOURCES, secrets: ['STRIPE_KEY'] }); + + expect(patches).toEqual([{ ...SCOPE, secrets: [{ key: 'STRIPE_KEY', value }] }]); + }); + + it('reports a --dotenv file that does not exist as a usage error before any read of the environment', async () => { + const { setter, events } = secretSetter({ terminal: {} }); + + await expect( + setter.set({ ...SCOPE, ...NO_SOURCES, envFiles: ['missing.env'], secrets: ['STRIPE_KEY'] }), + ).rejects.toThrow('--dotenv missing.env was not found.'); + expect(wire(events)).toEqual(['read:missing.env']); + }); }); describe('default variable io', () => { diff --git a/src/variables/variable.set.ts b/src/variables/variable.set.ts index 3dfd7ca0..34d3fd3e 100644 --- a/src/variables/variable.set.ts +++ b/src/variables/variable.set.ts @@ -1,14 +1,37 @@ import { styled } from '../core/style'; +import { clientExposedWarning, DEFAULT_SECRET_IO, readWithin } from '../core/secret-input'; +import type { SecretValueIo } from '../core/secret-input'; import type { ServiceContext } from '../core/service-context'; import type { EnvironmentParams } from '../environments/environments.api'; +import type { EnvironmentVariableInput } from '../environments/types'; import { chooseSources } from './variable.chooser'; import { DEFAULT_VARIABLE_IO, given } from './variable.io'; import type { VariableIo } from './variable.io'; import type { MergedVariables } from './variable.merge'; +import { parseDotenv } from './variable.dotenv'; +import { parseAssignment } from './variable.parse'; +import { + STDIN_PATH, + askSecretValue, + assertByteLimit, + assertDistinctSecrets, + assertEntryLimit, + assertNoBareVariables, + assertNoDotenvOnTerminal, + assertNotAlsoVariable, + assertNotHeldSecrets, + assertNotVariables, + assertPipedValues, + assertSecretValue, + assertStreamKeysNamed, + withoutTrailingNewline, +} from './variable.secrets'; import { collectVariables } from './variable.sources'; import { importFromStack, readSavedToken } from './variable.stack'; import type { SavedToken } from './variable.stack'; -import { variablesSetLine } from './variable.summary'; +import { secretRunLines, variablesSetLine } from './variable.summary'; +import { promptMessage } from './variable.values'; +import type { SecretInput } from './variables.api'; import { setVariables } from './variable.writer'; export interface SetVariablesRequest extends EnvironmentParams { @@ -17,23 +40,35 @@ export interface SetVariablesRequest extends EnvironmentParams { dataDir: string; fromStack?: boolean; alias?: string; + secrets?: string[]; } export const NO_CHANGES_LINE = 'No changes made.'; export const SKIPPED_LINE = 'Skipped adding variables.'; export const CHOOSE_SOURCES_MESSAGE = 'Add variables from'; +function keysOf(entries: { key?: string | undefined }[]): Set { + return new Set(entries.flatMap(({ key }) => (key === undefined ? [] : [key]))); +} + export class VariableSetter { constructor( private readonly services: ServiceContext, private readonly io: VariableIo = DEFAULT_VARIABLE_IO, private readonly savedToken: (alias: string) => SavedToken | undefined = readSavedToken, + private readonly secretIo: SecretValueIo = DEFAULT_SECRET_IO, ) {} async set(request: SetVariablesRequest): Promise { + const secrets = request.secrets ?? []; + + if (secrets.length > 0) { + await this.setWithSecrets(request, secrets); + return; + } + const { ux } = this.services; - const stack = (alias?: string) => - importFromStack({ org: request.org, alias }, { services: this.services, savedToken: this.savedToken }); + const stack = this.stackOf(request); const prompt = { message: CHOOSE_SOURCES_MESSAGE, skippable: false }; const asked = !given(request.vars) && !given(request.envFiles) && request.fromStack !== true && this.services.isTTY; const merged: MergedVariables | undefined = asked @@ -63,8 +98,127 @@ export class VariableSetter { this.services.api.variables, { org: request.org, project: request.project, environment: request.environment }, merged.variables, + { lister: this.services.api.secrets }, ); ux.print(variablesSetLine(merged, this.services.outputIsTTY === true)); } + + private stackOf(request: SetVariablesRequest) { + return (alias?: string) => + importFromStack({ org: request.org, alias }, { services: this.services, savedToken: this.savedToken }); + } + + private async askValue(key: string, lacking: string[]): Promise { + const value = this.services.isTTY + ? await askSecretValue(this.services.ux, promptMessage(key, lacking.indexOf(key) + 1, lacking.length)) + : withoutTrailingNewline(await readWithin(this.secretIo)); + + assertSecretValue(key, value); + + return value; + } + + private async setWithSecrets(request: SetVariablesRequest, keys: string[]): Promise { + const { ux, api } = this.services; + const colour = this.services.outputIsTTY === true; + const scope = { org: request.org, project: request.project, environment: request.environment }; + const assignments = (request.vars ?? []).map(parseAssignment); + + assertDistinctSecrets(keys); + assertNotAlsoVariable(assignments, keys); + assertNoBareVariables(assignments, this.services); + assertNoDotenvOnTerminal(request.envFiles, this.services); + + keys.forEach((key) => { + const warning = clientExposedWarning(key); + + if (warning !== undefined) { + ux.print(styled(warning, 'yellow', colour)); + } + }); + + let dotenvOnStdin = false; + let stdinText = ''; + const merged = await collectVariables( + { + vars: request.vars, + envFiles: request.envFiles, + autoDetect: false, + fromStack: request.fromStack, + alias: request.alias, + }, + { + ...this.io, + readFile: async (path) => { + if (path !== STDIN_PATH) { + return this.io.readFile(path); + } + + dotenvOnStdin = true; + stdinText = await readWithin({ ...this.secretIo, readStdin: this.io.readStdin }, 'dotenv'); + + return stdinText; + }, + services: this.services, + dataDir: request.dataDir, + stack: this.stackOf(request), + }, + ); + + const sourced = new Map(); + const variables: EnvironmentVariableInput[] = []; + + for (const entry of merged.variables) { + if (keys.includes(entry.key)) { + assertSecretValue(entry.key, entry.value); + sourced.set(entry.key, entry.value); + } else { + variables.push(entry); + } + } + + const lacking = keys.filter((key) => !sourced.has(key)); + + assertPipedValues(lacking, this.services, dotenvOnStdin); + + if (dotenvOnStdin) { + const streamed = parseDotenv(stdinText); + + assertStreamKeysNamed([...streamed.variables.map(({ key }) => key), ...streamed.skipped], keys); + } + + const environment = await api.environments.get(scope); + const heldSecrets = keysOf(await api.secrets.list(scope)); + const held = { variables: keysOf(environment.environmentVariables ?? []), secrets: heldSecrets }; + + const variableKeys = variables.map(({ key }) => key); + + assertNotVariables(keys, held.variables); + assertNotHeldSecrets(variableKeys, heldSecrets); + assertEntryLimit(held, variableKeys, keys); + + const secrets: SecretInput[] = []; + + for (const key of keys) { + secrets.push({ key, value: sourced.get(key) ?? (await this.askValue(key, lacking)) }); + } + + assertByteLimit([...variables, ...secrets]); + + await setVariables(api.variables, scope, variables, { + secrets, + lister: api.secrets, + environments: api.environments, + }); + + secretRunLines( + { + set: variableKeys, + added: keys.filter((key) => !heldSecrets.has(key)), + updated: keys.filter((key) => heldSecrets.has(key)), + }, + colour, + ).forEach((line) => ux.print(line)); + } } diff --git a/src/variables/variable.summary.test.ts b/src/variables/variable.summary.test.ts index 93fdede6..abdcf47d 100644 --- a/src/variables/variable.summary.test.ts +++ b/src/variables/variable.summary.test.ts @@ -1,4 +1,4 @@ -import { variablesSetLine } from './variable.summary'; +import { secretRunLines, variablesSetLine } from './variable.summary'; describe('variable summary', () => { it('names the total, every source that added keys and every override', () => { @@ -68,3 +68,36 @@ describe('variable summary', () => { expect(variablesSetLine(merged, false, 'ready to set')).toBe('✔ 0 variables ready to set'); }); }); + +describe('secret run summary', () => { + it('says set, added and updated on separate lines, in that order', () => { + const lines = secretRunLines({ set: ['API_URL'], added: ['STRIPE_KEY'], updated: ['DB_PASSWORD'] }, false); + + expect(lines).toEqual([ + '✔ 1 variable set: API_URL', + '✔ 1 secret added: STRIPE_KEY', + '✔ 1 secret updated: DB_PASSWORD', + ]); + }); + + it('uses the plural and lists every key of a kind', () => { + const lines = secretRunLines({ set: ['A', 'B'], added: ['C', 'D'], updated: ['E', 'F'] }, false); + + expect(lines).toEqual(['✔ 2 variables set: A, B', '✔ 2 secrets added: C, D', '✔ 2 secrets updated: E, F']); + }); + + it.each([ + [{ set: [], added: ['A', 'B'], updated: [] }, ['✔ 2 secrets added: A, B']], + [{ set: ['A'], added: [], updated: [] }, ['✔ 1 variable set: A']], + [{ set: [], added: [], updated: ['A'] }, ['✔ 1 secret updated: A']], + [{ set: [], added: [], updated: [] }, []], + ])('prints no line for a kind with no keys (%j)', (keys, expected) => { + expect(secretRunLines(keys, false)).toEqual(expected); + }); + + it('colours every line green only on a terminal', () => { + const keys = { set: ['A'], added: ['B'], updated: ['C'] }; + + expect(secretRunLines(keys, true)).toEqual(secretRunLines(keys, false).map((line) => `\u001b[32m${line}\u001b[39m`)); + }); +}); diff --git a/src/variables/variable.summary.ts b/src/variables/variable.summary.ts index f6e14706..aa8a69cd 100644 --- a/src/variables/variable.summary.ts +++ b/src/variables/variable.summary.ts @@ -16,3 +16,27 @@ export function variablesSetLine(merged: MergedVariables, outputIsTTY: boolean, return styled(`✔ ${total} ${plural(total)} ${state}${origin}`, 'green', outputIsTTY); } + +export interface SecretRunKeys { + set: string[]; + added: string[]; + updated: string[]; +} + +function runLine(keys: string[], noun: 'variable' | 'secret', state: string, outputIsTTY: boolean): string[] { + if (keys.length === 0) { + return []; + } + + const label = keys.length === 1 ? noun : `${noun}s`; + + return [styled(`✔ ${keys.length} ${label} ${state}: ${keys.join(', ')}`, 'green', outputIsTTY)]; +} + +export function secretRunLines({ set, added, updated }: SecretRunKeys, outputIsTTY: boolean): string[] { + return [ + ...runLine(set, 'variable', 'set', outputIsTTY), + ...runLine(added, 'secret', 'added', outputIsTTY), + ...runLine(updated, 'secret', 'updated', outputIsTTY), + ]; +} diff --git a/src/variables/variable.unset.test.ts b/src/variables/variable.unset.test.ts index 1f9d64cd..6abb03c0 100644 --- a/src/variables/variable.unset.test.ts +++ b/src/variables/variable.unset.test.ts @@ -1,17 +1,38 @@ +import { RemovalFailedError, SecretsNotRemovedError, SecretsRemovalStoppedError } from '../core/secret-input'; import { UsageError } from '../core/errors'; import type { UxLike } from '../core/prompt'; import type { ServiceContext } from '../core/service-context'; import type { Environment } from '../environments/types'; +import { LaunchApiError, LaunchNetworkError } from '../transport/errors'; import type { PatchVariablesParams } from './variables.api'; import { VariableRemover } from './variable.unset'; const SCOPE = { org: 'org1', project: 'proj1', environment: 'env1' }; -function fakes(held: Environment, answer = true) { +interface Harness { + held?: Environment; + secrets?: { key?: string; updatedAt?: string }[]; + answer?: boolean; + outputIsTTY?: boolean; + secretFailures?: Record; + patchFailure?: unknown; + readFailure?: unknown; + secretsReadFailure?: unknown; +} + +const HELD: Environment = { + name: 'staging', + environmentVariables: [{ key: 'API_KEY', value: 'never-printed-value' }, { key: 'DEBUG', value: 'true' }], +}; + +const SECRETS = [{ key: 'DB_PASSWORD' }, { key: 'STRIPE_KEY' }]; + +function harnessed(harness: Harness = {}) { const printed: string[] = []; const order: string[] = []; const questions: string[] = []; const patches: PatchVariablesParams[] = []; + const removals: string[] = []; const ux: UxLike = { print: (message: string) => { printed.push(message); @@ -21,18 +42,48 @@ function fakes(held: Environment, answer = true) { const services = { ux, isTTY: true, - outputIsTTY: false, + outputIsTTY: harness.outputIsTTY ?? false, api: { environments: { get: async () => { order.push('get'); - return held; + + if (harness.readFailure !== undefined) { + throw harness.readFailure; + } + + return harness.held ?? HELD; + }, + }, + secrets: { + list: async () => { + order.push('list'); + + if (harness.secretsReadFailure !== undefined) { + throw harness.secretsReadFailure; + } + + return harness.secrets ?? SECRETS; + }, + remove: async (params: { key: string }) => { + order.push(`remove ${params.key}`); + removals.push(params.key); + + if (harness.secretFailures && params.key in harness.secretFailures) { + throw harness.secretFailures[params.key]; + } }, }, variables: { patch: async (params: PatchVariablesParams) => { order.push('patch'); patches.push(params); + + if (harness.patchFailure !== undefined) { + throw harness.patchFailure; + } + + return []; }, }, }, @@ -40,41 +91,92 @@ function fakes(held: Environment, answer = true) { const confirm = async (question: string) => { order.push('confirm'); questions.push(question); - return answer; + return harness.answer ?? true; }; - return { printed, order, questions, patches, services, remover: new VariableRemover(services, confirm) }; + return { printed, order, questions, patches, removals, services, remover: new VariableRemover(services, confirm) }; } -const HELD: Environment = { - name: 'staging', - environmentVariables: [{ key: 'API_KEY', value: 'never-printed-value' }, { key: 'DEBUG', value: 'true' }], -}; +function forbidden(): LaunchApiError { + return new LaunchApiError(403, [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.WRITE_FORBIDDEN' }], { + 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.WRITE_FORBIDDEN': 'Permission is needed to change the secrets.', + }); +} describe('variable remover', () => { - it('reads, confirms, then patches out only the named key, naming the key and the environment', async () => { - const { remover, order, printed, patches, questions } = fakes(HELD); + it('works out each key kind, confirms once, patches the variables once and deletes each secret', async () => { + const { remover, order, printed, patches, removals, questions } = harnessed(); - const removed = await remover.remove({ ...SCOPE, keys: ['API_KEY'] }); + const removed = await remover.remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD'] }); expect(removed).toBe(true); - expect(order).toEqual(['get', 'confirm', 'patch']); - expect(questions).toEqual(['Are you sure you want to remove the variable API_KEY from the "staging" environment?']); - expect(patches).toEqual([{ ...SCOPE, unset: ['API_KEY'] }]); - expect(printed).toEqual(['✔ Variable API_KEY removed from the "staging" environment.']); + expect(order).toEqual(['get', 'list', 'confirm', 'patch', 'remove DB_PASSWORD']); + expect(questions).toEqual([ + 'Are you sure you want to remove the variable DEBUG and the secret DB_PASSWORD from the "staging" environment?', + ]); + expect(patches).toEqual([{ ...SCOPE, unset: ['DEBUG'] }]); + expect(removals).toEqual(['DB_PASSWORD']); + expect(printed).toEqual([ + '✔ Variable DEBUG removed from the "staging" environment.', + '✔ Secret DB_PASSWORD removed from the "staging" environment.', + ]); }); - it('names several keys together', async () => { - const { remover, printed, questions } = fakes(HELD); + it('names every key of both kinds in the one question and sends all variables in one patch', async () => { + const { remover, patches, removals, questions, printed } = harnessed(); + + await remover.remove({ ...SCOPE, keys: ['STRIPE_KEY', 'API_KEY', 'DB_PASSWORD', 'DEBUG'] }); + + expect(questions).toEqual([ + 'Are you sure you want to remove the variables API_KEY, DEBUG and the secrets STRIPE_KEY, DB_PASSWORD ' + + 'from the "staging" environment?', + ]); + expect(patches).toEqual([{ ...SCOPE, unset: ['API_KEY', 'DEBUG'] }]); + expect(removals).toEqual(['STRIPE_KEY', 'DB_PASSWORD']); + expect(printed).toHaveLength(4); + }); + + it('keeps the variable wording when every key is a variable and never calls the secrets delete', async () => { + const { remover, order, printed, patches, questions, removals } = harnessed(); await remover.remove({ ...SCOPE, keys: ['API_KEY', 'DEBUG'] }); + expect(order).toEqual(['get', 'confirm', 'patch']); expect(questions).toEqual(['Are you sure you want to remove the variables API_KEY, DEBUG from the "staging" environment?']); - expect(printed).toEqual(['✔ Variables API_KEY, DEBUG removed from the "staging" environment.']); + expect(patches).toEqual([{ ...SCOPE, unset: ['API_KEY', 'DEBUG'] }]); + expect(removals).toEqual([]); + expect(printed).toEqual([ + '✔ Variable API_KEY removed from the "staging" environment.', + '✔ Variable DEBUG removed from the "staging" environment.', + ]); + }); + + it('sends no variables patch when every key is a secret', async () => { + const { remover, order, printed, patches, questions, removals } = harnessed(); + + await remover.remove({ ...SCOPE, keys: ['DB_PASSWORD'] }); + + expect(order).toEqual(['get', 'list', 'confirm', 'remove DB_PASSWORD']); + expect(questions).toEqual(['Are you sure you want to remove the secret DB_PASSWORD from the "staging" environment?']); + expect(patches).toEqual([]); + expect(removals).toEqual(['DB_PASSWORD']); + expect(printed).toEqual(['✔ Secret DB_PASSWORD removed from the "staging" environment.']); + }); + + it('asks about each key once when a key is repeated', async () => { + const { remover, patches, removals, questions } = harnessed(); + + await remover.remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD', 'DEBUG', 'DB_PASSWORD'] }); + + expect(questions).toEqual([ + 'Are you sure you want to remove the variable DEBUG and the secret DB_PASSWORD from the "staging" environment?', + ]); + expect(patches).toEqual([{ ...SCOPE, unset: ['DEBUG'] }]); + expect(removals).toEqual(['DB_PASSWORD']); }); it('falls back to the environment reference when the environment carries no name', async () => { - const { remover, printed, questions } = fakes({ environmentVariables: [{ key: 'A', value: '1' }] }); + const { remover, printed, questions } = harnessed({ held: { environmentVariables: [{ key: 'A', value: '1' }] } }); await remover.remove({ ...SCOPE, keys: ['A'] }); @@ -83,70 +185,244 @@ describe('variable remover', () => { }); it('returns false and changes nothing when the user declines', async () => { - const { remover, order, printed, patches } = fakes(HELD, false); + const { remover, order, printed, patches, removals } = harnessed({ answer: false }); - const removed = await remover.remove({ ...SCOPE, keys: ['API_KEY'] }); + const removed = await remover.remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD'] }); expect(removed).toBe(false); - expect(order).toEqual(['get', 'confirm']); + expect(order).toEqual(['get', 'list', 'confirm']); expect(patches).toEqual([]); + expect(removals).toEqual([]); expect(printed).toEqual([]); }); - it('refuses a key that is not set before it asks anything and writes nothing', async () => { - const { remover, order, patches } = fakes(HELD); + it('refuses a key that is neither a variable nor a secret before it asks anything and writes nothing', async () => { + const { remover, order, patches, removals, printed } = harnessed(); - await expect(remover.remove({ ...SCOPE, keys: ['API_KEY', 'MISSING'] })).rejects.toThrow(UsageError); - await expect(remover.remove({ ...SCOPE, keys: ['MISSING'] })).rejects.toThrow('MISSING is not set in this environment.'); + await expect(remover.remove({ ...SCOPE, keys: ['API_KEY', 'DB_PASSWORD', 'NOPE'] })).rejects.toThrow(UsageError); + await expect(remover.remove({ ...SCOPE, keys: ['NOPE'] })).rejects.toThrow('NOPE is not set in this environment.'); expect(order).not.toContain('confirm'); expect(patches).toEqual([]); + expect(removals).toEqual([]); + expect(printed).toEqual([]); }); it('names every missing key together and uses the plural', async () => { - const { remover } = fakes(HELD); + const { remover } = harnessed(); await expect(remover.remove({ ...SCOPE, keys: ['API_KEY', 'X', 'Y'] })).rejects.toThrow( 'X, Y are not set in this environment.', ); }); - it('never puts a value in the question, the summary or an error', async () => { - const { remover, printed, questions } = fakes(HELD); + it('does not refuse a key that is only a secret as not set', async () => { + const { remover } = harnessed({ held: { name: 'staging', environmentVariables: [] } }); - await remover.remove({ ...SCOPE, keys: ['API_KEY'] }); + await expect(remover.remove({ ...SCOPE, keys: ['STRIPE_KEY'] })).resolves.toBe(true); + }); - expect(`${printed.join('\n')}${questions.join('\n')}`).not.toContain('never-printed-value'); + it('deletes the other secrets and patches the variables when one secret is refused, then fails naming it', async () => { + const { remover, order, printed, patches, removals } = harnessed({ + secretFailures: { DB_PASSWORD: forbidden() }, + }); + + const error = (await remover + .remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD', 'STRIPE_KEY'] }) + .catch((thrown: unknown) => thrown)) as SecretsNotRemovedError; + + expect(error).toBeInstanceOf(SecretsNotRemovedError); + expect(error.exitCode).toBe(1); + expect(error.message).toBe('1 of 2 secrets were not removed: DB_PASSWORD.'); + expect(order).toEqual(['get', 'list', 'confirm', 'patch', 'remove DB_PASSWORD', 'remove STRIPE_KEY']); + expect(patches).toEqual([{ ...SCOPE, unset: ['DEBUG'] }]); + expect(removals).toEqual(['DB_PASSWORD', 'STRIPE_KEY']); + expect(printed).toEqual([ + '✔ Variable DEBUG removed from the "staging" environment.', + 'Secret DB_PASSWORD was not removed: Permission is needed to change the secrets.', + '✔ Secret STRIPE_KEY removed from the "staging" environment.', + ]); + }); + + it('stops at a secret whose delete fails without an API answer, reporting the variables already removed', async () => { + const cause = new LaunchNetworkError('connection reset', undefined, false); + const { remover, removals } = harnessed({ secretFailures: { DB_PASSWORD: cause } }); + + const error = (await remover + .remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD', 'STRIPE_KEY'] }) + .catch((thrown: unknown) => thrown)) as SecretsRemovalStoppedError; + + expect(error).toBeInstanceOf(SecretsRemovalStoppedError); + expect(error.cause).toBe(cause); + expect(error.message).toBe( + 'Stopped at secret DB_PASSWORD: connection reset\n' + + 'Removed: DEBUG.\nFailed: DB_PASSWORD.\nNot attempted: STRIPE_KEY.', + ); + expect(removals).toEqual(['DB_PASSWORD']); + }); + + it('rethrows a refused variables patch unchanged, naming each variable on a red line, when no secret was asked for', async () => { + const failure = new UsageError('DEBUG is not set in this environment.'); + const { remover, printed, removals } = harnessed({ patchFailure: failure, outputIsTTY: true }); + + await expect(remover.remove({ ...SCOPE, keys: ['DEBUG'] })).rejects.toBe(failure); + expect(printed).toEqual([ + '\u001b[31mVariable DEBUG was not removed: DEBUG is not set in this environment.\u001b[39m', + ]); + expect(removals).toEqual([]); + }); + + it('names every variable on its own line when the variables patch is refused, then still deletes the secrets', async () => { + const failure = new LaunchApiError(409, [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE' }], { + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE': 'Run the command again.', + }); + const { remover, printed, removals } = harnessed({ patchFailure: failure }); + + await expect(remover.remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD', 'API_KEY'] })).rejects.toBe(failure); + expect(removals).toEqual(['DB_PASSWORD']); + expect(printed).toEqual([ + 'Variable DEBUG was not removed: Run the command again.', + 'Variable API_KEY was not removed: Run the command again.', + '✔ Secret DB_PASSWORD removed from the "staging" environment.', + ]); + }); + + it('throws one exit 1 error naming the variables and the secrets left in place when both parts fail', async () => { + const failure = new LaunchApiError(404, [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.NOT_FOUND' }], { + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.NOT_FOUND': 'A key was not found.', + }); + const { remover, removals, printed } = harnessed({ + patchFailure: failure, + secretFailures: { DB_PASSWORD: forbidden() }, + }); + + const error = (await remover + .remove({ ...SCOPE, keys: ['DEBUG', 'API_KEY', 'DB_PASSWORD', 'STRIPE_KEY'] }) + .catch((thrown: unknown) => thrown)) as RemovalFailedError; + + expect(error).toBeInstanceOf(RemovalFailedError); + expect(error).not.toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(1); + expect(error.cause).toBe(failure); + expect(error.message).toBe( + 'Some keys were not removed. Variables left in place: DEBUG, API_KEY (A key was not found.). ' + + 'Secrets left in place: DB_PASSWORD.', + ); + expect(removals).toEqual(['DB_PASSWORD', 'STRIPE_KEY']); + expect(printed).toContain('✔ Secret STRIPE_KEY removed from the "staging" environment.'); }); - it('propagates a failed read, a failed confirm and a failed write', async () => { - const reading = new VariableRemover( - { api: { environments: { get: async () => Promise.reject(new Error('get failed')) } } } as unknown as ServiceContext, - async () => true, + it('stops before any secret is deleted when the variables patch fails without an API answer, naming it', async () => { + const cause = new LaunchNetworkError('connection reset', undefined, false); + const { remover, order, printed, removals } = harnessed({ patchFailure: cause }); + + const error = (await remover + .remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD', 'STRIPE_KEY'] }) + .catch((thrown: unknown) => thrown)) as SecretsRemovalStoppedError; + + expect(error).toBeInstanceOf(SecretsRemovalStoppedError); + expect(error.exitCode).toBe(1); + expect(error.cause).toBe(cause); + expect(error.message).toBe( + 'Stopped at the variables: connection reset\n' + + 'Removed: none.\nFailed: DEBUG.\nNot attempted: DB_PASSWORD, STRIPE_KEY.', ); + expect(order).toEqual(['get', 'list', 'confirm', 'patch']); + expect(removals).toEqual([]); + expect(printed).toEqual([]); + }); - await expect(reading.remove({ ...SCOPE, keys: ['A'] })).rejects.toThrow('get failed'); + it('rethrows a variables patch that fails without an API answer unchanged when no secret was asked for', async () => { + const cause = new LaunchNetworkError('connection reset', undefined, false); + const { remover, printed, removals } = harnessed({ patchFailure: cause }); - const broken = new VariableRemover(fakes(HELD).services, async () => Promise.reject(new Error('prompt failed'))); + await expect(remover.remove({ ...SCOPE, keys: ['DEBUG'] })).rejects.toBe(cause); + expect(printed).toEqual([]); + expect(removals).toEqual([]); + }); - await expect(broken.remove({ ...SCOPE, keys: ['API_KEY'] })).rejects.toThrow('prompt failed'); + it('lists the variables whose patch failed among the failed keys when a secret delete then stops the run', async () => { + const { remover } = harnessed({ + patchFailure: new LaunchApiError(409, [], {}), + secretFailures: { DB_PASSWORD: new LaunchNetworkError('connection reset', undefined, false) }, + }); - const writing = new VariableRemover( - { - ux: { print: () => undefined }, - outputIsTTY: false, - api: { - environments: { get: async () => HELD }, - variables: { patch: async () => Promise.reject(new Error('patch failed')) }, - }, - } as unknown as ServiceContext, - async () => true, + await expect(remover.remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD'] })).rejects.toThrow( + 'Removed: none.\nFailed: DEBUG, DB_PASSWORD.\nNot attempted: none.', ); + }); + + it('colours the result lines only on a terminal', async () => { + const plain = harnessed({ secretFailures: { DB_PASSWORD: forbidden() } }); + const coloured = harnessed({ outputIsTTY: true, secretFailures: { DB_PASSWORD: forbidden() } }); + + await plain.remover.remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD'] }).catch(() => undefined); + await coloured.remover.remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD'] }).catch(() => undefined); - await expect(writing.remove({ ...SCOPE, keys: ['API_KEY'] })).rejects.toThrow('patch failed'); + expect(plain.printed.join('\n')).not.toContain('\u001b['); + expect(coloured.printed[0]).toContain('\u001b[32m'); + expect(coloured.printed[1]).toContain('\u001b[31m'); + }); + + it('never puts a value in the question, the lines or an error', async () => { + const { remover, printed, questions } = harnessed(); + + await remover.remove({ ...SCOPE, keys: ['API_KEY', 'DB_PASSWORD'] }); + + expect(`${printed.join('\n')}${questions.join('\n')}`).not.toContain('never-printed-value'); + }); + + it('reads the secrets for an environment that carries no variable list at all', async () => { + const { remover, order } = harnessed({ held: { name: 'staging' } }); + + await expect(remover.remove({ ...SCOPE, keys: ['STRIPE_KEY'] })).resolves.toBe(true); + expect(order).toEqual(['get', 'list', 'confirm', 'remove STRIPE_KEY']); + }); + + it('skips a held secret that has no key', async () => { + const { remover } = harnessed({ secrets: [{ updatedAt: '2026-12-03T07:53:26.577Z' }, { key: 'STRIPE_KEY' }] }); + + await expect(remover.remove({ ...SCOPE, keys: ['STRIPE_KEY'] })).resolves.toBe(true); + }); + + it('propagates a failed environment read, a failed secrets read and a failed confirm, writing nothing', async () => { + const reading = harnessed({ readFailure: new Error('get failed') }); + const listing = harnessed({ secretsReadFailure: new Error('list failed') }); + const broken = harnessed(); + const confirming = new VariableRemover(broken.services, async () => Promise.reject(new Error('prompt failed'))); + + await expect(reading.remover.remove({ ...SCOPE, keys: ['DEBUG'] })).rejects.toThrow('get failed'); + await expect(listing.remover.remove({ ...SCOPE, keys: ['STRIPE_KEY'] })).rejects.toThrow('list failed'); + await expect(confirming.remove({ ...SCOPE, keys: ['DEBUG'] })).rejects.toThrow('prompt failed'); + expect([reading, listing, broken].flatMap(({ patches, removals }) => [...patches, ...removals])).toEqual([]); + expect(reading.order).not.toContain('list'); + expect(listing.order).not.toContain('confirm'); + }); + + it('removes variables without reading the secrets and without failing on a secrets read that would be refused', async () => { + const refused = new LaunchApiError(403, [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.READ_FORBIDDEN' }], { + 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.READ_FORBIDDEN': 'Permission is needed to view the secrets.', + }); + const { remover, order, patches, printed } = harnessed({ secretsReadFailure: refused }); + + await expect(remover.remove({ ...SCOPE, keys: ['DEBUG', 'API_KEY', 'DEBUG'] })).resolves.toBe(true); + expect(order).toEqual(['get', 'confirm', 'patch']); + expect(patches).toEqual([{ ...SCOPE, unset: ['DEBUG', 'API_KEY'] }]); + expect(printed).toHaveLength(2); + }); + + it('reads the secrets when one of the keys is not a held variable and fails on a refused read before it asks', async () => { + const refused = new LaunchApiError(403, [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.READ_FORBIDDEN' }], { + 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.READ_FORBIDDEN': 'Permission is needed to view the secrets.', + }); + const { remover, order, patches } = harnessed({ secretsReadFailure: refused }); + + await expect(remover.remove({ ...SCOPE, keys: ['DEBUG', 'DB_PASSWORD'] })).rejects.toBe(refused); + expect(order).toEqual(['get', 'list']); + expect(patches).toEqual([]); }); it('removes a key whose value the API did not return, since only the key is sent', async () => { - const { remover, patches } = fakes({ name: 'staging', environmentVariables: [{ key: 'HIDDEN' }] }); + const { remover, patches } = harnessed({ held: { name: 'staging', environmentVariables: [{ key: 'HIDDEN' }] } }); await remover.remove({ ...SCOPE, keys: ['HIDDEN'] }); diff --git a/src/variables/variable.unset.ts b/src/variables/variable.unset.ts index dbd8a595..a8e11f49 100644 --- a/src/variables/variable.unset.ts +++ b/src/variables/variable.unset.ts @@ -1,15 +1,26 @@ +import { UsageError } from '../core/errors'; +import { RemovalFailedError, SecretsNotRemovedError, SecretsRemovalStoppedError } from '../core/secret-input'; import type { ServiceContext } from '../core/service-context'; -import type { EnvironmentParams } from '../environments/environments.api'; import { styled } from '../core/style'; +import type { EnvironmentParams } from '../environments/environments.api'; +import { LaunchApiError } from '../transport/errors'; import { notSetError } from './variable.errors'; -import { missingKeys, unsetVariables } from './variable.writer'; +import { kindsOf, unsetVariables } from './variable.writer'; export interface RemoveVariablesRequest extends EnvironmentParams { keys: string[]; } +function answered(error: unknown): error is Error { + return error instanceof LaunchApiError || error instanceof UsageError; +} + export type Confirm = (question: string) => Promise; +function described(noun: string, keys: string[]): string[] { + return keys.length === 0 ? [] : [`the ${keys.length === 1 ? noun : `${noun}s`} ${keys.join(', ')}`]; +} + export class VariableRemover { constructor( private readonly services: ServiceContext, @@ -19,33 +30,91 @@ export class VariableRemover { async remove(request: RemoveVariablesRequest): Promise { const { org, project, environment } = request; const scope = { org, project, environment }; - const held = await this.services.api.environments.get(scope); - const missing = missingKeys(held, request.keys); + const { api, ux } = this.services; + const held = await api.environments.get(scope); + const heldVariables = new Set((held.environmentVariables ?? []).map(({ key }) => key)); + const heldSecrets = request.keys.every((key) => heldVariables.has(key)) ? [] : await api.secrets.list(scope); + const { variables, secrets, missing } = kindsOf(held, heldSecrets, request.keys); if (missing.length > 0) { throw notSetError(missing); } const name = held.name ?? environment; - const keys = [...new Set(request.keys)]; - const listed = keys.join(', '); - const single = keys.length === 1; - const subject = `${single ? 'variable' : 'variables'} ${listed}`; - const question = `Are you sure you want to remove the ${subject} from the "${name}" environment?`; + const subject = [...described('variable', variables), ...described('secret', secrets)].join(' and '); + const question = `Are you sure you want to remove ${subject} from the "${name}" environment?`; if (!(await this.confirm(question))) { return false; } - await unsetVariables(this.services.api.variables, scope, request.keys); + const colour = this.services.outputIsTTY === true; + const removed: string[] = []; + const failed: string[] = []; - this.services.ux.print( - styled( - `✔ ${single ? 'Variable' : 'Variables'} ${listed} removed from the "${name}" environment.`, - 'green', - this.services.outputIsTTY === true, - ), + const patchFailure = await unsetVariables(api.variables, scope, variables).then( + () => undefined, + (error: unknown) => ({ error }), ); + const patched = patchFailure === undefined; + + if (patched) { + removed.push(...variables); + variables.forEach((key) => + ux.print(styled(`✔ Variable ${key} removed from the "${name}" environment.`, 'green', colour)), + ); + } else { + failed.push(...variables); + + const { error } = patchFailure; + + if (answered(error)) { + variables.forEach((key) => + ux.print(styled(`Variable ${key} was not removed: ${error.message}`, 'red', colour)), + ); + } else if (secrets.length > 0) { + throw new SecretsRemovalStoppedError({ + removed, + failed, + notAttempted: secrets, + cause: error, + at: 'variables', + }); + } + } + + const stayed: string[] = []; + + for (const [index, key] of secrets.entries()) { + try { + await api.secrets.remove({ org, project, environment, key }); + } catch (error) { + stayed.push(key); + + if (!(error instanceof LaunchApiError)) { + throw new SecretsRemovalStoppedError({ + removed, + failed: [...failed, ...stayed], + notAttempted: secrets.slice(index + 1), + cause: error, + }); + } + + ux.print(styled(`Secret ${key} was not removed: ${error.message}`, 'red', colour)); + continue; + } + + removed.push(key); + ux.print(styled(`✔ Secret ${key} removed from the "${name}" environment.`, 'green', colour)); + } + + if (!patched) { + throw stayed.length > 0 ? new RemovalFailedError(variables, stayed, patchFailure.error) : patchFailure.error; + } + + if (stayed.length > 0) { + throw new SecretsNotRemovedError(stayed, secrets.length); + } return true; } diff --git a/src/variables/variable.values.ts b/src/variables/variable.values.ts index c83fa4db..a07f7438 100644 --- a/src/variables/variable.values.ts +++ b/src/variables/variable.values.ts @@ -9,7 +9,7 @@ export interface ValueDeps { readStdin(): Promise; } -function promptMessage(key: string, position: number, total: number): string { +export function promptMessage(key: string, position: number, total: number): string { return total > 1 ? `Value for ${key} (${position}/${total})` : `Value for ${key}`; } diff --git a/src/variables/variable.writer.test.ts b/src/variables/variable.writer.test.ts index 35ed5ad6..06d5c9ca 100644 --- a/src/variables/variable.writer.test.ts +++ b/src/variables/variable.writer.test.ts @@ -1,11 +1,16 @@ import type { EnvironmentParams } from '../environments/environments.api'; import type { Environment } from '../environments/types'; +import { gluedValue } from '../../test/support/glued-value'; +import { UsageError } from '../core/errors'; +import { LaunchApiError } from '../transport/errors'; import type { PatchVariablesParams } from './variables.api'; -import { missingKeys, setVariables, unsetVariables } from './variable.writer'; +import { SecretKeyConflictError } from './variable.errors'; +import { kindsOf, setVariables, unsetVariables } from './variable.writer'; +import type { EnvironmentReader, SecretLister } from './variable.writer'; const PARAMS: EnvironmentParams = { org: 'org1', project: 'proj1', environment: 'env1' }; -function fakeStore(failure?: Error) { +function fakeStore(failure?: Error, patched: { key: string; updatedAt: string | undefined }[] = []) { const patches: PatchVariablesParams[] = []; return { @@ -17,11 +22,60 @@ function fakeStore(failure?: Error) { if (failure !== undefined) { throw failure; } + + return patched; }, }, }; } +const API_CONFLICT = new LaunchApiError(409, [ + { code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT', message: 'A key already exists.' }, +]); + +function fakeEnvironments(result: Environment | Error) { + const calls: EnvironmentParams[] = []; + const environments: EnvironmentReader = { + get: async (params) => { + calls.push(params); + + if (result instanceof Error) { + throw result; + } + + return result; + }, + }; + + return { calls, environments }; +} + +function failureOf(promise: Promise): Promise { + return promise.then( + () => { + throw new Error('expected the call to reject'); + }, + (thrown: unknown) => thrown as T, + ); +} + +function fakeLister(held: ({ key: string | undefined })[] | Error) { + const calls: EnvironmentParams[] = []; + const lister: SecretLister = { + list: async (params) => { + calls.push(params); + + if (held instanceof Error) { + throw held; + } + + return held; + }, + }; + + return { calls, lister }; +} + describe('variable writer set', () => { it('sends only the variables to set, without reading the environment first', async () => { const { store, patches } = fakeStore(); @@ -46,6 +100,218 @@ describe('variable writer set', () => { }); }); +describe('variable writer set with secrets', () => { + it('sends the variables and the secrets in one patch and returns what the store reports, without listing secrets', async () => { + const value = gluedValue(); + const patched = [{ key: 'STRIPE_KEY', updatedAt: '2026-12-03T07:53:26.577Z' }]; + const { store, patches } = fakeStore(undefined, patched); + const { lister, calls } = fakeLister([]); + + const result = await setVariables(store, PARAMS, [{ key: 'API_URL', value: 'https://x' }], { + secrets: [{ key: 'STRIPE_KEY', value }], + lister, + }); + + expect(patches).toEqual([ + { ...PARAMS, set: [{ key: 'API_URL', value: 'https://x' }], secrets: [{ key: 'STRIPE_KEY', value }] }, + ]); + expect(result).toEqual(patched); + expect(calls).toEqual([]); + }); + + it('sends a patch with only secrets when there are no variables to set', async () => { + const value = gluedValue(); + const { store, patches } = fakeStore(); + + await setVariables(store, PARAMS, [], { secrets: [{ key: 'STRIPE_KEY', value }] }); + + expect(patches).toEqual([{ ...PARAMS, secrets: [{ key: 'STRIPE_KEY', value }] }]); + expect(Object.keys(patches[0])).not.toContain('set'); + }); + + it('sends nothing when there are neither variables nor secrets', async () => { + const { store, patches } = fakeStore(); + + await setVariables(store, PARAMS, [], { secrets: [] }); + + expect(patches).toEqual([]); + }); + + it('sends no secrets key when none are given', async () => { + const { store, patches } = fakeStore(); + + await setVariables(store, PARAMS, [{ key: 'A', value: '1' }], {}); + + expect(Object.keys(patches[0])).toEqual(['org', 'project', 'environment', 'set']); + }); + + it('names each set key that is a held secret, one line each and once, when the patch is refused for a secret key', async () => { + const value = gluedValue(); + const { store } = fakeStore(new SecretKeyConflictError()); + const { lister, calls } = fakeLister([ + { key: 'STRIPE_KEY' }, + { key: undefined }, + { key: 'DB_PASSWORD' }, + { key: 'UNRELATED' }, + ]); + + const error = await failureOf( + setVariables( + store, + PARAMS, + [ + { key: 'API_URL', value: 'https://x' }, + { key: 'STRIPE_KEY', value }, + { key: 'DB_PASSWORD', value }, + { key: 'STRIPE_KEY', value }, + ], + { lister }, + ), + ); + + expect(error).toBeInstanceOf(SecretKeyConflictError); + expect(error.exitCode).toBe(1); + expect(error.message).toBe( + 'STRIPE_KEY is a secret. Use --secret STRIPE_KEY to replace its value.\n' + + 'DB_PASSWORD is a secret. Use --secret DB_PASSWORD to replace its value.', + ); + expect(error.message).not.toContain(value); + expect(calls).toEqual([PARAMS]); + }); + + it.each([[[{ key: 'OTHER' }]], [[]]])( + 'says generically that a key is a secret when none of the set keys is a held secret (%j)', + async (held) => { + const { store } = fakeStore(new SecretKeyConflictError()); + const { lister } = fakeLister(held); + + await expect(setVariables(store, PARAMS, [{ key: 'API_URL', value: 'https://x' }], { lister })).rejects.toThrow( + new SecretKeyConflictError(), + ); + }, + ); + + it('says generically that a key is a secret when listing the secrets fails, and does not surface the read failure', async () => { + const { store } = fakeStore(new SecretKeyConflictError()); + const { lister, calls } = fakeLister(new LaunchApiError(403, [{ code: 'x' }])); + + const error = await failureOf( + setVariables(store, PARAMS, [{ key: 'A', value: '1' }], { lister }), + ); + + expect(error).toBeInstanceOf(SecretKeyConflictError); + expect(error.message).toBe('A key you passed is a secret. Use --secret to replace its value.'); + expect(calls).toEqual([PARAMS]); + }); + + it('says generically that a key is a secret when there is no way to list the secrets', async () => { + const { store } = fakeStore(new SecretKeyConflictError()); + + const error = await failureOf(setVariables(store, PARAMS, [{ key: 'A', value: '1' }])); + + expect(error).toBeInstanceOf(SecretKeyConflictError); + expect(error.message).toBe( + 'A key you passed is a secret. Use --secret to replace its value.', + ); + }); + + it('keeps the held-secret wording for a set key even when secrets were sent, without reading the environment', async () => { + const { store } = fakeStore(new SecretKeyConflictError([], API_CONFLICT)); + const { lister } = fakeLister([{ key: 'STRIPE_KEY' }]); + const { environments, calls } = fakeEnvironments({ environmentVariables: [{ key: 'DB_PASSWORD' }] }); + + const error = await failureOf( + setVariables(store, PARAMS, [{ key: 'STRIPE_KEY', value: gluedValue() }], { + secrets: [{ key: 'DB_PASSWORD', value: gluedValue() }], + lister, + environments, + }), + ); + + expect(error).toBeInstanceOf(SecretKeyConflictError); + expect(error.message).toBe('STRIPE_KEY is a secret. Use --secret STRIPE_KEY to replace its value.'); + expect(calls).toEqual([]); + }); + + it('says each --secret key that became a variable is a variable when no set key is a held secret', async () => { + const { store } = fakeStore(new SecretKeyConflictError([], API_CONFLICT)); + const { lister } = fakeLister([]); + const { environments, calls } = fakeEnvironments({ + environmentVariables: [{ key: 'DB_PASSWORD' }, { key: 'OTHER' }, { key: 'STRIPE_KEY' }], + }); + + const error = await failureOf( + setVariables(store, PARAMS, [{ key: 'API_URL', value: 'https://x' }], { + secrets: [ + { key: 'STRIPE_KEY', value: gluedValue() }, + { key: 'NEW_KEY', value: gluedValue() }, + { key: 'DB_PASSWORD', value: gluedValue() }, + { key: 'STRIPE_KEY', value: gluedValue() }, + ], + lister, + environments, + }), + ); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe('STRIPE_KEY is a variable.\nDB_PASSWORD is a variable.'); + expect(calls).toEqual([PARAMS]); + }); + + it.each([ + ['no --secret key is a variable', { environmentVariables: [{ value: 'v' }, { key: 'OTHER' }] }], + ['the environment has no variables', {}], + ['the environment cannot be read', new Error('get failed')], + ])('falls back to the API answer when %s', async (_name, environment) => { + const { store } = fakeStore(new SecretKeyConflictError([], API_CONFLICT)); + const { environments } = fakeEnvironments(environment); + + await expect( + setVariables(store, PARAMS, [], { secrets: [{ key: 'STRIPE_KEY', value: gluedValue() }], environments }), + ).rejects.toBe(API_CONFLICT); + }); + + it('falls back to the API answer when there is no way to read the environment', async () => { + const { store } = fakeStore(new SecretKeyConflictError([], API_CONFLICT)); + + await expect( + setVariables(store, PARAMS, [], { secrets: [{ key: 'STRIPE_KEY', value: gluedValue() }] }), + ).rejects.toBe(API_CONFLICT); + }); + + it('keeps the generic wording when the conflict carries no API answer to fall back to', async () => { + const { store } = fakeStore(new SecretKeyConflictError()); + const { environments } = fakeEnvironments({}); + + await expect( + setVariables(store, PARAMS, [], { secrets: [{ key: 'STRIPE_KEY', value: gluedValue() }], environments }), + ).rejects.toThrow(new SecretKeyConflictError()); + }); + + it('does not read the environment when no secrets were sent', async () => { + const { store } = fakeStore(new SecretKeyConflictError([], API_CONFLICT)); + const { environments, calls } = fakeEnvironments({ environmentVariables: [{ key: 'A' }] }); + + const error = await failureOf( + setVariables(store, PARAMS, [{ key: 'A', value: '1' }], { environments }), + ); + + expect(error).toBeInstanceOf(SecretKeyConflictError); + expect(error.message).toBe('A key you passed is a secret. Use --secret to replace its value.'); + expect(calls).toEqual([]); + }); + + it('leaves the another-update-in-progress failure as it is and does not list secrets', async () => { + const failure = new LaunchApiError(409, [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE' }]); + const { store } = fakeStore(failure); + const { lister, calls } = fakeLister([{ key: 'A' }]); + + await expect(setVariables(store, PARAMS, [{ key: 'A', value: '1' }], { lister })).rejects.toBe(failure); + expect(calls).toEqual([]); + }); +}); + describe('variable writer unset', () => { it('sends only the keys to unset, once each, and returns them', async () => { const { store, patches } = fakeStore(); @@ -70,22 +336,36 @@ describe('variable writer unset', () => { }); }); -describe('variable writer missing keys', () => { - it('lists the wanted keys the environment does not hold, once each, in the order given', () => { - const environment = { environmentVariables: [{ key: 'A', value: '1' }] }; +describe('variable writer key kinds', () => { + const environment = { environmentVariables: [{ key: 'A', value: '1' }, { key: 'B' }] }; - expect(missingKeys(environment, ['X', 'A', 'Y', 'X'])).toEqual(['X', 'Y']); + it('sorts the wanted keys into variables, secrets and missing, once each, in the order given', () => { + const kinds = kindsOf(environment, [{ key: 'S' }, { key: 'T' }], ['T', 'X', 'B', 'S', 'A', 'X', 'B', 'Y']); + + expect(kinds).toEqual({ variables: ['B', 'A'], secrets: ['T', 'S'], missing: ['X', 'Y'] }); }); it('counts a stored key as held even when the API gave no value for it', () => { - expect(missingKeys({ environmentVariables: [{ key: 'A' }, { value: 'v' }] }, ['A'])).toEqual([]); + expect(kindsOf({ environmentVariables: [{ key: 'A' }, { value: 'v' }] }, [], ['A']).missing).toEqual([]); + }); + + it('ignores a held secret that has no key', () => { + expect(kindsOf({}, [{ key: undefined }, { key: 'S' }], ['S', 'A'])).toEqual({ + variables: [], + secrets: ['S'], + missing: ['A'], + }); + }); + + it.each([[{}], [{ environmentVariables: null }]])('treats an environment with no variables as holding none (%p)', (held) => { + expect(kindsOf(held as Environment, [], ['A'])).toEqual({ variables: [], secrets: [], missing: ['A'] }); }); - it.each([[{}], [{ environmentVariables: null }]])('treats an environment with no variables as holding none (%p)', (environment) => { - expect(missingKeys(environment as Environment, ['A'])).toEqual(['A']); + it('reads a key held as both a variable and a secret as a variable', () => { + expect(kindsOf(environment, [{ key: 'A' }], ['A'])).toEqual({ variables: ['A'], secrets: [], missing: [] }); }); - it('returns nothing when every key is held', () => { - expect(missingKeys({ environmentVariables: [{ key: 'A', value: '1' }] }, ['A'])).toEqual([]); + it('returns nothing missing when every key is held', () => { + expect(kindsOf(environment, [{ key: 'S' }], ['A', 'S'])).toEqual({ variables: ['A'], secrets: ['S'], missing: [] }); }); }); diff --git a/src/variables/variable.writer.ts b/src/variables/variable.writer.ts index ee55cdcd..d78a444c 100644 --- a/src/variables/variable.writer.ts +++ b/src/variables/variable.writer.ts @@ -1,25 +1,123 @@ import type { EnvironmentParams } from '../environments/environments.api'; import type { Environment, EnvironmentVariableInput } from '../environments/types'; -import type { PatchVariablesParams } from './variables.api'; +import { SecretKeyConflictError, notVariablesError } from './variable.errors'; +import type { PatchedSecret, PatchVariablesParams, SecretInput } from './variables.api'; export interface VariableStore { - patch(params: PatchVariablesParams): Promise; + patch(params: PatchVariablesParams): Promise; } -export function missingKeys(environment: Environment, keys: string[]): string[] { - const heldKeys = new Set((environment.environmentVariables ?? []).map(({ key }) => key)); +export interface SecretLister { + list(params: EnvironmentParams): Promise<{ key: string | undefined }[]>; +} + +export interface EnvironmentReader { + get(params: EnvironmentParams): Promise; +} + +export interface SetVariablesOptions { + secrets?: SecretInput[]; + lister?: SecretLister; + environments?: EnvironmentReader; +} + +export interface KeyKinds { + variables: string[]; + secrets: string[]; + missing: string[]; +} + +export function kindsOf(environment: Environment, secrets: { key?: string }[], keys: string[]): KeyKinds { + const heldVariables = new Set((environment.environmentVariables ?? []).map(({ key }) => key)); + const heldSecrets = new Set(secrets.map(({ key }) => key)); + const kinds: KeyKinds = { variables: [], secrets: [], missing: [] }; + + for (const key of new Set(keys)) { + if (heldVariables.has(key)) { + kinds.variables.push(key); + } else if (heldSecrets.has(key)) { + kinds.secrets.push(key); + } else { + kinds.missing.push(key); + } + } + + return kinds; +} + +async function heldSecretKeys(lister: SecretLister | undefined, params: EnvironmentParams): Promise> { + if (lister === undefined) { + return new Set(); + } + + try { + return new Set((await lister.list(params)).flatMap(({ key }) => (key === undefined ? [] : [key]))); + } catch { + return new Set(); + } +} - return [...new Set(keys)].filter((key) => !heldKeys.has(key)); +async function heldVariableKeys( + environments: EnvironmentReader | undefined, + params: EnvironmentParams, +): Promise> { + if (environments === undefined) { + return new Set(); + } + + try { + const { environmentVariables } = await environments.get(params); + + return new Set((environmentVariables ?? []).flatMap(({ key }) => (key === undefined ? [] : [key]))); + } catch { + return new Set(); + } +} + +async function namedConflict( + error: SecretKeyConflictError, + params: EnvironmentParams, + incoming: EnvironmentVariableInput[], + { secrets = [], lister, environments }: SetVariablesOptions, +): Promise { + const held = await heldSecretKeys(lister, params); + const keys = [...new Set(incoming.map(({ key }) => key))].filter((key) => held.has(key)); + + if (keys.length > 0) { + return new SecretKeyConflictError(keys); + } + + if (secrets.length === 0 || error.cause === undefined) { + return error; + } + + const variables = await heldVariableKeys(environments, params); + const now = [...new Set(secrets.map(({ key }) => key))].filter((key) => variables.has(key)); + + return now.length > 0 ? notVariablesError(now) : error.cause; } export async function setVariables( store: VariableStore, params: EnvironmentParams, incoming: EnvironmentVariableInput[], -): Promise { - if (incoming.length > 0) { - await store.patch({ ...params, set: incoming }); + options: SetVariablesOptions = {}, +): Promise { + const { secrets = [] } = options; + + if (incoming.length === 0 && secrets.length === 0) { + return []; } + + return store + .patch({ + ...params, + ...(incoming.length > 0 ? { set: incoming } : {}), + ...(secrets.length > 0 ? { secrets } : {}), + }) + .catch(async (error: unknown) => { + throw error instanceof SecretKeyConflictError ? await namedConflict(error, params, incoming, options) : error; + }); } export async function unsetVariables( diff --git a/src/variables/variables.api.test.ts b/src/variables/variables.api.test.ts index 235949e9..483a9385 100644 --- a/src/variables/variables.api.test.ts +++ b/src/variables/variables.api.test.ts @@ -1,7 +1,11 @@ import { MALFORMED_CODE } from '../transport/envelope'; import { UsageError } from '../core/errors'; -import { LaunchApiError } from '../transport/errors'; +import { EXIT_RUNTIME } from '../core/constants'; +import { REDACTED } from '../core/redact'; +import { LaunchApiError, LaunchNetworkError } from '../transport/errors'; import type { RestApiClient, RestRequest } from '../transport/rest-client'; +import { gluedValue } from '../../test/support/glued-value'; +import { SecretKeyConflictError } from './variable.errors'; import { VariablesApi } from './variables.api'; const SCOPE = { org: 'org1', project: 'proj1', environment: 'env1' }; @@ -21,6 +25,15 @@ function fakeRestClient(result: unknown) { return { client, requests, messages }; } +function failureOf(promise: Promise): Promise { + return promise.then( + () => { + throw new Error('expected the call to reject'); + }, + (thrown: unknown) => thrown as T, + ); +} + const TEMPLATE = [ { keyName: 'CONTENTSTACK_API_HOST', key: 'CONTENTSTACK_API_HOST', value: 'api.example.test' }, { keyName: 'CONTENTSTACK_CDN', key: 'CONTENTSTACK_CDN', value: 'cdn.example.test' }, @@ -162,4 +175,247 @@ describe('variables api', () => { await expect(new VariablesApi(client).patch({ ...SCOPE, set: [{ key: 'A', value: '1' }] })).rejects.toBe(notSet); }); + it('puts the secrets in the same PATCH body as the variables to set and returns the secrets the response names, never a value', async () => { + const value = gluedValue(); + const updatedAt = '2026-12-03T07:53:26.577Z'; + const { client, requests } = fakeRestClient({ + count: 1, + variables: [{ key: 'API_URL' }], + secrets: [{ key: 'STRIPE_KEY', updatedAt, value }], + }); + + const secrets = await new VariablesApi(client).patch({ + ...SCOPE, + set: [{ key: 'API_URL', value: 'https://example.test' }], + secrets: [{ key: 'STRIPE_KEY', value }], + }); + + expect(requests).toEqual([ + { + method: 'PATCH', + path: PATCH_PATH, + orgUid: 'org1', + projectUid: 'proj1', + body: { set: [{ key: 'API_URL', value: 'https://example.test' }], secrets: [{ key: 'STRIPE_KEY', value }] }, + }, + ]); + expect(secrets).toEqual([{ key: 'STRIPE_KEY', updatedAt }]); + expect(JSON.stringify(secrets)).not.toContain(value); + }); + + it('sends no secrets key when the patch carries only variables to set or to unset, and resolves to no secrets', async () => { + const { client, requests } = fakeRestClient({ count: 1, variables: [{ key: 'A' }] }); + const api = new VariablesApi(client); + + const afterSet = await api.patch({ ...SCOPE, set: [{ key: 'A', value: '1' }] }); + const afterUnset = await api.patch({ ...SCOPE, unset: ['B'] }); + + expect(requests.map(({ body }) => Object.keys(body as object))).toEqual([['set'], ['unset']]); + expect(afterSet).toEqual([]); + expect(afterUnset).toEqual([]); + }); + + it.each([ + [{ secrets: 'STRIPE_KEY' }, []], + [{ secrets: { key: 'STRIPE_KEY' } }, []], + [{ secrets: null }, []], + [null, []], + [undefined, []], + [{ secrets: [null, 'text', { updatedAt: '2026-12-03T07:53:26.577Z' }, { key: ' ' }, { key: 5 }] }, []], + [ + { secrets: [{ key: 'A', updatedAt: 5 }, { key: 'B' }, { key: 'C', updatedAt: ' ' }, { key: 'D', updatedAt: '2026-12-03T07:53:26.577Z' }] }, + [ + { key: 'A', updatedAt: undefined }, + { key: 'B', updatedAt: undefined }, + { key: 'C', updatedAt: undefined }, + { key: 'D', updatedAt: '2026-12-03T07:53:26.577Z' }, + ], + ], + ])('reads only the keyed secrets out of a response that may lack or garble the field (%j)', async (response, expected) => { + const { client } = fakeRestClient(response); + + const secrets = await new VariablesApi(client).patch({ ...SCOPE, unset: ['B'] }); + + expect(secrets).toEqual(expected); + }); + + it('redacts every secret value and its trimmed form from a rejected 400, keeping its status and code', async () => { + const first = gluedValue(); + const second = gluedValue(); + const padded = ` ${second} `; + const code = 'launch.ENVIRONMENT.SOMETHING_ELSE'; + const rejection = new LaunchApiError(400, [ + { code, message: `value ${first} is not valid` }, + { field: 'secrets', code, message: `value ${second} is not valid, sent as "${padded}"` }, + { code }, + ]); + const client = { request: async () => Promise.reject(rejection) } as unknown as RestApiClient; + + const error = await failureOf( + new VariablesApi(client).patch({ + ...SCOPE, + secrets: [ + { key: 'STRIPE_KEY', value: first }, + { key: 'DB_PASSWORD', value: padded }, + ], + }), + ); + + expect(error).toBeInstanceOf(LaunchApiError); + expect(error.status).toBe(400); + expect(error.code).toBe(code); + expect(error.message).toBe(`value ${REDACTED} is not valid`); + expect(error.errors).toEqual([ + { code, message: `value ${REDACTED} is not valid` }, + { field: 'secrets', code, message: `value ${REDACTED} is not valid, sent as "${REDACTED}"` }, + { code }, + ]); + expect(JSON.stringify([error.message, error.errors, error.rawErrors])).not.toContain(first); + expect(JSON.stringify([error.message, error.errors, error.rawErrors])).not.toContain(second); + }); + + it('redacts a secret value from a network failure of a patch that carried it, keeping it retryable', async () => { + const value = gluedValue(); + const failure = new LaunchNetworkError(`socket closed while sending ${value}`, new Error(value), true); + const client = { request: async () => Promise.reject(failure) } as unknown as RestApiClient; + + const error = await failureOf( + new VariablesApi(client).patch({ ...SCOPE, secrets: [{ key: 'STRIPE_KEY', value }] }), + ); + + expect(error).toBeInstanceOf(LaunchNetworkError); + expect(error.message).toBe(`socket closed while sending ${REDACTED}`); + expect(error.retryable).toBe(true); + expect(error.cause).toBeUndefined(); + }); + + it('keeps the wording of a coded failure of a patch that carried secrets', async () => { + const value = gluedValue(); + const rejection = new LaunchApiError(409, [ + { code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE', message: value }, + ]); + const client = { request: async () => Promise.reject(rejection) } as unknown as RestApiClient; + + const error = await failureOf( + new VariablesApi(client).patch({ ...SCOPE, secrets: [{ key: 'STRIPE_KEY', value }] }), + ); + + expect(error.status).toBe(409); + expect(error.message).toBe( + 'The change was not saved because another update to this environment was in progress. Run the command again.', + ); + expect(error.errors).toEqual([ + { code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE', message: REDACTED }, + ]); + }); + + it('replaces a foreign error that carries the request body with a plain error holding no value when secrets were sent', async () => { + const first = gluedValue(); + const second = gluedValue(); + const padded = ` ${second} `; + const failure = Object.assign(new Error(`write failed for ${first} and "${padded}" and ${second}`), { + config: { data: JSON.stringify({ secrets: [{ key: 'STRIPE_KEY', value: first }] }) }, + request: { body: first }, + }); + const client = { request: async () => Promise.reject(failure) } as unknown as RestApiClient; + + const error = await failureOf( + new VariablesApi(client).patch({ + ...SCOPE, + secrets: [ + { key: 'STRIPE_KEY', value: first }, + { key: 'DB_PASSWORD', value: padded }, + ], + }), + ); + + expect(error).not.toBe(failure); + expect(Object.getPrototypeOf(error)).toBe(Error.prototype); + expect(error.message).toBe(`write failed for ${REDACTED} and "${REDACTED}" and ${REDACTED}`); + expect(error.config).toBeUndefined(); + expect(error.request).toBeUndefined(); + expect(Object.keys(error)).toEqual([]); + expect(JSON.stringify([error.message, error.stack])).not.toContain(first); + expect(JSON.stringify([error.message, error.stack])).not.toContain(second); + }); + + it('passes a failure that is not an Error, and a CLI error, through unchanged when secrets were sent', async () => { + const thrown = 'plain text failure'; + const cli = new UsageError('A usage failure.'); + const secrets = [{ key: 'STRIPE_KEY', value: gluedValue() }]; + + await expect( + new VariablesApi({ request: async () => Promise.reject(thrown) } as unknown as RestApiClient).patch({ + ...SCOPE, + secrets, + }), + ).rejects.toBe(thrown); + await expect( + new VariablesApi({ request: async () => Promise.reject(cli) } as unknown as RestApiClient).patch({ + ...SCOPE, + secrets, + }), + ).rejects.toBe(cli); + }); + + it('leaves a foreign error untouched when the patch carried no secrets', async () => { + const failure = new Error('disk full'); + const client = { request: async () => Promise.reject(failure) } as unknown as RestApiClient; + + await expect(new VariablesApi(client).patch({ ...SCOPE, set: [{ key: 'A', value: '1' }] })).rejects.toBe(failure); + }); + + it.each([ + ['launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT'], + ['launch.ENVIRONMENT.ENVIRONMENT_SECRETS.ENVIRONMENT_SECRET_KEY_CONFLICT'], + ['ENVIRONMENT_SECRET_KEY_CONFLICT'], + ])('rejects a 409 with the code %s as the typed secret key conflict, naming no key and no value', async (code) => { + const value = gluedValue(); + const rejection = new LaunchApiError(409, [{ code, message: `STRIPE_KEY holds ${value}` }]); + const client = { request: async () => Promise.reject(rejection) } as unknown as RestApiClient; + + const error = await failureOf( + new VariablesApi(client).patch({ + ...SCOPE, + set: [{ key: 'STRIPE_KEY', value: 'https://example.test' }], + secrets: [{ key: 'DB_PASSWORD', value }], + }), + ); + + expect(error).toBeInstanceOf(SecretKeyConflictError); + expect(error.exitCode).toBe(EXIT_RUNTIME); + expect(error.message).toBe('A key you passed is a secret. Use --secret to replace its value.'); + expect(error.cause).toBeInstanceOf(LaunchApiError); + expect((error.cause as LaunchApiError).status).toBe(409); + expect((error.cause as LaunchApiError).code).toBe(code); + expect((error.cause as LaunchApiError).message).toBe(`STRIPE_KEY holds ${REDACTED}`); + expect(JSON.stringify([(error.cause as LaunchApiError).message, (error.cause as LaunchApiError).errors])).not.toContain(value); + }); + + it('rejects the secret key conflict of a patch that sent no secrets too', async () => { + const rejection = new LaunchApiError(409, [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT' }]); + const client = { request: async () => Promise.reject(rejection) } as unknown as RestApiClient; + + const error = await failureOf(new VariablesApi(client).patch({ ...SCOPE, set: [{ key: 'A', value: '1' }] })); + + expect(error).toBeInstanceOf(SecretKeyConflictError); + }); + + it.each([ + [409, 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE'], + [400, 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT'], + [409, 'launch.ENVIRONMENT.ENVIRONMENT_SECRET_KEY_CONFLICT_NOT'], + [500, 'ENVIRONMENT_SECRET_KEY_CONFLICT'], + ])('does not take a %p with the code %s for the secret key conflict', async (status, code) => { + const rejection = new LaunchApiError(status, [{ code }]); + const client = { request: async () => Promise.reject(rejection) } as unknown as RestApiClient; + + const error = await failureOf( + new VariablesApi(client).patch({ ...SCOPE, secrets: [{ key: 'STRIPE_KEY', value: gluedValue() }] }), + ); + + expect(error).not.toBeInstanceOf(SecretKeyConflictError); + expect((error as LaunchApiError).status).toBe(status); + expect((error as LaunchApiError).code).toBe(code); + }); }); diff --git a/src/variables/variables.api.ts b/src/variables/variables.api.ts index 8559a9de..e8dc02dc 100644 --- a/src/variables/variables.api.ts +++ b/src/variables/variables.api.ts @@ -6,7 +6,7 @@ import { malformed } from '../transport/envelope'; import type { ErrorMessages } from '../transport/errors'; import { LaunchApiError } from '../transport/errors'; import type { RestApiClient } from '../transport/rest-client'; -import { someNotSetError } from './variable.errors'; +import { SecretKeyConflictError, someNotSetError, withoutSecretValues } from './variable.errors'; export interface StackTemplateEntry { key: string; @@ -17,9 +17,32 @@ const VARIABLE_ERROR_MESSAGES: ErrorMessages = {}; const KEY_NOT_FOUND_CODE = 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.NOT_FOUND'; +const SECRET_KEY_CONFLICT_CODE = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT'; + +const SECRET_KEY_CONFLICT_SUFFIX = 'ENVIRONMENT_SECRET_KEY_CONFLICT'; + +function isSecretKeyConflict(error: unknown): error is LaunchApiError { + return ( + error instanceof LaunchApiError && + error.status === 409 && + (error.code === SECRET_KEY_CONFLICT_CODE || error.code.endsWith(SECRET_KEY_CONFLICT_SUFFIX)) + ); +} + +export interface SecretInput { + key: string; + value: string; +} + +export interface PatchedSecret { + key: string; + updatedAt: string | undefined; +} + export interface PatchVariablesParams extends EnvironmentParams { set?: EnvironmentVariableInput[]; unset?: string[]; + secrets?: SecretInput[]; } function textOf(value: unknown): string | undefined { @@ -36,6 +59,20 @@ function entryOf(value: unknown): StackTemplateEntry[] { return key === undefined ? [] : [{ key, value: textOf(value.value) }]; } +function patchedSecretOf(value: unknown): PatchedSecret[] { + if (!isRecord(value)) { + return []; + } + + const key = textOf(value.key); + + return key === undefined ? [] : [{ key, updatedAt: textOf(value.updatedAt) }]; +} + +function patchedSecretsOf(response: unknown): PatchedSecret[] { + return isRecord(response) && Array.isArray(response.secrets) ? response.secrets.flatMap(patchedSecretOf) : []; +} + export class VariablesApi { constructor(private readonly client: RestApiClient) {} @@ -52,22 +89,39 @@ export class VariablesApi { return response.flatMap(entryOf); } - async patch({ org, project, environment, set, unset }: PatchVariablesParams): Promise { - await this.client + async patch({ org, project, environment, set, unset, secrets }: PatchVariablesParams): Promise { + return this.client .request( { method: 'PATCH', path: `/projects/${project}/environments/${environment}/variables`, orgUid: org, projectUid: project, - body: { ...(set === undefined ? {} : { set }), ...(unset === undefined ? {} : { unset }) }, + body: { + ...(set === undefined ? {} : { set }), + ...(unset === undefined ? {} : { unset }), + ...(secrets === undefined ? {} : { secrets }), + }, }, ENVIRONMENT_ERROR_MESSAGES, ) - .catch((error: unknown) => { + .catch((failure: unknown) => { + const error = secrets?.length + ? withoutSecretValues( + failure, + secrets.map(({ value }) => value), + ENVIRONMENT_ERROR_MESSAGES, + ) + : failure; + + if (isSecretKeyConflict(error)) { + throw new SecretKeyConflictError([], error); + } + throw error instanceof LaunchApiError && error.code === KEY_NOT_FOUND_CODE && unset?.length ? someNotSetError(unset) : error; - }); + }) + .then(patchedSecretsOf); } } diff --git a/test/integration/retired-commands.test.ts b/test/integration/retired-commands.test.ts index e55b36d1..c17dcce1 100644 --- a/test/integration/retired-commands.test.ts +++ b/test/integration/retired-commands.test.ts @@ -63,6 +63,7 @@ describe('integration: retired V1 command names', () => { afterEach(() => { process.exitCode = 0; + nock.emitter.removeAllListeners('no match'); nock.cleanAll(); }); @@ -201,6 +202,29 @@ describe('integration: retired V1 command names', () => { expect(stdout).toMatch(new RegExp(`\\n\\s+${command}\\s+${summary}\\n`)); }); + it.each(['launch:secrets:list', 'launch:secrets:set', 'launch:secrets:unset'])( + 'does not register %s and answers it as an unknown command with exit 2 and no request', + async (name) => { + const registered = config.commands.map((command) => command.id); + const requests: string[] = []; + nock.emitter.on('no match', (request: { path?: string }) => requests.push(String(request.path))); + + const { error, stderr } = await runCommand([name], config); + + expect(registered).not.toContain(name); + expect(stderr).toBe('error: Run csdx launch --help to see all commands.\n'); + expect(error?.oclif?.exit).toBe(2); + expect(requests).toEqual([]); + expect(nock.pendingMocks()).toEqual([]); + }, + ); + + it('lists no launch:secrets topic under launch --help', async () => { + const { stdout } = await runCommand(['launch', '--help'], config); + + expect(stdout).not.toContain('launch:secrets'); + }); + it('registers launch:site:open and no launch:site:view', () => { const registered = config.commands.map((command) => command.id); diff --git a/test/integration/variables-list.test.ts b/test/integration/variables-list.test.ts index 80958698..ec6ed4aa 100644 --- a/test/integration/variables-list.test.ts +++ b/test/integration/variables-list.test.ts @@ -41,6 +41,22 @@ function environmentOfProject() { .reply(200, getFixture); } +const SECRET_UPDATED_AT = '2026-12-03T07:53:26.577Z'; + +function secretsOfEnvironment(status = 200) { + 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(`/manage/projects/${PROJECT_UID}/environments/${ENV_UID}/secrets`) + .reply( + status, + status === 200 + ? { secrets: [{ key: 'STRIPE_KEY', updatedAt: SECRET_UPDATED_AT }], count: 1 } + : { errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.READ_FORBIDDEN' }], status }, + ); +} + const LIST = ['launch:variables:list', '--org', ORG_UID, '--project', PROJECT_UID, '--env', ENV_UID, '--data-dir', DATA_DIR]; describe('integration: launch:variables:list driven through oclif runCommand', () => { @@ -66,24 +82,86 @@ describe('integration: launch:variables:list driven through oclif runCommand', ( nock.restore(); }); - it('reads the variables from the environment endpoint and prints each key with its value masked', async () => { + it('prints variables and secrets in one table with a type column and no value or escape code', async () => { + const restoreWidth = stdoutOfWidth(200); + + try { + const environment = environmentOfProject(); + const secrets = secretsOfEnvironment(); + + const { error, stdout } = await runCommand(LIST, config); + + expect(error).toBeUndefined(); + expect(environment.isDone()).toBe(true); + expect(secrets.isDone()).toBe(true); + expect(stdout).toMatch(/KEY\s+\u2502\s+TYPE\s+\u2502\s+VALUE\s+\u2502\s+UPDATED/); + expect(stdout).toContain( + '\u2502 key1 \u2502 variable \u2502 \u2022\u2022\u2022\u2022\u2022\u2022 \u2502 2025-11-06T07:39:53.582Z \u2502', + ); + expect(stdout).toContain( + `\u2502 STRIPE_KEY \u2502 secret \u2502 (write-only) \u2502 ${SECRET_UPDATED_AT} \u2502`, + ); + expect(stdout).not.toContain('value1'); + expect(stdout).not.toContain('\u001b['); + expect(stdout.trimEnd().split('\n').pop()).toBe('Showing 1-2 of 2'); + } finally { + restoreWidth(); + } + }); + + it('pages the variables and the secrets together with --limit and --skip', async () => { const restoreWidth = stdoutOfWidth(200); try { - const scope = environmentOfProject(); + environmentOfProject(); + secretsOfEnvironment(); + + const { error, stdout } = await runCommand([...LIST, '--limit', '1', '--skip', '1'], config); + + expect(error).toBeUndefined(); + expect(stdout).toContain('STRIPE_KEY'); + expect(stdout).not.toContain('key1'); + expect(stdout.trimEnd().split('\n').pop()).toBe('Showing 2-2 of 2'); + } finally { + restoreWidth(); + } + }); + + it('prints the variables table and a warning, and exits 0, when the secrets cannot be read', async () => { + const restoreWidth = stdoutOfWidth(200); + + try { + environmentOfProject(); + const secrets = secretsOfEnvironment(403); const { error, stdout } = await runCommand(LIST, config); expect(error).toBeUndefined(); - expect(scope.isDone()).toBe(true); - expect(stdout).toContain('\u2502 key1 \u2502 \u2022\u2022\u2022\u2022\u2022\u2022 \u2502 2025-11-06T07:39:53.582Z \u2502'); + expect(secrets.isDone()).toBe(true); + expect(stdout).toContain('key1'); + expect(stdout).toContain('variable'); expect(stdout).not.toContain('value1'); - expect(stdout.trimEnd().split('\n').pop()).toBe('Showing 1-1 of 1'); + expect(stdout).not.toContain('STRIPE_KEY'); + expect(stdout).not.toContain('\u001b['); + expect(stdout.trimEnd().split('\n').pop()).toBe('Permission is needed to view the secrets of this environment.'); } finally { restoreWidth(); } }); + it('prints the variables table and the not-found warning when the region has no secrets route', async () => { + environmentOfProject(); + nock(LAUNCH_HUB_URL) + .get(`/manage/projects/${PROJECT_UID}/environments/${ENV_UID}/secrets`) + .reply(404, { errors: [{ code: 'launch.ENVIRONMENT.NOT_FOUND' }], status: 404 }); + + const { error, stdout } = await runCommand(LIST, config); + + expect(error).toBeUndefined(); + expect(stdout).toContain('key1'); + expect(stdout.trimEnd().split('\n').pop()).toBe('The project or environment was not found.'); + }); + it('exits 1 with the CLI wording and no value when the environment does not exist', async () => { nock(LAUNCH_HUB_URL) .get(`/manage/projects/${PROJECT_UID}/environments/${ENV_UID}`) diff --git a/test/integration/variables-set-unset.test.ts b/test/integration/variables-set-unset.test.ts index 7c0a9f36..6c10b5da 100644 --- a/test/integration/variables-set-unset.test.ts +++ b/test/integration/variables-set-unset.test.ts @@ -1,9 +1,11 @@ import { randomBytes } from 'node:crypto'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { Readable } from 'node:stream'; import { authHandler, configHandler } from '@contentstack/cli-utilities'; +import { settings } from '@oclif/core'; import type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; @@ -12,6 +14,7 @@ import cmsFixture from '../fixtures/cms-environment-variables.json'; import getFixture from '../fixtures/environment-get.json'; import { answerPrompts, onTerminal } from '../support/terminal'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; +import { gluedValue } from '../support/glued-value'; import { projectOwnership } from '../support/project-ownership'; const LAUNCH_HUB_URL = 'https://launch-api.integration.test'; @@ -40,6 +43,7 @@ const SCOPE = ['--org', ORG_UID, '--project', PROJECT_UID, '--env', ENV_UID]; interface Wire { order: string[]; patch: unknown[]; + deleted: { body: string; contentType: unknown }[]; } function scopedHub() { @@ -73,17 +77,63 @@ function patchEndpoint(wire: Wire, status = 200, body: unknown = undefined) { }); } -function unsetEndpoints(wire: Wire, status = 200, body: unknown = undefined) { +function unsetReads(wire: Wire, variableKeys: string[], secretKeys: string[], secretsRead = true) { scopedHub() .get(ENV_PATH) .reply(200, () => { wire.order.push('get'); - return getFixture; + return { + environment: { ...getFixture.environment, environmentVariables: variableKeys.map((key) => ({ key, value: 'value1' })) }, + }; + }); + + if (!secretsRead) { + return; + } + + scopedHub() + .get(`${ENV_PATH}/secrets`) + .reply(200, () => { + wire.order.push('secrets'); + return { + secrets: secretKeys.map((key) => ({ key, updatedAt: '2026-12-03T07:53:26.577Z' })), + count: secretKeys.length, + }; }); +} + +function unsetEndpoints(wire: Wire, status = 200, body: unknown = undefined) { + unsetReads(wire, ['key1'], [], false); return patchEndpoint(wire, status, body); } +function secretDeletion(wire: Wire, key: string, status = 204) { + return scopedHub() + .delete(`${ENV_PATH}/secrets/${key}`) + .reply(status, function reply(_uri, requestBody) { + wire.order.push(`delete ${key}`); + wire.deleted.push({ body: String(requestBody), contentType: this.req.headers['content-type'] }); + + return status === 204 ? '' : { errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.WRITE_FORBIDDEN' }], status }; + }); +} + +function secretsEndpoint(keys: string[], status = 200) { + return scopedHub() + .get(`${ENV_PATH}/secrets`) + .reply(status, () => + status === 200 + ? { secrets: keys.map((key) => ({ key, updatedAt: '2026-12-03T07:53:26.577Z' })), count: keys.length } + : { errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.READ_FORBIDDEN' }], status }, + ); +} + +const SECRET_KEY_CONFLICT = { + errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT' }], + status: 409, +}; + function cmsEndpoint(sent: Wire) { return nock(LAUNCH_HUB_URL) .matchHeader('x-organization-uid', ORG_UID) @@ -94,8 +144,33 @@ function cmsEndpoint(sent: Wire) { }); } +function envEndpoint(variableKeys: string[]) { + return scopedHub() + .get(ENV_PATH) + .reply(200, { + environment: { ...getFixture.environment, environmentVariables: variableKeys.map((key) => ({ key })) }, + }); +} + +function pipedStdin(stream: Readable): () => void { + const original = Object.getOwnPropertyDescriptor(process, 'stdin'); + + Object.defineProperty(process, 'stdin', { value: stream, configurable: true }); + + return () => { + Object.defineProperty(process, 'stdin', original as PropertyDescriptor); + }; +} + +function filesIn(directory: string, except: string[] = []): string { + return readdirSync(directory) + .filter((name) => !except.includes(name)) + .map((name) => readFileSync(join(directory, name), 'utf8')) + .join('\n'); +} + function wire(): Wire { - return { order: [], patch: [] }; + return { order: [], patch: [], deleted: [] }; } describe('integration: launch:variables:set and :unset driven through oclif runCommand', () => { @@ -454,7 +529,11 @@ describe('integration: launch:variables:set and :unset driven through oclif runC expect(error?.oclif?.exit).toBe(1); expect(error?.message).toContain('Run the command again.'); - expect(stdout).not.toContain('removed'); + expect(stdout).toContain( + 'Variable key1 was not removed: The change was not saved because another update to this environment was in progress. ' + + 'Run the command again.', + ); + expect(stdout).not.toContain('\u2714'); }); it('exits 2 with the not-set wording when the key is gone by the time the PATCH lands', async () => { @@ -468,7 +547,27 @@ describe('integration: launch:variables:set and :unset driven through oclif runC expect(error?.oclif?.exit).toBe(2); expect(error?.message).toBe('key1 is not set in this environment.'); - expect(stdout).not.toContain('removed'); + expect(stdout).toContain('Variable key1 was not removed: key1 is not set in this environment.'); + expect(stdout).not.toContain('\u2714'); + }); + + it('exits 1 naming the variables and the secrets left in place when the PATCH and a DELETE both fail', async () => { + const sent = wire(); + unsetReads(sent, ['DEBUG'], ['DB_PASSWORD']); + patchEndpoint(sent, 404, { + errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.NOT_FOUND' }], + status: 404, + }); + secretDeletion(sent, 'DB_PASSWORD', 403); + + const { error } = await runCommand( + ['launch:variables:unset', ...SCOPE, '--key', 'DEBUG', '--key', 'DB_PASSWORD', '--yes'], + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toContain('Variables left in place: DEBUG'); + expect(error?.message).toContain('Secrets left in place: DB_PASSWORD.'); }); it('removes only the named key with --yes, patching out only that key', async () => { @@ -484,15 +583,182 @@ describe('integration: launch:variables:set and :unset driven through oclif runC expect(stdout).not.toContain('value1'); }); + it('works out each key kind, sending one PATCH for the variable and a bodyless DELETE for the secret', async () => { + const sent = wire(); + const unmatched: string[] = []; + const record = (request: { method?: string; path?: string }) => unmatched.push(`${request.method} ${request.path}`); + nock.emitter.on('no match', record); + unsetReads(sent, ['DEBUG'], ['DB_PASSWORD']); + const patch = patchEndpoint(sent); + const deletion = secretDeletion(sent, 'DB_PASSWORD'); + + try { + const { error, stdout } = await runCommand( + ['launch:variables:unset', ...SCOPE, '--key', 'DEBUG', '--key', 'DB_PASSWORD', '--yes'], + config, + ); + + expect(error).toBeUndefined(); + expect([patch.isDone(), deletion.isDone()]).toEqual([true, true]); + expect(sent.order).toEqual(['get', 'secrets', 'patch', 'delete DB_PASSWORD']); + expect(sent.patch).toEqual([{ unset: ['DEBUG'] }]); + expect(sent.deleted).toEqual([{ body: '', contentType: undefined }]); + expect(unmatched).toEqual([]); + expect(stdout).toContain('\u2714 Variable DEBUG removed from the "production" environment.'); + expect(stdout).toContain('\u2714 Secret DB_PASSWORD removed from the "production" environment.'); + expect(stdout.split('\n').filter((line) => line.includes('removed'))).toHaveLength(2); + } finally { + nock.emitter.removeListener('no match', record); + } + }); + + it('exits 1 naming the secret the server refused to delete, and still reports the variable removed', async () => { + const sent = wire(); + unsetReads(sent, ['DEBUG'], ['DB_PASSWORD']); + patchEndpoint(sent); + secretDeletion(sent, 'DB_PASSWORD', 403); + + const { error, stdout } = await runCommand( + ['launch:variables:unset', ...SCOPE, '--key', 'DEBUG', '--key', 'DB_PASSWORD', '--yes'], + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('1 of 1 secret was not removed: DB_PASSWORD.'); + expect(stdout).toContain('\u2714 Variable DEBUG removed from the "production" environment.'); + expect(stdout).toContain('Secret DB_PASSWORD was not removed: Permission is needed to change the secrets of this environment.'); + expect(sent.order).toEqual(['get', 'secrets', 'patch', 'delete DB_PASSWORD']); + }); + + it('names the variable the refused PATCH left in place, and still deletes the secret', async () => { + const sent = wire(); + unsetReads(sent, ['DEBUG'], ['DB_PASSWORD']); + patchEndpoint(sent, 409, { + errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE' }], + status: 409, + }); + const deletion = secretDeletion(sent, 'DB_PASSWORD'); + + const { error, stdout } = await runCommand( + ['launch:variables:unset', ...SCOPE, '--key', 'DEBUG', '--key', 'DB_PASSWORD', '--yes'], + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toContain('Run the command again.'); + expect(stdout).toContain('Variable DEBUG was not removed: The change was not saved'); + expect(stdout).toContain('\u2714 Secret DB_PASSWORD removed from the "production" environment.'); + expect(deletion.isDone()).toBe(true); + expect(sent.order).toEqual(['get', 'secrets', 'patch', 'delete DB_PASSWORD']); + }); + + it('stops before deleting any secret when the variables PATCH gets no API answer, naming where it stopped', async () => { + const sent = wire(); + unsetReads(sent, ['DEBUG'], ['DB_PASSWORD', 'STRIPE_KEY']); + scopedHub().patch(`${ENV_PATH}/variables`).replyWithError({ code: 'ECONNRESET', message: 'socket hang up' }); + const deletions = [secretDeletion(sent, 'DB_PASSWORD'), secretDeletion(sent, 'STRIPE_KEY')]; + + const { error, stdout } = await runCommand( + ['launch:variables:unset', ...SCOPE, '--key', 'DEBUG', '--key', 'DB_PASSWORD', '--key', 'STRIPE_KEY', '--yes'], + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toContain('Stopped at the variables: '); + expect(error?.message).toContain('Removed: none.\nFailed: DEBUG.\nNot attempted: DB_PASSWORD, STRIPE_KEY.'); + expect(deletions.map((deletion) => deletion.isDone())).toEqual([false, false]); + expect(sent.order).toEqual(['get', 'secrets']); + expect(stdout).not.toContain('\u2714'); + }); + + it('deletes only secrets without sending a variables PATCH when every key is a secret', async () => { + const sent = wire(); + unsetReads(sent, ['DEBUG'], ['DB_PASSWORD', 'STRIPE_KEY']); + secretDeletion(sent, 'DB_PASSWORD'); + secretDeletion(sent, 'STRIPE_KEY'); + + const { error, stdout } = await runCommand( + ['launch:variables:unset', ...SCOPE, '--key', 'DB_PASSWORD', '--key', 'STRIPE_KEY', '--yes'], + config, + ); + + expect(error).toBeUndefined(); + expect(sent.order).toEqual(['get', 'secrets', 'delete DB_PASSWORD', 'delete STRIPE_KEY']); + expect(sent.patch).toEqual([]); + expect(stdout).toContain('\u2714 Secret DB_PASSWORD removed'); + expect(stdout).toContain('\u2714 Secret STRIPE_KEY removed'); + }); + + it('exits 2 for a key that is neither a variable nor a secret and writes nothing, even beside a held secret', async () => { + const sent = wire(); + unsetReads(sent, ['DEBUG'], ['DB_PASSWORD']); + + const { error } = await runCommand( + ['launch:variables:unset', ...SCOPE, '--key', 'DB_PASSWORD', '--key', 'NOPE', '--yes'], + config, + ); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('NOPE is not set in this environment.'); + expect(sent.order).toEqual(['get', 'secrets']); + }); + + it('asks one question naming the variable and the secret and removes neither when the user declines', async () => { + const sent = wire(); + unsetReads(sent, ['DEBUG'], ['DB_PASSWORD']); + answerPrompts({ + 'Are you sure you want to remove the variable DEBUG and the secret DB_PASSWORD from the "production" environment?': + false, + }); + + const { error, stdout } = await onTerminal(() => + runCommand(['launch:variables:unset', ...SCOPE, '--key', 'DEBUG', '--key', 'DB_PASSWORD'], config), + ); + + expect(error?.oclif?.exit).toBe(3); + expect(stdout).toContain('Variables not removed.'); + expect(sent.order).toEqual(['get', 'secrets']); + }); + + it('exits 1 with the secrets wording and writes nothing when a key needs the secrets that cannot be read', async () => { + const sent = wire(); + scopedHub().get(ENV_PATH).reply(200, getFixture); + secretsEndpoint([], 403); + const patch = patchEndpoint(sent); + + const { error } = await runCommand(['launch:variables:unset', ...SCOPE, '--key', 'DB_PASSWORD', '--yes'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('Permission is needed to view the secrets of this environment.'); + expect(patch.isDone()).toBe(false); + }); + + it('removes a variable without reading the secrets, so a refused secrets read cannot block it', async () => { + const sent = wire(); + scopedHub().get(ENV_PATH).reply(200, () => { + sent.order.push('get'); + return getFixture; + }); + const secrets = secretsEndpoint([], 403); + patchEndpoint(sent); + + const { error, stdout } = await runCommand(['launch:variables:unset', ...SCOPE, '--key', 'key1', '--yes'], config); + + expect(error).toBeUndefined(); + expect(secrets.isDone()).toBe(false); + expect(sent.order).toEqual(['get', 'patch']); + expect(stdout).toContain('\u2714 Variable key1 removed from the "production" environment.'); + }); + it('exits 2 for a key that is not set and sends no PATCH', async () => { const sent = wire(); - unsetEndpoints(sent); + unsetReads(sent, ['key1'], []); const { error } = await runCommand(['launch:variables:unset', ...SCOPE, '--key', 'NOPE', '--yes'], config); expect(error?.oclif?.exit).toBe(2); expect(error?.message).toBe('NOPE is not set in this environment.'); - expect(sent.order).toEqual(['get']); + expect(sent.order).toEqual(['get', 'secrets']); }); it('exits 2 naming --yes without a terminal and sends no PATCH', async () => { @@ -618,6 +884,577 @@ describe('integration: launch:variables:set and :unset driven through oclif runC }); }); + describe('with --secret', () => { + let onWire: string[]; + let restoreStdin: (() => void) | undefined; + let debugBefore: boolean; + + function setArgs(...args: string[]): string[] { + return ['launch:variables:set', ...SCOPE, ...args, '--data-dir', workDir]; + } + + function pipe(text: string): void { + restoreStdin = pipedStdin(Readable.from([text])); + } + + function pipeCountingReads(): string[] { + const reads: string[] = []; + + restoreStdin = pipedStdin( + new Readable({ + read() { + reads.push('read'); + this.push(null); + }, + }), + ); + + return reads; + } + + function endpoints(options: { variables?: string[]; secrets?: string[]; patch?: Wire } = {}) { + const sent = options.patch ?? wire(); + + return { + sent, + environment: envEndpoint(options.variables ?? []), + secrets: secretsEndpoint(options.secrets ?? []), + patch: patchEndpoint(sent), + }; + } + + function leaked(value: string, result: { error?: Error; stdout: string; stderr: string }): boolean { + return `${result.error?.message ?? ''}${result.error?.stack ?? ''}${result.stdout}${result.stderr}`.includes( + value, + ); + } + + beforeEach(() => { + onWire = []; + debugBefore = settings.debug === true; + nock.emitter.on('no match', (request: { method?: string; path?: string }) => { + onWire.push(`${request.method ?? 'UNKNOWN'} ${request.path ?? ''}`); + }); + }); + + afterEach(() => { + restoreStdin?.(); + restoreStdin = undefined; + settings.debug = debugBefore; + nock.emitter.removeAllListeners('no match'); + }); + + it('names the held secret and exits 1 when an auto-detected .env holds its key, printing no value', async () => { + const value = gluedValue(); + const sent = wire(); + const patch = patchEndpoint(sent, 409, SECRET_KEY_CONFLICT); + const secrets = secretsEndpoint(['STRIPE_KEY', 'DB_PASSWORD']); + writeFileSync(join(workDir, '.env'), `API_URL=https://example.test\nSTRIPE_KEY=${value}\n`); + + const { error, stdout, stderr } = await runCommand(['launch:variables:set', ...SCOPE, '--data-dir', workDir], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('STRIPE_KEY is a secret. Use --secret STRIPE_KEY to replace its value.'); + expect(sent.patch).toEqual([ + { set: [{ key: 'API_URL', value: 'https://example.test' }, { key: 'STRIPE_KEY', value }] }, + ]); + expect(patch.isDone()).toBe(true); + expect(secrets.isDone()).toBe(true); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}`).not.toContain(value); + expect(stdout).not.toContain('variables set'); + }); + + it('names the held secret and exits 1 when --var holds its key, printing no value', async () => { + const value = gluedValue(); + const sent = wire(); + patchEndpoint(sent, 409, SECRET_KEY_CONFLICT); + const secrets = secretsEndpoint(['STRIPE_KEY']); + + const { error, stdout, stderr } = await runCommand( + ['launch:variables:set', ...SCOPE, '--var', `STRIPE_KEY=${value}`, '--data-dir', workDir], + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('STRIPE_KEY is a secret. Use --secret STRIPE_KEY to replace its value.'); + expect(secrets.isDone()).toBe(true); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}`).not.toContain(value); + }); + + it('says a --secret key is a variable when it became one between the first read and the refused PATCH', async () => { + const value = gluedValue(); + const sent = wire(); + pipe(`${value}\n`); + envEndpoint([]); + secretsEndpoint([]); + const patch = patchEndpoint(sent, 409, SECRET_KEY_CONFLICT); + const reread = envEndpoint(['STRIPE_KEY']); + + const result = await runCommand(setArgs('--secret', 'STRIPE_KEY'), config); + + expect(result.error?.oclif?.exit).toBe(2); + expect(result.error?.message).toBe('STRIPE_KEY is a variable.'); + expect(patch.isDone()).toBe(true); + expect(reread.isDone()).toBe(true); + expect(leaked(value, result)).toBe(false); + }); + + it('keeps the API message for a conflict that no key of the run explains', async () => { + const value = gluedValue(); + const sent = wire(); + pipe(`${value}\n`); + envEndpoint([]); + secretsEndpoint([]); + patchEndpoint(sent, 409, { + errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT', message: 'That key already exists.' }], + status: 409, + }); + const reread = envEndpoint(['UNRELATED']); + + const result = await runCommand(setArgs('--secret', 'STRIPE_KEY'), config); + + expect(result.error?.oclif?.exit).toBe(1); + expect(result.error?.message).toBe('That key already exists.'); + expect(reread.isDone()).toBe(true); + expect(leaked(value, result)).toBe(false); + }); + + it('says generically that a key is a secret when the secrets cannot be read after the conflict', async () => { + const value = gluedValue(); + const sent = wire(); + patchEndpoint(sent, 409, SECRET_KEY_CONFLICT); + const secrets = secretsEndpoint([], 403); + + const { error, stdout, stderr } = await runCommand( + ['launch:variables:set', ...SCOPE, '--var', `STRIPE_KEY=${value}`, '--data-dir', workDir], + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('A key you passed is a secret. Use --secret to replace its value.'); + expect(secrets.isDone()).toBe(true); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}`).not.toContain(value); + }); + + it('keeps the run-again wording for a concurrent update and reads no secrets', async () => { + const sent = wire(); + patchEndpoint(sent, 409, { + errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE' }], + status: 409, + }); + const secrets = secretsEndpoint(['STRIPE_KEY']); + + const { error } = await runCommand(['launch:variables:set', ...SCOPE, '--var', 'A=1', '--data-dir', workDir], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe( + 'The change was not saved because another update to this environment was in progress. Run the command again.', + ); + expect(secrets.isDone()).toBe(false); + }); + + it.each([ + ['on a terminal', true], + ['without a terminal', false], + ])('exits 2 for --secret KEY=value %s, echoing no value, asking nothing and sending nothing', async (_label, terminal) => { + const value = gluedValue(); + const prompts = answerPrompts({}); + const wired = endpoints(); + + const run = () => runCommand(setArgs('--secret', `STRIPE_KEY=${value}`), config); + const result = terminal ? await onTerminal(run) : await run(); + + expect(result.error?.oclif?.exit).toBe(2); + expect(result.error?.message).toBe( + '--secret takes a key only. Give the value at the prompt, on standard input or with --dotenv.', + ); + expect(leaked(value, result)).toBe(false); + expect(prompts.messages).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([false, false, false]); + expect(onWire).toEqual([]); + }); + + it('exits 2 for a --secret token with a value after a space, naming neither the key nor the value, sending nothing', async () => { + const value = gluedValue(); + const prompts = answerPrompts({}); + const wired = endpoints(); + + const result = await onTerminal(() => runCommand(setArgs('--secret', `"DB_PASSWORD ${value}"`), config)); + + expect(result.error?.oclif?.exit).toBe(2); + expect(result.error?.message).toBe( + '--secret takes a key made of letters, digits, _, . and -, starting with a letter or _. ' + + 'Give the value at the prompt, on standard input or with --dotenv.', + ); + expect(leaked(value, result)).toBe(false); + expect(leaked('DB_PASSWORD', result)).toBe(false); + expect(prompts.messages).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([false, false, false]); + expect(onWire).toEqual([]); + }); + + it('exits 2 for --dotenv - on a terminal, asking to pipe the dotenv text in, reading and sending nothing', async () => { + const prompts = answerPrompts({}); + const wired = endpoints(); + + const { error } = await onTerminal(() => runCommand(setArgs('--dotenv', '-', '--secret', 'STRIPE_KEY'), config)); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--dotenv - reads the dotenv text from standard input, and this is a terminal.'); + expect(error?.message).toContain('Pipe it in'); + expect(prompts.messages).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([false, false, false]); + expect(onWire).toEqual([]); + }); + + it('exits 1 naming a --var key that is a held secret before any prompt, sending no PATCH', async () => { + const value = gluedValue(); + const prompts = answerPrompts({}); + const wired = endpoints({ secrets: ['STRIPE_KEY'] }); + + const result = await onTerminal(() => + runCommand(setArgs('--var', `STRIPE_KEY=${value}`, '--secret', 'DB_PASSWORD'), config), + ); + + expect(result.error?.oclif?.exit).toBe(1); + expect(result.error?.message).toBe('STRIPE_KEY is a secret. Use --secret STRIPE_KEY to replace its value.'); + expect(leaked(value, result)).toBe(false); + expect(prompts.messages).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([true, true, false]); + expect(onWire).toEqual([]); + }); + + it('exits 2 for a value typed after the --secret key, not taking it for a second key, echoing it nowhere', async () => { + const value = gluedValue(); + const prompts = answerPrompts({}); + const wired = endpoints(); + + const result = await onTerminal(() => runCommand(setArgs('--secret', 'STRIPE_KEY', value), config)); + + expect(result.error?.oclif?.exit).toBe(2); + expect(leaked(value, result)).toBe(false); + expect(prompts.messages).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([false, false, false]); + expect(onWire).toEqual([]); + }); + + it('reads one piped value without a terminal, drops its newline and sends one PATCH with only secrets', async () => { + const value = gluedValue(); + pipe(`${value}\n`); + const wired = endpoints(); + + const { error, stdout, stderr } = await runCommand(setArgs('--secret', 'STRIPE_KEY'), config); + + expect(error).toBeUndefined(); + expect(wired.sent.order).toEqual(['patch']); + expect(wired.sent.patch).toEqual([{ secrets: [{ key: 'STRIPE_KEY', value }] }]); + expect(stdout).toContain('✔ 1 secret added: STRIPE_KEY'); + expect(`${stdout}${stderr}`).not.toContain(value); + expect(onWire).toEqual([]); + }); + + it('replaces a held secret on a terminal with no confirmation', async () => { + const typed = gluedValue(); + const prompts = answerPrompts({ 'Value for STRIPE_KEY': typed }); + const wired = endpoints({ secrets: ['STRIPE_KEY'] }); + + const { error, stdout } = await onTerminal(() => runCommand(setArgs('--secret', 'STRIPE_KEY'), config)); + + expect(error).toBeUndefined(); + expect(prompts.messages).toEqual(['Value for STRIPE_KEY']); + expect(wired.sent.patch).toEqual([{ secrets: [{ key: 'STRIPE_KEY', value: typed }] }]); + expect(stdout).toContain('✔ 1 secret updated: STRIPE_KEY'); + expect(onWire).toEqual([]); + }); + + it('replaces a held secret piped without a terminal and without --yes', async () => { + const piped = gluedValue(); + pipe(piped); + const wired = endpoints({ secrets: ['STRIPE_KEY'] }); + + const { error, stdout } = await runCommand(setArgs('--secret', 'STRIPE_KEY'), config); + + expect(error).toBeUndefined(); + expect(wired.sent.patch).toEqual([{ secrets: [{ key: 'STRIPE_KEY', value: piped }] }]); + expect(stdout).toContain('✔ 1 secret updated: STRIPE_KEY'); + expect(onWire).toEqual([]); + }); + + it('sets every secret of one run from a --dotenv - stream, with no prompt and no variable', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + pipe(`STRIPE_KEY=${stripe}\nDB_PASSWORD=${password}\n`); + const wired = endpoints(); + + const { error, stdout } = await runCommand( + setArgs('--dotenv', '-', '--secret', 'STRIPE_KEY,DB_PASSWORD'), + config, + ); + + expect(error).toBeUndefined(); + expect(wired.sent.patch).toEqual([ + { + secrets: [ + { key: 'STRIPE_KEY', value: stripe }, + { key: 'DB_PASSWORD', value: password }, + ], + }, + ]); + expect(stdout).toContain('✔ 2 secrets added: STRIPE_KEY, DB_PASSWORD'); + expect(onWire).toEqual([]); + }); + + it('exits 2 naming a --dotenv - key that --secret does not name, sending nothing and printing no value', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + pipe(`STRIPE_KEY=${stripe}\nDB_PASSWORD=${password}\n`); + const wired = endpoints(); + + const result = await runCommand(setArgs('--dotenv', '-', '--secret', 'STRIPE_KEY'), config); + + expect(result.error?.oclif?.exit).toBe(2); + expect(result.error?.message).toContain('holds DB_PASSWORD, which is not named in --secret'); + expect(result.error?.message).not.toContain('STRIPE_KEY,'); + expect(leaked(stripe, result)).toBe(false); + expect(leaked(password, result)).toBe(false); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([false, false, false]); + expect(wired.sent.patch).toEqual([]); + expect(onWire).toEqual([]); + }); + + it('takes secrets from a --dotenv file and leaves the secret keys out of set', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + const path = join(workDir, 'ci.env'); + writeFileSync(path, `API_URL=https://x\nSTRIPE_KEY=${stripe}\nDB_PASSWORD=${password}\n`); + const wired = endpoints(); + + const { error } = await runCommand(setArgs('--dotenv', path, '--secret', 'STRIPE_KEY,DB_PASSWORD'), config); + + expect(error).toBeUndefined(); + expect(wired.sent.patch).toEqual([ + { + set: [{ key: 'API_URL', value: 'https://x' }], + secrets: [ + { key: 'STRIPE_KEY', value: stripe }, + { key: 'DB_PASSWORD', value: password }, + ], + }, + ]); + }); + + it('exits 2 naming --dotenv - when a second key needs stdin, reading nothing and sending nothing', async () => { + const reads = pipeCountingReads(); + const wired = endpoints(); + + const { error } = await runCommand(setArgs('--secret', 'STRIPE_KEY,DB_PASSWORD'), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--dotenv -'); + expect(reads).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([false, false, false]); + expect(onWire).toEqual([]); + }); + + it('exits 2 for --secret with a bare --var KEY without a terminal, reading nothing and sending nothing', async () => { + const reads = pipeCountingReads(); + const wired = endpoints(); + + const { error } = await runCommand(setArgs('--secret', 'STRIPE_KEY', '--var', 'API_TOKEN'), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('API_TOKEN has no value'); + expect(reads).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([false, false, false]); + expect(onWire).toEqual([]); + }); + + it.each([ + ['on a terminal', true], + ['without a terminal', false], + ])('exits 2 for a key in both --var KEY=value and --secret %s, naming the key and not the value', async (_label, terminal) => { + const value = gluedValue(); + const prompts = answerPrompts({}); + const wired = endpoints(); + + const run = () => runCommand(setArgs('--var', `STRIPE_KEY=${value}`, '--secret', 'STRIPE_KEY'), config); + const result = terminal ? await onTerminal(run) : await run(); + + expect(result.error?.oclif?.exit).toBe(2); + expect(result.error?.message).toContain('STRIPE_KEY is in both --var and --secret'); + expect(leaked(value, result)).toBe(false); + expect(prompts.messages).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([false, false, false]); + expect(onWire).toEqual([]); + }); + + it('exits 2 with "KEY is a variable." for a held variable, before any prompt, writing nothing', async () => { + const prompts = answerPrompts({}); + const wired = endpoints({ variables: ['API_URL'] }); + + const { error } = await onTerminal(() => runCommand(setArgs('--secret', 'API_URL'), config)); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('API_URL is a variable.'); + expect(prompts.messages).toEqual([]); + expect([wired.environment.isDone(), wired.secrets.isDone(), wired.patch.isDone()]).toEqual([true, true, false]); + expect(onWire).toEqual([]); + }); + + it('sends one PATCH with the variables and both secrets, asks numbered prompts and prints three lines', async () => { + const stripe = gluedValue(); + const password = gluedValue(); + const prompts = answerPrompts({ + 'Value for STRIPE_KEY (1/2)': stripe, + 'Value for DB_PASSWORD (2/2)': password, + }); + const wired = endpoints({ secrets: ['DB_PASSWORD'] }); + + const { error, stdout, stderr } = await onTerminal(() => + runCommand(setArgs('--var', 'API_URL=https://x', '--secret', 'STRIPE_KEY,DB_PASSWORD'), config), + ); + + expect(error).toBeUndefined(); + expect(prompts.messages).toEqual(['Value for STRIPE_KEY (1/2)', 'Value for DB_PASSWORD (2/2)']); + expect(wired.sent.order).toEqual(['patch']); + expect(wired.sent.patch).toEqual([ + { + set: [{ key: 'API_URL', value: 'https://x' }], + secrets: [ + { key: 'STRIPE_KEY', value: stripe }, + { key: 'DB_PASSWORD', value: password }, + ], + }, + ]); + expect(stdout).toContain('✔ 1 variable set: API_URL\n'); + expect(stdout).toContain('✔ 1 secret added: STRIPE_KEY\n'); + expect(stdout).toContain('✔ 1 secret updated: DB_PASSWORD\n'); + expect(`${stdout}${stderr}`).not.toContain(stripe); + expect(`${stdout}${stderr}`).not.toContain(password); + expect(onWire).toEqual([]); + }); + + it('exits 1 with the run-again wording, prints no result line and tries nothing else when the one PATCH is refused', async () => { + pipe(`${gluedValue()}\n`); + const sent = wire(); + envEndpoint([]); + secretsEndpoint([]); + patchEndpoint(sent, 409, { + errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE' }], + status: 409, + }); + + const { error, stdout } = await runCommand( + setArgs('--var', 'API_URL=https://x', '--secret', 'STRIPE_KEY'), + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe( + 'The change was not saved because another update to this environment was in progress. Run the command again.', + ); + expect(stdout).not.toMatch(/ set| added| updated/); + expect(sent.order).toEqual(['patch']); + expect(onWire).toEqual([]); + }); + + it('prints no value in stdout, stderr or the debug fallback when the PATCH is refused with debug on', async () => { + const value = gluedValue(); + settings.debug = true; + pipe(`${value}\n`); + const sent = wire(); + envEndpoint([]); + secretsEndpoint([]); + patchEndpoint(sent, 400, { + errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.VALUE.INVALID', message: `rejected ${value}` }], + status: 400, + }); + + const result = await runCommand(setArgs('--secret', 'STRIPE_KEY'), config); + + expect(result.error).toBeDefined(); + expect(result.error?.oclif?.exit).not.toBe(0); + expect(sent.patch).toEqual([{ secrets: [{ key: 'STRIPE_KEY', value }] }]); + expect(leaked(value, result)).toBe(false); + }); + + it('lists the --secret flag with both help sentences', async () => { + const { error, stdout } = await runCommand(['launch:variables:set', '--help'], config); + const help = stdout.replace(/\s+/g, ' '); + + expect(error).toBeUndefined(); + expect(help).toContain('--secret=...'); + expect(help).toContain('variable, the value can be read in the UI'); + expect(help).toContain("write-only, the value can't be read back. Replaces the value if KEY is already a secret."); + expect(help).toContain('launch:variables:set'); + expect(help).toMatch(/--secret STRIPE_KEY/); + }); + + it('does not open the source chooser or read .env on a terminal when only --secret is given', async () => { + const value = gluedValue(); + writeFileSync(join(workDir, '.env'), 'API_URL=https://x\n'); + const prompts = answerPrompts({ 'Value for STRIPE_KEY': value }); + const wired = endpoints(); + + const { error, stdout } = await onTerminal(() => runCommand(setArgs('--secret', 'STRIPE_KEY'), config)); + + expect(error).toBeUndefined(); + expect(prompts.messages).toEqual(['Value for STRIPE_KEY']); + expect(wired.sent.patch).toEqual([{ secrets: [{ key: 'STRIPE_KEY', value }] }]); + expect(stdout).not.toContain('Using variables from'); + }); + + it.each([ + ['a data dir holding .env.local', true], + ['an empty data dir', false], + ])('ignores .env.local and still succeeds without a terminal with %s', async (_label, hasEnvFile) => { + const value = gluedValue(); + + if (hasEnvFile) { + writeFileSync(join(workDir, '.env.local'), 'API_URL=https://x\n'); + } + + pipe(`${value}\n`); + const wired = endpoints(); + + const { error, stdout } = await runCommand(setArgs('--secret', 'STRIPE_KEY'), config); + + expect(error).toBeUndefined(); + expect(wired.sent.patch).toEqual([{ secrets: [{ key: 'STRIPE_KEY', value }] }]); + expect(stdout).not.toContain('Using variables from'); + expect(stdout).not.toContain('No variables to set'); + }); + + it.each([ + ['a prompt', 'prompt'], + ['standard input', 'stdin'], + ['a dotenv file', 'dotenv'], + ])('puts a value given by %s in no stdout, stderr, prompt or written file', async (_label, how) => { + const value = gluedValue(); + const prompts = answerPrompts({ 'Value for STRIPE_KEY': value }); + const wired = endpoints(); + const dotenv = 'ci.env'; + + if (how === 'dotenv') { + writeFileSync(join(workDir, dotenv), `STRIPE_KEY=${value}\n`); + } + + if (how === 'stdin') { + pipe(`${value}\n`); + } + + const argv = how === 'dotenv' ? setArgs('--dotenv', join(workDir, dotenv), '--secret', 'STRIPE_KEY') : setArgs('--secret', 'STRIPE_KEY'); + const result = how === 'prompt' ? await onTerminal(() => runCommand(argv, config)) : await runCommand(argv, config); + + expect(result.error).toBeUndefined(); + expect(wired.sent.patch).toEqual([{ secrets: [{ key: 'STRIPE_KEY', value }] }]); + expect(leaked(value, result)).toBe(false); + expect(JSON.stringify(prompts.payloads)).not.toContain(value); + expect(prompts.messages.join('\n')).not.toContain(value); + expect(filesIn(workDir, [dotenv])).not.toContain(value); + }); + }); + it('exits 2 naming --key when none is given', async () => { const { error } = await runCommand(['launch:variables:unset', ...SCOPE, '--yes'], config); From 732cb45bee7d6c447dff280467ff16d7d31be6f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 06:51:34 +0000 Subject: [PATCH 3/3] docs(variables): say in set --help that --secret replaces with no confirmation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CL-8991: per TRD D4 a secret is added or replaced with no prompt and no --yes. The command description now says so, and that a client-exposed prefix (NEXT_PUBLIC_) prints a warning before any value is asked. #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_01EptZEirUBSbkUz3Gh8Xzzo --- src/commands/launch/variables/set.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/commands/launch/variables/set.ts b/src/commands/launch/variables/set.ts index bf9f77ca..a04937d7 100644 --- a/src/commands/launch/variables/set.ts +++ b/src/commands/launch/variables/set.ts @@ -17,7 +17,9 @@ const setInputs = inputs({ export default class VariablesSet extends LaunchCommand { static description = 'Add or change environment variables from --var, --dotenv or a detected .env file; later sources win. ' + - 'Mark a key as a secret with --secret KEY: its value is write-only and is never a flag'; + 'Mark a key as a secret with --secret KEY: its value is write-only and is never a flag. ' + + 'A new secret is added, and one that already exists is replaced, with no confirmation and no --yes; ' + + 'a key with a client-exposed prefix such as NEXT_PUBLIC_ prints a warning first'; static examples = [ '$ csdx launch:variables:set --org --project --env ' +