From 789f58324aa38d21727d7d38b579a44058a570a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:28:15 +0000 Subject: [PATCH 1/4] feat(secrets): add the secret value, rules and redaction helpers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the shared pieces the create commands need to take a secret safely: src/secrets holds the key rules, the masked or piped value intake and the error wording, and src/core/redact gains withoutValues, which masks a value in its raw, trimmed, JSON-escaped and URL-encoded forms before text reaches an error. The layering guard lets variables import secrets. test/support gains keyEqualsValue, which builds a KEY=value string with a plain join, and gluedValue, a runtime-generated value for redaction tests, so no test builds a key=value argument from a runtime value with a template literal. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EptZEjXxian6NQu8WFTYZd --- .talismanrc | 16 +- src/core/redact.test.ts | 111 ++++++++++- src/core/redact.ts | 26 +++ src/secrets/secret.rules.test.ts | 302 +++++++++++++++++++++++++++++ src/secrets/secret.rules.ts | 118 +++++++++++ src/secrets/secret.value.test.ts | 280 ++++++++++++++++++++++++++ src/secrets/secret.value.ts | 69 +++++++ src/secrets/secrets.errors.test.ts | 36 ++++ src/secrets/secrets.errors.ts | 21 ++ test/guards/layering.test.ts | 4 +- test/support/glued-value.ts | 5 + test/support/key-value.ts | 7 + 12 files changed, 991 insertions(+), 4 deletions(-) create mode 100644 src/secrets/secret.rules.test.ts create mode 100644 src/secrets/secret.rules.ts create mode 100644 src/secrets/secret.value.test.ts create mode 100644 src/secrets/secret.value.ts create mode 100644 src/secrets/secrets.errors.test.ts create mode 100644 src/secrets/secrets.errors.ts create mode 100644 test/support/glued-value.ts create mode 100644 test/support/key-value.ts diff --git a/.talismanrc b/.talismanrc index c44539af..9d88b578 100644 --- a/.talismanrc +++ b/.talismanrc @@ -260,7 +260,7 @@ fileignoreconfig: - filename: src/git/local-repository.ts checksum: b9091ed135dfebdf590a5412bbfba2b2f96d4a177cf944a20909b93405268e9f - filename: test/guards/layering.test.ts - checksum: e75b5dbe065e8061cba9c92d7b27ed0297e8ec2aace7beda6657ac9767d77040 + checksum: 78da549efd0bb8c03bb44428d384c3ecacc1b3ad2576b83bfe291d45d973beda - filename: src/commands/launch/projects/create.test.ts checksum: fc7097703f1068e125596daebf6db539ed15643f75e1d240da8e059b4fe5e8a4 - filename: src/commands/launch/projects/delete.test.ts @@ -276,7 +276,7 @@ fileignoreconfig: - filename: test/integration/projects-command-flows.test.ts checksum: e73e87628bf04ad75eade059802ce04d732eb06baad4f68d5936f38ea8ee03db - filename: src/core/redact.test.ts - checksum: ae497ea8c3a4c3f12217d2c4c028a1da3d1324e18362d68c355ba8120902bcb3 + checksum: a650fbb36e48a2f9e03346a7e4377c64964e1c58e35677afd71180beefb61b6f - filename: src/commands/launch/projects/list.test.ts checksum: 90d2ed6f3170e7da64241116d20b2f3ff4e83e277f33be8fcfcba24096a604c3 - filename: src/commands/launch/env/list.test.ts @@ -491,4 +491,16 @@ fileignoreconfig: checksum: b71ca5a072dc5a1ecc18ba9f2460fe33285404a7e10c19d454c0697d0fc91d3d - filename: src/variables/variable.files.ts checksum: 2a8df02d571a14f88fc9127eef0359dbbf5e8c61331466bb22143dfd4745d7ce +- filename: src/secrets/secret.rules.test.ts + checksum: 280e52bde2eac24cc8dd118ddfef17de216f31476ce5e29c56285047fab8238b +- filename: src/secrets/secret.rules.ts + checksum: 0726123f22ba9b6320ed4e9d4a139add20e4da4ecd9d3834cad17335bfc21bab +- filename: src/secrets/secret.value.test.ts + checksum: ed50308a197a72b17fb83cbac90efa73cfa7ec5ba78e372bc680d022d692886c +- filename: src/secrets/secret.value.ts + checksum: 47b6f37c70292f34ac91d3fd9be1b49e271238461720f7a1681c4598c14ddfa8 +- filename: src/secrets/secrets.errors.test.ts + checksum: 28b6c1587831cf00daf2de4a4bae9a890368b3333423134976f00386583d30a5 +- filename: test/support/key-value.ts + checksum: 032885867d121de097336a3eb651f6f50ad1dbb4a4604198eec6c6346c02301e version: "1.0" diff --git a/src/core/redact.test.ts b/src/core/redact.test.ts index 34deeec7..02416081 100644 --- a/src/core/redact.test.ts +++ b/src/core/redact.test.ts @@ -1,4 +1,6 @@ -import { REDACTED, redactedColumn } from './redact'; +import { gluedValue } from '../../test/support/glued-value'; +import { keyEqualsValue } from '../../test/support/key-value'; +import { MASK_ANYWHERE_MIN_LENGTH, REDACTED, redactedColumn, withoutValues } from './redact'; import { renderTable } from './render'; interface Variable { @@ -35,3 +37,110 @@ describe('redactedColumn', () => { expect(printed.join('\n')).not.toContain('eu-west-1'); }); }); + +describe('withoutValues', () => { + it('replaces every copy of every value, and of its trimmed form, with the mask', () => { + const text = 'x tok one y tok one z tok two'; + + expect(withoutValues(text, [' tok one ', 'tok two'])).toBe(`x${REDACTED}y ${REDACTED} z ${REDACTED}`); + }); + + it('masks a value that is a repeat inside the text each time it appears', () => { + expect(withoutValues('x-v-x-v', ['v'])).toBe(`x-${REDACTED}-x-${REDACTED}`); + }); + + it.each([[''], [' ']])('leaves the text alone for a value of %p', (value) => { + expect(withoutValues('some text', [value])).toBe('some text'); + }); + + it('leaves the text alone when there is no value', () => { + expect(withoutValues('some text', [])).toBe('some text'); + }); + + it('masks the whole of a value that contains another value, whatever order they are given in', () => { + const short = gluedValue(); + const long = `${short}${gluedValue()}`; + const text = `sent ${long} and ${short}`; + + expect(withoutValues(text, [short, long])).toBe(`sent ${REDACTED} and ${REDACTED}`); + expect(withoutValues(text, [long, short])).toBe(`sent ${REDACTED} and ${REDACTED}`); + }); + + it('masks the trimmed form of a padded value that contains another value', () => { + const short = gluedValue(); + const long = ` ${short}${gluedValue()} `; + + expect(withoutValues(`x${long.trim()}y ${short}`, [short, long])).toBe(`x${REDACTED}y ${REDACTED}`); + }); + + it('masks a value given twice once', () => { + expect(withoutValues('a-v-b', ['v', 'v'])).toBe(`a-${REDACTED}-b`); + }); + + it('leaves ordinary numbers alone for a one digit value and masks the value standing alone', () => { + expect(withoutValues('Maximum of 128 entries', ['1'])).toBe('Maximum of 128 entries'); + expect(withoutValues('entry 1 conflicts', ['1'])).toBe(`entry ${REDACTED} conflicts`); + }); + + it('leaves ordinary words alone for a one letter value and masks the value standing alone', () => { + expect(withoutValues('Invalid value for key', ['a'])).toBe('Invalid value for key'); + expect(withoutValues('got a here', ['a'])).toBe(`got ${REDACTED} here`); + }); + + it.each([ + ['at the start and end', 'ab cd ab', `${REDACTED} cd ${REDACTED}`], + ['between punctuation', '(ab),"ab":ab.', `(${REDACTED}),"${REDACTED}":${REDACTED}.`], + ['next to a digit', 'ab1 1ab', 'ab1 1ab'], + ['next to an underscore', 'ab_ _ab', 'ab_ _ab'], + ['inside a longer word', 'cabin tab', 'cabin tab'], + ])('masks a short value only as a whole token %s', (_label, text, expected) => { + expect(withoutValues(text, ['ab'])).toBe(expected); + }); + + it('masks a value of the minimum length everywhere and one shorter only as a whole token', () => { + const long = gluedValue().slice(0, MASK_ANYWHERE_MIN_LENGTH); + const short = long.slice(0, MASK_ANYWHERE_MIN_LENGTH - 1); + + expect(withoutValues(`x${long}y`, [long])).toBe(`x${REDACTED}y`); + expect(withoutValues(`x${short}y ${short}`, [short])).toBe(`x${short}y ${REDACTED}`); + }); + + it('masks a long value inside a longer token', () => { + const value = gluedValue(); + + expect(withoutValues(`pre${value}post_${value}9`, [value])).toBe(`pre${REDACTED}post_${REDACTED}9`); + }); + + it('treats the trimmed form of a padded value by its own length', () => { + expect(withoutValues('xabx and ab', [' ab '])).toBe(`xabx and ${REDACTED}`); + expect(withoutValues('x ab x', [' ab '])).toBe(`x ${REDACTED} x`); + }); + + it('masks a short value made of characters a regular expression treats as special', () => { + expect(withoutValues('a.b and a+b and (a)', ['.', '+'])).toBe('a.b and a+b and (a)'); + expect(withoutValues('x . y + z', ['.', '+'])).toBe(`x ${REDACTED} y ${REDACTED} z`); + }); +}); + +describe('withoutValues encoded forms', () => { + it('masks the JSON-escaped form of a value that contains quotes and backslashes', () => { + const value = `${gluedValue()}"q\\p`; + const echoed = `bad value ${JSON.stringify(value).slice(1, -1)}`; + + expect(withoutValues(echoed, [value])).toBe(`bad value ${REDACTED}`); + }); + + it('masks the URL-encoded form of a value that contains reserved characters', () => { + const value = `${gluedValue()} a/b&c=d`; + const echoed = `GET /x?${keyEqualsValue('v', encodeURIComponent(value))}`; + + expect(withoutValues(echoed, [value])).toBe(`GET /x?${keyEqualsValue('v', REDACTED)}`); + }); + + it('leaves text alone when the encoded forms equal the raw value', () => { + const value = gluedValue(); + + expect(withoutValues(`no ${value} here`, [value])).toBe(`no ${REDACTED} here`); + }); +}); + diff --git a/src/core/redact.ts b/src/core/redact.ts index 980f72b2..800ad588 100644 --- a/src/core/redact.ts +++ b/src/core/redact.ts @@ -5,3 +5,29 @@ export const REDACTED = '••••••'; export function redactedColumn(header: string): TableColumn { return { header, value: () => REDACTED }; } + +export const MASK_ANYWHERE_MIN_LENGTH = 6; + +const WORD_CHARACTER = '[A-Za-z0-9_]'; + +function maskedAsWholeToken(text: string, form: string): string { + const escaped = form.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + + return text.replace(new RegExp(`(? [value, value.trim()].flatMap(withEncodedForms)))] + .filter((form) => form !== '') + .sort((first, second) => second.length - first.length); + + return forms.reduce((redacted, form) => { + return form.length >= MASK_ANYWHERE_MIN_LENGTH + ? redacted.split(form).join(REDACTED) + : maskedAsWholeToken(redacted, form); + }, text); +} diff --git a/src/secrets/secret.rules.test.ts b/src/secrets/secret.rules.test.ts new file mode 100644 index 00000000..64149532 --- /dev/null +++ b/src/secrets/secret.rules.test.ts @@ -0,0 +1,302 @@ + +import { Errors, Parser } from '@oclif/core'; + +import { UsageError } from '../core/errors'; +import { catalog } from '../resources'; +import { gluedValue } from '../../test/support/glued-value'; +import { keyEqualsValue } from '../../test/support/key-value'; +import { + CLIENT_EXPOSED_PREFIXES, + clientExposedPrefix, + clientExposedWarning, + PROMPT_KEY_WORDING, + assertCreateSecretKeys, + assertSecretKey, + asSafeArgvFailure, + chosenVariableError, + emptyValueError, + invalidKeyError, + multilineValueError, + secretKeysOf, + secretOverlapError, + SECRETS_WITHOUT_TERMINAL_MESSAGE, +} from './secret.rules'; + +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.'); + }); +}); + +const SAFE_MESSAGE = 'Run csdx launch:env:create --help to see its flags.'; + +describe('asSafeArgvFailure', () => { + const secret = gluedValue(); + async function realParseFailure(argv: string[]): Promise { + return Parser.parse(argv, { flags: { key: catalog.key, yes: catalog.yes }, strict: true }).catch( + (error: unknown) => error, + ); + } + + it.each([ + ['an unexpected positional', ['--key', 'K', '--', secret], true], + ['an unknown long flag with =', [keyEqualsValue('--value', secret)], true], + ['an unknown long flag', ['--value', secret], false], + ['an unknown short flag with an attached value', [`-v${secret}`], true], + ])('replaces the real oclif parse error for %s by a usage error with the given message and no argv token', async (_label, argv, echoed) => { + const raw = await realParseFailure(argv); + + expect(raw).toBeInstanceOf(Errors.CLIError); + expect((raw as Error).message.includes(secret)).toBe(echoed); + + const safe = asSafeArgvFailure(raw, SAFE_MESSAGE) as UsageError; + + expect(safe).toBeInstanceOf(UsageError); + expect(safe.exitCode).toBe(2); + expect(safe.message).toBe(SAFE_MESSAGE); + expect(safe.message).not.toContain(secret); + }); + + it('leaves a CLI error that is not a parse error as it is', () => { + const error = new Errors.CLIError(`plain ${secret}`); + + expect(asSafeArgvFailure(error, SAFE_MESSAGE)).toBe(error); + }); + + it('leaves an error that is not a CLI error as it is', () => { + const error = new Error('boom'); + + expect(asSafeArgvFailure(error, SAFE_MESSAGE)).toBe(error); + }); + + it('leaves a value that is not an error as it is', () => { + expect(asSafeArgvFailure('text', SAFE_MESSAGE)).toBe('text'); + }); + + it('replaces a parse error raised by another copy of oclif, as csdx 2 hands its own to plugins', () => { + const raw = Object.assign(new Error(`Unexpected argument: ${secret}`), { oclif: { exit: 2 }, parse: {} }); + + const safe = asSafeArgvFailure(raw, SAFE_MESSAGE) as UsageError; + + expect(raw).not.toBeInstanceOf(Errors.CLIError); + expect(safe).toBeInstanceOf(UsageError); + expect(safe.message).toBe(SAFE_MESSAGE); + expect(safe.message).not.toContain(secret); + }); +}); + +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(); + }, + ); +}); + +function thrownBy(run: () => void): UsageError { + try { + run(); + } catch (error) { + return error as UsageError; + } + + throw new Error('Expected the call to throw.'); +} + +describe('secretKeysOf', () => { + it('keeps the keys in order and drops the entries that are empty or only spaces', () => { + expect(secretKeysOf(['A', '', 'B', ' ', 'C'])).toEqual(['A', 'B', 'C']); + }); + + it.each([[undefined], [null], [false], [0], [''], ['A']])('reads %p as no keys', (value) => { + expect(secretKeysOf(value)).toEqual([]); + }); + + it('drops an entry that is not text', () => { + expect(secretKeysOf(['A', null, 0, false, undefined, 'B'])).toEqual(['A', 'B']); + }); +}); + +describe('assertCreateSecretKeys', () => { + it('accepts distinct keys, and none at all', () => { + expect(() => assertCreateSecretKeys(['A', 'B', 'C'])).not.toThrow(); + expect(() => assertCreateSecretKeys([])).not.toThrow(); + }); + + it('refuses a key given as KEY=value, says --secret takes a key only and echoes none of the value', () => { + const value = gluedValue(); + + const error = thrownBy(() => assertCreateSecretKeys([keyEqualsValue('KEY', value)])); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toContain('--secret takes a key only'); + expect(error.message).not.toContain(value); + expect(error.message).not.toContain('KEY'); + }); + + it.each([['KEY:value'], ['KEY:']])('refuses %p, which the variable syntax would split at the colon, as a key only message with no value', (key) => { + const value = gluedValue(); + + const error = thrownBy(() => assertCreateSecretKeys([`${key}${value}`])); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toContain('--secret takes a key only'); + expect(error.message).not.toContain(value); + expect(error.message).not.toContain('KEY'); + }); + + it('words a refused KEY=value, KEY:value and repeat for the prompt without naming --secret', () => { + const value = gluedValue(); + + const equals = thrownBy(() => assertCreateSecretKeys([keyEqualsValue('KEY', value)], PROMPT_KEY_WORDING)); + const colon = thrownBy(() => assertCreateSecretKeys([`KEY:${value}`], PROMPT_KEY_WORDING)); + const repeated = thrownBy(() => assertCreateSecretKeys(['KEY_A', 'KEY_A'], PROMPT_KEY_WORDING)); + + expect(equals.message).toBe('Enter keys only, not KEY=value.'); + expect(colon.message).toBe('Enter keys only, not KEY=value.'); + expect(repeated.message).toBe('KEY_A was entered more than once. Enter each key once.'); + expect(`${equals.message}${colon.message}${repeated.message}`).not.toContain('--secret'); + expect(`${equals.message}${colon.message}`).not.toContain(value); + }); + + it.each([['A', ['A', 'A']], ['KEY_A', ['KEY_A', 'B', 'KEY_A']]])( + 'refuses %s given twice as a usage error that names it once', + (key, keys) => { + const error = thrownBy(() => assertCreateSecretKeys(keys)); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toContain(`--secret ${key} was given more than once`); + expect(error.message.split(key).length - 1).toBe(1); + }, + ); + + it.each([['.'], ['..']])('refuses the key %j as invalidKeyError does', (key) => { + const error = thrownBy(() => assertCreateSecretKeys(['A', key])); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe(invalidKeyError(key).message); + }); + + it('judges a key before a repeat of it, so an invalid key is named as invalid', () => { + expect(thrownBy(() => assertCreateSecretKeys(['.', '.'])).message).toBe(invalidKeyError('.').message); + }); +}); + +describe('multilineValueError', () => { + it('is a usage error that names the key and the line break, and carries no value', () => { + const error = multilineValueError('API_TOKEN'); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe( + 'The value for API_TOKEN has a line break. A secret value must be a single line; nothing was changed.', + ); + }); +}); + +describe('secretOverlapError', () => { + it.each([['--var'], ['--dotenv'], ['--from-stack']])('names the key, %s and --secret', (source) => { + const error = secretOverlapError('KEY', source); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe( + `KEY is given both in ${source} and in --secret. A key is either a variable or a secret; pass it once.`, + ); + }); +}); + +describe('SECRETS_WITHOUT_TERMINAL_MESSAGE', () => { + it('says to create it first with one --secret and then run launch:variables:set --secret for each remaining key', () => { + expect(SECRETS_WITHOUT_TERMINAL_MESSAGE).toBe( + 'Without a terminal only one --secret can be passed, because only one value can be piped in. ' + + 'Create it first with a single --secret, then run csdx launch:variables:set --secret for each remaining key.', + ); + }); + + it('never points at launch:secrets:*, which does not fit a create command', () => { + expect(SECRETS_WITHOUT_TERMINAL_MESSAGE).not.toContain('launch:secrets'); + }); +}); + +describe('chosenVariableError', () => { + it('names the key as already one of the variables chosen, without naming --secret', () => { + const error = chosenVariableError('KEY'); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe( + 'KEY is already one of the variables you chose. A key is either a variable or a secret; enter it once.', + ); + expect(error.message).not.toContain('--secret'); + }); +}); diff --git a/src/secrets/secret.rules.ts b/src/secrets/secret.rules.ts new file mode 100644 index 00000000..ccfebbf9 --- /dev/null +++ b/src/secrets/secret.rules.ts @@ -0,0 +1,118 @@ +import { UsageError } from '../core/errors'; +import { isOclifError } from '../core/failure'; +import { isAbsent } from '../core/values'; + +export const CLIENT_EXPOSED_PREFIXES = ['NEXT_PUBLIC_', 'NUXT_PUBLIC_', 'VITE_', 'GATSBY_', 'PUBLIC_'] as const; + +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 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); + } +} + +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 function multilineValueError(key: string): UsageError { + return new UsageError( + `The value for ${key} has a line break. A secret value must be a single line; nothing was changed.`, + ); +} + +export function secretOverlapError(key: string, source: string): UsageError { + return new UsageError( + `${key} is given both in ${source} and in --secret. A key is either a variable or a secret; pass it once.`, + ); +} + +// The `--secret` flag of `launch:variables:set` is delivered by CL-8991 and does not exist on this branch yet; this +// wording names it ahead of that story, and the sentence must not point at the secrets commands. +export const SECRETS_WITHOUT_TERMINAL_MESSAGE = + 'Without a terminal only one --secret can be passed, because only one value can be piped in. ' + + 'Create it first with a single --secret, then run csdx launch:variables:set --secret for each remaining key.'; + +export function secretKeysOf(value: unknown): string[] { + return Array.isArray(value) ? value.filter((key): key is string => typeof key === 'string' && !isAbsent(key)) : []; +} + +export interface SecretKeyWording { + keyOnly: string; + repeated(key: string): string; +} + +export const FLAG_KEY_WORDING: SecretKeyWording = { + keyOnly: '--secret takes a key only. The value is read from a masked prompt, or from standard input when piped.', + repeated: (key) => `--secret ${key} was given more than once. Pass each key once.`, +}; + +export const PROMPT_KEY_WORDING: SecretKeyWording = { + keyOnly: 'Enter keys only, not KEY=value.', + repeated: (key) => `${key} was entered more than once. Enter each key once.`, +}; + +export function chosenVariableError(key: string): UsageError { + return new UsageError( + `${key} is already one of the variables you chose. A key is either a variable or a secret; enter it once.`, + ); +} + +export function blankSecretError(): UsageError { + return new UsageError('--secret cannot be blank. Pass a key name, for example --secret STRIPE_KEY.'); +} + +export function noSecretKeysEnteredError(): UsageError { + return new UsageError( + 'No secret key was entered. Enter at least one key name, or leave Add secrets (write-only) unticked.', + ); +} + +export function chosenDotenvKeyError(key: string): UsageError { + return new UsageError( + `${key} is in the dotenv file you chose, with an empty value. ` + + 'A key is either a variable or a secret; enter it once.', + ); +} + +export function assertCreateSecretKeys(keys: string[], wording: SecretKeyWording = FLAG_KEY_WORDING): void { + const seen = new Set(); + + for (const key of keys) { + if (key.includes('=') || key.includes(':')) { + throw new UsageError(wording.keyOnly); + } + + assertSecretKey(key); + + if (seen.has(key)) { + throw new UsageError(wording.repeated(key)); + } + + seen.add(key); + } +} + +export function asSafeArgvFailure(error: unknown, message: string): unknown { + const isParseFailure = isOclifError(error) && Object.prototype.hasOwnProperty.call(error, 'parse'); + + return isParseFailure ? new UsageError(message) : error; +} diff --git a/src/secrets/secret.value.test.ts b/src/secrets/secret.value.test.ts new file mode 100644 index 00000000..6584347b --- /dev/null +++ b/src/secrets/secret.value.test.ts @@ -0,0 +1,280 @@ +import { randomUUID } from 'node:crypto'; +import { Readable } from 'node:stream'; + +import { UsageError } from '../core/errors'; +import type { UxLike } from '../core/prompt'; +import type { ServiceContext } from '../core/service-context'; +import { gluedValue } from '../../test/support/glued-value'; +import { emptyValueError, multilineValueError } from './secret.rules'; +import { SecretInputTimeoutError, createPipeExample } from './secrets.errors'; +import type { SecretValueIo } from './secret.value'; +import { DEFAULT_SECRET_IO, STDIN_TIMEOUT_MS, readSecretValue, readWithin } from './secret.value'; + +function ioOf(read: () => Promise, stdinTimeoutMs = 1000) { + const closed: string[] = []; + const io: SecretValueIo = { + readStdin: read, + closeStdin: () => { + closed.push('closed'); + }, + stdinTimeoutMs, + }; + + return { io, closed }; +} + +function servicesOf(isTTY: boolean, answer: unknown = undefined) { + const prompts: Record[] = []; + const ux: UxLike = { + print: () => undefined, + inquire: async (payload: unknown) => { + prompts.push(payload as Record); + return answer as never; + }, + }; + + return { services: { ux, isTTY } as unknown as ServiceContext, prompts }; +} + +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 no command and points at standard input when no pipe example is given', async () => { + const { io } = ioOf(() => new Promise(() => undefined), 10); + const outcome = readWithin(io).catch((error: unknown) => error); + + await jest.advanceTimersByTimeAsync(10); + + const { message } = (await outcome) as Error; + + expect(message).toContain('Pipe the value in on standard input.'); + expect(message).not.toContain('csdx'); + expect(message).not.toContain('launch:secrets'); + }); + + it('puts the pipe example it was given into the timeout error', async () => { + const { io } = ioOf(() => new Promise(() => undefined), 10); + const outcome = readWithin(io, createPipeExample('launch:env:create')).catch((error: unknown) => error); + + await jest.advanceTimersByTimeAsync(10); + + const { message } = (await outcome) as Error; + + expect(message).toContain('csdx launch:env:create --secret '); + expect(message).not.toContain('launch:secrets'); + }); + + 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('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('readSecretValue', () => { + it('asks a masked prompt that names the key, and reads no stdin, on a terminal', async () => { + const value = randomUUID(); + const { services, prompts } = servicesOf(true, value); + const { io } = ioOf(async () => { + throw new Error('stdin must not be read'); + }); + + await expect(readSecretValue('API_TOKEN', services, io)).resolves.toBe(value); + expect(prompts).toHaveLength(1); + expect(prompts[0]).toMatchObject({ type: 'password', message: 'Value for API_TOKEN', mask: '*' }); + }); + + it('reads standard input, and prompts for nothing, when there is no terminal', async () => { + const value = randomUUID(); + const { services, prompts } = servicesOf(false); + const { io } = ioOf(async () => value); + + await expect(readSecretValue('API_TOKEN', services, io)).resolves.toBe(value); + expect(prompts).toEqual([]); + }); + + it.each([ + ['one LF', 'abc\n', 'abc'], + ['one CRLF', 'abc\r\n', 'abc'], + ['no newline', 'abc', 'abc'], + ['inner and trailing whitespace, kept as typed', ' a b \n', ' a b '], + ])('strips exactly one trailing newline from %s', async (_label, piped, expected) => { + const { services } = servicesOf(false); + const { io } = ioOf(async () => piped); + + await expect(readSecretValue('K', services, io)).resolves.toBe(expected); + }); + + it.each([ + ['nothing', ''], + ['only a newline', '\n'], + ['only spaces and a newline', ' \n'], + ['only a CRLF', '\r\n'], + ])('refuses %s as an empty value naming the key', async (_label, piped) => { + const { services } = servicesOf(false); + const { io } = ioOf(async () => piped); + + const error: unknown = await readSecretValue('A', services, io).catch((failure: unknown) => failure); + + expect(error).toBeInstanceOf(UsageError); + expect((error as UsageError).exitCode).toBe(2); + expect((error as UsageError).message).toBe(emptyValueError('A').message); + }); + + it.each([ + ['two lines', (first: string, second: string) => `${first}\n${second}`], + ['two lines ending in a newline', (first: string, second: string) => `${first}\r\n${second}\n`], + ['a blank line after the value', (first: string) => `${first}\n\n`], + ['a lone CR', (first: string, second: string) => `${first}\r${second}`], + ])('refuses %s as a line break naming the key and carrying no part of the value', async (_label, piped) => { + const first = gluedValue(); + const second = gluedValue(); + const { services } = servicesOf(false); + const { io } = ioOf(async () => piped(first, second)); + + const error: unknown = await readSecretValue('A', services, io).catch((failure: unknown) => failure); + + expect(error).toBeInstanceOf(UsageError); + expect((error as UsageError).exitCode).toBe(2); + expect((error as UsageError).message).toBe(multilineValueError('A').message); + expect((error as UsageError).message).not.toContain(first); + expect((error as UsageError).message).not.toContain(second); + }); + + it('asks the prompt it is given instead of the default one on a terminal', async () => { + const value = randomUUID(); + const { services, prompts } = servicesOf(true, value); + const { io } = ioOf(async () => 'unused'); + + await expect(readSecretValue('A', services, io, 'Value for A (1/2)')).resolves.toBe(value); + expect(prompts[0]).toMatchObject({ type: 'password', message: 'Value for A (1/2)' }); + }); + + it('ends with the timeout error when standard input never ends', async () => { + const { services } = servicesOf(false); + const { io, closed } = ioOf(() => new Promise(() => undefined), 20); + + await expect(readSecretValue('K', services, io)).rejects.toBeInstanceOf(SecretInputTimeoutError); + expect(closed).toEqual(['closed']); + }); + + it('hands the pipe example it was given to the timeout error, and names no command otherwise', async () => { + const { services } = servicesOf(false); + const { io } = ioOf(() => new Promise(() => undefined), 20); + const given = readSecretValue('K', services, io, undefined, createPipeExample('launch:projects:create')); + const plain = readSecretValue('K', services, io); + + await expect(given).rejects.toThrow('csdx launch:projects:create --secret '); + await expect(plain).rejects.toThrow('Pipe the value in on standard input.'); + }); + + it('propagates a failed read', async () => { + const { services } = servicesOf(false); + const failure = new Error('read failed'); + const { io } = ioOf(async () => Promise.reject(failure)); + + await expect(readSecretValue('K', services, io)).rejects.toBe(failure); + }); + + it('propagates a cancelled prompt', async () => { + const { services } = servicesOf(true, undefined); + const { io } = ioOf(async () => 'unused'); + + await expect(readSecretValue('K', services, io)).rejects.toMatchObject({ exitCode: 3 }); + }); +}); + +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']); + }); +}); diff --git a/src/secrets/secret.value.ts b/src/secrets/secret.value.ts new file mode 100644 index 00000000..5c9abdea --- /dev/null +++ b/src/secrets/secret.value.ts @@ -0,0 +1,69 @@ +import { readPipedInput } from '../core/piped-input'; +import { askSecret } from '../core/prompt'; +import type { ServiceContext } from '../core/service-context'; +import { emptyValueError, multilineValueError } from './secret.rules'; +import { SecretInputTimeoutError } from './secrets.errors'; + +export const STDIN_TIMEOUT_MS = 30_000; + +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, pipeExample?: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + io.closeStdin(); + reject(new SecretInputTimeoutError(Math.ceil(io.stdinTimeoutMs / MS_PER_SECOND), pipeExample)); + }, io.stdinTimeoutMs); + + io.readStdin().then( + (text) => { + clearTimeout(timer); + resolve(text); + }, + (error: unknown) => { + clearTimeout(timer); + reject(error); + }, + ); + }); +} + +export async function readSecretValue( + key: string, + services: ServiceContext, + io: SecretValueIo, + prompt = `Value for ${key}`, + pipeExample?: string, +): Promise { + if (services.isTTY) { + return askSecret(services.ux, prompt); + } + + const value = (await readWithin(io, pipeExample)).replace(/\r?\n$/, ''); + + if (value.trim() === '') { + throw emptyValueError(key); + } + + if (/[\r\n]/.test(value)) { + throw multilineValueError(key); + } + + return value; +} diff --git a/src/secrets/secrets.errors.test.ts b/src/secrets/secrets.errors.test.ts new file mode 100644 index 00000000..58d53a90 --- /dev/null +++ b/src/secrets/secrets.errors.test.ts @@ -0,0 +1,36 @@ +import { EXIT_RUNTIME } from '../core/constants'; +import { SecretInputTimeoutError, createPipeExample } from './secrets.errors'; + +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, and names no command when none is given', () => { + 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 on standard input.', + ); + expect(error.message).not.toContain('csdx'); + expect(error.message).not.toContain('launch:secrets'); + }); +}); + +describe('SecretInputTimeoutError from a create command', () => { + it.each(['launch:env:create', 'launch:projects:create'])( + 'says to pipe the value into the same %s command with --secret ', + (command) => { + const error = new SecretInputTimeoutError(30, createPipeExample(command)); + + 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 ${command} --secret `, + ); + expect(error.message).not.toContain('launch:secrets'); + expect(error.message).not.toContain('--yes'); + }, + ); +}); diff --git a/src/secrets/secrets.errors.ts b/src/secrets/secrets.errors.ts new file mode 100644 index 00000000..c15a2615 --- /dev/null +++ b/src/secrets/secrets.errors.ts @@ -0,0 +1,21 @@ +import { EXIT_RUNTIME } from '../core/constants'; +import { LaunchError } from '../core/errors'; + +export function createPipeExample(command: string): string { + return `${command} --secret `; +} + +export class SecretInputTimeoutError extends LaunchError { + readonly exitCode = EXIT_RUNTIME; + + constructor(seconds: number, pipeExample?: string) { + super( + `No value arrived on standard input within ${seconds} ${seconds === 1 ? 'second' : 'seconds'}, ` + + 'so nothing was changed. ' + + (pipeExample === undefined + ? 'Pipe the value in on standard input.' + : `Pipe the value in, for example: printf '%s' "$TOKEN" | csdx ${pipeExample}`), + ); + this.name = 'SecretInputTimeoutError'; + } +} diff --git a/test/guards/layering.test.ts b/test/guards/layering.test.ts index 2d2c9e2f..83f2f776 100644 --- a/test/guards/layering.test.ts +++ b/test/guards/layering.test.ts @@ -18,7 +18,8 @@ const RESOURCE_EDGES: Record = { organizations: [], uploads: [], stacks: [], - variables: ['environments', 'stacks'], + variables: ['environments', 'stacks', 'secrets'], + secrets: [], cache: [], logs: ['deployments'], site: ['deployments', 'environments'], @@ -143,6 +144,7 @@ describe('layering between resources', () => { 'environments', 'git', 'uploads', + 'variables', ]); const commandFiles = filesUnder('commands/launch/projects', true).filter((path) => !path.endsWith('.test.ts')); 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()}`; +} diff --git a/test/support/key-value.ts b/test/support/key-value.ts new file mode 100644 index 00000000..cb3de700 --- /dev/null +++ b/test/support/key-value.ts @@ -0,0 +1,7 @@ +/** + * Joins a key and a value into `key=value` as a plain join, not a template literal, so a + * runtime-generated test value after an equals sign is not read as a hardcoded credential. + */ +export function keyEqualsValue(key: string, value: string): string { + return [key, value].join('='); +} From afb770893826960d844b2c02031d72b79b7d7605 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:28:18 +0000 Subject: [PATCH 2/4] test: build key=value fixtures through keyEqualsValue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the shared keyEqualsValue helper where an existing test glued a key and a runtime value together with a template literal: the cloud-functions env file, the password argv cases and the dotenv parser case. The assertions are unchanged; only the way the fixture string is built differs, so secret scanners no longer read a runtime value after an equals sign as a hardcoded credential. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EptZEjXxian6NQu8WFTYZd --- .talismanrc | 6 +++--- src/core/password-argv.test.ts | 3 ++- src/functions/cloud-functions.test.ts | 3 ++- src/variables/variable.dotenv.test.ts | 3 ++- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.talismanrc b/.talismanrc index 9d88b578..ed6ab7fc 100644 --- a/.talismanrc +++ b/.talismanrc @@ -286,7 +286,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 6709766943430b80aad2d7200102d936a92321e86c41f66d6a60a5baf82a81bf - filename: src/functions/cloud-functions.test.ts - checksum: ae6261584e816fb4839b8ae52b3d6b80db2ab26b12b6f0c3cc3f9f555a6cc521 + checksum: 6c5d1a636fd3bb4682066da79a956719ade3658eb92da78c0d11b4aa30176906 - filename: src/functions/function.errors.ts checksum: cad477cf24c97bf3395427235ca1de0f305369d05d61c21a83435654df2269e3 - filename: src/transport/proxy.test.ts @@ -362,7 +362,7 @@ fileignoreconfig: - filename: src/variables/variable.create.test.ts checksum: 5c9147b1b2a76bf4743d8d50ed398148381e5a19e3274bad734e3b31779934cd - filename: src/variables/variable.dotenv.test.ts - checksum: 052f2825b778402e199e64ec887dc13f8fc2748535b8d176eb73dc6528f14824 + checksum: f90a4f1fa2ececb5c09669336119545d9ad9e9bcc07fac0af9ee363203f69dd0 - filename: src/variables/variable.dotenv.ts checksum: 9dae58ca744cf45332d054387fa0707169d01c1b57754af5133898c0c0efeb8c - filename: src/variables/variable.errors.ts @@ -474,7 +474,7 @@ fileignoreconfig: - filename: src/core/password-argv.ts checksum: 22a5aa7d95c6a5113a034d2cc9af4f152f8a366f1c271f86cd317ea2046f5b1d - filename: src/core/password-argv.test.ts - checksum: df87a19d09ff07b95d8118dd7e6bae5a13a86f0ecb8dce97e6022481d1e11256 + checksum: 49aaf0938b2db30eb4d5b239a40e5ff4e19191baae2925bcef75c562909b2485 - filename: test/integration/prompt-ctrl-c-on-a-terminal.test.ts checksum: f712885cded1bef4d64a8e1d7532f95b6696e7d7522dfeba55edf211d07fb837 - filename: test/integration/usage-errors.test.ts diff --git a/src/core/password-argv.test.ts b/src/core/password-argv.test.ts index d39057ab..407c1c5d 100644 --- a/src/core/password-argv.test.ts +++ b/src/core/password-argv.test.ts @@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto'; import { UsageError } from './errors'; import { PASSWORD_ON_ARGV, refusePasswordOnArgv } from './password-argv'; +import { keyEqualsValue } from '../../test/support/key-value'; const password = randomBytes(8).toString('hex'); @@ -9,7 +10,7 @@ describe('refusePasswordOnArgv', () => { it.each([ ['-p followed by a value', ['--env', 'staging', '-p', password]], ['--password followed by a value', ['--password', password, '--env', 'staging']], - ['--password=', [`--password=${password}`]], + ['--password=', [keyEqualsValue('--password', password)]], ['-p written as one word', [`-p${password}`]], ])('refuses %s with a usage error that never repeats the value', (_form, argv) => { const refusal = captured(() => refusePasswordOnArgv(argv)); diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 91ede491..ed72328e 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -16,6 +16,7 @@ import { answerRequestError, CloudFunctions, functionFilesImporting, isOutsideDi import { PortInUseError } from './function.errors'; import * as loader from './load-data-url'; import { loadDataURL } from './load-data-url'; +import { keyEqualsValue } from '../../test/support/key-value'; interface HttpResponse { status: number; @@ -1948,7 +1949,7 @@ describe('CloudFunctions serve routing', () => { it('loads the env file beside the functions directory before the functions load', async () => { const envValue = randomUUID(); - writeFileSync(join(workspace, '.env'), `LAUNCH_TEST_VALUE=${envValue}\n`); + writeFileSync(join(workspace, '.env'), `${keyEqualsValue('LAUNCH_TEST_VALUE', envValue)}\n`); writeFunctionFile( 'env.js', [ diff --git a/src/variables/variable.dotenv.test.ts b/src/variables/variable.dotenv.test.ts index 3422f76c..d843fab2 100644 --- a/src/variables/variable.dotenv.test.ts +++ b/src/variables/variable.dotenv.test.ts @@ -1,4 +1,5 @@ import { DotenvLineError, parseDotenv } from './variable.dotenv'; +import { keyEqualsValue } from '../../test/support/key-value'; function lineErrorOf(text: string): DotenvLineError { try { @@ -29,7 +30,7 @@ describe('variable dotenv', () => { ['URL', 'https://x.test/#/home'], ['PW', 'p@ss#word1'], ])('keeps a # with no space or tab before it in an unquoted value (%s)', (key, value) => { - expect(parseDotenv(`${key}=${value}`).variables).toEqual([{ key, value }]); + expect(parseDotenv(keyEqualsValue(key, value)).variables).toEqual([{ key, value }]); }); it.each([['A=value #123'], ['A=value\t#123'], ['A=value # note']])( From 04de230498e4108b2795b2028cd08f44a2c06410 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:28:21 +0000 Subject: [PATCH 3/4] feat(create): add --secret to projects:create and env:create MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add write-only secrets to the two create commands. The variables layer gets the `--secret` flag and its secretFlag rule (key only, no KEY=value, no repeats, no clash with --var or --from-stack), prepareSecretInput for the dotenv, terminal and piped-value checks, masked prompts and chooser wording, and a create summary that names secret keys and never a value. variablesForCreate now returns both the variables and the secrets. The builder and the creators send them as `secrets: [{key, value}]` on the create-environment body, and in `environment.secrets` of POST /projects, with no follow-up call. The APIs word the secret key conflict, the multi-line value and the combined size limits for a request that carried secrets, and mask every secret value in the error they rethrow, so a value never travels through argv, the variables checklist or an error message. The integration tests build every secret argument with keyEqualsValue. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EptZEjXxian6NQu8WFTYZd --- .talismanrc | 67 ++- src/commands/launch/env/create.test.ts | 69 ++- src/commands/launch/env/create.ts | 21 +- src/commands/launch/projects/create.test.ts | 57 +- src/commands/launch/projects/create.ts | 21 +- src/environments/environment.builder.test.ts | 80 ++- src/environments/environment.builder.ts | 17 +- src/environments/environment.create.test.ts | 150 +++++- src/environments/environment.create.ts | 11 +- src/environments/environment.errors.test.ts | 194 ++++++- src/environments/environment.errors.ts | 102 ++++ src/environments/environments.api.test.ts | 215 +++++++- src/environments/environments.api.ts | 31 +- src/environments/types.ts | 2 + src/projects/project.create.test.ts | 174 +++++- src/projects/project.create.ts | 13 +- src/projects/project.errors.ts | 6 + src/projects/projects.api.test.ts | 123 ++++- src/projects/projects.api.ts | 25 +- src/variables/variable.chooser.ts | 61 ++- src/variables/variable.create.test.ts | 430 +++++++++++++-- src/variables/variable.create.ts | 79 ++- src/variables/variable.errors.ts | 7 + src/variables/variable.inputs.test.ts | 45 +- src/variables/variable.inputs.ts | 9 + src/variables/variable.parse.ts | 8 +- src/variables/variable.rules.test.ts | 153 +++++- src/variables/variable.rules.ts | 37 ++ src/variables/variable.secrets.test.ts | 210 ++++++++ src/variables/variable.secrets.ts | 59 +++ src/variables/variable.set.ts | 2 +- src/variables/variable.stack.test.ts | 11 +- src/variables/variable.stack.ts | 7 + src/variables/variable.summary.test.ts | 69 +++ src/variables/variable.summary.ts | 24 +- src/variables/variable.values.test.ts | 124 ++++- src/variables/variable.values.ts | 38 ++ test/integration/environments-create.test.ts | 530 ++++++++++++++++++- test/integration/projects-create.test.ts | 295 ++++++++++- 39 files changed, 3408 insertions(+), 168 deletions(-) create mode 100644 src/variables/variable.secrets.test.ts create mode 100644 src/variables/variable.secrets.ts diff --git a/.talismanrc b/.talismanrc index ed6ab7fc..f7ba3aa0 100644 --- a/.talismanrc +++ b/.talismanrc @@ -28,7 +28,7 @@ fileignoreconfig: - filename: src/projects/types.ts checksum: 73826a3686cd0793e7813e80c54bfdc78cddb72b085d2861854f20064a23fdc8 - filename: src/projects/projects.api.ts - checksum: 4393359ce73a1c0cf53b68feb3c5273e68bc334872e61b98b6dc595dc7db897c + checksum: 78a79aa4b25910872dbe31053d527dcb9091ee6abb69ef4c07e8db652d01ea99 - filename: src/core/service-context.test.ts checksum: b9d5a3f355966cefceed66885634100a6657967bb087f60ac23bd98681b188fa - filename: src/core/rules.test.ts @@ -86,6 +86,7 @@ fileignoreconfig: - "b2c3d4e5f60718293a4b5c6d" - "c3d4e5f60718293a4b5c6d7e" - filename: src/projects/projects.api.test.ts + checksum: dfb61104f2a235412808f7187b7dddcebc40fdd4eeeb10d5bc6e69343cb31035 allowed_patterns: - "the caller passes neither" - "the caller must pass a uid instead" @@ -93,20 +94,23 @@ fileignoreconfig: allowed_patterns: - "formFieldKey" - filename: src/projects/project.create.test.ts + checksum: f6b1b7e67866ecd97a6ea842fc0bc1c150fd2786f4c2ad6cb6b863b8d9cc4587 allowed_patterns: - "'SECRET=hunter2'" - "formFieldKey" - filename: test/integration/projects-create.test.ts - checksum: 531f1dee468b8dd95acba2e173e6014d4d57d448526464b837d32a8a85409cf7 + checksum: 9e5a805f4e9f04aa0596e7f378fd9f14bd528ce10e36fa129e0161f2b2128f16 - filename: test/fixtures/README.md checksum: d801c84c8b7d7f38f967573e9a3a70da4405b7cbcbf10d2a6e5be3d65fb3daa1 allowed_patterns: - "formFieldKey" - "\\{key, value\\}" - filename: src/environments/environments.api.ts + checksum: d19157d174c747658cd4933eef69e743b93c16634a55c049a58d56524f99434f ignore_detectors: - filename - filename: src/environments/environments.api.test.ts + checksum: 517f6740ba80471e423d2b9d6a1770fc507c891728c716583267539148e4f85d ignore_detectors: - filename - filename: src/transport/envelope.ts @@ -124,12 +128,13 @@ fileignoreconfig: ignore_detectors: - filename - filename: src/environments/environment.builder.ts + checksum: 3869abe9d25b9eae9a50db2e6e8529832d65343df6e2db2e1c69d3c6b1514b59 ignore_detectors: - filename - filename: src/environments/environment.builder.test.ts ignore_detectors: - filename - checksum: 7895190eca678d0d7c755924915e4b26bc32e3a0b63bda109e5d8ea81b46e16f + checksum: ae3560b1807beec85062e821cb1af0ce77c0f751183247d9087c6ebe5f9cf35a - filename: src/environments/environment.update.ts checksum: eb5536ef1f2c4a21005ddefe2678ac4ad97ca09530d971e377a301c506a1dbe2 ignore_detectors: @@ -139,9 +144,11 @@ fileignoreconfig: ignore_detectors: - filename - filename: src/environments/environment.create.ts + checksum: 6503b24477b213f9d13c6aeb4c5da2330b5710bf3b82fc07c841c5792fab4744 ignore_detectors: - filename - filename: src/environments/environment.create.test.ts + checksum: 1380878bb4d4e09d8f76b9c679fec2c7ddfcd4a22c3760f62a7e1e8e8b6233ab ignore_detectors: - filename - filename: src/environments/environment.rules.ts @@ -262,7 +269,7 @@ fileignoreconfig: - filename: test/guards/layering.test.ts checksum: 78da549efd0bb8c03bb44428d384c3ecacc1b3ad2576b83bfe291d45d973beda - filename: src/commands/launch/projects/create.test.ts - checksum: fc7097703f1068e125596daebf6db539ed15643f75e1d240da8e059b4fe5e8a4 + checksum: f82bcd0d443bb3b640c79c24c8409934d731de443e7337517705c2129f8addcf - filename: src/commands/launch/projects/delete.test.ts checksum: 1a3b472cb9cf0aa0be3a17831891eb980f9e6eef5f753d12089d54f16001330b - filename: test/integration/projects-delete.test.ts @@ -316,7 +323,7 @@ fileignoreconfig: - filename: test/credential-guard.setup.ts checksum: 519ccbeb0552fdb1d5f27308c56477c0258ee6cc0adec8f618e8e5bc047cbf6d - filename: src/environments/types.ts - checksum: c45a2ed513e295ef56da5a6a014e31cb7de3612fc699a3d3b157e525843e8303 + checksum: 956cf48c592b348010f54074502cd7517f0dc6fce1c2c433a44872331a690bbe - filename: src/commands/launch/env/get.test.ts checksum: 6b79822734553c7417c0a8774fae221609d008be22834113661c9925f17017b9 - filename: test/integration/environments-delete.test.ts @@ -324,7 +331,7 @@ fileignoreconfig: - filename: src/commands/launch/env/delete.test.ts checksum: 8c38c55fae804e355f30c74d14aeb252deb850685259267afb443a6ea9190048 - filename: src/environments/environment.errors.ts - checksum: 2cf9b4a951cb5f46d1f1603134c34ed722a77e442f07b0d5ec189850b41d053f + checksum: 7b03425b856e6358a3e6e08ffdfc70c9445296b63758e2e5fc44f05b067bf892 - filename: src/core/prompt.ts checksum: f055d7a2ece49f6476b8fc8ca8a951448d52e0e908723c7b715fd7b0a42576e7 - filename: src/core/prompt.test.ts @@ -342,7 +349,7 @@ fileignoreconfig: - "-p, --password" - "-u, --username" - filename: test/integration/environments-create.test.ts - checksum: b2bae2f96095ceb5b345339550f0af5dcf9e30b3fce2f98aca51a6e791d710cb + checksum: 27e711f6050e03d71792905547e4bd807815afcd8437794423972c63ba2a4e2d - filename: src/commands/launch/variables/list.test.ts checksum: 87ccb762f4931326fc50bca1c01aeb4a16d552e4dfa141d00370fdfafa4363be - filename: src/commands/launch/variables/set.test.ts @@ -352,27 +359,27 @@ fileignoreconfig: - filename: src/commands/launch/variables/unset.ts checksum: 233c50867eb28f61275ea58535f2839fda3d023b678cd38a9f9e853925de9719 - filename: src/environments/environment.errors.test.ts - checksum: 33ae71db0a46173c903659438a77d1d441797a8296e0591dbaa48512f32a4cab + checksum: f2e08fdef2b66a08f3688bdead2b82a044cb127b50e68b93fcd541d6175fa58c - filename: src/stacks/stacks.api.test.ts checksum: 8366a24de9871db79249ff8163ce8d07437053f2eb7d3a2744e6fac09429999a - filename: src/stacks/stacks.api.ts checksum: e03dbc26c3b49fce67cc40c4c2963da863d292ed9c40b81d51e016215947ad40 - filename: src/variables/variable.chooser.ts - checksum: 7b286b31c49e7501fed220cc6d8c082a451bf8c81b0202242545cff7031e22bb + checksum: fa79b47d4a7d0a76af8605c2fe374fe285d6005885199f131c01fe49485b0634 - filename: src/variables/variable.create.test.ts - checksum: 5c9147b1b2a76bf4743d8d50ed398148381e5a19e3274bad734e3b31779934cd + checksum: 84c92f2796d3dc4f3d7d445630f87c3b408cb61e6c79327652752a372cb61835 - filename: src/variables/variable.dotenv.test.ts checksum: f90a4f1fa2ececb5c09669336119545d9ad9e9bcc07fac0af9ee363203f69dd0 - filename: src/variables/variable.dotenv.ts checksum: 9dae58ca744cf45332d054387fa0707169d01c1b57754af5133898c0c0efeb8c - filename: src/variables/variable.errors.ts - checksum: f66b960365b83561f70b5fcef521bcc8a00d99b4415fb6a5df5bcf752a91d480 + checksum: f06cc423b9be9d29d9aeeb34808fb50820bcbffa71c5fe8639fc97b0ee08ae7c - filename: src/variables/variable.files.test.ts checksum: 301bc761c194453c0ec6fe073bf83960712e8f298f2fb6b782c1eadafd5089f5 - filename: src/variables/variable.inputs.test.ts - checksum: 11f41a57e57d9fec46afddd9f8a62df76eaf6fec4afbccf39fe4bce23a978eaf + checksum: 72d54b26b2ca4c0664c346dbd2683246eb2481a00cd56fd3850a4d810a972ec0 - filename: src/variables/variable.inputs.ts - checksum: b29fcc7fdddc938507d060ff3590d1d0705f5e8f173b232a488fa09d4c96c177 + checksum: 6ff3fb44f5703d20eef8bddd2a2b7462023ff6c4bc3a8238b227f97ab6bc2607 - filename: src/variables/variable.merge.test.ts checksum: 581a5cc5d9d23223643bd461525c6755205ebf16f33ae7388c8e88de19461fbf - filename: src/variables/variable.merge.ts @@ -382,7 +389,7 @@ fileignoreconfig: - filename: src/variables/variable.parse.test.ts checksum: 8cfcd7f3b0784f525238ab09d8cbe8b8d8fb3a90eb164cb5bd4cdf15a8740e86 - filename: src/variables/variable.parse.ts - checksum: 912ef100eaec7e08ffef90100f8559a224aed709bd4527dcf15653f8b4131287 + checksum: eeac3736ca9f3ac3e330a08694374695769e06937f136b255a64169f77da1eb5 - filename: src/variables/variable.presenter.test.ts checksum: 62e8b0eff16ed4408d929092ce6808aeabea001a6cc15780d46c4ac4226eec3d - filename: src/variables/variable.presenter.ts @@ -394,21 +401,21 @@ fileignoreconfig: - filename: src/variables/variable.sources.ts checksum: 93bbe08cb16298372a18fcf7ce8a77b08179ce7c90e1f3f3699336c70da08c39 - filename: src/variables/variable.stack.test.ts - checksum: d3478b2d0ec06d831706780a7fac806b8d525d4441b2085d3eb24ac058e38bcc + checksum: 1b4937feb547d6db4b4b0ed70fde84fa5ea768c2d6075790b2fd38ef15f18a49 - filename: src/variables/variable.stack.ts - checksum: 9d4bd5b72063e0d3951e01696794ec7409294a64ff65693b8dc910fe0a2d2c2d + checksum: 04d4701abbecff173cd4e7b9d2a5410aa269da23c4b17ba9eb8232309529f14a - filename: src/variables/variable.summary.test.ts - checksum: 8b214a1f1f43ac1a76434b75e4ff1ffd73a9e73dc2a0d6bae9ca43fd678182e5 + checksum: cd1261e52a3b93896facbdfe24390bf2f3da92b8ca6b9766fb4c15abb432682f - filename: src/variables/variable.summary.ts - checksum: 0da287557a5c4280074d1a26aeff4f7d95b205e4266ff47c18b62665134f5bdc + checksum: 041624781cdfe9e29e1f744e9b8fa9d97ff88cb73d56dde0c2683328afab31b8 - filename: src/variables/variable.unset.test.ts checksum: 8797c7aa2960fc0328d5cab8cfdddf674ac624ace95f79338520851a2c7b732a - filename: src/variables/variable.unset.ts checksum: 4050a023edd3c6db1507eb2d0f2815d8c0c03622b2810b4977a8fba6e83818fe - filename: src/variables/variable.values.test.ts - checksum: cdedaa03735077efdfac3cfdc8a05e7f13e1fc3f1bc2274b8ed9f493f496d43c + checksum: 59c8429a2e7c75fb22be2c1303606f85fb396e1ef8c250e8dd1febbddb922e0a - filename: src/variables/variable.values.ts - checksum: 9e078c80c9dd18d9cc9db43c58c702bf9e14d60bbd4d1d2efc41227e754c0fbc + checksum: 4e12447016100a3d30b393de4bbd5b56048693708fb041014561649eacb51968 - filename: src/variables/variable.writer.test.ts checksum: 7991a4ba0c58f187dfebf01092642459ce89b297f453159ca8e0953a2ee7e2b8 - filename: src/variables/variable.writer.ts @@ -480,7 +487,7 @@ fileignoreconfig: - filename: test/integration/usage-errors.test.ts checksum: 6cbb2c552e3c9a08a91474ffe907c67926343c2f2cb9297125163b765ec53e60 - filename: src/projects/project.create.ts - checksum: ffa8a52b365d01235b49a7b9ea4e2a09f29fb5b142fc8b680c8583f6dc14455f + checksum: ee14c7986b87faef0fe99fb457f56fb9a15105529dbbc4c68173c517ba0fd5d3 - filename: src/core/errors.ts checksum: dee8ba2e978b65d5b16f915846b1adc5560a4bf2932b1a4482b451119bca7f41 - filename: src/organizations/organization.errors.ts @@ -491,6 +498,14 @@ fileignoreconfig: checksum: b71ca5a072dc5a1ecc18ba9f2460fe33285404a7e10c19d454c0697d0fc91d3d - filename: src/variables/variable.files.ts checksum: 2a8df02d571a14f88fc9127eef0359dbbf5e8c61331466bb22143dfd4745d7ce +- filename: src/commands/launch/env/create.test.ts + checksum: c0561866b5f883697afd7b25ccfc9b652618f605ce1f200776005451ba870713 +- filename: src/commands/launch/env/create.ts + checksum: 742ab7c2a2c0e725828e6bc875a6b5c6611004b21d3a652d311d54b88f36cb11 +- filename: src/commands/launch/projects/create.ts + checksum: d9b3d42a9012e63a143ae6aacf5cf17ff2b1b97fc7de07fe4714cc03c8a86c7f +- filename: src/projects/project.errors.ts + checksum: 8603795adc2f4ef05dc2ada42a80985c03242f21c126277b31152f39f5db2dbd - filename: src/secrets/secret.rules.test.ts checksum: 280e52bde2eac24cc8dd118ddfef17de216f31476ce5e29c56285047fab8238b - filename: src/secrets/secret.rules.ts @@ -501,6 +516,16 @@ fileignoreconfig: checksum: 47b6f37c70292f34ac91d3fd9be1b49e271238461720f7a1681c4598c14ddfa8 - filename: src/secrets/secrets.errors.test.ts checksum: 28b6c1587831cf00daf2de4a4bae9a890368b3333423134976f00386583d30a5 +- filename: src/variables/variable.create.ts + checksum: d6b9a605031934029eb71d435ed906f8e5d374b0db2b05bead06c369585b732b +- filename: src/variables/variable.rules.test.ts + checksum: 83cfffd9d5d270ae2d0281a54c201556127749347694a05abba68c2d7d279a75 +- filename: src/variables/variable.rules.ts + checksum: 5b745a3b020d5095235c110a796d60b450b193f696c8ec7c42ccf1a7a83171ab +- filename: src/variables/variable.secrets.test.ts + checksum: 245fac8b800587e6084e1867a5d52f5dbbddac5d3a64fc8f8bd606f3210706b2 +- filename: src/variables/variable.secrets.ts + checksum: aa878e43e3515f2c9c57dfacf1d689b6a5a3ff1dfee7ca996976b0835ab89318 - filename: test/support/key-value.ts checksum: 032885867d121de097336a3eb651f6f50ad1dbb4a4604198eec6c6346c02301e version: "1.0" diff --git a/src/commands/launch/env/create.test.ts b/src/commands/launch/env/create.test.ts index b7944688..6b9f4066 100644 --- a/src/commands/launch/env/create.test.ts +++ b/src/commands/launch/env/create.test.ts @@ -1,10 +1,15 @@ +import { Parser } from '@oclif/core'; +import type { Errors } from '@oclif/core'; + import { UsageError } from '../../../core/errors'; import { ENVIRONMENT_NAME_MAX_LENGTH } from '../../../environments/environment.inputs'; import { catalog, resolution } from '../../../resources'; import { DEPLOYMENT_WAIT_TIMEOUT_MS } from '../../../deployments/deployment.watcher'; import { EnvironmentCreator } from '../../../environments/environment.create'; import { serverCommandFrameworkGate } from '../../../environments/environment.inputs'; -import { aliasRequiresFromStack, singleDotenv } from '../../../variables/variable.rules'; +import { aliasRequiresFromStack, secretFlag, singleDotenv } from '../../../variables/variable.rules'; +import { gluedValue } from '../../../../test/support/glued-value'; +import { variableFlags } from '../../../variables/variable.inputs'; import EnvironmentsCreate from './create'; function commandUnderTest(resolved: Record) { @@ -44,6 +49,7 @@ describe('launch:env:create', () => { 'cs-auth': 'disable', var: ['A=1', 'B'], dotenv: ['a.env'], + secret: ['C', 'D'], 'from-stack': true, alias: 'my-prod', }).run(); @@ -65,6 +71,7 @@ describe('launch:env:create', () => { csAuth: 'disable', vars: ['A=1', 'B'], envFiles: ['a.env'], + secrets: ['C', 'D'], fromStack: true, alias: 'my-prod', }, @@ -94,11 +101,12 @@ describe('launch:env:create', () => { 'cs-auth': {}, var: {}, dotenv: {}, + secret: {}, 'from-stack': {}, alias: {}, }); expect(Object.keys(EnvironmentsCreate.flags).sort()).toEqual(Object.keys(EnvironmentsCreate.inputs).sort()); - expect(EnvironmentsCreate.rules).toEqual([serverCommandFrameworkGate, aliasRequiresFromStack, singleDotenv]); + expect(EnvironmentsCreate.rules).toEqual([serverCommandFrameworkGate, aliasRequiresFromStack, singleDotenv, secretFlag]); }); it('describes --name as the environment its own, leaving the project wording alone', () => { @@ -116,5 +124,60 @@ describe('launch:env:create', () => { ); await expect(nameSpec.normalize('n'.repeat(ENVIRONMENT_NAME_MAX_LENGTH + 1))).rejects.toThrow(UsageError); }); -}); + it('documents --secret as a repeatable, optional key-only flag whose value comes from a prompt or standard input', () => { + const flag = EnvironmentsCreate.flags.secret as { multiple?: boolean; required?: boolean; type: string; description?: string }; + + expect(EnvironmentsCreate.flags.secret).toBe(variableFlags.secret); + expect(flag.multiple).toBe(true); + expect(flag.required).toBeFalsy(); + expect(flag.type).toBe('option'); + expect(flag.description).toContain('key only'); + expect(flag.description).toContain('masked prompt'); + expect(flag.description).toContain('standard input'); + }); + + it('shows --secret in the examples, with a prompt and with a piped value that carries what a GitHub environment needs without a terminal', () => { + const examples = EnvironmentsCreate.examples as string[]; + const piped = examples.find((example) => example.startsWith("$ printf '%s' \"$STRIPE_KEY\" | csdx launch:env:create")); + + expect(examples.some((example) => example.includes('--secret STRIPE_KEY,DB_PASSWORD'))).toBe(true); + expect(piped).toContain('--secret STRIPE_KEY'); + expect(piped).toContain('--org --project --name staging'); + expect(piped).toContain('--branch '); + expect(piped).toContain('--framework NextJs'); + }); + + it('passes the secret keys on as they were resolved, leaving the values to the creator', async () => { + const requests: { secrets?: string[] }[] = []; + jest.spyOn(EnvironmentCreator.prototype, 'create').mockImplementation(async (request) => { + requests.push(request); + }); + + await commandUnderTest({ secret: ['STRIPE_KEY'] }).run(); + + expect(requests[0].secrets).toEqual(['STRIPE_KEY']); + }); + + it('replaces a parse failure that would echo a token with its help line, writing the token nowhere', async () => { + const value = gluedValue(); + const raw = (await Parser.parse(['--secret', 'STRIPE_KEY', value], { flags: { secret: variableFlags.secret } }).catch( + (error: unknown) => error, + )) as Error; + const written: string[] = []; + jest.spyOn(process.stderr, 'write').mockImplementation((chunk: unknown) => { + written.push(String(chunk)); + return true; + }); + + const error = (await (commandUnderTest({}) as unknown as { catch(e: Error): Promise }) + .catch(raw) + .catch((thrown: unknown) => thrown)) as Errors.CLIError; + + expect(raw.message).toContain(value); + expect(error.oclif.exit).toBe(2); + expect(error.message).toBe('Run csdx launch:env:create --help to see its flags.'); + expect(written).toEqual(['error: Run csdx launch:env:create --help to see its flags.\n']); + expect(written.join('')).not.toContain(value); + }); +}); diff --git a/src/commands/launch/env/create.ts b/src/commands/launch/env/create.ts index f1fea945..a8b0b3d4 100644 --- a/src/commands/launch/env/create.ts +++ b/src/commands/launch/env/create.ts @@ -3,7 +3,12 @@ import { flagsFor, inputs } from '../../../core/inputs'; import { defaultWatchTiming } from '../../../deployments/deployment.watcher'; import { EnvironmentCreator } from '../../../environments/environment.create'; import { serverCommandFrameworkGate, withEnvironmentWording } from '../../../environments/environment.inputs'; -import { aliasRequiresFromStack, singleDotenv } from '../../../variables/variable.rules'; +import { + aliasRequiresFromStack, + asSafeCreateFailure, + secretFlag, + singleDotenv, +} from '../../../variables/variable.rules'; const createInputs = inputs({ org: { required: true }, @@ -19,6 +24,7 @@ const createInputs = inputs({ 'cs-auth': {}, var: {}, dotenv: {}, + secret: {}, 'from-stack': {}, alias: {}, }); @@ -31,13 +37,19 @@ export default class EnvironmentsCreate extends LaunchCommand --project --name staging --data-dir ./site ' + '# a FileUpload project uploads the folder', + '$ csdx launch:env:create --org --project --name staging ' + + '--var API_URL=https://api.example.test --secret STRIPE_KEY,DB_PASSWORD ' + + '# each secret value is asked at a masked prompt', + "$ printf '%s' \"$STRIPE_KEY\" | csdx launch:env:create --org --project " + + '--name staging --branch --framework NextJs --secret STRIPE_KEY ' + + '# a single secret can be piped in', ]; static inputs = createInputs; static flags = withEnvironmentWording(flagsFor(createInputs)); - static rules = [serverCommandFrameworkGate, aliasRequiresFromStack, singleDotenv]; + static rules = [serverCommandFrameworkGate, aliasRequiresFromStack, singleDotenv, secretFlag]; async run(): Promise { const resolved = this.resolved; @@ -58,8 +70,13 @@ export default class EnvironmentsCreate extends LaunchCommand { + return super.catch(asSafeCreateFailure(err, 'launch:env:create') as Error); + } } diff --git a/src/commands/launch/projects/create.test.ts b/src/commands/launch/projects/create.test.ts index a585b6b2..daf24114 100644 --- a/src/commands/launch/projects/create.test.ts +++ b/src/commands/launch/projects/create.test.ts @@ -1,10 +1,16 @@ +import { Parser } from '@oclif/core'; +import type { Errors } from '@oclif/core'; + import type { defaultWatchTiming } from '../../../deployments/deployment.watcher'; import { DEPLOYMENT_WAIT_TIMEOUT_MS } from '../../../deployments/deployment.watcher'; import { serverCommandFrameworkGate } from '../../../environments/environment.inputs'; -import { aliasRequiresFromStack, singleDotenv } from '../../../variables/variable.rules'; +import { aliasRequiresFromStack, secretFlag, singleDotenv } from '../../../variables/variable.rules'; +import { gluedValue } from '../../../../test/support/glued-value'; +import { variableFlags } from '../../../variables/variable.inputs'; import { ProjectCreator } from '../../../projects/project.create'; type WatchTiming = ReturnType; +import EnvironmentsCreate from '../env/create'; import ProjectsCreate from './create'; function commandUnderTest(resolved: Record, dataDir = '/tmp/site') { @@ -42,6 +48,7 @@ describe('launch:projects:create', () => { 'cs-auth': 'disable', var: ['A=1', 'B'], dotenv: ['a.env'], + secret: ['C', 'D'], 'from-stack': true, alias: 'my-prod', }).run(); @@ -65,6 +72,7 @@ describe('launch:projects:create', () => { csAuth: 'disable', vars: ['A=1', 'B'], envFiles: ['a.env'], + secrets: ['C', 'D'], fromStack: true, alias: 'my-prod', }, @@ -101,7 +109,7 @@ describe('launch:projects:create', () => { }); it('declares only the framework gate as a rule, leaving GitHub-only flags on FileUpload to a confirmation', () => { - expect(ProjectsCreate.rules).toEqual([serverCommandFrameworkGate, aliasRequiresFromStack, singleDotenv]); + expect(ProjectsCreate.rules).toEqual([serverCommandFrameworkGate, aliasRequiresFromStack, singleDotenv, secretFlag]); }); it('declares every flag it reads and requires only the organization', () => { @@ -121,6 +129,7 @@ describe('launch:projects:create', () => { 'cs-auth', 'var', 'dotenv', + 'secret', 'from-stack', 'alias', ]); @@ -171,4 +180,48 @@ describe('launch:projects:create', () => { '# the repository comes from the folder\'s GitHub remote', ); }); + + it('documents --secret with the same definition as env:create, optional and key-only', () => { + const flag = ProjectsCreate.flags.secret as { multiple?: boolean; required?: boolean; type: string; description?: string }; + + expect(ProjectsCreate.flags.secret).toBe(variableFlags.secret); + expect(EnvironmentsCreate.flags.secret).toBe(ProjectsCreate.flags.secret); + expect(flag.multiple).toBe(true); + expect(flag.required).toBeFalsy(); + expect(flag.type).toBe('option'); + expect(flag.description).toContain('key only'); + }); + + it('shows --secret in the examples, with a prompt and with a piped value that carries what a GitHub project needs without a terminal', () => { + const examples = ProjectsCreate.examples as string[]; + const piped = examples.find((example) => example.includes("printf '%s' \"$STRIPE_KEY\" | csdx launch:projects:create")); + + expect(examples.some((example) => example.includes('--secret STRIPE_KEY,DB_PASSWORD'))).toBe(true); + expect(piped).toContain('--secret STRIPE_KEY'); + expect(piped).toContain('--org --type GitHub --name --env-name '); + expect(piped).toContain('--branch '); + expect(piped).toContain('--framework NextJs'); + }); + + it('replaces a parse failure that would echo a token with its help line, writing the token nowhere', async () => { + const value = gluedValue(); + const raw = (await Parser.parse(['--secret', 'STRIPE_KEY', value], { flags: { secret: variableFlags.secret } }).catch( + (error: unknown) => error, + )) as Error; + const written: string[] = []; + jest.spyOn(process.stderr, 'write').mockImplementation((chunk: unknown) => { + written.push(String(chunk)); + return true; + }); + + const error = (await (commandUnderTest({}) as unknown as { catch(e: Error): Promise }) + .catch(raw) + .catch((thrown: unknown) => thrown)) as Errors.CLIError; + + expect(raw.message).toContain(value); + expect(error.oclif.exit).toBe(2); + expect(error.message).toBe('Run csdx launch:projects:create --help to see its flags.'); + expect(written).toEqual(['error: Run csdx launch:projects:create --help to see its flags.\n']); + expect(written.join('')).not.toContain(value); + }); }); diff --git a/src/commands/launch/projects/create.ts b/src/commands/launch/projects/create.ts index 3b87bf8a..6fd6b99a 100644 --- a/src/commands/launch/projects/create.ts +++ b/src/commands/launch/projects/create.ts @@ -3,7 +3,12 @@ import { flagsFor, inputs } from '../../../core/inputs'; import { defaultWatchTiming } from '../../../deployments/deployment.watcher'; import { serverCommandFrameworkGate } from '../../../environments/environment.inputs'; import { ProjectCreator } from '../../../projects/project.create'; -import { aliasRequiresFromStack, singleDotenv } from '../../../variables/variable.rules'; +import { + aliasRequiresFromStack, + asSafeCreateFailure, + secretFlag, + singleDotenv, +} from '../../../variables/variable.rules'; const createInputs = inputs({ org: { required: true }, @@ -21,6 +26,7 @@ const createInputs = inputs({ 'cs-auth': {}, var: {}, dotenv: {}, + secret: {}, 'from-stack': {}, alias: {}, }); @@ -35,13 +41,19 @@ export default class ProjectsCreate extends LaunchCommand { '--data-dir ./site --framework Other --build-cmd "npm run build" --output-dir ./ --res-mode buffered', '$ csdx launch:projects:create --org --type GitHub --data-dir ./my-clone ' + '# the repository comes from the folder\'s GitHub remote', + '$ csdx launch:projects:create --org --type GitHub --name --env-name ' + + '--var API_URL=https://api.example.test --secret STRIPE_KEY,DB_PASSWORD ' + + '# each secret value is asked at a masked prompt', + "$ printf '%s' \"$STRIPE_KEY\" | csdx launch:projects:create --org --type GitHub --name " + + '--env-name --branch --framework NextJs --secret STRIPE_KEY ' + + '# a single secret can be piped in', ]; static inputs = createInputs; static flags = flagsFor(createInputs); - static rules = [serverCommandFrameworkGate, aliasRequiresFromStack, singleDotenv]; + static rules = [serverCommandFrameworkGate, aliasRequiresFromStack, singleDotenv, secretFlag]; async run(): Promise { const resolved = this.resolved; @@ -64,8 +76,13 @@ export default class ProjectsCreate extends LaunchCommand { csAuth: resolved['cs-auth'], vars: resolved.var, envFiles: resolved['dotenv'], + secrets: resolved.secret, fromStack: resolved['from-stack'], alias: resolved.alias, }); } + + protected async catch(err: Error & { exitCode?: number }): Promise { + return super.catch(asSafeCreateFailure(err, 'launch:projects:create') as Error); + } } diff --git a/src/environments/environment.builder.test.ts b/src/environments/environment.builder.test.ts index 27cd04ca..31147152 100644 --- a/src/environments/environment.builder.test.ts +++ b/src/environments/environment.builder.test.ts @@ -1,15 +1,18 @@ import { MissingInputError, UsageError } from '../core/errors'; import type { ServiceContext } from '../core/service-context'; import type { ApiSurface } from '../resources'; +import { gluedValue } from '../../test/support/glued-value'; +import type { VariableIo } from '../variables/variable.io'; import { EnvironmentBuilder } from './environment.builder'; import type { EnvironmentRequest, EnvironmentSource } from './types'; const ENV_NAME = 'Production'; const GIT_SOURCE: EnvironmentSource = { detected: {}, branch: 'main' }; -function builder(options: { isTTY?: boolean; answers?: unknown[] } = {}) { +function builder(options: { isTTY?: boolean; answers?: unknown[]; io?: VariableIo } = {}) { const printed: string[] = []; const asked: { message: string; default?: unknown }[] = []; + const types: unknown[] = []; const answers = [...(options.answers ?? [])]; const services: ServiceContext = { @@ -19,8 +22,9 @@ function builder(options: { isTTY?: boolean; answers?: unknown[] } = {}) { printed.push(message); }, inquire: async (payload: unknown) => { - const { message, default: initial } = payload as { message: string; default?: unknown }; + const { message, default: initial, type } = payload as { message: string; default?: unknown; type?: unknown }; asked.push({ message, default: initial }); + types.push(type); return answers.shift() as never; }, }, @@ -28,7 +32,7 @@ function builder(options: { isTTY?: boolean; answers?: unknown[] } = {}) { outputIsTTY: false, }; - return { environments: new EnvironmentBuilder(services), printed, asked }; + return { environments: new EnvironmentBuilder(services, options.io), printed, asked, types }; } const EVERY_FLAG: EnvironmentRequest = { @@ -60,7 +64,7 @@ describe('EnvironmentBuilder', () => { autoDeployOnPush: true, isContentstackAuthenticationEnabled: false, }); - expect(asked).toEqual([{ message: 'Add environment variables', default: undefined }]); + expect(asked).toEqual([{ message: 'Add variables from', default: undefined }]); expect(printed).toEqual(['Skipped adding environment variables.']); }); @@ -94,7 +98,7 @@ describe('EnvironmentBuilder', () => { await environments.build({ ...EVERY_FLAG, csAuth: undefined }, ENV_NAME, GIT_SOURCE, undefined); - expect(asked.map((entry) => entry.message)).toEqual(['Contentstack Authentication', 'Add environment variables']); + expect(asked.map((entry) => entry.message)).toEqual(['Contentstack Authentication', 'Add variables from']); }); it('carries an upload uid and leaves auto-deploy unset when none was given', async () => { @@ -192,7 +196,7 @@ describe('EnvironmentBuilder', () => { { message: 'Server command', default: 'node .' }, { message: 'Response mode', default: 'buffered' }, { message: 'Contentstack Authentication', default: 'enable' }, - { message: 'Add environment variables', default: undefined }, + { message: 'Add variables from', default: undefined }, ]); expect(environment).toEqual( expect.objectContaining({ @@ -214,4 +218,68 @@ describe('EnvironmentBuilder', () => { expect(asked.map((question) => question.message)).not.toContain('Server command'); expect(environment.serverCommand).toBeUndefined(); }); + + it('asks a masked prompt per secret, never the variables checklist, and sends the secrets next to the variables', async () => { + const [first, second] = [gluedValue(), gluedValue()]; + const { environments, asked, types } = builder({ isTTY: true, answers: [first, second] }); + + const environment = await environments.build({ ...EVERY_FLAG, secrets: ['A', 'B'] }, ENV_NAME, GIT_SOURCE, undefined); + + expect(asked.map((entry) => entry.message)).toEqual(['Value for A (1/2)', 'Value for B (2/2)']); + expect(types).toEqual(['password', 'password']); + expect(environment.environmentVariables).toEqual([]); + expect(environment.secrets).toEqual([ + { key: 'A', value: first }, + { key: 'B', value: second }, + ]); + }); + + it('reads the one piped secret from the io it was given when there is no terminal', async () => { + const value = gluedValue(); + const reads: number[] = []; + const io: VariableIo = { + readFile: async () => '', + exists: () => false, + readStdin: async () => { + reads.push(1); + return value; + }, + }; + const { environments, asked } = builder({ isTTY: false, io }); + + const environment = await environments.build({ ...EVERY_FLAG, secrets: ['A'] }, ENV_NAME, GIT_SOURCE, undefined); + + expect(environment.secrets).toEqual([{ key: 'A', value }]); + expect(environment.environmentVariables).toEqual([]); + expect(reads).toEqual([1]); + expect(asked).toEqual([]); + }); + + it.each([[undefined], [[]]])('sends no secrets property, and asks only the checklist on a terminal, for secrets of %p', async (secrets) => { + const { environments, asked } = builder({ isTTY: true, answers: [['Skip adding environment variables']] }); + + const environment = await environments.build({ ...EVERY_FLAG, secrets }, ENV_NAME, GIT_SOURCE, undefined); + + expect(environment).not.toHaveProperty('secrets'); + expect(asked.map((entry) => entry.message)).toEqual(['Add variables from']); + }); + + it.each([[undefined], [[]]])('sends no secrets property and reads no stdin without a terminal, for secrets of %p', async (secrets) => { + const reads: number[] = []; + const io: VariableIo = { + readFile: async () => '', + exists: () => false, + readStdin: async () => { + reads.push(1); + return ''; + }, + }; + const { environments, asked } = builder({ isTTY: false, io }); + + const environment = await environments.build({ ...EVERY_FLAG, secrets }, ENV_NAME, GIT_SOURCE, undefined); + + expect(environment).not.toHaveProperty('secrets'); + expect(asked).toEqual([]); + expect(reads).toEqual([]); + }); }); diff --git a/src/environments/environment.builder.ts b/src/environments/environment.builder.ts index 5372fe3a..d6f1654a 100644 --- a/src/environments/environment.builder.ts +++ b/src/environments/environment.builder.ts @@ -12,6 +12,8 @@ import { SERVER_COMMAND_FRAMEWORKS, } from './frameworks'; import { variablesForCreate } from '../variables/variable.create'; +import { DEFAULT_VARIABLE_IO } from '../variables/variable.io'; +import type { VariableIo } from '../variables/variable.io'; import type { CreateEnvironmentInput, DetectedFramework, EnvironmentRequest, EnvironmentSource } from './types'; export function frameworkLabelOf(detected: unknown): string | undefined { @@ -25,7 +27,10 @@ export function frameworkLabelOf(detected: unknown): string | undefined { } export class EnvironmentBuilder { - constructor(private readonly services: ServiceContext) {} + constructor( + private readonly services: ServiceContext, + private readonly io: VariableIo = DEFAULT_VARIABLE_IO, + ) {} async build( request: EnvironmentRequest, @@ -57,18 +62,26 @@ export class EnvironmentBuilder { environment.isContentstackAuthenticationEnabled = csAuth === 'enable'; } - environment.environmentVariables = await variablesForCreate( + const { environmentVariables, secrets } = await variablesForCreate( { org: request.org, vars: request.vars, envFiles: request.envFiles, + secrets: request.secrets, fromStack: request.fromStack, alias: request.alias, dataDir: request.dataDir ?? '.', }, this.services, + this.io, ); + environment.environmentVariables = environmentVariables; + + if (secrets.length > 0) { + environment.secrets = secrets; + } + return environment; } diff --git a/src/environments/environment.create.test.ts b/src/environments/environment.create.test.ts index a03c7ad5..8981e6eb 100644 --- a/src/environments/environment.create.test.ts +++ b/src/environments/environment.create.test.ts @@ -1,4 +1,8 @@ -import { MissingInputError } from '../core/errors'; +import { MissingInputError, UsageError } from '../core/errors'; +import { gluedValue } from '../../test/support/glued-value'; +import { emptyValueError, secretOverlapError, SECRETS_WITHOUT_TERMINAL_MESSAGE } from '../secrets/secret.rules'; +import { SecretInputTimeoutError } from '../secrets/secrets.errors'; +import type { SecretIntakeIo } from '../variables/variable.secrets'; import type { ServiceContext } from '../core/service-context'; import { DeploymentUnsuccessfulError } from '../deployments/deployment.errors'; import { DeploymentFollower } from '../deployments/deployment.follower'; @@ -30,6 +34,7 @@ interface Harness { watchFails?: Error; createFails?: Error; createdEnvironment?: unknown; + io?: SecretIntakeIo; } function creatorUnderTest(harness: Harness = {}) { @@ -133,7 +138,7 @@ function creatorUnderTest(harness: Harness = {}) { }, }; - return { creator: new EnvironmentCreator(services, timing), calls, lines, asked, created, slept }; + return { creator: new EnvironmentCreator(services, timing, harness.io), calls, lines, asked, created, slept }; } function request(fields: Partial = {}): EnvironmentCreateRequest { @@ -251,7 +256,7 @@ describe('EnvironmentCreator', () => { 'Output directory': './.next', 'Response mode': 'streaming', 'Contentstack Authentication': 'enable', - 'Add environment variables': ['Skip adding environment variables'], + 'Add variables from': ['Skip adding environment variables'], }, }); @@ -265,7 +270,7 @@ describe('EnvironmentCreator', () => { 'Output directory', 'Response mode', 'Contentstack Authentication', - 'Add environment variables', + 'Add variables from', ]); expect(calls[1]).toBe( 'branches {"org":"org1","provider":"GitHub","namespace":"octo-user","repoName":"octo-user/site","limit":100,"skip":0}', @@ -284,14 +289,14 @@ describe('EnvironmentCreator', () => { answers: { 'Environment name': 'staging', 'Contentstack Authentication': 'enable', - 'Add environment variables': ['Skip adding environment variables'], + 'Add variables from': ['Skip adding environment variables'], }, }); await creator.create(request({ name: undefined, branch: undefined, framework: 'GATSBY', buildCmd: 'b', outputDir: 'o' })); expect(calls[1]).toMatch(/^upload /); - expect(asked).toEqual(['Environment name', 'Contentstack Authentication', 'Add environment variables']); + expect(asked).toEqual(['Environment name', 'Contentstack Authentication', 'Add variables from']); }); it.each([ @@ -440,4 +445,137 @@ describe('EnvironmentCreator', () => { 'Environment "pre-release" was created.', ); }); + + describe('with --secret', () => { + function intake(options: { piped?: string | Promise; files?: Record } = {}) { + const stdinReads: number[] = []; + const closed: number[] = []; + const io: SecretIntakeIo = { + secrets: { + readStdin: async () => { + stdinReads.push(1); + return options.piped ?? ''; + }, + closeStdin: () => { + closed.push(1); + }, + stdinTimeoutMs: 20, + }, + variables: { + readFile: async (path: string) => { + if (!(path in (options.files ?? {}))) { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); + } + + return (options.files ?? {})[path]; + }, + exists: () => false, + readStdin: async () => { + throw new Error('the base stdin must not be read'); + }, + }, + }; + + return { io, stdinReads, closed }; + } + + it('reads the one piped value before the project is looked up, and creates the environment with it as a secret', async () => { + const value = gluedValue(); + const { io, stdinReads } = intake({ piped: `${value}\n` }); + const { creator, calls, created } = creatorUnderTest({ io }); + + await creator.create(request({ csAuth: 'disable', secrets: ['A'] })); + + expect(calls[0]).toBe('project {"org":"org1","project":"proj1"}'); + expect(stdinReads).toEqual([1]); + expect(created[0]).toMatchObject({ + input: { environmentVariables: [], secrets: [{ key: 'A', value }] }, + }); + }); + + it('ends with the timeout error, closing stdin, before any project lookup, upload or create', async () => { + const { io, closed } = intake({ piped: new Promise(() => undefined) }); + const { creator, calls } = creatorUnderTest({ io, project: UPLOAD_PROJECT }); + + const error: unknown = await creator.create(request({ secrets: ['A'] })).catch((failure: unknown) => failure); + + expect(error).toBeInstanceOf(SecretInputTimeoutError); + expect((error as Error).message).toContain('csdx launch:env:create --secret '); + expect((error as Error).message).not.toContain('launch:secrets'); + expect(closed).toEqual([1]); + expect(calls).toEqual([]); + }); + + it('refuses an empty piped value before any request', async () => { + const { io } = intake({ piped: '\n' }); + const { creator, calls } = creatorUnderTest({ io }); + + await expect(creator.create(request({ secrets: ['A'] }))).rejects.toThrow(emptyValueError('A').message); + expect(calls).toEqual([]); + }); + + it('refuses more than one secret without a terminal before reading stdin or sending anything', async () => { + const { io, stdinReads } = intake({ piped: gluedValue() }); + const { creator, calls } = creatorUnderTest({ io }); + + await expect(creator.create(request({ secrets: ['A', 'B'] }))).rejects.toThrow( + SECRETS_WITHOUT_TERMINAL_MESSAGE, + ); + expect(stdinReads).toEqual([]); + expect(calls).toEqual([]); + }); + + it('refuses a secret that is also a key of the --dotenv file before any request, reading no stdin', async () => { + const { io, stdinReads } = intake({ piped: gluedValue(), files: { 'staging.env': 'A=1\n' } }); + const { creator, calls } = creatorUnderTest({ io }); + + const failure = await creator + .create(request({ secrets: ['A'], envFiles: ['staging.env'] })) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as Error).message).toBe(secretOverlapError('A', '--dotenv').message); + expect(stdinReads).toEqual([]); + expect(calls).toEqual([]); + }); + + it('sends the dotenv keys as variables and the secret apart, asking the masked prompt after the build settings', async () => { + const value = gluedValue(); + const { io, stdinReads } = intake({ files: { 'staging.env': 'API_URL=from-file\n' } }); + const { creator, asked, created } = creatorUnderTest({ + io, + isTTY: true, + answers: { + 'Build command': 'npm run build', + 'Output directory': './.next', + 'Framework preset': 'NextJs', + 'Contentstack Authentication': 'enable', + 'Value for A': value, + }, + }); + + await creator.create(request({ secrets: ['A'], envFiles: ['staging.env'], resMode: 'buffered' })); + + expect(asked[asked.length - 1]).toBe('Value for A'); + expect(asked).not.toContain('Add variables from'); + expect(stdinReads).toEqual([]); + expect(created[0]).toMatchObject({ + input: { environmentVariables: [{ key: 'API_URL', value: 'from-file' }], secrets: [{ key: 'A', value }] }, + }); + }); + + it('sends the same request as before when no secret is passed, reading no stdin', async () => { + const { io, stdinReads } = intake({ piped: gluedValue() }); + const { creator, created } = creatorUnderTest({ io }); + + await creator.create(request({ csAuth: 'disable' })); + + expect(stdinReads).toEqual([]); + expect(created[0]).toEqual({ + org: 'org1', + project: 'proj1', + input: expect.not.objectContaining({ secrets: expect.anything() }), + }); + }); + }); }); diff --git a/src/environments/environment.create.ts b/src/environments/environment.create.ts index 8827a8b6..71fe59c3 100644 --- a/src/environments/environment.create.ts +++ b/src/environments/environment.create.ts @@ -8,6 +8,8 @@ import { asSentence, messageOf } from '../core/values'; import { askBranch } from '../git/git.prompt'; import { LaunchApiError } from '../transport/errors'; import { FolderUploader } from '../uploads/upload.folder'; +import { DEFAULT_SECRET_INTAKE_IO, prepareSecretInput } from '../variables/variable.secrets'; +import type { SecretIntakeIo } from '../variables/variable.secrets'; import { EnvironmentBuilder } from './environment.builder'; import type { GitScope } from './environment.rules'; import { gitScopeOf, withoutRepositoryFlags } from './environment.rules'; @@ -59,10 +61,12 @@ export class EnvironmentCreator { constructor( private readonly services: ServiceContext, private readonly timing: WatchTiming, + private readonly io: SecretIntakeIo = DEFAULT_SECRET_INTAKE_IO, ) {} async create(given: EnvironmentCreateRequest): Promise { const { org, project } = given; + const variableIo = await prepareSecretInput(given, this.services, this.io, 'launch:env:create'); const current = await this.services.api.projects.get({ org, project }); const request = withoutRepositoryFlags( given, @@ -76,7 +80,12 @@ export class EnvironmentCreator { ? await this.fromUpload(request) : await this.fromRepository(request, gitScopeOf(org, current.repository)); - const input = await new EnvironmentBuilder(this.services).build(request, name, source, request.autoDeploy); + const input = await new EnvironmentBuilder(this.services, variableIo).build( + request, + name, + source, + request.autoDeploy, + ); const environment = await this.services.api.environments.create({ org, project, input }); diff --git a/src/environments/environment.errors.test.ts b/src/environments/environment.errors.test.ts index f4c418c8..9f318ab5 100644 --- a/src/environments/environment.errors.test.ts +++ b/src/environments/environment.errors.test.ts @@ -1,5 +1,8 @@ -import { LaunchApiError } from '../transport/errors'; -import { ENVIRONMENT_ERROR_MESSAGES } from './environment.errors'; +import { inspect } from 'util'; +import { gluedValue } from '../../test/support/glued-value'; +import { REDACTED } from '../core/redact'; +import { LaunchApiError, LaunchNetworkError } from '../transport/errors'; +import { ENVIRONMENT_ERROR_MESSAGES, asRedactedFailure } from './environment.errors'; const VARIABLE_CODES: Record = { 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.BYTE_SIZE_LIMIT_REACHED': @@ -23,3 +26,190 @@ describe('environment errors', () => { expect(error.message).not.toContain('never-printed-value'); }); }); + +function withCause(error: T, cause: unknown): T { + Object.defineProperty(error, 'cause', { value: cause, writable: true, configurable: true, enumerable: false }); + return error; +} + +function redact(error: unknown, value: string): unknown { + return asRedactedFailure(error, [{ key: 'A', value }], ENVIRONMENT_ERROR_MESSAGES); +} + +function surfacesOf(failure: unknown): string[] { + const error = failure as Error; + return [JSON.stringify(failure), String(failure), String(error.stack), inspect(failure, { depth: 5 })]; +} + +describe('asRedactedFailure for an error that is not a Launch error', () => { + it('keeps the class, the name and the frames of a TypeError and masks the value in message and stack', () => { + const value = gluedValue(); + const original = new TypeError(`Cannot read properties of ${value}`); + + const failure = redact(original, value) as TypeError; + + expect(failure).toBeInstanceOf(TypeError); + expect(failure).not.toBe(original); + expect(failure.name).toBe('TypeError'); + expect(failure.message).toBe(`Cannot read properties of ${REDACTED}`); + expect(failure.stack).toContain(`TypeError: Cannot read properties of ${REDACTED}`); + expect(failure.stack).toContain('environment.errors.test.ts'); + expect((failure.stack ?? '').split('\n').slice(1)).toEqual((original.stack ?? '').split('\n').slice(1)); + expect(failure.stack).not.toContain(value); + }); + + it('shows the value nowhere in the error, its stack, its cause chain or its own properties', () => { + const value = gluedValue(); + const nested = Object.assign(new RangeError(`nested ${value}`), { response: { data: value } }); + const cause = Object.assign(withCause(new Error(`cause ${value}`), nested), { config: { data: value } }); + const original = Object.assign(withCause(new TypeError(`top ${value}`), cause), { + body: value, + rawErrors: [value], + }); + + const failure = redact(original, value) as TypeError & { cause: Error & { cause: Error } }; + + expect(Object.keys(failure)).toEqual([]); + expect(Object.keys(failure.cause)).toEqual([]); + expect(failure.cause).toBeInstanceOf(Error); + expect(failure.cause.message).toBe(`cause ${REDACTED}`); + expect(failure.cause.cause).toBeInstanceOf(RangeError); + expect(failure.cause.cause.message).toBe(`nested ${REDACTED}`); + expect(failure.cause.cause.stack).toContain(`RangeError: nested ${REDACTED}`); + for (const surface of [ + ...surfacesOf(failure), + ...surfacesOf(failure.cause), + ...surfacesOf(failure.cause.cause), + ]) { + expect(surface).not.toContain(value); + } + expect(inspect(failure, { depth: 5 })).toContain(`nested ${REDACTED}`); + }); + + it('masks a cause that is text and drops a cause that is neither text nor an error', () => { + const value = gluedValue(); + + const text = redact(withCause(new Error('top'), `body was ${value}`), value) as { cause: unknown }; + const object = redact(withCause(new Error('top'), { data: value }), value) as { cause: unknown }; + const number = redact(withCause(new Error('top'), 7), value) as Error; + + expect(text.cause).toBe(`body was ${REDACTED}`); + expect(object.cause).toBeUndefined(); + expect(Object.prototype.hasOwnProperty.call(object, 'cause')).toBe(false); + expect(Object.prototype.hasOwnProperty.call(number, 'cause')).toBe(false); + expect(inspect(object, { depth: 5 })).not.toContain(value); + }); + + it('ends a cause chain that loops back on itself, without the value', () => { + const value = gluedValue(); + const first = new Error(`first ${value}`); + const second = withCause(new Error(`second ${value}`), first); + withCause(first, second); + + const failure = redact(first, value); + + for (const surface of surfacesOf(failure)) { + expect(surface).not.toContain(value); + } + expect(inspect(failure, { depth: 50 })).toContain(`second ${REDACTED}`); + }); + + it('keeps an own name a subclass set, masked and not enumerable, and builds a stack when there is none', () => { + class FetchFailure extends Error { + constructor(message: string) { + super(message); + this.name = 'FetchFailure'; + } + } + const value = gluedValue(); + const original = new FetchFailure(`failed for ${value}`); + Object.defineProperty(original, 'stack', { value: undefined, configurable: true }); + + const failure = redact(original, value) as FetchFailure; + + expect(failure).toBeInstanceOf(FetchFailure); + expect(failure.name).toBe('FetchFailure'); + expect(Object.keys(failure)).toEqual([]); + expect(failure.stack).toBe(`FetchFailure: failed for ${REDACTED}`); + expect(String(failure)).toBe(`FetchFailure: failed for ${REDACTED}`); + }); + + it('masks every secret value when there are several, in the message, the stack and the cause', () => { + const [first, second] = [gluedValue(), gluedValue()]; + const original = withCause(new TypeError(`${first} then ${second}`), new Error(`${second} and ${first}`)); + + const failure = asRedactedFailure( + original, + [ + { key: 'A', value: first }, + { key: 'B', value: second }, + ], + ENVIRONMENT_ERROR_MESSAGES, + ) as TypeError & { cause: Error }; + + expect(failure.message).toBe(`${REDACTED} then ${REDACTED}`); + expect(failure.cause.message).toBe(`${REDACTED} and ${REDACTED}`); + for (const surface of [...surfacesOf(failure), ...surfacesOf(failure.cause)]) { + expect(surface).not.toContain(first); + expect(surface).not.toContain(second); + } + }); +}); + +describe('asRedactedFailure for a network failure', () => { + it('keeps the class, the retryable flag and the frames, and a redacted cause instead of the raw HTTP error', () => { + const value = gluedValue(); + const raw = Object.assign(new Error(`socket hang up sending ${value}`), { + config: { data: value, headers: { authorization: value } }, + request: { body: value }, + response: { data: value }, + }); + const original = new LaunchNetworkError(`failed sending ${value}`, raw, true); + + const failure = redact(original, value) as LaunchNetworkError; + const cause = failure.cause as Error & Record; + + expect(failure).toBeInstanceOf(LaunchNetworkError); + expect(failure.name).toBe('LaunchNetworkError'); + expect(failure.message).toBe(`failed sending ${REDACTED}`); + expect(failure.retryable).toBe(true); + expect(failure.stack).toContain(`LaunchNetworkError: failed sending ${REDACTED}`); + expect(failure.stack).toContain('environment.errors.test.ts'); + expect(cause).toBeInstanceOf(Error); + expect(cause).not.toBe(raw); + expect(cause.message).toBe(`socket hang up sending ${REDACTED}`); + expect(cause.config).toBeUndefined(); + expect(cause.request).toBeUndefined(); + expect(cause.response).toBeUndefined(); + expect(Object.keys(cause)).toEqual([]); + for (const surface of [...surfacesOf(failure), ...surfacesOf(cause)]) { + expect(surface).not.toContain(value); + } + }); + + it('keeps a network failure with no cause without one', () => { + const failure = redact(new LaunchNetworkError('down', undefined, false), gluedValue()) as LaunchNetworkError; + + expect(failure).toBeInstanceOf(LaunchNetworkError); + expect(failure.cause).toBeUndefined(); + expect(failure.retryable).toBe(false); + }); +}); + +describe('asRedactedFailure for an API failure', () => { + it('keeps the frames of the original error, masks the value in them and never points at the rebuild', () => { + const value = gluedValue(); + const original = new LaunchApiError(400, [{ code: 'launch.UNKNOWN', message: `rejected ${value}` }]); + + const failure = redact(original, value) as LaunchApiError; + + expect(failure).toBeInstanceOf(LaunchApiError); + expect(failure).not.toBe(original); + expect(failure.stack).toContain(`LaunchApiError: rejected ${REDACTED}`); + expect(failure.stack).toContain('environment.errors.test.ts'); + expect(failure.stack).not.toContain('asRedactedFailure'); + expect((failure.stack ?? '').split('\n').slice(1)).toEqual((original.stack ?? '').split('\n').slice(1)); + expect(failure.stack).not.toContain(value); + expect(Object.keys(failure)).not.toContain('stack'); + }); +}); diff --git a/src/environments/environment.errors.ts b/src/environments/environment.errors.ts index 920c21ec..498f941e 100644 --- a/src/environments/environment.errors.ts +++ b/src/environments/environment.errors.ts @@ -1,4 +1,8 @@ +import { LaunchError } from '../core/errors'; +import { withoutValues } from '../core/redact'; +import { LaunchApiError, LaunchNetworkError } from '../transport/errors'; import type { ErrorMessages } from '../transport/errors'; +import type { EnvironmentVariableInput } from './types'; const CLI_BUG_MESSAGE = 'The update could not be sent correctly. This is a bug in the CLI.'; @@ -25,3 +29,101 @@ export const ENVIRONMENT_ERROR_MESSAGES: ErrorMessages = { }; export const DUPLICATE_NAME_CODE = 'launch.ENVIRONMENT.DUPLICATE_NAME'; + +const ENV_WRITE_ONLY_CODE_PREFIX = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS'; + +const SECRET_KEY_CONFLICT_MESSAGE = 'A secret or a variable with that key already exists in this environment.'; +const SECRET_MULTILINE_MESSAGE = 'A secret value must be a single line.'; + +export const CREATE_WITH_SECRETS_MESSAGES: ErrorMessages = { + [`${ENV_WRITE_ONLY_CODE_PREFIX}.KEY.CONFLICT`]: SECRET_KEY_CONFLICT_MESSAGE, + [`${ENV_WRITE_ONLY_CODE_PREFIX}.VALUE.MULTILINE`]: SECRET_MULTILINE_MESSAGE, + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.MAX_COUNT_REACHED': + 'This environment has reached its limit of 128 variables and secrets together.', + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.BYTE_SIZE_LIMIT_REACHED': + 'The variables and secrets together are larger than the 14 KB Launch allows. ' + + 'Remove some of them or shorten their values.', +}; + +export const ENVIRONMENT_CREATE_WITH_SECRETS_MESSAGES: ErrorMessages = { + ...ENVIRONMENT_ERROR_MESSAGES, + ...CREATE_WITH_SECRETS_MESSAGES, +}; + +const MAX_CAUSE_DEPTH = 8; + +function hidden(target: object, key: string, value: unknown): void { + Object.defineProperty(target, key, { value, writable: true, configurable: true, enumerable: false }); +} + +function redactedStack(error: Error, values: string[]): string { + return withoutValues(typeof error.stack === 'string' ? error.stack : `${error.name}: ${error.message}`, values); +} + +function redactedCause(error: Error, values: string[], depth: number): unknown { + const { cause } = error as { cause?: unknown }; + + if (typeof cause === 'string') { + return withoutValues(cause, values); + } + + return cause instanceof Error && depth < MAX_CAUSE_DEPTH ? redactedCopy(cause, values, depth) : undefined; +} + +function nativeErrorLike(error: Error): Error { + return Object.setPrototypeOf(new Error(), Object.getPrototypeOf(error)); +} + +function redactedCopy(error: Error, values: string[], depth = 1): Error { + const copy = nativeErrorLike(error); + const cause = redactedCause(error, values, depth + 1); + + hidden(copy, 'message', withoutValues(String(error.message), values)); + hidden(copy, 'stack', redactedStack(error, values)); + + if (Object.prototype.hasOwnProperty.call(error, 'name')) { + hidden(copy, 'name', withoutValues(String(error.name), values)); + } + + if (cause !== undefined) { + hidden(copy, 'cause', cause); + } + + return copy; +} + +export function asRedactedFailure( + error: unknown, + secrets: EnvironmentVariableInput[], + messages: ErrorMessages, +): unknown { + const values = secrets.map(({ value }) => value); + + if (error instanceof LaunchApiError) { + const entries = error.errors.map((entry) => + entry.message === undefined ? entry : { ...entry, message: withoutValues(entry.message, values) }, + ); + + const rebuilt = new LaunchApiError(error.status, entries, messages); + hidden(rebuilt, 'stack', redactedStack(error, values)); + + return rebuilt; + } + + if (error instanceof LaunchNetworkError) { + const network = new LaunchNetworkError( + withoutValues(error.message, values), + redactedCause(error, values, 1), + error.retryable, + ); + hidden(network, 'stack', redactedStack(error, values)); + + return network; + } + + if (error instanceof LaunchError) { + return error; + } + + return error instanceof Error ? redactedCopy(error, values) : error; +} diff --git a/src/environments/environments.api.test.ts b/src/environments/environments.api.test.ts index 8ca0352e..84a1b010 100644 --- a/src/environments/environments.api.test.ts +++ b/src/environments/environments.api.test.ts @@ -1,9 +1,13 @@ import { randomBytes } from 'node:crypto'; import { EXIT_USAGE, MAX_PAGES } from '../core/constants'; -import { LaunchApiError } from '../transport/errors'; +import { UsageError } from '../core/errors'; +import { REDACTED } from '../core/redact'; +import { gluedValue } from '../../test/support/glued-value'; +import { LaunchApiError, LaunchNetworkError } from '../transport/errors'; +import type { ApiErrorEntry, ErrorMessages } from '../transport/errors'; import type { RestApiClient, RestRequest } from '../transport/rest-client'; -import { ENVIRONMENT_ERROR_MESSAGES } from './environment.errors'; +import { ENVIRONMENT_CREATE_WITH_SECRETS_MESSAGES, ENVIRONMENT_ERROR_MESSAGES } from './environment.errors'; import type { EnvironmentsPage } from './environments.api'; import { ENVIRONMENT_SCAN_PAGE_SIZE, EnvironmentScanLimitError, EnvironmentsApi } from './environments.api'; @@ -474,3 +478,210 @@ describe('EnvironmentsApi', () => { await expect(new EnvironmentsApi(client).commits({ ...SCOPE, environment: ENVIRONMENT })).rejects.toBe(failure); }); }); + +const SECRETS_NAMESPACE = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS'; +const VARIABLES_NAMESPACE = 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES'; + +function createInput(secrets?: { key: string; value: string }[]) { + return { + name: 'staging', + outputDirectory: './out', + frameworkPreset: 'OTHER' as const, + environmentVariables: [], + ...(secrets === undefined ? {} : { secrets }), + }; +} + +function rejectingWith(fail: (messages: ErrorMessages) => unknown) { + return { + request: async (_req: RestRequest, messages: ErrorMessages) => { + throw fail(messages); + }, + } as unknown as RestApiClient; +} + +function rejectedWithCode(code: string, status = 400, message = 'raw') { + return rejectingWith((messages) => new LaunchApiError(status, [{ code, message }], messages)); +} + +describe('EnvironmentsApi create with secrets', () => { + const SECRETS = [{ key: 'A', value: gluedValue() }]; + + it.each([ + [`${SECRETS_NAMESPACE}.KEY.CONFLICT`, 409, 'A secret or a variable with that key already exists in this environment.'], + [`${SECRETS_NAMESPACE}.VALUE.MULTILINE`, 400, 'A secret value must be a single line.'], + ])('words %s with the secrets wording when the request carried secrets', async (code, status, message) => { + const failure = await new EnvironmentsApi(rejectedWithCode(code, status)) + .create({ ...SCOPE, input: createInput(SECRETS) }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchApiError); + expect((failure as LaunchApiError).message).toBe(message); + expect((failure as LaunchApiError).status).toBe(status); + expect((failure as LaunchApiError).code).toBe(code); + }); + + it.each([ + [`${VARIABLES_NAMESPACE}.MAX_COUNT_REACHED`, '128 variables and secrets together'], + [`${VARIABLES_NAMESPACE}.BYTE_SIZE_LIMIT_REACHED`, '14 KB'], + ])('words %s as a limit on variables and secrets together, not the variables-only text', async (code, fragment) => { + const failure = await new EnvironmentsApi(rejectedWithCode(code)) + .create({ ...SCOPE, input: createInput(SECRETS) }) + .catch((error: unknown) => error); + + const message = (failure as LaunchApiError).message; + + expect(message).toContain(fragment); + expect(message).toContain('variables and secrets'); + expect(message).not.toBe(ENVIRONMENT_ERROR_MESSAGES[code]); + }); + + it.each([[undefined], [[]]])( + 'keeps the variables-only wording for a request with secrets of %p', + async (secrets) => { + const code = `${VARIABLES_NAMESPACE}.MAX_COUNT_REACHED`; + + const failure = await new EnvironmentsApi(rejectedWithCode(code)) + .create({ ...SCOPE, input: createInput(secrets) }) + .catch((error: unknown) => error); + + expect((failure as LaunchApiError).message).toBe(ENVIRONMENT_ERROR_MESSAGES[code]); + }, + ); + + it('does not use the secrets wording for a key conflict when the request carried no secrets', async () => { + const failure = await new EnvironmentsApi(rejectedWithCode(`${SECRETS_NAMESPACE}.KEY.CONFLICT`, 409, 'raw conflict')) + .create({ ...SCOPE, input: createInput() }) + .catch((error: unknown) => error); + + expect((failure as LaunchApiError).message).toBe('raw conflict'); + }); + + it('sends the secrets in the body and the secrets wording as the error messages', async () => { + const { client, requests, messages } = fakeRestClient({ environment: { uid: ENVIRONMENT, name: 'staging' } }); + const input = createInput(SECRETS); + + await new EnvironmentsApi(client).create({ ...SCOPE, input }); + + expect(requests[0].body).toBe(input); + expect(messages[0]).toBe(ENVIRONMENT_CREATE_WITH_SECRETS_MESSAGES); + }); + + it('masks the value in an API message that echoes it, keeping the status, the code and the entry', async () => { + const value = ` ${gluedValue()} `; + const failure = await new EnvironmentsApi( + rejectingWith((messages) => new LaunchApiError(400, [{ code: 'launch.SOMETHING.ELSE', message: `bad ${value} or ${value.trim()}` }], messages)), + ) + .create({ ...SCOPE, input: createInput([{ key: 'A', value }]) }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchApiError); + expect((failure as LaunchApiError).message).toBe(`bad ${REDACTED} or ${REDACTED}`); + expect((failure as LaunchApiError).status).toBe(400); + expect((failure as LaunchApiError).code).toBe('launch.SOMETHING.ELSE'); + expect(JSON.stringify((failure as LaunchApiError).rawErrors)).not.toContain(value.trim()); + }); + + it('leaves an API entry with no message as it is', async () => { + const entries: ApiErrorEntry[] = [{ code: 'launch.SOMETHING.ELSE' }]; + const failure = await new EnvironmentsApi(rejectingWith((messages) => new LaunchApiError(400, entries, messages))) + .create({ ...SCOPE, input: createInput(SECRETS) }) + .catch((error: unknown) => error); + + expect((failure as LaunchApiError).errors).toEqual(entries); + }); + + it('masks the value in a network failure, keeping its type, retryable flag and a redacted cause', async () => { + const value = ` ${gluedValue()} `; + const cause = new Error(`request body ${value}`); + const failure = await new EnvironmentsApi( + rejectingWith(() => new LaunchNetworkError(`failed sending ${value} and ${value.trim()}`, cause, true)), + ) + .create({ ...SCOPE, input: createInput([{ key: 'A', value }]) }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchNetworkError); + expect((failure as LaunchNetworkError).message).toBe(`failed sending ${REDACTED} and ${REDACTED}`); + expect((failure as LaunchNetworkError).retryable).toBe(true); + expect((failure as LaunchNetworkError).cause).not.toBe(cause); + expect(((failure as LaunchNetworkError).cause as Error).message).toBe(`request body ${REDACTED}`); + }); + + it('keeps a network failure that is not retryable not retryable', async () => { + const failure = await new EnvironmentsApi(rejectingWith(() => new LaunchNetworkError('down', undefined, false))) + .create({ ...SCOPE, input: createInput(SECRETS) }) + .catch((error: unknown) => error); + + expect((failure as LaunchNetworkError).retryable).toBe(false); + }); + + it('masks the value in a plain error, so a debug print of the error cannot show it', async () => { + const value = ` ${gluedValue()} `; + const failure = await new EnvironmentsApi(rejectingWith(() => new Error(`boom ${value} then ${value.trim()}`))) + .create({ ...SCOPE, input: createInput([{ key: 'A', value }]) }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toBe(`boom ${REDACTED} then ${REDACTED}`); + }); + + it('masks every secret value when there are several', async () => { + const [first, second] = [gluedValue(), gluedValue()]; + const failure = await new EnvironmentsApi(rejectingWith(() => new Error(`${first} and ${second}`))) + .create({ + ...SCOPE, + input: createInput([ + { key: 'A', value: first }, + { key: 'B', value: second }, + ]), + }) + .catch((error: unknown) => error); + + expect((failure as Error).message).toBe(`${REDACTED} and ${REDACTED}`); + }); + + it('masks the whole of every value when one secret value contains another, in a plain error and an API message', async () => { + const short = gluedValue(); + const tail = gluedValue(); + const long = `${short}${tail}`; + const input = createInput([ + { key: 'A', value: short }, + { key: 'B', value: long }, + ]); + + const plain = await new EnvironmentsApi(rejectingWith(() => new Error(`boom ${long} then ${short}`))) + .create({ ...SCOPE, input }) + .catch((error: unknown) => error); + const api = await new EnvironmentsApi( + rejectingWith((messages) => new LaunchApiError(400, [{ code: 'launch.X', message: `bad ${long}` }], messages)), + ) + .create({ ...SCOPE, input }) + .catch((error: unknown) => error); + + expect((plain as Error).message).toBe(`boom ${REDACTED} then ${REDACTED}`); + expect((api as LaunchApiError).message).toBe(`bad ${REDACTED}`); + expect(`${(plain as Error).message}${(api as Error).message}`).not.toContain(tail); + }); + + it('lets a CLI error that is not an API or network failure through as it is', async () => { + const own = new UsageError('not for the API'); + + await expect( + new EnvironmentsApi(rejectingWith(() => own)).create({ ...SCOPE, input: createInput(SECRETS) }), + ).rejects.toBe(own); + }); + + it('lets a thrown value that is not an error through as it is', async () => { + await expect( + new EnvironmentsApi(rejectingWith(() => 'plain text')).create({ ...SCOPE, input: createInput(SECRETS) }), + ).rejects.toBe('plain text'); + }); + + it('does not touch an error when the request carried no secret', async () => { + const failure = new Error('boom'); + + await expect(new EnvironmentsApi(rejectingWith(() => failure)).create({ ...SCOPE, input: createInput() })).rejects.toBe( + failure, + ); + }); +}); diff --git a/src/environments/environments.api.ts b/src/environments/environments.api.ts index d1285b64..c0dc4f3c 100644 --- a/src/environments/environments.api.ts +++ b/src/environments/environments.api.ts @@ -2,8 +2,14 @@ import { scanPages } from '../core/paging'; import { UsageError } from '../core/errors'; import { assertArray, assertPage, hasUid, malformed, unwrap } from '../transport/envelope'; import { LaunchApiError } from '../transport/errors'; +import type { ErrorMessages } from '../transport/errors'; import type { RestApiClient, RestRequest } from '../transport/rest-client'; -import { DUPLICATE_NAME_CODE, ENVIRONMENT_ERROR_MESSAGES } from './environment.errors'; +import { + DUPLICATE_NAME_CODE, + ENVIRONMENT_CREATE_WITH_SECRETS_MESSAGES, + ENVIRONMENT_ERROR_MESSAGES, + asRedactedFailure, +} from './environment.errors'; import type { Commit, CreateEnvironmentInput, @@ -77,8 +83,8 @@ function asTakenName(error: unknown, renaming: boolean): unknown { export class EnvironmentsApi { constructor(private readonly client: RestApiClient) {} - private request(req: RestRequest): Promise { - return this.client.request(req, ENVIRONMENT_ERROR_MESSAGES); + private request(req: RestRequest, messages: ErrorMessages = ENVIRONMENT_ERROR_MESSAGES): Promise { + return this.client.request(req, messages); } async list(params: ListEnvironmentsParams): Promise { @@ -116,12 +122,19 @@ export class EnvironmentsApi { } async create(params: CreateEnvironmentParams): Promise { - const response = await this.request({ - method: 'POST', - path: `/projects/${params.project}/environments`, - orgUid: params.org, - projectUid: params.project, - body: params.input, + const secrets = params.input.secrets ?? []; + const messages = secrets.length > 0 ? ENVIRONMENT_CREATE_WITH_SECRETS_MESSAGES : ENVIRONMENT_ERROR_MESSAGES; + const response = await this.request( + { + method: 'POST', + path: `/projects/${params.project}/environments`, + orgUid: params.org, + projectUid: params.project, + body: params.input, + }, + messages, + ).catch((error: unknown) => { + throw secrets.length > 0 ? asRedactedFailure(error, secrets, messages) : error; }); const environment = unwrap(response, 'environment', 'environment response'); diff --git a/src/environments/types.ts b/src/environments/types.ts index f7a2ae6d..b4ba2537 100644 --- a/src/environments/types.ts +++ b/src/environments/types.ts @@ -93,6 +93,7 @@ export interface CreateEnvironmentInput { serverCommand?: string; frameworkPreset: FrameworkPreset; environmentVariables: EnvironmentVariableInput[]; + secrets?: EnvironmentVariableInput[]; isStreamingEnabled?: boolean; autoDeployOnPush?: boolean; isContentstackAuthenticationEnabled?: boolean; @@ -110,6 +111,7 @@ export interface EnvironmentRequest { dataDir?: string; vars?: string[]; envFiles?: string[]; + secrets?: string[]; fromStack?: boolean; alias?: string; framework?: FrameworkPreset; diff --git a/src/projects/project.create.test.ts b/src/projects/project.create.test.ts index d2fa66c0..f0f3626a 100644 --- a/src/projects/project.create.test.ts +++ b/src/projects/project.create.test.ts @@ -6,6 +6,10 @@ import { tmpdir } from 'node:os'; import { basename, join } from 'node:path'; import { CancelledError, MissingInputError, SessionExpiredError, UsageError } from '../core/errors'; +import { gluedValue } from '../../test/support/glued-value'; +import { emptyValueError, secretOverlapError, SECRETS_WITHOUT_TERMINAL_MESSAGE } from '../secrets/secret.rules'; +import { SecretInputTimeoutError } from '../secrets/secrets.errors'; +import type { SecretIntakeIo } from '../variables/variable.secrets'; import type { UxLike } from '../core/prompt'; import type { ServiceContext } from '../core/service-context'; import { DeploymentUnsuccessfulError } from '../deployments/deployment.errors'; @@ -114,9 +118,10 @@ interface Scenario { environmentFails?: Error; latestFails?: Error; createdProject?: unknown; + io?: SecretIntakeIo; } -const VARIABLES_PROMPT = 'Add environment variables'; +const VARIABLES_PROMPT = 'Add variables from'; const SKIP_VARIABLES = 'Skip adding environment variables'; const CONNECT_URL = 'https://dev11-app.csnonprod.com/#!/launch/settings/connected-accounts'; const CONNECTION_IDENTIFIED = 'info: GitHub connection identified!'; @@ -308,7 +313,7 @@ function harness(scenario: Scenario = {}) { }; return { - creator: new ProjectCreator(services, advancingTiming(timeline)), + creator: new ProjectCreator(services, advancingTiming(timeline), scenario.io), opened, timeline, printed, @@ -2149,3 +2154,168 @@ describe('ProjectCreator when the project name is already taken', () => { expect(printed).not.toContain('error: New project creation failed!'); }); }); + +describe('ProjectCreator with --secret', () => { + function intake(options: { piped?: string | Promise; files?: Record } = {}) { + const stdinReads: number[] = []; + const closed: number[] = []; + const io: SecretIntakeIo = { + secrets: { + readStdin: async () => { + stdinReads.push(1); + return options.piped ?? ''; + }, + closeStdin: () => { + closed.push(1); + }, + stdinTimeoutMs: 20, + }, + variables: { + readFile: async (path: string) => { + if (!(path in (options.files ?? {}))) { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); + } + + return (options.files ?? {})[path]; + }, + exists: () => false, + readStdin: async () => { + throw new Error('the base stdin must not be read'); + }, + }, + }; + + return { io, stdinReads, closed }; + } + + function nothingSent(run: ReturnType): void { + expect(run.created).toEqual([]); + expect(run.gitCalls).toEqual([]); + expect(run.calls.namespaces).toEqual([]); + expect(run.calls.signedUploadUrl).toEqual([]); + } + + beforeEach(() => { + dataDir = mkdtempSync(join(tmpdir(), 'launch-create-')); + writeFileSync(join(dataDir, 'index.html'), SITE_PAGE); + cloneOf('my-org/my-repo'); + }); + + afterEach(() => { + rmSync(dataDir, { recursive: true, force: true }); + }); + + it('puts the one piped secret in environment.secrets next to an empty environmentVariables, for a GitHub project', async () => { + const value = gluedValue(); + const { io } = intake({ piped: `${value}\n` }); + const { creator, created, printed } = harness({ io }); + + await creator.create(gitRequest({ secrets: ['A'] })); + + expect(bodyOf(created).environment).toMatchObject({ + environmentVariables: [], + secrets: [{ key: 'A', value }], + }); + expect(printed.join('\n')).not.toContain(value); + }); + + it('puts the secret in the environment of a FileUpload project beside the upload uid', async () => { + const value = gluedValue(); + const { io } = intake({ piped: value }); + const { creator, created } = harness({ io }); + + await creator.create(uploadRequest({ secrets: ['A'] })); + + expect(bodyOf(created).environment).toMatchObject({ + uploadUid: 'upload-uid', + secrets: [{ key: 'A', value }], + }); + expect((bodyOf(created).environment as Record).gitBranch).toBeUndefined(); + }); + + it('sends the dotenv keys as variables and the secret apart', async () => { + const value = gluedValue(); + const { io } = intake({ piped: value, files: { 'staging.env': 'API_URL=from-file\n' } }); + const { creator, created } = harness({ io }); + + await creator.create(gitRequest({ secrets: ['A'], envFiles: ['staging.env'] })); + + expect(bodyOf(created).environment).toMatchObject({ + environmentVariables: [{ key: 'API_URL', value: 'from-file' }], + secrets: [{ key: 'A', value }], + }); + }); + + it('refuses more than one secret without a terminal before the connection check, any lookup or upload', async () => { + const { io, stdinReads } = intake({ piped: gluedValue() }); + const run = harness({ io }); + + await expect(run.creator.create(gitRequest({ secrets: ['A', 'B'] }))).rejects.toThrow( + SECRETS_WITHOUT_TERMINAL_MESSAGE, + ); + nothingSent(run); + expect(stdinReads).toEqual([]); + }); + + it('refuses it before zipping a FileUpload folder too', async () => { + const { io } = intake({ piped: gluedValue() }); + const run = harness({ io }); + + await expect(run.creator.create(uploadRequest({ secrets: ['A', 'B'] }))).rejects.toThrow( + SECRETS_WITHOUT_TERMINAL_MESSAGE, + ); + nothingSent(run); + }); + + it('refuses a secret that is also a key of the --dotenv file before any request, reading no stdin', async () => { + const { io, stdinReads } = intake({ piped: gluedValue(), files: { 'staging.env': 'A=1\n' } }); + const run = harness({ io }); + + await expect(run.creator.create(gitRequest({ secrets: ['A'], envFiles: ['staging.env'] }))).rejects.toThrow( + secretOverlapError('A', '--dotenv').message, + ); + nothingSent(run); + expect(stdinReads).toEqual([]); + }); + + it('refuses an empty piped value before any request', async () => { + const { io } = intake({ piped: '' }); + const run = harness({ io }); + + await expect(run.creator.create(gitRequest({ secrets: ['A'] }))).rejects.toThrow(emptyValueError('A').message); + nothingSent(run); + }); + + it('ends with the timeout error, closing stdin, before any request', async () => { + const { io, closed } = intake({ piped: new Promise(() => undefined) }); + const run = harness({ io }); + + const error: unknown = await run.creator.create(gitRequest({ secrets: ['A'] })).catch((failure: unknown) => failure); + + expect(error).toBeInstanceOf(SecretInputTimeoutError); + expect((error as Error).message).toContain('csdx launch:projects:create --secret '); + expect((error as Error).message).not.toContain('launch:secrets'); + expect(closed).toEqual([1]); + nothingSent(run); + }); + + it('asks the masked prompt last on a terminal, after Contentstack Authentication, and never the variables checklist', async () => { + const value = gluedValue(); + const { creator, created, everyPrompt } = harness({ isTTY: true, answers: [value] }); + + await creator.create(gitRequest({ secrets: ['A'] })); + + expect(everyPrompt).toEqual(['Value for A']); + expect(bodyOf(created).environment).toMatchObject({ secrets: [{ key: 'A', value }] }); + }); + + it('sends no secrets property and reads no stdin when none was passed', async () => { + const { io, stdinReads } = intake({ piped: gluedValue() }); + const { creator, created } = harness({ io }); + + await creator.create(gitRequest()); + + expect(bodyOf(created).environment).not.toHaveProperty('secrets'); + expect(stdinReads).toEqual([]); + }); +}); diff --git a/src/projects/project.create.ts b/src/projects/project.create.ts index 21514b20..1f1ac168 100644 --- a/src/projects/project.create.ts +++ b/src/projects/project.create.ts @@ -16,6 +16,8 @@ import type { WatchTiming } from '../deployments/deployment.watcher'; import { EnvironmentBuilder } from '../environments/environment.builder'; import { ENVIRONMENT_NAME_MAX_LENGTH } from '../environments/environment.inputs'; import { withoutRepositoryFlags } from '../environments/environment.rules'; +import { DEFAULT_SECRET_INTAKE_IO, prepareSecretInput } from '../variables/variable.secrets'; +import type { SecretIntakeIo } from '../variables/variable.secrets'; import { repositoryLabel } from '../git/git.presenter'; import { repositorySearchTerm } from '../git/git.prompt'; import type { LocalGitHubRepository } from '../git/local-repository'; @@ -55,21 +57,21 @@ function shownPath(path: string): string { export class ProjectCreator { private readonly source: ProjectSource; - private readonly environments: EnvironmentBuilder; private readonly follower: FirstDeploymentFollower; constructor( private readonly services: ServiceContext, private readonly timing: WatchTiming, + private readonly io: SecretIntakeIo = DEFAULT_SECRET_INTAKE_IO, ) { this.source = new ProjectSource(services); - this.environments = new EnvironmentBuilder(services); this.follower = new FirstDeploymentFollower(services, this.timing); } async create(request: CreateRequest): Promise { this.refuseLinkedFolder(request); + const variableIo = await prepareSecretInput(request, this.services, this.io, 'launch:projects:create'); const choice = await this.projectType(request); this.warnGitFlagsOffGitHub(request, choice); @@ -88,7 +90,12 @@ export class ProjectCreator { ); const source = upload ?? (await this.source.selectGitSource(request, local as LocalGitHubRepository, namespace as string)); - const environment = await this.environments.build(request, envName, source, autoDeploy); + const environment = await new EnvironmentBuilder(this.services, variableIo).build( + request, + envName, + source, + autoDeploy, + ); const input: CreateProjectInput = { name, diff --git a/src/projects/project.errors.ts b/src/projects/project.errors.ts index 0751abb4..a87f738b 100644 --- a/src/projects/project.errors.ts +++ b/src/projects/project.errors.ts @@ -2,6 +2,7 @@ import { EXIT_RUNTIME } from '../core/constants'; import type { ExitCode } from '../core/errors'; import { LaunchError } from '../core/errors'; import type { ErrorMessages } from '../transport/errors'; +import { CREATE_WITH_SECRETS_MESSAGES } from '../environments/environment.errors'; import { GIT_PROVIDER_ERROR_MESSAGES } from '../git/git.errors'; /** @@ -48,3 +49,8 @@ export const PROJECT_ERROR_MESSAGES: ErrorMessages = { 'launch.PROJECT.UPLOADED_FILE_NOT_FOUND_ERROR': 'Your uploaded project files could not be found; the upload may have expired. Run the command again.', }; + +export const PROJECT_CREATE_WITH_SECRETS_MESSAGES: ErrorMessages = { + ...PROJECT_ERROR_MESSAGES, + ...CREATE_WITH_SECRETS_MESSAGES, +}; diff --git a/src/projects/projects.api.test.ts b/src/projects/projects.api.test.ts index 15ac1884..0fd9c396 100644 --- a/src/projects/projects.api.test.ts +++ b/src/projects/projects.api.test.ts @@ -1,6 +1,10 @@ import { EXIT_USAGE, MAX_PAGES } from '../core/constants'; import { PROJECT_SCAN_PAGE_SIZE } from './projects.api'; -import { LaunchApiError, parseErrorEnvelope } from '../transport/errors'; +import { REDACTED } from '../core/redact'; +import { gluedValue } from '../../test/support/glued-value'; +import { CREATE_WITH_SECRETS_MESSAGES, ENVIRONMENT_CREATE_WITH_SECRETS_MESSAGES } from '../environments/environment.errors'; +import { LaunchApiError, LaunchNetworkError, parseErrorEnvelope } from '../transport/errors'; +import type { ErrorMessages } from '../transport/errors'; import type { RestApiClient, RestRequest } from '../transport/rest-client'; import type { ProjectsPage } from './types'; import { buildApi } from '../resources'; @@ -587,3 +591,120 @@ describe('ProjectsApi create and detection endpoints', () => { await expect(new ProjectsApi(client).fileFramework({ org: 'org1', uploadUid: 'u' })).resolves.toEqual({}); }); }); + +describe('ProjectsApi create with secrets', () => { + const SECRETS = [{ key: 'A', value: gluedValue() }]; + + function createInput(secrets?: { key: string; value: string }[]) { + return { + name: 'sample-project', + projectType: 'FILEUPLOAD' as const, + environment: { + name: 'Default', + outputDirectory: './', + frameworkPreset: 'OTHER' as const, + environmentVariables: [], + ...(secrets === undefined ? {} : { secrets }), + }, + fileUpload: { uploadUid: 'upload-uid' }, + }; + } + + function rejectingWith(fail: (messages: ErrorMessages) => unknown) { + return { + request: async (_req: RestRequest, messages: ErrorMessages) => { + throw fail(messages); + }, + } as unknown as RestApiClient; + } + + it.each(Object.entries(CREATE_WITH_SECRETS_MESSAGES))( + 'words %s as the environment create does when the environment carried secrets', + async (code, message) => { + const failure = await new ProjectsApi( + rejectingWith((messages) => new LaunchApiError(400, [{ code, message: 'raw' }], messages)), + ) + .create({ org: 'org1', input: createInput(SECRETS) }) + .catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(LaunchApiError); + expect((failure as LaunchApiError).message).toBe(message); + expect(ENVIRONMENT_CREATE_WITH_SECRETS_MESSAGES[code]).toBe(message); + }, + ); + + it('sends the project messages with the secrets wording on top when the environment carried secrets', async () => { + const messages: unknown[] = []; + const client = { + request: async (_req: RestRequest, errorMessages: unknown) => { + messages.push(errorMessages); + return { project: { uid: 'p1' } }; + }, + } as unknown as RestApiClient; + + await new ProjectsApi(client).create({ org: 'org1', input: createInput(SECRETS) }); + + expect(messages[0]).toEqual({ ...PROJECT_ERROR_MESSAGES, ...CREATE_WITH_SECRETS_MESSAGES }); + }); + + it.each([[undefined], [[]]])('keeps the project messages untouched for secrets of %p', async (secrets) => { + const messages: unknown[] = []; + const client = { + request: async (_req: RestRequest, errorMessages: unknown) => { + messages.push(errorMessages); + return { project: { uid: 'p1' } }; + }, + } as unknown as RestApiClient; + + await new ProjectsApi(client).create({ org: 'org1', input: createInput(secrets) }); + + expect(messages[0]).toBe(PROJECT_ERROR_MESSAGES); + }); + + it('masks the secret values in an error that echoes them, and in a network failure, keeping their types', async () => { + const value = gluedValue(); + const input = createInput([{ key: 'A', value }]); + + const api = await new ProjectsApi( + rejectingWith((messages) => new LaunchApiError(400, [{ code: 'launch.X', message: `bad ${value}` }], messages)), + ) + .create({ org: 'org1', input }) + .catch((error: unknown) => error); + const network = await new ProjectsApi(rejectingWith(() => new LaunchNetworkError(`sent ${value}`, undefined, true))) + .create({ org: 'org1', input }) + .catch((error: unknown) => error); + + expect(api).toBeInstanceOf(LaunchApiError); + expect((api as LaunchApiError).message).toBe(`bad ${REDACTED}`); + expect(network).toBeInstanceOf(LaunchNetworkError); + expect((network as LaunchNetworkError).message).toBe(`sent ${REDACTED}`); + expect((network as LaunchNetworkError).retryable).toBe(true); + }); + + it('masks the whole of every value when one secret value contains another', async () => { + const short = gluedValue(); + const tail = gluedValue(); + const long = `${short}${tail}`; + const input = createInput([ + { key: 'A', value: short }, + { key: 'B', value: long }, + ]); + + const failure = await new ProjectsApi( + rejectingWith((messages) => new LaunchApiError(400, [{ code: 'launch.X', message: `bad ${long} / ${short}` }], messages)), + ) + .create({ org: 'org1', input }) + .catch((error: unknown) => error); + + expect((failure as LaunchApiError).message).toBe(`bad ${REDACTED} / ${REDACTED}`); + expect((failure as LaunchApiError).message).not.toContain(tail); + }); + + it('does not touch an error when the environment carried no secret', async () => { + const failure = new Error('boom'); + + await expect( + new ProjectsApi(rejectingWith(() => failure)).create({ org: 'org1', input: createInput() }), + ).rejects.toBe(failure); + }); +}); diff --git a/src/projects/projects.api.ts b/src/projects/projects.api.ts index 94b5ea26..4a1387a5 100644 --- a/src/projects/projects.api.ts +++ b/src/projects/projects.api.ts @@ -2,9 +2,11 @@ import { scanPages } from '../core/paging'; import { UsageError } from '../core/errors'; import { isRecord } from '../core/values'; import { assertPage, hasUid, malformed, unwrap } from '../transport/envelope'; +import type { ErrorMessages } from '../transport/errors'; import type { RestApiClient, RestRequest } from '../transport/rest-client'; import type { DetectedFramework } from '../environments/types'; -import { PROJECT_ERROR_MESSAGES } from './project.errors'; +import { asRedactedFailure } from '../environments/environment.errors'; +import { PROJECT_CREATE_WITH_SECRETS_MESSAGES, PROJECT_ERROR_MESSAGES } from './project.errors'; import type { CreateProjectInput, IdentifiedProject, @@ -87,8 +89,8 @@ export class ProjectScanLimitError extends UsageError { export class ProjectsApi { constructor(private readonly client: RestApiClient) {} - private request(req: RestRequest): Promise { - return this.client.request(req, PROJECT_ERROR_MESSAGES); + private request(req: RestRequest, messages: ErrorMessages = PROJECT_ERROR_MESSAGES): Promise { + return this.client.request(req, messages); } async list(params: ListProjectsParams): Promise { @@ -137,11 +139,18 @@ export class ProjectsApi { } async create(params: CreateProjectParams): Promise { - const response = await this.request({ - method: 'POST', - path: '/projects', - orgUid: params.org, - body: params.input, + const secrets = params.input.environment.secrets ?? []; + const messages = secrets.length > 0 ? PROJECT_CREATE_WITH_SECRETS_MESSAGES : PROJECT_ERROR_MESSAGES; + const response = await this.request( + { + method: 'POST', + path: '/projects', + orgUid: params.org, + body: params.input, + }, + messages, + ).catch((error: unknown) => { + throw secrets.length > 0 ? asRedactedFailure(error, secrets, messages) : error; }); const project = unwrap(response, 'project', 'project response'); diff --git a/src/variables/variable.chooser.ts b/src/variables/variable.chooser.ts index 0cb488f1..b2225274 100644 --- a/src/variables/variable.chooser.ts +++ b/src/variables/variable.chooser.ts @@ -5,7 +5,15 @@ import { askChoices, askText } from '../core/prompt'; import { renderTable } from '../core/render'; import type { ServiceContext } from '../core/service-context'; import type { EnvironmentVariableInput } from '../environments/types'; +import { + PROMPT_KEY_WORDING, + assertCreateSecretKeys, + chosenDotenvKeyError, + chosenVariableError, + noSecretKeysEnteredError, +} from '../secrets/secret.rules'; import { detectEnvFile, readEnvFiles } from './variable.files'; +import type { EnvFileSource } from './variable.files'; import { mergeSources } from './variable.merge'; import type { MergedVariables, VariableSource } from './variable.merge'; import { parseAssignment, splitLine } from './variable.parse'; @@ -18,22 +26,30 @@ import { completeValues } from './variable.values'; export interface ChooserPrompt { message: string; skippable: boolean; + secrets?: boolean; +} + +export interface ChosenSources { + merged: MergedVariables; + secretKeys: string[]; } export const STACK_CHOICE = 'Import variables from a stack'; export const FILE_CHOICE = 'Import variables from a dotenv file'; export const TYPED_CHOICE = 'Manually add custom variables'; +export const WRITE_ONLY_CHOICE = 'Add secrets (write-only)'; export const SKIP_CHOICE = 'Skip adding environment variables'; const FILE_QUESTION = 'Path to the dotenv file'; export const TYPED_QUESTION = 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")'; +export const SECRET_KEYS_QUESTION = 'Enter secret key names only, separated by spaces, no values (Ex: KEY1 KEY2)'; const TYPED_LABEL = 'manual entry'; async function askForFile( detected: string | undefined, services: ServiceContext, io: VariableIo, -): Promise { +): Promise { const path = await askText(services.ux, FILE_QUESTION, detected); const sources = await readEnvFiles([path], io); @@ -51,19 +67,49 @@ async function askForTyped(services: ServiceContext, io: VariableIo): Promise { + const line = await askText(services.ux, SECRET_KEYS_QUESTION); + const keys = line.split(/[\s,]+/).filter((key) => key !== ''); + + if (keys.length === 0) { + throw noSecretKeysEnteredError(); + } + + assertCreateSecretKeys(keys, PROMPT_KEY_WORDING); + + const clash = keys.find((key) => chosen.variables.some((variable) => variable.key === key)); + + if (clash !== undefined) { + throw chosenVariableError(clash); + } + + const skippedClash = keys.find((key) => skippedKeys.includes(key)); + + if (skippedClash !== undefined) { + throw chosenDotenvKeyError(skippedClash); + } + + return keys; +} + export async function chooseSources( dataDir: string, services: ServiceContext, io: VariableIo, stack: StackImporter, prompt: ChooserPrompt, -): Promise { +): Promise { const detected = detectEnvFile(dataDir, io.exists); const fileName = detected === undefined ? FILE_CHOICE : `${FILE_CHOICE} (${basename(detected)} found)`; const choices = [ { name: STACK_CHOICE, value: STACK_CHOICE }, { name: fileName, value: FILE_CHOICE }, { name: TYPED_CHOICE, value: TYPED_CHOICE }, + ...(prompt.secrets === true ? [{ name: WRITE_ONLY_CHOICE, value: WRITE_ONLY_CHOICE }] : []), ...(prompt.skippable ? [{ name: SKIP_CHOICE, value: SKIP_CHOICE }] : []), ]; const picked = await askChoices(services.ux, prompt.message, choices, { requireOne: false }); @@ -81,18 +127,25 @@ export async function chooseSources( } const sources: VariableSource[] = []; + const skippedKeys: string[] = []; if (picked.includes(STACK_CHOICE)) { sources.push({ label: 'stack', variables: await stack() }); } if (picked.includes(FILE_CHOICE)) { - sources.push(...(await askForFile(detected, services, io))); + const fileSources = await askForFile(detected, services, io); + + sources.push(...fileSources); + skippedKeys.push(...fileSources.flatMap((source) => source.skipped)); } if (picked.includes(TYPED_CHOICE)) { sources.push({ label: TYPED_LABEL, variables: await askForTyped(services, io) }); } - return mergeSources(sources); + const merged = mergeSources(sources); + const secretKeys = picked.includes(WRITE_ONLY_CHOICE) ? await askForSecretKeys(services, merged, skippedKeys) : []; + + return { merged, secretKeys }; } diff --git a/src/variables/variable.create.test.ts b/src/variables/variable.create.test.ts index 8a399053..d8947c24 100644 --- a/src/variables/variable.create.test.ts +++ b/src/variables/variable.create.test.ts @@ -1,7 +1,15 @@ -import { randomUUID } from 'node:crypto'; +import { randomBytes, randomUUID } from 'node:crypto'; import { CancelledError, UsageError } from '../core/errors'; import type { UxLike } from '../core/prompt'; import type { ServiceContext } from '../core/service-context'; +import { gluedValue } from '../../test/support/glued-value'; +import { keyEqualsValue } from '../../test/support/key-value'; +import { + chosenDotenvKeyError, + chosenVariableError, + clientExposedWarning, + SECRETS_WITHOUT_TERMINAL_MESSAGE, +} from '../secrets/secret.rules'; import { variablesForCreate } from './variable.create'; const PICKED_TOKEN = `cs-${randomUUID()}`; @@ -11,8 +19,19 @@ const STACK = 'Import variables from a stack'; const SKIP = 'Skip adding environment variables'; const FILE = 'Import variables from a dotenv file'; const TYPED = 'Manually add custom variables'; - -function fakes(options: { isTTY?: boolean; answers?: Record; files?: Record } = {}) { +const SECRETS = 'Add secrets (write-only)'; +const SECRET_KEYS_QUESTION = 'Enter secret key names only, separated by spaces, no values (Ex: KEY1 KEY2)'; + +function fakes( + options: { + isTTY?: boolean; + outputIsTTY?: boolean; + answers?: Record; + files?: Record; + stdin?: string; + template?: { key: string; value: string }[]; + } = {}, +) { const files = options.files ?? {}; const printed: string[] = []; const asked: { message: string; payload: Record }[] = []; @@ -42,13 +61,15 @@ function fakes(options: { isTTY?: boolean; answers?: Record; fi services: { ux, isTTY: options.isTTY ?? true, - outputIsTTY: false, + outputIsTTY: options.outputIsTTY ?? false, api: { stacks: { list: async () => [{ name: 'Shop', apiKey: 'blt1' }], deliveryTokens: async () => [{ name: 'prod-token', token: PICKED_TOKEN, environment: 'production' }], }, - variables: { stackTemplate: async () => [{ key: 'CONTENTSTACK_API_HOST', value: 'api.example.test' }] }, + variables: { + stackTemplate: async () => options.template ?? [{ key: 'CONTENTSTACK_API_HOST', value: 'api.example.test' }], + }, }, } as unknown as ServiceContext, io: { @@ -64,7 +85,7 @@ function fakes(options: { isTTY?: boolean; answers?: Record; fi exists: (path: string) => path in files, readStdin: async () => { stdinReads.push(1); - return ''; + return options.stdin ?? ''; }, }, }; @@ -76,7 +97,7 @@ describe('variable create', () => { it('uses the flags as given, never asks, never auto-detects, and prints the provenance', async () => { const { services, io, asked, reads, printed } = fakes({ files: { 'a.env': 'FROM_FILE=1', '/work/.env': 'X=1' } }); - const variables = await variablesForCreate({ vars: ['TYPED=2'], envFiles: ['a.env'], dataDir: '/work', org: 'org1' }, services, io); + const { environmentVariables: variables } = await variablesForCreate({ vars: ['TYPED=2'], envFiles: ['a.env'], dataDir: '/work', org: 'org1' }, services, io); expect(variables).toEqual([ { key: 'FROM_FILE', value: '1' }, @@ -90,21 +111,21 @@ describe('variable create', () => { it('returns nothing without a terminal and without flags, asking nothing and reading nothing', async () => { const { services, io, asked, reads, printed } = fakes({ isTTY: false, files: { '/work/.env': 'X=1' } }); - expect(await variablesForCreate(NONE, services, io)).toEqual([]); + expect((await variablesForCreate(NONE, services, io)).environmentVariables).toEqual([]); expect(asked).toEqual([]); expect(reads).toEqual([]); expect(printed).toEqual([]); }); it('treats empty flag lists as no flags', async () => { - const { services, io, asked } = fakes({ answers: { 'Add environment variables': [SKIP] } }); + const { services, io, asked } = fakes({ answers: { 'Add variables from': [SKIP] } }); - expect(await variablesForCreate({ vars: [], envFiles: [], dataDir: '/work', org: 'org1' }, services, io)).toEqual([]); - expect(asked.map((entry) => entry.message)).toEqual(['Add environment variables']); + expect((await variablesForCreate({ vars: [], envFiles: [], dataDir: '/work', org: 'org1' }, services, io)).environmentVariables).toEqual([]); + expect(asked.map((entry) => entry.message)).toEqual(['Add variables from']); }); it('offers a checkbox of the sources and Skip as the last choice', async () => { - const { services, io, asked } = fakes({ answers: { 'Add environment variables': [SKIP] } }); + const { services, io, asked } = fakes({ answers: { 'Add variables from': [SKIP] } }); await variablesForCreate(NONE, services, io); @@ -114,13 +135,14 @@ describe('variable create', () => { { name: STACK, value: STACK }, { name: FILE, value: FILE }, { name: TYPED, value: TYPED }, + { name: SECRETS, value: SECRETS }, { name: SKIP, value: SKIP }, ], }); }); it('lets a bare Enter through the checkbox with nothing selected', async () => { - const { services, io, asked } = fakes({ answers: { 'Add environment variables': [] } }); + const { services, io, asked } = fakes({ answers: { 'Add variables from': [] } }); await variablesForCreate(NONE, services, io); @@ -129,29 +151,29 @@ describe('variable create', () => { }); it('returns nothing and says so when Skip is chosen', async () => { - const { services, io, printed } = fakes({ answers: { 'Add environment variables': [SKIP] } }); + const { services, io, printed } = fakes({ answers: { 'Add variables from': [SKIP] } }); - expect(await variablesForCreate(NONE, services, io)).toEqual([]); + expect((await variablesForCreate(NONE, services, io)).environmentVariables).toEqual([]); expect(printed).toEqual(['Skipped adding environment variables.']); }); it('refuses Skip combined with another choice as a usage error before asking anything else', async () => { - const { services, io, asked } = fakes({ answers: { 'Add environment variables': [SKIP, FILE] } }); + const { services, io, asked } = fakes({ answers: { 'Add variables from': [SKIP, FILE] } }); await expect(variablesForCreate(NONE, services, io)).rejects.toThrow(UsageError); await expect(variablesForCreate(NONE, services, io)).rejects.toThrow( "'Skip adding environment variables' cannot be combined with the other options.", ); - expect(asked.map((entry) => entry.message)).toEqual(['Add environment variables', 'Add environment variables']); + expect(asked.map((entry) => entry.message)).toEqual(['Add variables from', 'Add variables from']); }); it('asks for a dotenv path defaulting to the detected file and reads it', async () => { const { services, io, asked, reads, printed } = fakes({ files: { '/work/.env.local': 'A=1', '/work/other.env': 'B=2' }, - answers: { 'Add environment variables': [FILE], 'Path to the dotenv file': '/work/other.env' }, + answers: { 'Add variables from': [FILE], 'Path to the dotenv file': '/work/other.env' }, }); - const variables = await variablesForCreate(NONE, services, io); + const { environmentVariables: variables } = await variablesForCreate(NONE, services, io); expect(asked[1].payload).toMatchObject({ default: '/work/.env.local' }); expect(reads).toEqual(['/work/other.env']); @@ -162,10 +184,10 @@ describe('variable create', () => { it('reports the empty-value entries of a dotenv file it was pointed at, as the flag path does', async () => { const { services, io, printed } = fakes({ files: { 'x.env': 'A=1\nSECRET=\n' }, - answers: { 'Add environment variables': [FILE], 'Path to the dotenv file': 'x.env' }, + answers: { 'Add variables from': [FILE], 'Path to the dotenv file': 'x.env' }, }); - const variables = await variablesForCreate(NONE, services, io); + const { environmentVariables: variables } = await variablesForCreate(NONE, services, io); expect(variables).toEqual([{ key: 'A', value: '1' }]); expect(printed).toContain('Skipped 1 variable with an empty value in x.env: SECRET.'); @@ -174,7 +196,7 @@ describe('variable create', () => { it('offers no default path when no dotenv file is detected', async () => { const { services, io, asked } = fakes({ files: { 'x.env': 'A=1' }, - answers: { 'Add environment variables': [FILE], 'Path to the dotenv file': 'x.env' }, + answers: { 'Add variables from': [FILE], 'Path to the dotenv file': 'x.env' }, }); await variablesForCreate(NONE, services, io); @@ -186,13 +208,13 @@ describe('variable create', () => { const { services, io, printed } = fakes({ files: { 'a.env': 'API_URL=file\nF=1' }, answers: { - 'Add environment variables': [FILE, TYPED], + 'Add variables from': [FILE, TYPED], 'Path to the dotenv file': 'a.env', 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'API_URL="sk live secret" N=2', }, }); - const variables = await variablesForCreate(NONE, services, io); + const { environmentVariables: variables } = await variablesForCreate(NONE, services, io); expect(variables).toEqual([ { key: 'API_URL', value: 'sk live secret' }, @@ -207,13 +229,13 @@ describe('variable create', () => { it('asks a hidden prompt for a typed key that has no value', async () => { const { services, io, asked } = fakes({ answers: { - 'Add environment variables': [TYPED], + 'Add variables from': [TYPED], 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'API_KEY', 'Value for API_KEY': 's3cret', }, }); - const variables = await variablesForCreate(NONE, services, io); + const { environmentVariables: variables } = await variablesForCreate(NONE, services, io); expect(variables).toEqual([{ key: 'API_KEY', value: 's3cret' }]); expect(asked[2].payload).toMatchObject({ type: 'password' }); @@ -221,7 +243,7 @@ describe('variable create', () => { it('echoes the typed keys with masked values and never a value', async () => { const { services, io, printed } = fakes({ - answers: { 'Add environment variables': [TYPED], 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'A=never-printed-value' }, + answers: { 'Add variables from': [TYPED], 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'A=never-printed-value' }, }); await variablesForCreate(NONE, services, io); @@ -234,25 +256,25 @@ describe('variable create', () => { }); it.each([[undefined], [[]]])('skips and says so, as Skip does, when nothing was selected (%p)', async (answer) => { - const { services, io, printed } = fakes({ answers: { 'Add environment variables': answer } }); + const { services, io, printed } = fakes({ answers: { 'Add variables from': answer } }); - expect(await variablesForCreate(NONE, services, io)).toEqual([]); + expect((await variablesForCreate(NONE, services, io)).environmentVariables).toEqual([]); expect(printed).toEqual(['Skipped adding environment variables.']); }); it('propagates a cancelled path prompt, an unreadable file and a malformed typed line', async () => { - const cancelled = fakes({ answers: { 'Add environment variables': [FILE], 'Path to the dotenv file': undefined } }); + const cancelled = fakes({ answers: { 'Add variables from': [FILE], 'Path to the dotenv file': undefined } }); await expect(variablesForCreate(NONE, cancelled.services, cancelled.io)).rejects.toThrow(CancelledError); - const missing = fakes({ answers: { 'Add environment variables': [FILE], 'Path to the dotenv file': 'nope.env' } }); + const missing = fakes({ answers: { 'Add variables from': [FILE], 'Path to the dotenv file': 'nope.env' } }); await expect(variablesForCreate(NONE, missing.services, missing.io)).rejects.toThrow( '--dotenv nope.env was not found.', ); const malformed = fakes({ - answers: { 'Add environment variables': [TYPED], 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'A="oops' }, + answers: { 'Add variables from': [TYPED], 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'A="oops' }, }); await expect(variablesForCreate(NONE, malformed.services, malformed.io)).rejects.toThrow( @@ -265,7 +287,7 @@ describe('variable create', () => { const savedToken = (alias: string) => alias === 'my-prod' ? { token: SAVED_TOKEN, apiKey: 'blt9', environment: 'staging' } : undefined; - const variables = await variablesForCreate( + const { environmentVariables: variables } = await variablesForCreate( { vars: ['CONTENTSTACK_ENVIRONMENT=override'], envFiles: undefined, dataDir: '/work', org: 'org1', fromStack: true, alias: 'my-prod' }, services, io, @@ -299,17 +321,17 @@ describe('variable create', () => { it('offers the stack as a source, asks the stack and token pickers, and merges it before the other sources', async () => { const { services, io, asked, printed } = fakes({ answers: { - 'Add environment variables': [STACK, TYPED], + 'Add variables from': [STACK, TYPED], Stack: '0', 'Delivery token': '0', 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'EXTRA=1', }, }); - const variables = await variablesForCreate(NONE, services, io); + const { environmentVariables: variables } = await variablesForCreate(NONE, services, io); expect(asked.map((entry) => entry.message)).toEqual([ - 'Add environment variables', + 'Add variables from', 'Stack', 'Delivery token', 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")', @@ -326,10 +348,344 @@ describe('variable create', () => { }); it('refuses Skip combined with the stack choice', async () => { - const { services, io } = fakes({ answers: { 'Add environment variables': [SKIP, STACK] } }); + const { services, io } = fakes({ answers: { 'Add variables from': [SKIP, STACK] } }); + + await expect(variablesForCreate(NONE, services, io)).rejects.toThrow( + "'Skip adding environment variables' cannot be combined with the other options.", + ); + }); + + it('sends every dotenv key as a variable, and the piped value of the one --secret as a secret, asking nothing', async () => { + const value = gluedValue(); + const { services, io, asked, stdinReads } = fakes({ + isTTY: false, + files: { 'staging.env': 'API_URL=from-file\nFROM_FILE=1\n' }, + stdin: `${value}\n`, + }); + + const created = await variablesForCreate({ ...NONE, envFiles: ['staging.env'], secrets: ['A'] }, services, io); + + expect(created.environmentVariables).toEqual([ + { key: 'API_URL', value: 'from-file' }, + { key: 'FROM_FILE', value: '1' }, + ]); + expect(created.secrets).toEqual([{ key: 'A', value }]); + expect(stdinReads).toEqual([1]); + expect(asked).toEqual([]); + }); + + it('keeps every key of --from-stack, the delivery token included, a variable when --secret is passed too', async () => { + const stackToken = randomBytes(16).toString('hex'); + const value = gluedValue(); + const { services, io } = fakes({ + answers: { 'Value for A': value }, + template: [ + { key: 'CONTENTSTACK_API_HOST', value: 'api.example.test' }, + { key: 'CONTENTSTACK_CDN', value: 'cdn.example.test' }, + ], + }); + const savedToken = () => ({ token: stackToken, apiKey: 'blt9', environment: 'staging' }); + + const created = await variablesForCreate( + { ...NONE, fromStack: true, alias: 'prod', secrets: ['A'] }, + services, + io, + savedToken, + ); + + expect(created.environmentVariables.map((variable) => variable.key)).toEqual([ + 'CONTENTSTACK_API_HOST', + 'CONTENTSTACK_CDN', + 'CONTENTSTACK_API_KEY', + 'CONTENTSTACK_DELIVERY_TOKEN', + 'CONTENTSTACK_ENVIRONMENT', + ]); + expect(created.environmentVariables).toContainEqual({ key: 'CONTENTSTACK_DELIVERY_TOKEN', value: stackToken }); + expect(created.secrets).toEqual([{ key: 'A', value }]); + }); + + it('skips the checklist and asks only the masked prompts when secrets are the only thing given on a terminal', async () => { + const [first, second] = [gluedValue(), gluedValue()]; + const { services, io, asked, printed } = fakes({ + answers: { 'Value for A (1/2)': first, 'Value for B (2/2)': second }, + }); + + const created = await variablesForCreate({ ...NONE, secrets: ['A', 'B'] }, services, io); + + expect(asked.map((entry) => entry.message)).toEqual(['Value for A (1/2)', 'Value for B (2/2)']); + expect(asked.map((entry) => entry.payload.type)).toEqual(['password', 'password']); + expect(created.environmentVariables).toEqual([]); + expect(created.secrets).toEqual([ + { key: 'A', value: first }, + { key: 'B', value: second }, + ]); + expect(printed).toEqual(['✔ 2 secrets (A, B) ready to set']); + expect(printed.join('\n')).not.toContain(first); + expect(printed.join('\n')).not.toContain(second); + }); + + it('names the variables and the secret keys together in the summary of a create with both', async () => { + const { services, io, printed } = fakes({ answers: { 'Value for A': gluedValue() } }); + + await variablesForCreate({ ...NONE, vars: ['X=1'], secrets: ['A'] }, services, io); + + expect(printed).toEqual(['✔ 1 variable (1 from --var) and 1 secret (A) ready to set']); + }); + + it.each([[undefined], [[]], [['', ' ']]])('treats secrets of %p as none and keeps the checklist', async (secrets) => { + const { services, io, asked } = fakes({ answers: { 'Add variables from': [SKIP] } }); + + const created = await variablesForCreate({ ...NONE, secrets }, services, io); + + expect(asked.map((entry) => entry.message)).toEqual(['Add variables from']); + expect(created.secrets).toEqual([]); + }); + + it('refuses more than one secret without a terminal before reading stdin', async () => { + const { services, io, stdinReads } = fakes({ isTTY: false, stdin: gluedValue() }); + + await expect(variablesForCreate({ ...NONE, secrets: ['A', 'B'] }, services, io)).rejects.toThrow( + SECRETS_WITHOUT_TERMINAL_MESSAGE, + ); + expect(stdinReads).toEqual([]); + }); + + it('offers Add secrets (write-only) after the other sources and before Skip', async () => { + const { services, io, asked } = fakes({ answers: { 'Add variables from': [SKIP] } }); + + await variablesForCreate(NONE, services, io); + + expect((asked[0].payload.choices as { name: string }[]).map((choice) => choice.name)).toEqual([ + STACK, + FILE, + TYPED, + SECRETS, + SKIP, + ]); + }); + + it('asks for the secret keys then one masked prompt per key, and adds nothing to the variables, when picked', async () => { + const [first, second] = [gluedValue(), gluedValue()]; + const { services, io, asked, printed } = fakes({ + answers: { + 'Add variables from': [SECRETS], + [SECRET_KEYS_QUESTION]: 'A B', + 'Value for A (1/2)': first, + 'Value for B (2/2)': second, + }, + }); + + const created = await variablesForCreate(NONE, services, io); + + expect(asked.map((entry) => entry.message)).toEqual([ + 'Add variables from', + SECRET_KEYS_QUESTION, + 'Value for A (1/2)', + 'Value for B (2/2)', + ]); + expect(asked[2].payload).toMatchObject({ type: 'password' }); + expect(created.environmentVariables).toEqual([]); + expect(created.secrets).toEqual([ + { key: 'A', value: first }, + { key: 'B', value: second }, + ]); + expect(printed).toEqual(['✔ 2 secrets (A, B) ready to set']); + }); + + it('takes the secret keys of the prompt separated by commas as well as spaces', async () => { + const { services, io } = fakes({ + answers: { + 'Add variables from': [SECRETS], + [SECRET_KEYS_QUESTION]: 'A, B,C', + 'Value for A (1/3)': gluedValue(), + 'Value for B (2/3)': gluedValue(), + 'Value for C (3/3)': gluedValue(), + }, + }); + + const created = await variablesForCreate(NONE, services, io); + + expect(created.secrets.map((secret) => secret.key)).toEqual(['A', 'B', 'C']); + }); + + it('keeps the typed variables of the checklist and the secrets apart', async () => { + const value = gluedValue(); + const { services, io, printed } = fakes({ + answers: { + 'Add variables from': [TYPED, SECRETS], + 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'X=1', + [SECRET_KEYS_QUESTION]: 'A', + 'Value for A': value, + }, + }); + + const created = await variablesForCreate(NONE, services, io); + + expect(created.environmentVariables).toEqual([{ key: 'X', value: '1' }]); + expect(created.secrets).toEqual([{ key: 'A', value }]); + expect(printed.join('\n')).toContain('1 variable (1 from manual entry) and 1 secret (A) ready to set'); + }); + + it("refuses 'Skip adding environment variables' combined with the secrets choice before asking for any key", async () => { + const { services, io, asked } = fakes({ answers: { 'Add variables from': [SECRETS, SKIP] } }); await expect(variablesForCreate(NONE, services, io)).rejects.toThrow( "'Skip adding environment variables' cannot be combined with the other options.", ); + expect(asked.map((entry) => entry.message)).toEqual(['Add variables from']); + }); + + it('refuses a secret key at the prompt that is also a variable chosen in the same run, before any value is asked', async () => { + const { services, io, asked } = fakes({ + answers: { + 'Add variables from': [TYPED, SECRETS], + 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'A=1', + [SECRET_KEYS_QUESTION]: 'A', + }, + }); + + await expect(variablesForCreate(NONE, services, io)).rejects.toThrow(chosenVariableError('A').message); + expect(asked.map((entry) => entry.message)).not.toContain('Value for A'); + }); + + it.each([ + ['KEY=value', 'Enter keys only, not KEY=value.'], + ['KEY:value', 'Enter keys only, not KEY=value.'], + ['A A', 'A was entered more than once. Enter each key once.'], + ['..', '".." cannot be used as a secret key'], + ])('refuses the secret keys %p typed at the prompt in prompt wording, before any value is asked', async (typed, message) => { + const { services, io, asked } = fakes({ + answers: { 'Add variables from': [SECRETS], [SECRET_KEYS_QUESTION]: typed }, + }); + + const failure = await variablesForCreate(NONE, services, io).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as UsageError).message).toContain(message); + expect((failure as UsageError).message).not.toContain('--secret'); + expect(asked.map((entry) => entry.message)).toEqual(['Add variables from', SECRET_KEYS_QUESTION]); + }); + + it.each([[' '], [' , '], [',,']])( + 'refuses %p at the keys prompt as no key entered, before any value is asked and without naming --secret', + async (typed) => { + const { services, io, asked } = fakes({ + answers: { 'Add variables from': [SECRETS], [SECRET_KEYS_QUESTION]: typed }, + }); + + const failure = await variablesForCreate(NONE, services, io).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as UsageError).exitCode).toBe(2); + expect((failure as UsageError).message).toBe( + 'No secret key was entered. Enter at least one key name, or leave Add secrets (write-only) unticked.', + ); + expect(asked.map((entry) => entry.message)).toEqual(['Add variables from', SECRET_KEYS_QUESTION]); + }, + ); + + it('asks the secret keys as plain text naming keys only and no values, never masked', async () => { + const { services, io, asked } = fakes({ + answers: { 'Add variables from': [SECRETS], [SECRET_KEYS_QUESTION]: 'A', 'Value for A': gluedValue() }, + }); + + await variablesForCreate(NONE, services, io); + + expect(asked[1].payload).toMatchObject({ type: 'input' }); + expect(asked[1].message).toContain('names only'); + expect(asked[1].message).toContain('no values'); + expect(asked[1].message).not.toContain('KEY1='); + }); + + it('refuses a secret key at the prompt that is an empty entry of the picked dotenv file, as --dotenv with --secret does', async () => { + const { services, io, asked } = fakes({ + files: { 'x.env': `${keyEqualsValue('API_KEY', '')}\nB=1\n` }, + answers: { + 'Add variables from': [FILE, SECRETS], + 'Path to the dotenv file': 'x.env', + [SECRET_KEYS_QUESTION]: 'API_KEY', + }, + }); + + const failure = await variablesForCreate(NONE, services, io).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(UsageError); + expect((failure as UsageError).message).toBe(chosenDotenvKeyError('API_KEY').message); + expect((failure as UsageError).message).not.toContain('--secret'); + expect(asked.map((entry) => entry.message)).not.toContain('Value for API_KEY'); + }); + + it('accepts a secret key at the prompt that is not in the picked dotenv file, empty entries included', async () => { + const value = gluedValue(); + const { services, io } = fakes({ + files: { 'x.env': `${keyEqualsValue('API_KEY', '')}\nB=1\n` }, + answers: { + 'Add variables from': [FILE, SECRETS], + 'Path to the dotenv file': 'x.env', + [SECRET_KEYS_QUESTION]: 'OTHER', + 'Value for OTHER': value, + }, + }); + + const created = await variablesForCreate(NONE, services, io); + + expect(created.environmentVariables).toEqual([{ key: 'B', value: '1' }]); + expect(created.secrets).toEqual([{ key: 'OTHER', value }]); + }); + + it('never echoes a value typed after the key at the keys prompt', async () => { + const value = gluedValue(); + const { services, io, printed } = fakes({ + answers: { 'Add variables from': [SECRETS], [SECRET_KEYS_QUESTION]: `KEY:${value}` }, + }); + + const failure = await variablesForCreate(NONE, services, io).catch((error: unknown) => error); + + expect(`${(failure as Error).message}${printed.join('\n')}`).not.toContain(value); + }); + + it('prints the client-exposed warning once for a secret key with a public prefix, and none for a variable', async () => { + const { services, io, printed } = fakes({ isTTY: false, stdin: gluedValue() }); + + await variablesForCreate({ ...NONE, vars: ['NEXT_PUBLIC_URL=1'], secrets: ['NEXT_PUBLIC_KEY'] }, services, io); + + const warning = clientExposedWarning('NEXT_PUBLIC_KEY') as string; + + expect(printed.filter((line) => line === warning)).toHaveLength(1); + expect(printed.filter((line) => line.includes('NEXT_PUBLIC_URL'))).toEqual([]); + }); + + it('colours the warning yellow only when the output is a terminal', async () => { + const plain = fakes({ isTTY: false, stdin: gluedValue(), outputIsTTY: false }); + const coloured = fakes({ isTTY: false, stdin: gluedValue(), outputIsTTY: true }); + + await variablesForCreate({ ...NONE, secrets: ['VITE_KEY'] }, plain.services, plain.io); + await variablesForCreate({ ...NONE, secrets: ['VITE_KEY'] }, coloured.services, coloured.io); + + const warning = clientExposedWarning('VITE_KEY') as string; + + expect(plain.printed).toContain(warning); + expect(coloured.printed).not.toContain(warning); + expect(coloured.printed.some((line) => line.includes(warning) && line.includes('\u001b['))).toBe(true); + }); + + it('prints no warning for a secret key without a public prefix', async () => { + const { services, io, printed } = fakes({ isTTY: false, stdin: gluedValue() }); + + await variablesForCreate({ ...NONE, secrets: ['API_KEY'] }, services, io); + + expect(printed.filter((line) => line.startsWith('Warning'))).toEqual([]); + }); + + it('propagates a cancelled secret prompt', async () => { + const { services, io } = fakes({ answers: { 'Value for A': undefined } }); + + await expect(variablesForCreate({ ...NONE, secrets: ['A'] }, services, io)).rejects.toThrow(CancelledError); + }); + + it('refuses a piped empty value for a secret without sending anything', async () => { + const { services, io } = fakes({ isTTY: false, stdin: '\n' }); + + await expect(variablesForCreate({ ...NONE, secrets: ['A'] }, services, io)).rejects.toThrow(UsageError); }); }); diff --git a/src/variables/variable.create.ts b/src/variables/variable.create.ts index 537322d0..f248b4f2 100644 --- a/src/variables/variable.create.ts +++ b/src/variables/variable.create.ts @@ -1,12 +1,19 @@ +import { styled } from '../core/style'; import type { ServiceContext } from '../core/service-context'; import type { EnvironmentVariableInput } from '../environments/types'; +import { clientExposedWarning, secretKeysOf } from '../secrets/secret.rules'; import { chooseSources } from './variable.chooser'; +import type { ChosenSources } from './variable.chooser'; import { collectVariables } from './variable.sources'; +import { mergeSources } from './variable.merge'; import { DEFAULT_VARIABLE_IO, given } from './variable.io'; import type { VariableIo } from './variable.io'; +import { parseAssignment } from './variable.parse'; import { importFromStack, readSavedToken } from './variable.stack'; import type { SavedToken, StackImporter } from './variable.stack'; import { variablesSetLine } from './variable.summary'; +import { CHOOSE_SOURCES_MESSAGE } from './variable.set'; +import { completeSecrets } from './variable.values'; export interface CreateVariablesRequest { vars: string[] | undefined; @@ -15,28 +22,58 @@ export interface CreateVariablesRequest { org: string; fromStack?: boolean; alias?: string; + secrets?: string[]; } -const CHOOSE_MESSAGE = 'Add environment variables'; +export interface CreatedVariables { + environmentVariables: EnvironmentVariableInput[]; + secrets: EnvironmentVariableInput[]; +} -async function askForVariables( +function askForVariables( request: CreateVariablesRequest, services: ServiceContext, io: VariableIo, stack: StackImporter, -): Promise { - const merged = await chooseSources(request.dataDir, services, io, stack, { - message: CHOOSE_MESSAGE, +): Promise { + return chooseSources(request.dataDir, services, io, stack, { + message: CHOOSE_SOURCES_MESSAGE, skippable: true, + secrets: true, }); +} - if (merged === undefined) { - return []; +async function gather( + request: CreateVariablesRequest, + keys: string[], + services: ServiceContext, + io: VariableIo, + stack: StackImporter, +): Promise { + if (given(request.vars) || given(request.envFiles) || request.fromStack === true) { + const merged = await collectVariables( + { vars: request.vars, envFiles: request.envFiles, fromStack: request.fromStack, alias: request.alias }, + { ...io, services, dataDir: request.dataDir, stack }, + ); + + return { merged, secretKeys: keys }; } - services.ux.print(variablesSetLine(merged, services.outputIsTTY === true, 'ready to set')); + if (keys.length > 0) { + return { merged: mergeSources([]), secretKeys: keys }; + } - return merged.variables; + return services.isTTY ? askForVariables(request, services, io, stack) : undefined; +} + +function warnClientExposed(keys: string[], services: ServiceContext): void { + for (const key of keys) { + const warning = clientExposedWarning(key); + + if (warning !== undefined) { + services.ux.print(styled(warning, 'yellow', services.outputIsTTY === true)); + } + } } export async function variablesForCreate( @@ -44,19 +81,23 @@ export async function variablesForCreate( services: ServiceContext, io: VariableIo = DEFAULT_VARIABLE_IO, savedToken: (alias: string) => SavedToken | undefined = readSavedToken, -): Promise { +): Promise { const stack: StackImporter = (alias) => importFromStack({ org: request.org, alias }, { services, savedToken }); + const gathered = await gather(request, secretKeysOf(request.secrets), services, io, stack); - if (given(request.vars) || given(request.envFiles) || request.fromStack === true) { - const merged = await collectVariables( - { vars: request.vars, envFiles: request.envFiles, fromStack: request.fromStack, alias: request.alias }, - { ...io, services, dataDir: request.dataDir, stack }, - ); + if (gathered === undefined) { + return { environmentVariables: [], secrets: [] }; + } - services.ux.print(variablesSetLine(merged, services.outputIsTTY === true, 'ready to set')); + warnClientExposed(gathered.secretKeys, services); - return merged.variables; - } + const secrets = await completeSecrets( + gathered.secretKeys, + { services, readStdin: io.readStdin }, + (request.vars ?? []).map(parseAssignment), + ); + + services.ux.print(variablesSetLine(gathered.merged, services.outputIsTTY === true, 'ready to set', secrets)); - return services.isTTY ? askForVariables(request, services, io, stack) : []; + return { environmentVariables: gathered.merged.variables, secrets }; } diff --git a/src/variables/variable.errors.ts b/src/variables/variable.errors.ts index 9789fb2c..fc5ec7fe 100644 --- a/src/variables/variable.errors.ts +++ b/src/variables/variable.errors.ts @@ -9,3 +9,10 @@ export function someNotSetError(keys: string[]): UsageError { ? notSetError(keys) : new UsageError(`At least one of ${keys.join(', ')} is not set in this environment.`); } + +export function sharedStdinError(varKey: string, secretKey: string): UsageError { + return new UsageError( + `--var ${varKey} and --secret ${secretKey} both read standard input, and only one value can be piped in. ` + + `Give ${varKey} a value as --var ${varKey}= or in a --dotenv file, or run on a terminal.`, + ); +} diff --git a/src/variables/variable.inputs.test.ts b/src/variables/variable.inputs.test.ts index 62ab84a2..aa834f49 100644 --- a/src/variables/variable.inputs.test.ts +++ b/src/variables/variable.inputs.test.ts @@ -1,3 +1,5 @@ +import { randomUUID } from 'node:crypto'; + import { Parser } from '@oclif/core'; import { catalog } from '../resources'; @@ -5,14 +7,14 @@ 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', 'dotenv', 'key', 'secret', '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', 'dotenv', 'key', 'secret'] 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', 'dotenv', 'key', 'secret', 'from-stack', 'alias'] as const)('never marks %s required at parse time', (name) => { expect(variableFlags[name].required).toBeFalsy(); }); @@ -76,4 +78,41 @@ describe('variable inputs', () => { expect(parsed.flags['dotenv']).toEqual(['a.env', 'b.env']); expect(parsed.flags.key).toEqual(['X', 'Y']); }); + + it('reads --secret A,B and a repeated --secret as the same keys, in argv order', async () => { + const flags = { secret: variableFlags.secret }; + + const commaList = await Parser.parse(['--secret', 'A,B', '--secret', 'C'], { flags }); + const repeated = await Parser.parse(['--secret', 'A', '--secret', 'B', '--secret', 'C'], { flags }); + const pair = await Parser.parse(['--secret', 'A,B'], { flags }); + const twice = await Parser.parse(['--secret', 'A', '--secret', 'B'], { flags }); + + expect(commaList.flags.secret).toEqual(['A', 'B', 'C']); + expect(repeated.flags.secret).toEqual(commaList.flags.secret); + expect(twice.flags.secret).toEqual(pair.flags.secret); + }); + + it('refuses a token after --secret KEY as an unexpected argument instead of taking it as a second key', async () => { + const value = randomUUID(); + const flags = { secret: variableFlags.secret }; + + const parsing = Parser.parse(['--secret', 'STRIPE_KEY', value], { flags }); + + await expect(parsing).rejects.toThrow('Unexpected argument'); + }); + + it('stops --secret at a flag and keeps a comma list and a repeat after a lone key', async () => { + const flags = { secret: variableFlags.secret, project: catalog.project }; + + const parsed = await Parser.parse(['--secret', 'A,B', '--project', 'x', '--secret', 'C'], { flags }); + + expect(parsed.flags.secret).toEqual(['A', 'B', 'C']); + expect(parsed.flags.project).toBe('x'); + }); + + it('describes --secret as a key only, with the value from a masked prompt or standard input', () => { + expect(variableFlags.secret.description).toContain('key only'); + expect(variableFlags.secret.description).toContain('masked prompt'); + expect(variableFlags.secret.description).toContain('standard input'); + }); }); diff --git a/src/variables/variable.inputs.ts b/src/variables/variable.inputs.ts index 254f7395..2ce18530 100644 --- a/src/variables/variable.inputs.ts +++ b/src/variables/variable.inputs.ts @@ -14,6 +14,14 @@ export const variableFlags = { description: 'Path to a dotenv file, absolute or relative to the current folder', }), key: Flags.string({ multiple: true, description: 'Environment variable key, repeatable' }), + secret: Flags.string({ + multiple: true, + multipleNonGreedy: true, + delimiter: ',', + description: + 'Secret key only, repeatable or comma separated: --secret A --secret B or --secret A,B. ' + + 'The value is read from a masked prompt, or from standard input when piped, never from the command line', + }), 'from-stack': Flags.boolean({ description: 'Import the variables of a Contentstack stack. Asks for the stack and a delivery token on a terminal', }), @@ -27,6 +35,7 @@ export const variableResolution = { var: {} satisfies ResolutionSpec, dotenv: {} satisfies ResolutionSpec, key: {} satisfies ResolutionSpec, + secret: {} satisfies ResolutionSpec, 'from-stack': {} satisfies ResolutionSpec, alias: {} satisfies ResolutionSpec, }; diff --git a/src/variables/variable.parse.ts b/src/variables/variable.parse.ts index 93e66d54..37076e99 100644 --- a/src/variables/variable.parse.ts +++ b/src/variables/variable.parse.ts @@ -11,9 +11,15 @@ function separatorIndex(token: string): number { return separators.length === 0 ? -1 : Math.min(...separators); } +export function keyOfAssignment(token: string): string { + const at = separatorIndex(token); + + return (at === -1 ? token : token.slice(0, at)).trim(); +} + export function parseAssignment(token: string): Assignment { const at = separatorIndex(token); - const key = (at === -1 ? token : token.slice(0, at)).trim(); + const key = keyOfAssignment(token); if (key === '') { throw new UsageError('A variable is missing its key. Use =.'); diff --git a/src/variables/variable.rules.test.ts b/src/variables/variable.rules.test.ts index 5fbe3a89..8e99bd87 100644 --- a/src/variables/variable.rules.test.ts +++ b/src/variables/variable.rules.test.ts @@ -1,5 +1,12 @@ +import { Errors, Parser } from '@oclif/core'; + import { UsageError } from '../core/errors'; -import { aliasRequiresFromStack, singleDotenv } from './variable.rules'; +import { gluedValue } from '../../test/support/glued-value'; +import { keyEqualsValue } from '../../test/support/key-value'; +import { blankSecretError, invalidKeyError, secretOverlapError } from '../secrets/secret.rules'; +import { STACK_VARIABLE_KEYS } from './variable.stack'; +import { variableFlags } from './variable.inputs'; +import { aliasRequiresFromStack, asSafeCreateFailure, secretFlag, singleDotenv } from './variable.rules'; describe('variable rules', () => { it('refuses --alias without --from-stack, naming both', () => { @@ -38,4 +45,148 @@ describe('variable rules', () => { it.each([[undefined], [[]], [['a.env']]])('accepts no --dotenv or a single one (%p)', (dotenv) => { expect(() => singleDotenv({ dotenv }, {})).not.toThrow(); }); + + describe('--secret', () => { + function thrownBy(run: () => void): UsageError { + try { + run(); + } catch (error) { + return error as UsageError; + } + + throw new Error('Expected the rule to throw.'); + } + + it('refuses a key that is also given through --var as a key and value, naming the key, --var and --secret and never the value', () => { + const value = gluedValue(); + + const error = thrownBy(() => secretFlag({ var: [keyEqualsValue('KEY', value)], secret: ['KEY'] }, {})); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe(secretOverlapError('KEY', '--var').message); + expect(error.message).not.toContain(value); + }); + + it.each([['KEY'], ['KEY=1'], ['KEY:1'], [' KEY =1']])('finds the key of the --var token %p', (token) => { + expect(() => secretFlag({ var: [token], secret: ['KEY'] }, {})).toThrow(secretOverlapError('KEY', '--var').message); + }); + + it('accepts a --secret next to a --var of another key, and either one alone', () => { + expect(() => secretFlag({ var: ['OTHER=1'], secret: ['KEY'] }, {})).not.toThrow(); + expect(() => secretFlag({ var: ['OTHER=1'] }, {})).not.toThrow(); + expect(() => secretFlag({ secret: ['KEY'] }, {})).not.toThrow(); + }); + + it.each(STACK_VARIABLE_KEYS.map((key) => [key]))( + 'refuses %s, a key --from-stack gives, as a secret, naming --from-stack', + (key) => { + expect(() => secretFlag({ 'from-stack': true, secret: [key] }, {})).toThrow( + secretOverlapError(key, '--from-stack').message, + ); + }, + ); + + it('accepts a stack key as a secret when --from-stack is not passed', () => { + expect(() => secretFlag({ 'from-stack': false, secret: ['CONTENTSTACK_API_KEY'] }, {})).not.toThrow(); + expect(() => secretFlag({ secret: ['CONTENTSTACK_API_KEY'] }, {})).not.toThrow(); + }); + + it.each([[['']], [[' ']], [['A', '']], [['', 'A']], [['A', ' ']], [['\t']]])( + 'refuses the blank --secret entry in %p with exit 2 instead of dropping it', + (secret) => { + const error = thrownBy(() => secretFlag({ secret }, {})); + + expect(error).toBeInstanceOf(UsageError); + expect(error.exitCode).toBe(2); + expect(error.message).toBe(blankSecretError().message); + expect(error.message).toContain('--secret cannot be blank'); + expect(error.message).not.toContain('launch:secrets'); + }, + ); + + it('refuses a blank entry produced by a trailing comma or a doubled comma, as --secret A, and --secret A,,B', async () => { + const flags = { secret: variableFlags.secret }; + + for (const argv of [['--secret', 'A,'], ['--secret', 'A,,B'], ['--secret', ',']]) { + const parsed = await Parser.parse(argv, { flags }); + + expect(() => secretFlag({ secret: parsed.flags.secret }, {})).toThrow(blankSecretError().message); + } + }); + + it('accepts a --secret that was not passed, an empty list and non-blank keys', () => { + expect(() => secretFlag({ secret: undefined }, {})).not.toThrow(); + expect(() => secretFlag({ secret: [] }, {})).not.toThrow(); + expect(() => secretFlag({ secret: ['A', 'B'] }, {})).not.toThrow(); + }); + + it('refuses a key and value joined by an equals sign, saying --secret takes a key only and echoing none of the value', () => { + const value = gluedValue(); + + const error = thrownBy(() => secretFlag({ secret: [keyEqualsValue('KEY', value)] }, {})); + + expect(error.message).toContain('--secret takes a key only'); + expect(error.message).not.toContain(value); + }); + + it('refuses --secret KEY:value as a key only message, echoing none of the value', () => { + const value = gluedValue(); + + const error = thrownBy(() => secretFlag({ secret: [`KEY:${value}`] }, {})); + + expect(error.message).toContain('--secret takes a key only'); + expect(error.message).not.toContain(value); + }); + + it('refuses the same key twice from --secret A --secret A and from --secret A,A, naming it once', async () => { + const flags = { secret: variableFlags.secret }; + const repeated = await Parser.parse(['--secret', 'KEY_A', '--secret', 'KEY_A'], { flags }); + const commaList = await Parser.parse(['--secret', 'KEY_A,KEY_A'], { flags }); + + for (const parsed of [repeated, commaList]) { + const error = thrownBy(() => secretFlag({ secret: parsed.flags.secret }, {})); + + expect(error.message).toContain('--secret KEY_A was given more than once'); + expect(error.message.split('KEY_A').length - 1).toBe(1); + } + }); + + it.each([['.'], ['..']])('refuses the key %j before looking at anything else', (key) => { + expect(thrownBy(() => secretFlag({ var: [`${key}=1`], secret: [key] }, {})).message).toBe( + invalidKeyError(key).message, + ); + }); + + it.each([[undefined], [null], [[]], [false], [0]])('accepts a command that gave no --secret (%p)', (secret) => { + expect(() => secretFlag({ secret, var: ['A=1'], 'from-stack': true }, {})).not.toThrow(); + }); + }); +}); + +describe('asSafeCreateFailure', () => { + it.each([['launch:env:create'], ['launch:projects:create']])( + 'replaces a parse failure that echoes a token with the help line of %s, as a usage error', + async (command) => { + const value = gluedValue(); + const raw = await Parser.parse(['--secret', 'STRIPE_KEY', value], { flags: { secret: variableFlags.secret } }).catch( + (error: unknown) => error, + ); + + const safe = asSafeCreateFailure(raw, command) as UsageError; + + expect(raw).toBeInstanceOf(Errors.CLIError); + expect((raw as Error).message).toContain(value); + expect(safe).toBeInstanceOf(UsageError); + expect(safe.exitCode).toBe(2); + expect(safe.message).toBe(`Run csdx ${command} --help to see its flags.`); + expect(safe.message).not.toContain(value); + }, + ); + + it('hands a failure that is not a parse failure back untouched', () => { + const failure = new UsageError('--alias is only used with --from-stack.'); + + expect(asSafeCreateFailure(failure, 'launch:env:create')).toBe(failure); + }); }); diff --git a/src/variables/variable.rules.ts b/src/variables/variable.rules.ts index fac097ee..1886a0b5 100644 --- a/src/variables/variable.rules.ts +++ b/src/variables/variable.rules.ts @@ -1,7 +1,20 @@ import { UsageError } from '../core/errors'; import type { Rule } from '../core/rules'; import { isAbsent } from '../core/values'; +import { + assertCreateSecretKeys, + asSafeArgvFailure, + blankSecretError, + secretKeysOf, + secretOverlapError, +} from '../secrets/secret.rules'; import { MULTIPLE_DOTENV_PATHS } from './variable.files'; +import { keyOfAssignment } from './variable.parse'; +import { STACK_VARIABLE_KEYS } from './variable.stack'; + +export function asSafeCreateFailure(error: unknown, command: string): unknown { + return asSafeArgvFailure(error, `Run csdx ${command} --help to see its flags.`); +} export const aliasRequiresFromStack: Rule = (resolved) => { if (!isAbsent(resolved.alias) && resolved['from-stack'] !== true) { @@ -17,3 +30,27 @@ export const singleDotenv: Rule = (resolved) => { throw new UsageError(MULTIPLE_DOTENV_PATHS); } }; + +export const secretFlag: Rule = (resolved) => { + if (Array.isArray(resolved.secret) && resolved.secret.some((key) => isAbsent(key))) { + throw blankSecretError(); + } + + const keys = secretKeysOf(resolved.secret); + + assertCreateSecretKeys(keys); + + const varKeys = (Array.isArray(resolved.var) ? resolved.var : []).map((token: string) => keyOfAssignment(token)); + const clash = keys.find((key) => varKeys.includes(key)); + + if (clash !== undefined) { + throw secretOverlapError(clash, '--var'); + } + + const fromStack = resolved['from-stack'] === true; + const stackClash = fromStack ? keys.find((key) => STACK_VARIABLE_KEYS.includes(key)) : undefined; + + if (stackClash !== undefined) { + throw secretOverlapError(stackClash, '--from-stack'); + } +}; diff --git a/src/variables/variable.secrets.test.ts b/src/variables/variable.secrets.test.ts new file mode 100644 index 00000000..0a276e20 --- /dev/null +++ b/src/variables/variable.secrets.test.ts @@ -0,0 +1,210 @@ +import { UsageError } from '../core/errors'; +import type { UxLike } from '../core/prompt'; +import type { ServiceContext } from '../core/service-context'; +import { gluedValue } from '../../test/support/glued-value'; +import { keyEqualsValue } from '../../test/support/key-value'; +import { emptyValueError, secretOverlapError, SECRETS_WITHOUT_TERMINAL_MESSAGE } from '../secrets/secret.rules'; +import { SecretInputTimeoutError } from '../secrets/secrets.errors'; +import type { SecretValueIo } from '../secrets/secret.value'; +import type { VariableIo } from './variable.io'; +import { prepareSecretInput } from './variable.secrets'; + +const CREATE_COMMAND = 'launch:env:create'; + +function harness(options: { isTTY?: boolean; piped?: string | Promise; files?: Record } = {}) { + const prompts: string[] = []; + const fileReads: string[] = []; + const stdinReads: number[] = []; + const closed: number[] = []; + const files = options.files ?? {}; + const ux: UxLike = { + print: () => undefined, + inquire: (async (payload: { message: string }) => { + prompts.push(payload.message); + return undefined; + }) as UxLike['inquire'], + }; + const services = { ux, isTTY: options.isTTY ?? false } as unknown as ServiceContext; + const base: VariableIo = { + readFile: async (path: string) => { + fileReads.push(path); + + if (!(path in files)) { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); + } + + return files[path]; + }, + exists: () => false, + readStdin: async () => { + throw new Error('the base stdin must not be read'); + }, + }; + const secretIo: SecretValueIo = { + readStdin: async () => { + stdinReads.push(1); + return options.piped ?? ''; + }, + closeStdin: () => { + closed.push(1); + }, + stdinTimeoutMs: 20, + }; + + return { services, base, secretIo, prompts, fileReads, stdinReads, closed }; +} + +describe('prepareSecretInput', () => { + it.each([[undefined], [[]], [['', ' ']]])( + 'hands back the io it was given and reads nothing when no secret was passed (%p)', + async (secrets) => { + const { services, base, secretIo, fileReads, stdinReads, prompts } = harness({ isTTY: false }); + + const io = await prepareSecretInput({ secrets, envFiles: ['x.env'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND); + + expect(io).toBe(base); + expect(fileReads).toEqual([]); + expect(stdinReads).toEqual([]); + expect(prompts).toEqual([]); + }, + ); + + it('refuses a secret whose key is a variable of the --dotenv file, naming it and --dotenv and never its value', async () => { + const value = gluedValue(); + const { services, base, secretIo, stdinReads, prompts } = harness({ + files: { 'staging.env': `${keyEqualsValue('A', value)}\nB=2\n` }, + }); + + const refused = prepareSecretInput({ secrets: ['A'], envFiles: ['staging.env'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND); + + await expect(refused).rejects.toThrow(UsageError); + await expect(refused).rejects.toThrow(secretOverlapError('A', '--dotenv').message); + await expect(refused).rejects.not.toThrow(value); + expect(stdinReads).toEqual([]); + expect(prompts).toEqual([]); + }); + + it('checks the --dotenv file on a terminal too, and reads no stdin there', async () => { + const { services, base, secretIo, stdinReads } = harness({ isTTY: true, files: { 'staging.env': 'A=1\n' } }); + + await expect( + prepareSecretInput({ secrets: ['A'], envFiles: ['staging.env'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND), + ).rejects.toThrow(secretOverlapError('A', '--dotenv').message); + expect(stdinReads).toEqual([]); + }); + + it('refuses a secret whose key is in the dotenv file with an empty value, the same as one with a value', async () => { + const { services, base, secretIo, stdinReads } = harness({ piped: gluedValue(), files: { 'staging.env': 'A=\nB=2\n' } }); + + const refused = prepareSecretInput({ secrets: ['A'], envFiles: ['staging.env'] }, services, { + secrets: secretIo, + variables: base, + }, CREATE_COMMAND); + + await expect(refused).rejects.toThrow(UsageError); + await expect(refused).rejects.toThrow(secretOverlapError('A', '--dotenv').message); + expect(stdinReads).toEqual([]); + }); + + it('accepts a dotenv file that does not name the secret key at all, empty entries included', async () => { + const { services, base, secretIo } = harness({ piped: gluedValue(), files: { 'staging.env': 'OTHER=\nB=2\n' } }); + + await expect( + prepareSecretInput({ secrets: ['A'], envFiles: ['staging.env'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND), + ).resolves.toBeDefined(); + }); + + it('propagates an unreadable --dotenv file', async () => { + const { services, base, secretIo } = harness(); + + await expect( + prepareSecretInput({ secrets: ['A'], envFiles: ['nope.env'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND), + ).rejects.toThrow('--dotenv nope.env was not found.'); + }); + + it('refuses more than one secret without a terminal before reading the file or stdin', async () => { + const { services, base, secretIo, stdinReads, fileReads } = harness({ piped: gluedValue() }); + + await expect(prepareSecretInput({ secrets: ['A', 'B'], envFiles: ['x.env'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND)).rejects.toThrow( + SECRETS_WITHOUT_TERMINAL_MESSAGE, + ); + expect(stdinReads).toEqual([]); + expect(fileReads).toEqual([]); + }); + + it('refuses a secret next to a bare --var KEY without a terminal before reading stdin', async () => { + const { services, base, secretIo, stdinReads } = harness({ piped: gluedValue() }); + + await expect(prepareSecretInput({ secrets: ['A'], vars: ['TOKEN'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND)).rejects.toThrow( + '--var TOKEN and --secret A both read standard input', + ); + expect(stdinReads).toEqual([]); + }); + + it('reads and checks the one piped value without a terminal, and hands it on for the single later read', async () => { + const value = gluedValue(); + const { services, base, secretIo, stdinReads } = harness({ piped: `${value}\n` }); + + const io = await prepareSecretInput({ secrets: ['A'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND); + + expect(stdinReads).toEqual([1]); + expect(await io.readStdin()).toBe(value); + expect(await io.readStdin()).toBe(value); + expect(stdinReads).toEqual([1]); + expect(io.readFile).toBe(base.readFile); + expect(io.exists).toBe(base.exists); + }); + + it.each([['an empty pipe', ''], ['a lone newline', '\n']])('refuses %s as the empty-value error', async (_label, piped) => { + const { services, base, secretIo } = harness({ piped }); + + await expect(prepareSecretInput({ secrets: ['A'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND)).rejects.toThrow( + emptyValueError('A').message, + ); + }); + + it('refuses a piped value with a line break without echoing it', async () => { + const [first, second] = [gluedValue(), gluedValue()]; + const { services, base, secretIo } = harness({ piped: `${first}\n${second}` }); + + const refused = prepareSecretInput({ secrets: ['A'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND); + + await expect(refused).rejects.toThrow('The value for A has a line break.'); + await expect(refused).rejects.not.toThrow(first); + await expect(refused).rejects.not.toThrow(second); + }); + + it('ends with the timeout error, closing stdin, when nothing arrives', async () => { + const { services, base, secretIo, closed } = harness({ piped: new Promise(() => undefined) }); + + await expect(prepareSecretInput({ secrets: ['A'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND)).rejects.toBeInstanceOf( + SecretInputTimeoutError, + ); + expect(closed).toEqual([1]); + }); + + it.each(['launch:env:create', 'launch:projects:create'])( + 'says in the timeout error to pipe the value into the same %s command with --secret , not into a secrets command', + async (command) => { + const { services, base, secretIo } = harness({ piped: new Promise(() => undefined) }); + + const error: unknown = await prepareSecretInput({ secrets: ['A'] }, services, { secrets: secretIo, variables: base }, command).catch( + (failure: unknown) => failure, + ); + + expect(error).toBeInstanceOf(SecretInputTimeoutError); + expect((error as Error).message).toContain(`csdx ${command} --secret `); + expect((error as Error).message).not.toContain('launch:secrets'); + }, + ); + + it('leaves the values to the prompts on a terminal, reading no stdin and asking nothing yet', async () => { + const { services, base, secretIo, stdinReads, prompts } = harness({ isTTY: true }); + + const io = await prepareSecretInput({ secrets: ['A'] }, services, { secrets: secretIo, variables: base }, CREATE_COMMAND); + + expect(io).toBe(base); + expect(stdinReads).toEqual([]); + expect(prompts).toEqual([]); + }); +}); diff --git a/src/variables/variable.secrets.ts b/src/variables/variable.secrets.ts new file mode 100644 index 00000000..7344389b --- /dev/null +++ b/src/variables/variable.secrets.ts @@ -0,0 +1,59 @@ +import type { ServiceContext } from '../core/service-context'; +import { secretKeysOf, secretOverlapError } from '../secrets/secret.rules'; +import { DEFAULT_SECRET_IO, readSecretValue } from '../secrets/secret.value'; +import type { SecretValueIo } from '../secrets/secret.value'; +import { createPipeExample } from '../secrets/secrets.errors'; +import { readEnvFiles } from './variable.files'; +import { DEFAULT_VARIABLE_IO } from './variable.io'; +import type { VariableIo } from './variable.io'; +import { parseAssignment } from './variable.parse'; +import { pipedSecrets } from './variable.values'; + +export interface SecretIntakeRequest { + secrets?: string[]; + vars?: string[]; + envFiles?: string[]; +} + +async function refuseDotenvOverlap(keys: string[], envFiles: string[] | undefined, io: VariableIo): Promise { + const sources = await readEnvFiles(envFiles ?? [], io); + const taken = sources.flatMap((source) => [...source.variables.map((variable) => variable.key), ...source.skipped]); + const clash = keys.find((key) => taken.includes(key)); + + if (clash !== undefined) { + throw secretOverlapError(clash, '--dotenv'); + } +} + +export interface SecretIntakeIo { + secrets: SecretValueIo; + variables: VariableIo; +} + +export const DEFAULT_SECRET_INTAKE_IO: SecretIntakeIo = { secrets: DEFAULT_SECRET_IO, variables: DEFAULT_VARIABLE_IO }; + +export async function prepareSecretInput( + request: SecretIntakeRequest, + services: ServiceContext, + io: SecretIntakeIo, + command: string, +): Promise { + const base = io.variables; + const keys = secretKeysOf(request.secrets); + + if (keys.length === 0) { + return base; + } + + const piped = pipedSecrets(keys, (request.vars ?? []).map(parseAssignment), services); + + await refuseDotenvOverlap(keys, request.envFiles, base); + + if (!piped) { + return base; + } + + const value = await readSecretValue(keys[0], services, io.secrets, undefined, createPipeExample(command)); + + return { ...base, readStdin: async () => value }; +} diff --git a/src/variables/variable.set.ts b/src/variables/variable.set.ts index 3dfd7ca0..2307b427 100644 --- a/src/variables/variable.set.ts +++ b/src/variables/variable.set.ts @@ -37,7 +37,7 @@ export class VariableSetter { 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 - ? await chooseSources(request.dataDir, this.services, this.io, stack, prompt) + ? (await chooseSources(request.dataDir, this.services, this.io, stack, prompt))?.merged : await collectVariables( { vars: request.vars, diff --git a/src/variables/variable.stack.test.ts b/src/variables/variable.stack.test.ts index ace514b2..5a101921 100644 --- a/src/variables/variable.stack.test.ts +++ b/src/variables/variable.stack.test.ts @@ -7,7 +7,7 @@ import type { ServiceContext } from '../core/service-context'; import type { DeliveryToken, Stack } from '../stacks/stacks.api'; import { StackLookupError } from '../stacks/stack.errors'; import type { StackTemplateEntry } from './variables.api'; -import { importFromStack, readSavedToken } from './variable.stack'; +import { STACK_VARIABLE_KEYS, importFromStack, readSavedToken } from './variable.stack'; import type { SavedToken } from './variable.stack'; const PROD_TOKEN = `cs-${randomUUID()}`; @@ -112,6 +112,15 @@ function saved(entries: Record) { const NOTHING_SAVED = () => undefined; describe('variable stack import with --alias', () => { + it('names, in STACK_VARIABLE_KEYS, exactly the keys it imports', async () => { + const { services } = fakes(); + const { savedToken } = saved({ 'my-prod': SAVED }); + + const variables = await importFromStack({ org: 'org1', alias: 'my-prod' }, { services, savedToken }); + + expect(variables.map((variable) => variable.key)).toEqual(STACK_VARIABLE_KEYS); + }); + it('builds the five variables from the saved token and the CMS template without asking anything', async () => { const { services, calls, printed } = fakes(); const { savedToken, asked } = saved({ 'my-prod': SAVED }); diff --git a/src/variables/variable.stack.ts b/src/variables/variable.stack.ts index 6a781cb7..0d936705 100644 --- a/src/variables/variable.stack.ts +++ b/src/variables/variable.stack.ts @@ -34,6 +34,13 @@ interface Credentials { const TEMPLATE_HOST_KEYS = ['CONTENTSTACK_API_HOST', 'CONTENTSTACK_CDN']; +export const STACK_VARIABLE_KEYS = [ + ...TEMPLATE_HOST_KEYS, + 'CONTENTSTACK_API_KEY', + 'CONTENTSTACK_DELIVERY_TOKEN', + 'CONTENTSTACK_ENVIRONMENT', +]; + function textOf(value: unknown): string | undefined { return typeof value === 'string' && value.trim() !== '' ? value : undefined; } diff --git a/src/variables/variable.summary.test.ts b/src/variables/variable.summary.test.ts index 93fdede6..20992032 100644 --- a/src/variables/variable.summary.test.ts +++ b/src/variables/variable.summary.test.ts @@ -1,3 +1,4 @@ +import { gluedValue } from '../../test/support/glued-value'; import { variablesSetLine } from './variable.summary'; describe('variable summary', () => { @@ -67,4 +68,72 @@ describe('variable summary', () => { expect(variablesSetLine(merged, false, 'ready to set')).toBe('✔ 0 variables ready to set'); }); + + it('names the secret keys and the variables together, and no value of either', () => { + const [variableValue, firstValue, secondValue] = [gluedValue(), gluedValue(), gluedValue()]; + const line = variablesSetLine( + { variables: [{ key: 'X', value: variableValue }], added: [{ label: '--var', count: 1 }], overrides: [] }, + false, + 'ready to set', + [ + { key: 'A', value: firstValue }, + { key: 'B', value: secondValue }, + ], + ); + + expect(line).toBe('✔ 1 variable (1 from --var) and 2 secrets (A, B) ready to set'); + expect([variableValue, firstValue, secondValue].filter((value) => line.includes(value))).toEqual([]); + }); + + it('puts every origin and override right after the variable count, so none reads as the origin of a secret', () => { + const line = variablesSetLine( + { + variables: [ + { key: 'X', value: gluedValue() }, + { key: 'Y', value: gluedValue() }, + ], + added: [ + { label: 'a.env', count: 1 }, + { label: '--var', count: 1 }, + ], + overrides: [{ label: '--var', keys: ['X'] }], + }, + false, + 'ready to set', + [{ key: 'A', value: gluedValue() }], + ); + + expect(line).toBe('✔ 2 variables (1 from a.env, 1 from --var, X overridden by --var) and 1 secret (A) ready to set'); + }); + + it('keeps the dash after the state when there are no secrets', () => { + const merged = { + variables: [{ key: 'X', value: gluedValue() }], + added: [{ label: '--var', count: 1 }], + overrides: [], + }; + + expect(variablesSetLine(merged, false, 'ready to set')).toBe('✔ 1 variable ready to set — 1 from --var'); + expect(variablesSetLine(merged, false, 'ready to set', [])).toBe('✔ 1 variable ready to set — 1 from --var'); + }); + + it('counts only the secrets when there are no variables, and uses the singular for one', () => { + const merged = { variables: [], added: [], overrides: [] }; + + expect(variablesSetLine(merged, false, 'ready to set', [{ key: 'A', value: gluedValue() }])).toBe( + '✔ 1 secret (A) ready to set', + ); + expect( + variablesSetLine(merged, false, 'ready to set', [ + { key: 'A', value: gluedValue() }, + { key: 'B', value: gluedValue() }, + ]), + ).toBe('✔ 2 secrets (A, B) ready to set'); + }); + + it('keeps the variables-only line when the secrets list is empty', () => { + const merged = { variables: [], added: [], overrides: [] }; + + expect(variablesSetLine(merged, false, 'ready to set', [])).toBe('✔ 0 variables ready to set'); + }); }); diff --git a/src/variables/variable.summary.ts b/src/variables/variable.summary.ts index f6e14706..f1ef4dd6 100644 --- a/src/variables/variable.summary.ts +++ b/src/variables/variable.summary.ts @@ -1,18 +1,36 @@ import { styled } from '../core/style'; +import type { EnvironmentVariableInput } from '../environments/types'; import type { MergedVariables } from './variable.merge'; function plural(count: number): string { return count === 1 ? 'variable' : 'variables'; } -export function variablesSetLine(merged: MergedVariables, outputIsTTY: boolean, state = 'set'): string { +function secretsPart(secrets: EnvironmentVariableInput[]): string { + const noun = secrets.length === 1 ? 'secret' : 'secrets'; + + return `${secrets.length} ${noun} (${secrets.map(({ key }) => key).join(', ')})`; +} + +export function variablesSetLine( + merged: MergedVariables, + outputIsTTY: boolean, + state = 'set', + secrets: EnvironmentVariableInput[] = [], +): string { const total = merged.variables.length; const provenance = [ ...merged.added.map(({ label, count }) => `${count} from ${label}`), ...merged.overrides.map(({ label, keys }) => `${keys.join(', ')} overridden by ${label}`), ]; - const origin = provenance.length > 0 ? ` — ${provenance.join(', ')}` : ''; + const attached = total > 0 && secrets.length > 0 && provenance.length > 0; + const origin = provenance.length > 0 && !attached ? ` — ${provenance.join(', ')}` : ''; + const variablesPart = `${total} ${plural(total)}${attached ? ` (${provenance.join(', ')})` : ''}`; + const counted = [ + ...(total > 0 || secrets.length === 0 ? [variablesPart] : []), + ...(secrets.length > 0 ? [secretsPart(secrets)] : []), + ]; - return styled(`✔ ${total} ${plural(total)} ${state}${origin}`, 'green', outputIsTTY); + return styled(`✔ ${counted.join(' and ')} ${state}${origin}`, 'green', outputIsTTY); } diff --git a/src/variables/variable.values.test.ts b/src/variables/variable.values.test.ts index efaa4a49..15d1d916 100644 --- a/src/variables/variable.values.test.ts +++ b/src/variables/variable.values.test.ts @@ -1,7 +1,9 @@ import { CancelledError, UsageError } from '../core/errors'; import type { UxLike } from '../core/prompt'; import type { ServiceContext } from '../core/service-context'; -import { completeValues } from './variable.values'; +import { emptyValueError, SECRETS_WITHOUT_TERMINAL_MESSAGE } from '../secrets/secret.rules'; +import { gluedValue } from '../../test/support/glued-value'; +import { completeSecrets, completeValues, pipedSecrets } from './variable.values'; function fakes(answers: string[] = [], stdin = '') { const prompts: { message: string; type: string }[] = []; @@ -130,3 +132,123 @@ describe('variable values', () => { expect(JSON.stringify(prompts)).not.toContain('never-printed-value'); }); }); + +describe('secret values', () => { + it('asks a masked prompt per key in the order given, with an n/m counter, and reads no stdin on a terminal', async () => { + const [first, second] = [gluedValue(), gluedValue()]; + const { deps, prompts, stdinReads } = fakes([first, second]); + + const completed = await completeSecrets(['A', 'B'], deps(true)); + + expect(completed).toEqual([ + { key: 'A', value: first }, + { key: 'B', value: second }, + ]); + expect(prompts).toEqual([ + { message: 'Value for A (1/2)', type: 'password' }, + { message: 'Value for B (2/2)', type: 'password' }, + ]); + expect(stdinReads).toEqual([]); + }); + + it('asks a lone key with no counter', async () => { + const value = gluedValue(); + const { deps, prompts } = fakes([value]); + + expect(await completeSecrets(['A'], deps(true))).toEqual([{ key: 'A', value }]); + expect(prompts).toEqual([{ message: 'Value for A', type: 'password' }]); + }); + + it('reads the one piped value, drops its final line break and asks nothing, without a terminal', async () => { + const value = gluedValue(); + const { deps, prompts, stdinReads } = fakes([], `${value}\n`); + + expect(await completeSecrets(['A'], deps(false))).toEqual([{ key: 'A', value }]); + expect(prompts).toEqual([]); + expect(stdinReads).toEqual([1]); + }); + + it('does nothing for no keys', async () => { + const { deps, prompts, stdinReads } = fakes(); + + expect(await completeSecrets([], deps(false))).toEqual([]); + expect(prompts).toEqual([]); + expect(stdinReads).toEqual([]); + }); + + it('refuses a piped empty value as the empty-value usage error for that key', async () => { + const { deps } = fakes([], '\n'); + + await expect(completeSecrets(['A'], deps(false))).rejects.toThrow(emptyValueError('A').message); + }); + + it('refuses more than one secret without a terminal before reading stdin', async () => { + const { deps, prompts, stdinReads } = fakes([], gluedValue()); + + await expect(completeSecrets(['A', 'B'], deps(false))).rejects.toThrow(SECRETS_WITHOUT_TERMINAL_MESSAGE); + expect(prompts).toEqual([]); + expect(stdinReads).toEqual([]); + }); + + it('refuses a secret next to a bare --var KEY without a terminal, naming both, before reading stdin', async () => { + const { deps, stdinReads } = fakes([], gluedValue()); + const refused = completeSecrets(['A'], deps(false), [{ key: 'TOKEN', value: undefined }]); + + await expect(refused).rejects.toThrow(UsageError); + await expect(refused).rejects.toThrow( + '--var TOKEN and --secret A both read standard input, and only one value can be piped in. ' + + 'Give TOKEN a value as --var TOKEN= or in a --dotenv file, or run on a terminal.', + ); + expect(stdinReads).toEqual([]); + }); + + it('accepts a secret next to a --var that has a value without a terminal', async () => { + const value = gluedValue(); + const { deps } = fakes([], value); + + expect(await completeSecrets(['A'], deps(false), [{ key: 'TOKEN', value: 'x' }])).toEqual([{ key: 'A', value }]); + }); + + it('accepts a secret next to a bare --var KEY on a terminal, where both are asked', async () => { + const value = gluedValue(); + const { deps } = fakes([value]); + + expect(await completeSecrets(['A'], deps(true), [{ key: 'TOKEN', value: undefined }])).toEqual([ + { key: 'A', value }, + ]); + }); + + it('propagates a cancelled prompt', async () => { + const { deps } = fakes([undefined as unknown as string]); + + await expect(completeSecrets(['A'], deps(true))).rejects.toThrow(CancelledError); + }); +}); + +describe('pipedSecrets', () => { + it.each([ + [true, ['A'], false], + [true, ['A', 'B'], false], + [false, [], false], + [false, ['A'], true], + ])('on a terminal %p with keys %p says the values are piped: %p', (isTTY, keys, expected) => { + const { deps } = fakes(); + + expect(pipedSecrets(keys, [], deps(isTTY).services)).toBe(expected); + }); + + it('refuses more than one secret without a terminal', () => { + const { deps } = fakes(); + + expect(() => pipedSecrets(['A', 'B'], [], deps(false).services)).toThrow(SECRETS_WITHOUT_TERMINAL_MESSAGE); + }); + + it('refuses a secret next to a bare --var without a terminal, and only then', () => { + const { deps } = fakes(); + const bare = [{ key: 'TOKEN', value: undefined }]; + + expect(() => pipedSecrets(['A'], bare, deps(false).services)).toThrow('--var TOKEN and --secret A both read'); + expect(() => pipedSecrets([], bare, deps(false).services)).not.toThrow(); + expect(() => pipedSecrets(['A'], bare, deps(true).services)).not.toThrow(); + }); +}); diff --git a/src/variables/variable.values.ts b/src/variables/variable.values.ts index c83fa4db..451db580 100644 --- a/src/variables/variable.values.ts +++ b/src/variables/variable.values.ts @@ -2,6 +2,9 @@ import { UsageError } from '../core/errors'; import { askSecret } from '../core/prompt'; import type { ServiceContext } from '../core/service-context'; import type { EnvironmentVariableInput } from '../environments/types'; +import { SECRETS_WITHOUT_TERMINAL_MESSAGE } from '../secrets/secret.rules'; +import { DEFAULT_SECRET_IO, readSecretValue } from '../secrets/secret.value'; +import { sharedStdinError } from './variable.errors'; import type { Assignment } from './variable.parse'; export interface ValueDeps { @@ -55,3 +58,38 @@ export async function completeValues( return completed; } + +export function pipedSecrets(secrets: string[], assignments: Assignment[], services: ServiceContext): boolean { + const piped = !services.isTTY && secrets.length > 0; + + if (piped && secrets.length > 1) { + throw new UsageError(SECRETS_WITHOUT_TERMINAL_MESSAGE); + } + + const bare = assignments.find((assignment) => assignment.value === undefined); + + if (piped && bare !== undefined) { + throw sharedStdinError(bare.key, secrets[0]); + } + + return piped; +} + +export async function completeSecrets( + keys: string[], + deps: ValueDeps, + assignments: Assignment[] = [], +): Promise { + pipedSecrets(keys, assignments, deps.services); + + const io = { ...DEFAULT_SECRET_IO, readStdin: deps.readStdin }; + const completed: EnvironmentVariableInput[] = []; + + for (const [index, key] of keys.entries()) { + const value = await readSecretValue(key, deps.services, io, promptMessage(key, index + 1, keys.length)); + + completed.push({ key, value }); + } + + return completed; +} diff --git a/test/integration/environments-create.test.ts b/test/integration/environments-create.test.ts index 546f29d2..4fa46581 100644 --- a/test/integration/environments-create.test.ts +++ b/test/integration/environments-create.test.ts @@ -1,17 +1,22 @@ import { randomBytes } from 'node:crypto'; -import { 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 type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; +import { terminalUx } from '../../src/core/terminal-ux'; import * as watcher from '../../src/deployments/deployment.watcher'; +import { DEFAULT_SECRET_IO } from '../../src/secrets/secret.value'; +import { gluedValue } from '../support/glued-value'; +import { keyEqualsValue } from '../support/key-value'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; import { projectOwnership } from '../support/project-ownership'; -import { answerPrompts, onTerminal } from '../support/terminal'; +import { CTRL_C, answerPrompts, onTerminal } from '../support/terminal'; import projectFixture from '../fixtures/project-get.json'; @@ -63,8 +68,51 @@ const GITHUB_ARGS = [ DATA_DIR, ]; +const FULLY_FLAGGED = [...GITHUB_ARGS, '--cs-auth', 'enable', '--server-cmd', 'serve']; +const SECRET_CODES = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS'; + let config: Interfaces.Config; let onWire: string[]; +let restoreStdin: (() => void) | undefined; + +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 pipe(text: string): void { + restoreStdin = pipedStdin(Readable.from([text])); +} + +function stdinThatRecordsReads(): string[] { + const reads: string[] = []; + + restoreStdin = pipedStdin( + new Readable({ + read() { + reads.push('read'); + this.push(null); + }, + }), + ); + + return reads; +} + +function withDataDir(args: string[], directory: string): string[] { + return [...args.slice(0, -1), directory]; +} + +function filesIn(directory: string): string { + return readdirSync(directory) + .map((name) => readFileSync(join(directory, name), 'utf8')) + .join('\n'); +} function hub(): nock.Scope { return nock(LAUNCH_HUB_URL).matchHeader('x-organization-uid', ORG_UID).matchHeader('x-project-uid', PROJECT_UID); @@ -124,6 +172,8 @@ describe('integration: launch:env:create on the wire', () => { afterEach(() => { process.exitCode = 0; + restoreStdin?.(); + restoreStdin = undefined; nock.emitter.removeAllListeners('no match'); nock.cleanAll(); }); @@ -202,7 +252,7 @@ describe('integration: launch:env:create on the wire', () => { const file = join(DATA_DIR, `env-create-${randomBytes(4).toString('hex')}.env`); writeFileSync(file, 'API_URL=from-file\nFROM_FILE=1\n'); const prompts = answerPrompts({ - 'Add environment variables': ['Import variables from a dotenv file', 'Manually add custom variables'], + 'Add variables from': ['Import variables from a dotenv file', 'Manually add custom variables'], 'Path to the dotenv file': file, 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'API_URL=typed DEBUG=true', }); @@ -214,7 +264,7 @@ describe('integration: launch:env:create on the wire', () => { expect(error).toBeUndefined(); expect(prompts.messages).toEqual([ - 'Add environment variables', + 'Add variables from', 'Path to the dotenv file', 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")', ]); @@ -232,7 +282,7 @@ describe('integration: launch:env:create on the wire', () => { const file = join(DATA_DIR, `env-create-${randomBytes(4).toString('hex')}.env`); writeFileSync(file, 'CONTENTSTACK_ENVIRONMENT=from-file\nFROM_FILE=1\n'); const prompts = answerPrompts({ - 'Add environment variables': [ + 'Add variables from': [ 'Import variables from a stack', 'Import variables from a dotenv file', 'Manually add custom variables', @@ -251,7 +301,7 @@ describe('integration: launch:env:create on the wire', () => { expect(error).toBeUndefined(); expect(prompts.messages).toEqual([ - 'Add environment variables', + 'Add variables from', 'Stack', 'Delivery token', 'Path to the dotenv file', @@ -272,7 +322,7 @@ describe('integration: launch:env:create on the wire', () => { }); it('creates with no variables when Skip is chosen', async () => { - answerPrompts({ 'Add environment variables': ['Skip adding environment variables'] }); + answerPrompts({ 'Add variables from': ['Skip adding environment variables'] }); const sent: { environmentVariables?: unknown }[] = []; stubCreate(sent); stubFollowUp('LIVE'); @@ -284,7 +334,7 @@ describe('integration: launch:env:create on the wire', () => { }); it('creates with no variables when Enter is pressed with nothing selected', async () => { - const prompts = answerPrompts({ 'Add environment variables': [] }); + const prompts = answerPrompts({ 'Add variables from': [] }); const sent: { environmentVariables?: unknown }[] = []; stubCreate(sent); stubFollowUp('LIVE'); @@ -292,13 +342,42 @@ describe('integration: launch:env:create on the wire', () => { const { error, stdout } = await onTerminal(() => runCommand(WITH_AUTH, config)); expect(error).toBeUndefined(); - expect(prompts.messages).toEqual(['Add environment variables']); + expect(prompts.messages).toEqual(['Add variables from']); expect(stdout).toContain('Skipped adding environment variables.'); expect(sent[0].environmentVariables).toEqual([]); }); + it('T21 offers Add secrets (write-only), asks for the keys and then each value masked, and sends them as secrets', async () => { + const value = gluedValue(); + const prompts = answerPrompts({ + 'Add variables from': ['Add secrets (write-only)'], + 'Enter secret key names only, separated by spaces, no values (Ex: KEY1 KEY2)': 'A', + 'Value for A': value, + }); + const sent: { environmentVariables?: unknown; secrets?: unknown }[] = []; + stubCreate(sent); + stubFollowUp('LIVE'); + + const { error, stdout } = await onTerminal(() => runCommand(WITH_AUTH, config)); + + expect(error).toBeUndefined(); + expect(prompts.messages).toEqual([ + 'Add variables from', + 'Enter secret key names only, separated by spaces, no values (Ex: KEY1 KEY2)', + 'Value for A', + ]); + expect((prompts.payloads[0].choices as { name: string }[]).map((choice) => choice.name)).toContain( + 'Add secrets (write-only)', + ); + expect(prompts.payloads[2]).toMatchObject({ type: 'password' }); + expect(sent[0].secrets).toEqual([{ key: 'A', value }]); + expect(sent[0].environmentVariables).toEqual([]); + expect(stdout).not.toContain(value); + expect(onWire).toEqual([]); + }); + it('refuses Skip combined with another source before creating anything', async () => { - answerPrompts({ 'Add environment variables': ['Skip adding environment variables', 'Manually add custom variables'] }); + answerPrompts({ 'Add variables from': ['Skip adding environment variables', 'Manually add custom variables'] }); const sent: unknown[] = []; stubCreate(sent); @@ -322,4 +401,435 @@ describe('integration: launch:env:create on the wire', () => { `To see the cause, run:\n csdx launch:logs:get --org ${ORG_UID} --project ${PROJECT_UID} --env ${ENV_UID}`, ); }); + + describe('with --secret', () => { + function nothingWasCreated(sent: unknown[]): void { + const pending = nock.pendingMocks(); + + expect(sent).toEqual([]); + expect(onWire).toEqual([]); + expect(pending.some((mock) => mock.startsWith('POST ') && mock.endsWith(ENV_PATH))).toBe(true); + expect(pending.some((mock) => mock.includes('/manage/projects/framework'))).toBe(true); + } + + it('T1 asks a masked prompt per secret on a terminal and sends both in secrets next to the variables, printing neither', async () => { + const [valueA, valueB] = [gluedValue(), gluedValue()]; + const prompts = answerPrompts({ 'Value for A (1/2)': valueA, 'Value for B (2/2)': valueB }); + const sent: unknown[] = []; + stubCreate(sent); + stubFollowUp('LIVE'); + + const { error, stdout, stderr } = await onTerminal(() => + runCommand([...FULLY_FLAGGED, '--secret', 'A', '--secret', 'B'], config), + ); + + expect(error).toBeUndefined(); + expect(prompts.messages).toEqual(['Value for A (1/2)', 'Value for B (2/2)']); + expect(prompts.payloads.map((payload) => payload.type)).toEqual(['password', 'password']); + expect(sent).toEqual([ + expect.objectContaining({ + environmentVariables: [], + secrets: [ + { key: 'A', value: valueA }, + { key: 'B', value: valueB }, + ], + }), + ]); + expect(stdout).toContain('✔ Environment created successfully.'); + expect(stdout).toContain('✔ 2 secrets (A, B) ready to set'); + expect(onWire).toEqual([]); + expect(`${stdout}${stderr}`).not.toContain(valueA); + expect(`${stdout}${stderr}`).not.toContain(valueB); + }); + + it('T1 takes --secret A,B as the same two keys', async () => { + const prompts = answerPrompts({ 'Value for A (1/2)': gluedValue(), 'Value for B (2/2)': gluedValue() }); + const sent: { secrets?: { key: string }[] }[] = []; + stubCreate(sent); + stubFollowUp('LIVE'); + + const { error } = await onTerminal(() => runCommand([...FULLY_FLAGGED, '--secret', 'A,B'], config)); + + expect(error).toBeUndefined(); + expect(prompts.messages).toEqual(['Value for A (1/2)', 'Value for B (2/2)']); + expect(sent[0].secrets?.map((secret) => secret.key)).toEqual(['A', 'B']); + }); + + it('T9 reads the one piped value without a terminal and asks nothing', async () => { + const value = gluedValue(); + pipe(`${value}\n`); + const sent: unknown[] = []; + stubCreate(sent); + stubFollowUp('LIVE'); + + const { error, stdout, stderr } = await runCommand([...GITHUB_ARGS, '--secret', 'A'], config); + + expect(error).toBeUndefined(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); + expect(sent).toEqual([expect.objectContaining({ environmentVariables: [], secrets: [{ key: 'A', value }] })]); + expect(onWire).toEqual([]); + expect(`${stdout}${stderr}`).not.toContain(value); + }); + + it('T6 sends every key of the dotenv file as a variable, never as a secret, and the piped value as the secret', async () => { + const value = gluedValue(); + const file = join(DATA_DIR, `env-create-${randomBytes(4).toString('hex')}.env`); + writeFileSync(file, 'API_URL=from-file\nFROM_FILE=1\n'); + pipe(value); + const sent: unknown[] = []; + stubCreate(sent); + stubFollowUp('LIVE'); + + const { error, stdout } = await runCommand([...GITHUB_ARGS, '--dotenv', file, '--secret', 'A'], config); + + expect(error).toBeUndefined(); + expect(sent).toEqual([ + expect.objectContaining({ + environmentVariables: [ + { key: 'API_URL', value: 'from-file' }, + { key: 'FROM_FILE', value: '1' }, + ], + secrets: [{ key: 'A', value }], + }), + ]); + expect(stdout).toMatch(/✔ 2 variables \(2 from [^)]+\) and 1 secret \(A\) ready to set/); + }); + + it('T7 refuses a key in both the dotenv file and --secret with exit 2 before any request, reading no stdin', async () => { + const value = gluedValue(); + const file = join(DATA_DIR, `env-create-${randomBytes(4).toString('hex')}.env`); + writeFileSync(file, `${keyEqualsValue('A', value)}\n`); + const reads = stdinThatRecordsReads(); + const sent: unknown[] = []; + stubCreate(sent); + + const { error, stdout, stderr } = await runCommand([...GITHUB_ARGS, '--dotenv', file, '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('A is given both in --dotenv and in --secret'); + expect(`${error?.message}${stdout}${stderr}`).not.toContain(value); + expect(reads).toEqual([]); + expect(terminalUx.inquire).not.toHaveBeenCalled(); + nothingWasCreated(sent); + }); + + it('T10 refuses a key and value joined by an equals sign on --secret with exit 2 saying it takes a key only, never echoing the value', async () => { + const value = gluedValue(); + const reads = stdinThatRecordsReads(); + const sent: unknown[] = []; + stubCreate(sent); + + const { error, stdout, stderr } = await runCommand( + [...GITHUB_ARGS, '--secret', keyEqualsValue('KEY', value)], + config, + ); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--secret takes a key only'); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}`).not.toContain(value); + expect(reads).toEqual([]); + nothingWasCreated(sent); + }); + + it('refuses a value given as its own argument after --secret KEY with exit 2, saving and printing it nowhere', async () => { + const value = gluedValue(); + const reads = stdinThatRecordsReads(); + const sent: unknown[] = []; + stubCreate(sent); + const prompts = answerPrompts({}); + + const { error, stdout, stderr } = await onTerminal(() => + runCommand([...GITHUB_ARGS, '--secret', 'STRIPE_KEY', value], config), + ); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('Run csdx launch:env:create --help to see its flags.'); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}`).not.toContain(value); + expect(`${error?.message}${stdout}${stderr}`).not.toContain('Value for'); + expect(prompts.messages).toEqual([]); + expect(reads).toEqual([]); + nothingWasCreated(sent); + }); + + it.each([ + ['an empty string', ['--secret', '""']], + ['a whitespace string', ['--secret', '" "']], + ['a trailing comma', ['--secret', 'A,']], + ['an empty entry beside a key', ['--secret', 'A', '--secret', '""']], + ])('refuses a blank --secret from %s with exit 2 before any request, instead of dropping it', async (_label, secretArgs) => { + const reads = stdinThatRecordsReads(); + const sent: unknown[] = []; + stubCreate(sent); + const prompts = answerPrompts({}); + + const { error, stdout, stderr } = await onTerminal(() => runCommand([...GITHUB_ARGS, ...secretArgs], config)); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--secret cannot be blank'); + expect(stdout).not.toContain('ready to set'); + expect(`${stdout}${stderr}`).not.toContain('created successfully'); + expect(prompts.messages).toEqual([]); + expect(reads).toEqual([]); + nothingWasCreated(sent); + }); + + it('T10 refuses --secret KEY:value like KEY=value, echoing none of the value', async () => { + const value = gluedValue(); + const reads = stdinThatRecordsReads(); + const sent: unknown[] = []; + stubCreate(sent); + + const { error, stdout, stderr } = await runCommand([...GITHUB_ARGS, '--secret', `KEY:${value}`], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--secret takes a key only'); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}`).not.toContain(value); + expect(reads).toEqual([]); + nothingWasCreated(sent); + }); + + it('creates from the piped --secret example as written, with only the placeholders filled in', async () => { + const value = gluedValue(); + pipe(`${value}\n`); + const sent: unknown[] = []; + stubCreate(sent); + stubFollowUp('LIVE'); + + const { error } = await runCommand( + [ + 'launch:env:create', + '--org', + ORG_UID, + '--project', + PROJECT_UID, + '--name', + 'staging', + '--branch', + 'main', + '--framework', + 'NextJs', + '--secret', + 'STRIPE_KEY', + '--data-dir', + DATA_DIR, + ], + config, + ); + + expect(error).toBeUndefined(); + expect(sent).toEqual([expect.objectContaining({ name: 'staging', secrets: [{ key: 'STRIPE_KEY', value }] })]); + expect(onWire).toEqual([]); + }); + + it('refuses a key in both --var and --secret with exit 2 before any request, never echoing the --var value', async () => { + const value = gluedValue(); + const sent: unknown[] = []; + stubCreate(sent); + + const { error, stdout, stderr } = await runCommand( + [...GITHUB_ARGS, '--var', keyEqualsValue('KEY', value), '--secret', 'KEY'], + config, + ); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('KEY is given both in --var and in --secret'); + expect(`${error?.message}${stdout}${stderr}`).not.toContain(value); + nothingWasCreated(sent); + }); + + it('refuses the same key twice with exit 2 before any request', async () => { + const sent: unknown[] = []; + stubCreate(sent); + + const { error } = await runCommand([...GITHUB_ARGS, '--secret', 'A', '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--secret A was given more than once'); + nothingWasCreated(sent); + }); + + it('T14 refuses an empty piped value with exit 2 and sends nothing', async () => { + pipe(''); + const sent: unknown[] = []; + stubCreate(sent); + + const { error } = await runCommand([...GITHUB_ARGS, '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('The value for A is empty. A secret needs a non-empty value; nothing was changed.'); + nothingWasCreated(sent); + }); + + it('refuses a piped value with a line break with exit 2 and sends nothing, echoing neither line', async () => { + const [first, second] = [gluedValue(), gluedValue()]; + pipe(`${first}\n${second}\n`); + const sent: unknown[] = []; + stubCreate(sent); + + const { error, stdout, stderr } = await runCommand([...GITHUB_ARGS, '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('The value for A has a line break.'); + expect(`${error?.message}${stdout}${stderr}`).not.toContain(first); + expect(`${error?.message}${stdout}${stderr}`).not.toContain(second); + nothingWasCreated(sent); + }); + + it('refuses more than one secret without a terminal, saying to create it first, reading no stdin', async () => { + const reads = stdinThatRecordsReads(); + const sent: unknown[] = []; + stubCreate(sent); + + const { error } = await runCommand([...GITHUB_ARGS, '--secret', 'A,B'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('Create it first with a single --secret'); + expect(error?.message).not.toContain('Create the environment first'); + expect(error?.message).toContain('then run csdx launch:variables:set --secret for each remaining key.'); + expect(error?.message).not.toContain('launch:secrets'); + expect(reads).toEqual([]); + nothingWasCreated(sent); + }); + + it('refuses --secret next to a bare --var KEY without a terminal, reading no stdin', async () => { + const reads = stdinThatRecordsReads(); + const sent: unknown[] = []; + stubCreate(sent); + + const { error } = await runCommand([...GITHUB_ARGS, '--var', 'TOKEN', '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--var TOKEN and --secret A both read standard input'); + expect(reads).toEqual([]); + nothingWasCreated(sent); + }); + + it.each([['.'], ['..']])('refuses the key %j with exit 2 before reading anything', async (key) => { + const reads = stdinThatRecordsReads(); + const sent: unknown[] = []; + stubCreate(sent); + + const { error } = await runCommand([...GITHUB_ARGS, '--secret', key], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain(`"${key}" cannot be used as a secret key`); + expect(reads).toEqual([]); + nothingWasCreated(sent); + }); + + it('T18 exits 3 and creates nothing when Ctrl-C is pressed at the secret prompt', async () => { + answerPrompts({ 'Value for A': CTRL_C }); + const sent: unknown[] = []; + stubCreate(sent); + + const { error, stdout } = await onTerminal(() => runCommand([...FULLY_FLAGGED, '--secret', 'A'], config)); + + expect(error?.oclif?.exit).toBe(3); + expect(sent).toEqual([]); + expect(stdout).not.toContain('✔ Environment created successfully.'); + }); + + it.each([['NEXT_PUBLIC_API'], ['NUXT_PUBLIC_API'], ['VITE_API'], ['GATSBY_API'], ['PUBLIC_API']])( + 'T23 warns that %s is exposed to the client and still creates the environment', + async (key) => { + pipe(gluedValue()); + const sent: unknown[] = []; + stubCreate(sent); + stubFollowUp('LIVE'); + + const { error, stdout } = await runCommand([...GITHUB_ARGS, '--secret', key], config); + + expect(error).toBeUndefined(); + expect(stdout).toContain(`Warning: ${key} starts with`); + expect(stdout).toContain('inlined into client JavaScript at build time'); + expect(sent).toHaveLength(1); + }, + ); + + it.each([ + ['a key conflict', 409, `${SECRET_CODES}.KEY.CONFLICT`, 'A secret or a variable with that key already exists in this environment.'], + ['a multi-line value', 400, `${SECRET_CODES}.VALUE.MULTILINE`, 'A secret value must be a single line.'], + [ + 'the variable count limit', + 400, + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.MAX_COUNT_REACHED', + 'This environment has reached its limit of 128 variables and secrets together.', + ], + [ + 'the size limit', + 400, + 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.BYTE_SIZE_LIMIT_REACHED', + 'The variables and secrets together are larger than the 14 KB Launch allows. Remove some of them or shorten their values.', + ], + ])('T27 words %s with the secrets wording and exits 1, printing no value', async (_label, status, code, message) => { + const value = gluedValue(); + const workDir = mkdtempSync(join(tmpdir(), 'launch-env-create-')); + pipe(value); + projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID); + hub().get(`/manage/projects/${PROJECT_UID}`).reply(200, projectFixture); + nock(LAUNCH_HUB_URL) + .matchHeader('x-organization-uid', ORG_UID) + .get('/manage/projects/framework') + .query(true) + .reply(200, { framework: 'OTHER', buildCommand: 'npx @11ty/eleventy', outputDirectory: './_site' }); + hub() + .post(ENV_PATH) + .reply(status, { errors: [{ code, message: `bad value ${value}` }] }); + + try { + const { error, stdout, stderr } = await runCommand( + withDataDir([...GITHUB_ARGS, '--secret', 'A'], workDir), + config, + ); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe(message); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}${filesIn(workDir)}`).not.toContain(value); + expect(stdout).not.toContain('✔ Environment created successfully.'); + } finally { + rmSync(workDir, { recursive: true, force: true }); + } + }); + + it('T27 shows REDACTED where the server echoes the value in a message the CLI has no wording for', async () => { + const value = gluedValue(); + pipe(value); + projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID); + hub().get(`/manage/projects/${PROJECT_UID}`).reply(200, projectFixture); + nock(LAUNCH_HUB_URL) + .matchHeader('x-organization-uid', ORG_UID) + .get('/manage/projects/framework') + .query(true) + .reply(200, { framework: 'OTHER', buildCommand: 'npx @11ty/eleventy', outputDirectory: './_site' }); + hub() + .post(ENV_PATH) + .reply(400, { errors: [{ code: 'launch.ENVIRONMENT.VALUE.INVALID', message: `value ${value} is not allowed` }] }); + + const { error, stdout, stderr } = await runCommand([...GITHUB_ARGS, '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('value •••••• is not allowed'); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}`).not.toContain(value); + }); + + it('T19 ends with a clear error and sends nothing when standard input never ends', async () => { + const original = DEFAULT_SECRET_IO.stdinTimeoutMs; + restoreStdin = pipedStdin(new Readable({ read() {} })); + DEFAULT_SECRET_IO.stdinTimeoutMs = 50; + const sent: unknown[] = []; + stubCreate(sent); + + try { + const { error } = await runCommand([...GITHUB_ARGS, '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toContain('No value arrived on standard input'); + expect(error?.message).toContain('csdx launch:env:create --secret '); + expect(error?.message).not.toContain('launch:secrets'); + nothingWasCreated(sent); + } finally { + DEFAULT_SECRET_IO.stdinTimeoutMs = original; + } + }); + }); }); diff --git a/test/integration/projects-create.test.ts b/test/integration/projects-create.test.ts index 6416c162..fb4d100e 100644 --- a/test/integration/projects-create.test.ts +++ b/test/integration/projects-create.test.ts @@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, join } from 'node:path'; +import { Readable } from 'node:stream'; import { authHandler, configHandler } from '@contentstack/cli-utilities'; import type { Interfaces } from '@oclif/core'; @@ -12,6 +13,9 @@ import open from 'open'; import { DEPLOYMENT_LOG_LOOKBACK_MS } from '../../src/deployments/deployment.log-tail'; import * as watcher from '../../src/deployments/deployment.watcher'; +import { terminalUx } from '../../src/core/terminal-ux'; +import { gluedValue } from '../support/glued-value'; +import { keyEqualsValue } from '../support/key-value'; import { CTRL_C, answerPrompts, onTerminal } from '../support/terminal'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; @@ -105,6 +109,32 @@ function carriesEveryFormField(signed: ReturnType, body: let config: Interfaces.Config; let onWire: string[]; let dataDir: string; +let restoreStdin: (() => void) | undefined; + +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 stdinThatRecordsReads(): string[] { + const reads: string[] = []; + + restoreStdin = pipedStdin( + new Readable({ + read() { + reads.push('read'); + this.push(null); + }, + }), + ); + + return reads; +} function hub(): nock.Scope { return nock(LAUNCH_HUB_URL).matchHeader('x-organization-uid', ORG_UID); @@ -295,6 +325,8 @@ describe('integration: launch:projects:create on the wire', () => { afterEach(() => { process.exitCode = 0; + restoreStdin?.(); + restoreStdin = undefined; rmSync(dataDir, { recursive: true, force: true }); nock.emitter.removeAllListeners('no match'); nock.cleanAll(); @@ -536,7 +568,7 @@ describe('integration: launch:projects:create on the wire', () => { 'Output directory': './public', 'Response mode': 'buffered', 'Contentstack Authentication': 'enable', - 'Add environment variables': ['Skip adding environment variables'], + 'Add variables from': ['Skip adding environment variables'], }); const organizations = nock('https://cma.integration.test') .get('/v3/organizations') @@ -573,7 +605,7 @@ describe('integration: launch:projects:create on the wire', () => { 'Output directory', 'Response mode', 'Contentstack Authentication', - 'Add environment variables', + 'Add variables from', ]); expect(prompts.payloads[2].default).toBe(basename(dataDir)); expect(onWire).toEqual([]); @@ -629,7 +661,7 @@ describe('integration: launch:projects:create on the wire', () => { 'Output directory': '.next', 'Response mode': 'streaming', 'Contentstack Authentication': 'disable', - 'Add environment variables': ['Skip adding environment variables'], + 'Add variables from': ['Skip adding environment variables'], }); nock('https://cma.integration.test') .get('/v3/organizations') @@ -668,7 +700,7 @@ describe('integration: launch:projects:create on the wire', () => { 'Output directory', 'Response mode', 'Contentstack Authentication', - 'Add environment variables', + 'Add variables from', ]); expect(prompts.payloads.map((payload) => payload.default)).toEqual([ undefined, @@ -719,7 +751,7 @@ describe('integration: launch:projects:create on the wire', () => { 'Output directory': '.next', 'Response mode': 'buffered', 'Contentstack Authentication': 'enable', - 'Add environment variables': ['Skip adding environment variables'], + 'Add variables from': ['Skip adding environment variables'], }); stubRepositoryLookup(); const branches = hub() @@ -751,7 +783,7 @@ describe('integration: launch:projects:create on the wire', () => { 'Output directory', 'Response mode', 'Contentstack Authentication', - 'Add environment variables', + 'Add variables from', ]); expect([branches.isDone(), create.isDone()]).toEqual([true, true]); expect((body as { repository: unknown }).repository).toEqual({ @@ -766,7 +798,7 @@ describe('integration: launch:projects:create on the wire', () => { it('asks on a terminal only for what argv left out, and nothing that a flag supplied', async () => { const prompts = answerPrompts({ 'Framework preset': 'NextJs', - 'Add environment variables': ['Skip adding environment variables'], + 'Add variables from': ['Skip adding environment variables'], }); stubGitLookups(); const create = hub().post('/manage/projects').query({}).reply(201, { project: CREATED_PROJECT }); @@ -776,14 +808,14 @@ describe('integration: launch:projects:create on the wire', () => { const { error } = await onTerminal(() => runCommand(args, config)); expect(error).toBeUndefined(); - expect(prompts.messages).toEqual(['Framework preset', 'Add environment variables']); + expect(prompts.messages).toEqual(['Framework preset', 'Add variables from']); expect(create.isDone()).toBe(true); expect(onWire).toEqual([]); }); it('asks only for variables on a terminal when every other value is a flag, and a bare Enter skips them', async () => { let body: { environment?: { environmentVariables?: unknown } } | undefined; - const prompts = answerPrompts({ 'Add environment variables': [] }); + const prompts = answerPrompts({ 'Add variables from': [] }); stubGitLookups(); const create = hub() .post('/manage/projects', (sent: typeof body) => { @@ -797,7 +829,7 @@ describe('integration: launch:projects:create on the wire', () => { const { error } = await onTerminal(() => runCommand(gitFlags(), config)); expect(error).toBeUndefined(); - expect(prompts.messages).toEqual(['Add environment variables']); + expect(prompts.messages).toEqual(['Add variables from']); expect(create.isDone()).toBe(true); expect(body?.environment?.environmentVariables).toEqual([]); expect(onWire).toEqual([]); @@ -939,7 +971,7 @@ describe('integration: launch:projects:create on the wire', () => { const file = join(dataDir, 'picked.env'); writeFileSync(file, 'API_URL=from-file\nFROM_FILE=1\n'); const prompts = answerPrompts({ - 'Add environment variables': ['Import variables from a dotenv file', 'Manually add custom variables'], + 'Add variables from': ['Import variables from a dotenv file', 'Manually add custom variables'], 'Path to the dotenv file': file, 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")': 'API_URL=typed DEBUG=true', }); @@ -951,7 +983,7 @@ describe('integration: launch:projects:create on the wire', () => { expect(error).toBeUndefined(); expect(prompts.messages).toEqual([ - 'Add environment variables', + 'Add variables from', 'Path to the dotenv file', 'Enter variables separated by spaces (Ex: KEY1=value1 KEY2:value2 KEY3="value with spaces")', ]); @@ -970,7 +1002,7 @@ describe('integration: launch:projects:create on the wire', () => { const file = join(dataDir, 'picked.env'); writeFileSync(file, 'CONTENTSTACK_ENVIRONMENT=from-file\nFROM_FILE=1\n'); const prompts = answerPrompts({ - 'Add environment variables': [ + 'Add variables from': [ 'Import variables from a stack', 'Import variables from a dotenv file', 'Manually add custom variables', @@ -989,7 +1021,7 @@ describe('integration: launch:projects:create on the wire', () => { expect(error).toBeUndefined(); expect(prompts.messages).toEqual([ - 'Add environment variables', + 'Add variables from', 'Stack', 'Delivery token', 'Path to the dotenv file', @@ -1011,7 +1043,7 @@ describe('integration: launch:projects:create on the wire', () => { it('refuses Skip combined with another source before creating anything', async () => { answerPrompts({ - 'Add environment variables': ['Skip adding environment variables', 'Manually add custom variables'], + 'Add variables from': ['Skip adding environment variables', 'Manually add custom variables'], }); stubGitLookups(); const create = captureBody(); @@ -1023,6 +1055,239 @@ describe('integration: launch:projects:create on the wire', () => { }); }); + describe('with --secret', () => { + it('T4 asks the masked prompt for a Git project and sends the secret in environment.secrets, printing no value', async () => { + const value = gluedValue(); + const prompts = answerPrompts({ 'Value for A': value }); + stubGitLookups(); + const created = captureCreate(); + stubFollowUp('LIVE'); + + const { error, stdout, stderr } = await onTerminal(() => runCommand([...gitFlags(), '--secret', 'A'], config)); + + expect(error).toBeUndefined(); + expect(prompts.messages).toEqual(['Value for A']); + expect(prompts.payloads[0]).toMatchObject({ type: 'password' }); + expect(created.body()).toMatchObject({ environment: { environmentVariables: [], secrets: [{ key: 'A', value }] } }); + expect(stdout).toContain('✔ 1 secret (A) ready to set'); + expect(`${stdout}${stderr}`).not.toContain(value); + expect(onWire).toEqual([]); + }); + + it('refuses a value given as its own argument after --secret KEY with exit 2, saving and printing it nowhere', async () => { + const value = gluedValue(); + const reads = stdinThatRecordsReads(); + const prompts = answerPrompts({}); + stubGitLookups(); + const created = captureCreate(); + + const { error, stdout, stderr } = await onTerminal(() => + runCommand([...gitFlags(), '--secret', 'STRIPE_KEY', value], config), + ); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('Run csdx launch:projects:create --help to see its flags.'); + expect(`${error?.message}${error?.stack ?? ''}${stdout}${stderr}`).not.toContain(value); + expect(`${error?.message}${stdout}${stderr}`).not.toContain('Value for'); + expect(prompts.messages).toEqual([]); + expect(reads).toEqual([]); + expect(created.scope.isDone()).toBe(false); + expect(nock.pendingMocks().some((mock) => mock.startsWith('POST ') && mock.endsWith('/manage/projects'))).toBe(true); + expect(onWire).toEqual([]); + }); + + it.each([ + ['an empty string', ['--secret', '""']], + ['a whitespace string', ['--secret', '" "']], + ['a trailing comma', ['--secret', 'A,']], + ['an empty entry beside a key', ['--secret', 'A', '--secret', '""']], + ])('refuses a blank --secret from %s with exit 2 before any request, instead of dropping it', async (_label, secretArgs) => { + const reads = stdinThatRecordsReads(); + const prompts = answerPrompts({}); + stubGitLookups(); + const created = captureCreate(); + + const { error, stdout, stderr } = await onTerminal(() => runCommand([...gitFlags(), ...secretArgs], config)); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--secret cannot be blank'); + expect(stdout).not.toContain('ready to set'); + expect(`${stdout}${stderr}`).not.toContain('created successfully'); + expect(prompts.messages).toEqual([]); + expect(reads).toEqual([]); + expect(created.scope.isDone()).toBe(false); + expect(onWire).toEqual([]); + }); + + it('T5 sends the secret in the environment of a FileUpload project, beside the upload uid and out of the archive', async () => { + const value = gluedValue(); + const prompts = answerPrompts({ 'Value for A': value }); + const signedUpload = awsSignedUpload(); + let uploaded: unknown; + hub().get('/manage/projects/upload/signed_url').query({}).reply(200, signedUpload); + nock(UPLOAD_HOST) + .post('/bucket', (sent: unknown) => { + uploaded = sent; + return true; + }) + .reply(204); + hub().get('/manage/projects/file-framework').query({ uploadUid: 'upload-uid' }).reply(200, { framework: 'OTHER' }); + const created = captureCreate(); + stubFollowUp('DEPLOYED'); + + const { error, stdout, stderr } = await onTerminal(() => + runCommand( + [ + 'launch:projects:create', + '--org', + ORG_UID, + '--type', + 'FileUpload', + '--name', + '"My Site"', + '--env-name', + 'Default', + '--framework', + 'Other', + '--build-cmd', + '"npm run build"', + '--output-dir', + './', + '--res-mode', + 'buffered', + '--server-cmd', + 'serve', + '--cs-auth', + 'enable', + '--secret', + 'A', + '--data-dir', + dataDir, + ], + config, + ), + ); + + expect(error).toBeUndefined(); + expect(prompts.messages).toEqual(['Value for A']); + expect(created.body()).toMatchObject({ + environment: { uploadUid: 'upload-uid', secrets: [{ key: 'A', value }] }, + }); + expect(created.body()).not.toHaveProperty('repository'); + expect(asSent(uploaded)).not.toContain(value); + expect(`${stdout}${stderr}`).not.toContain(value); + expect(onWire).toEqual([]); + }); + + it('T15 refuses more than one secret without a terminal, saying to create it first, before any request', async () => { + const reads = stdinThatRecordsReads(); + stubGitLookups(); + captureCreate(); + + const { error } = await runCommand([...gitFlags(), '--secret', 'A,B'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('Create it first with a single --secret'); + expect(error?.message).not.toContain('Create the environment first'); + expect(error?.message).toContain('then run csdx launch:variables:set --secret for each remaining key.'); + expect(error?.message).not.toContain('launch:secrets'); + expect(reads).toEqual([]); + expect(terminalUx.inquire).not.toHaveBeenCalled(); + expect(nock.pendingMocks().filter((mock) => mock.includes('/manage/git-namespaces') || mock.includes('POST'))).toHaveLength(2); + expect(onWire).toEqual([]); + }); + + it('reads the one piped value without a terminal and sends it as the secret, apart from the dotenv variables', async () => { + const value = gluedValue(); + const file = join(dataDir, 'staging.env'); + writeFileSync(file, 'API_URL=from-file\n'); + restoreStdin = pipedStdin(Readable.from([`${value}\n`])); + stubGitLookups(); + const created = captureCreate(); + stubFollowUp('LIVE'); + + const { error, stdout, stderr } = await runCommand([...gitFlags(), '--dotenv', file, '--secret', 'A'], config); + + expect(error).toBeUndefined(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); + expect(created.body()).toMatchObject({ + environment: { + environmentVariables: [{ key: 'API_URL', value: 'from-file' }], + secrets: [{ key: 'A', value }], + }, + }); + expect(`${stdout}${stderr}`).not.toContain(value); + }); + + it('creates from the piped --secret example as written, with only the placeholders filled in', async () => { + const value = gluedValue(); + restoreStdin = pipedStdin(Readable.from([`${value}\n`])); + stubGitLookups(); + const created = captureCreate(); + stubFollowUp('LIVE'); + + const { error } = await runCommand( + [ + 'launch:projects:create', + '--org', + ORG_UID, + '--type', + 'GitHub', + '--name', + '"My Site"', + '--env-name', + 'Default', + '--branch', + 'main', + '--framework', + 'NextJs', + '--secret', + 'STRIPE_KEY', + '--data-dir', + dataDir, + ], + config, + ); + + expect(error).toBeUndefined(); + expect(created.body()).toMatchObject({ environment: { secrets: [{ key: 'STRIPE_KEY', value }] } }); + expect(onWire).toEqual([]); + }); + + it('refuses a key in both the dotenv file and --secret with exit 2 before any request', async () => { + const file = join(dataDir, 'staging.env'); + writeFileSync(file, `${keyEqualsValue('A', gluedValue())}\n`); + const reads = stdinThatRecordsReads(); + stubGitLookups(); + captureCreate(); + + const { error } = await runCommand([...gitFlags(), '--dotenv', file, '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('A is given both in --dotenv and in --secret'); + expect(reads).toEqual([]); + expect(onWire).toEqual([]); + }); + + it('words an API refusal of the secrets with the secrets wording, printing no value', async () => { + const value = gluedValue(); + restoreStdin = pipedStdin(Readable.from([value])); + stubGitLookups(); + hub() + .post('/manage/projects') + .query({}) + .reply(409, { + errors: [{ code: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT', message: `conflict ${value}` }], + }); + + const { error, stdout, stderr } = await runCommand([...gitFlags(), '--secret', 'A'], config); + + expect(error?.oclif?.exit).toBe(1); + expect(`${stdout}${stderr}`).toContain('A secret or a variable with that key already exists in this environment.'); + expect(`${error?.message}${stdout}${stderr}`).not.toContain(value); + }); + }); + it('sends an empty variable list and asks nothing about variables without a terminal and without flags', async () => { let body: { environment?: { environmentVariables?: unknown } } | undefined; stubGitLookups(); From 49b26908472f27cc157478560b11915d512cef03 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:28:24 +0000 Subject: [PATCH 4/4] docs: document --secret on the create commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Describe `--secret` on projects:create and env:create in AGENTS.md and README.md: how its value is read, the rules it enforces, the request body it produces, and the redaction that now covers the create errors. The existing cloud functions guidance in AGENTS.md is kept as it was on the base branch. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EptZEjXxian6NQu8WFTYZd --- .talismanrc | 4 ++-- AGENTS.md | 54 +++++++++++++++++++++++++++++++++++++++++------------ README.md | 20 +++++++++++++++++--- 3 files changed, 61 insertions(+), 17 deletions(-) diff --git a/.talismanrc b/.talismanrc index f7ba3aa0..77fb08d4 100644 --- a/.talismanrc +++ b/.talismanrc @@ -246,7 +246,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 5e00b7347fb405145f6b1059ef533ff5b58ef5b4e4f2af5fab3b5dd9424529c4 + checksum: 78445e7e0b4e54b6f830aabb035e74494c320b95223f9e3835d617912f429320 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\\)`" @@ -343,7 +343,7 @@ fileignoreconfig: - filename: src/commands/launch/env/update.test.ts checksum: 82c76af721bfdfd8eb7cf49494ffbe15d98b988e98bca1015b9d34b42b5226bd - filename: README.md - checksum: 47317e2767ecf41a22f3ba728f2c5a8098f8d17879af095199504e4eab54081f + checksum: 3524b1a41a4b570545f4a3b866cb0d488d55aea333ad751569e44851e819da7c allowed_patterns: - "password-protection" - "-p, --password" diff --git a/AGENTS.md b/AGENTS.md index ed255f97..6553046e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -370,6 +370,32 @@ combined with the others; a bare Enter with nothing ticked skips the same way, a empty list. There is no `--no-vars` flag: variables are never required, so a fully flagged create on a terminal stops only at that checkbox, and a pipe or CI run skips it. +`projects:create` and `env:create` also take `--secret`, repeatable or comma separated (`--secret A --secret B`, +`--secret A,B`), key only. The flag is `multipleNonGreedy`, so a word after a key (`--secret KEY value`) is an +unexpected argument that exits 2, never a second key, and both create commands pass parse failures through +`asSafeCreateFailure` so no argv token is echoed. Its value comes from a masked prompt on a terminal, or from standard input when there is +a single `--secret` and no terminal, never from argv; `--dotenv` and `--from-stack` always give variables, whether +or not `--secret` is passed. The secrets go in `secrets: [{key, value}]` on the create-environment body (and in +`environment.secrets` of `POST /projects`), next to `environmentVariables`, with no follow-up secrets call, and +`variablesForCreate` returns both lists. Usage errors are raised before the create's own requests (the project read, +framework detection, the upload and the create POST), but after the lookups the resolution chain makes for `--org`, +`--project` and `--env`, because the chain resolves every input before `run()`. `secretFlag` +(`src/variables/variable.rules.ts`, a `static rules` entry) refuses `KEY=value`, `KEY:value`, a repeated key, `.` and +`..`, and a key also given by `--var` or by `--from-stack` (`STACK_VARIABLE_KEYS`). `prepareSecretInput` +(`src/variables/variable.secrets.ts`), which `EnvironmentCreator` and `ProjectCreator` run first, refuses a key that +is also in the `--dotenv` file (an empty value counts), more than one secret without a terminal (the error, `SECRETS_WITHOUT_TERMINAL_MESSAGE`, says to create it with one `--secret`, then names +`launch:variables:set --secret ` for each remaining key; that flag is planned, delivered by CL-8991, and does not exist yet), a bare `--var KEY` beside a secret without a terminal (both read +standard input), and an empty or multi-line piped value. It reads the one piped value before those requests, so a +stalled pipe ends in `SecretInputTimeoutError` with nothing created; raised from a create command it says to pipe the value into +that same command (`launch:env:create` or `launch:projects:create`) with `--secret ` (`createPipeExample`). On a terminal the values are asked +last, after Contentstack Authentication, as `Value for A (1/2)`; `--secret` alone skips the `Add variables from` +checklist, and a prompt-only run offers `Add secrets (write-only)` there, with its own wording (`PROMPT_KEY_WORDING`, `chosenVariableError`) that never names +`--secret`. A key with a client-exposed prefix prints +`clientExposedWarning`. `EnvironmentsApi.create` and `ProjectsApi.create` word the secret key conflict, the +multi-line value and the combined 128-entry / 14 KB limits with the secrets wording only when the request carried +secrets, and mask every secret value in the error they rethrow (`asRedactedFailure`). The create summary names the +secret keys and never a value. + **`--from-stack` and `--alias`.** `--from-stack` is a bare flag on `variables:set`, `projects:create` and `env:create`; `--alias ` (`-a`) names a delivery token saved with `csdx auth:tokens:add`, and is a usage error without `--from-stack` (`aliasRequiresFromStack`). With an alias the token is read from the `tokens` config object @@ -380,8 +406,8 @@ plus the stack's API key, the token and its environment. `src/stacks/` owns the `CmaSession.fetchStacks` / `fetchDeliveryTokens`, which page 100 at a time. `fetchStacks` scopes by organization on the stack handle (`stack({ organization_uid })`), which the SDK sends as the `organization_uid` header and an `org_uid` query filter (inside `query()` it would be a plain query parameter), and `StacksApi.list` also drops -any stack whose `org_uid` names another organization; `variables` may import `stacks` and -`environments` and nothing else (`RESOURCE_EDGES`). A delivery token value is never printed or logged. +any stack whose `org_uid` names another organization; `variables` may import `stacks`, +`environments` and `secrets` and nothing else (`RESOURCE_EDGES`). A delivery token value is never printed or logged. Two harness traps. `@oclif/test`'s `runCommand` joins argv with spaces and splits it again, so a value containing a space must be passed pre-quoted there (`'"MSG=hello world"'`); the real parser keeps it whole, which @@ -1020,25 +1046,29 @@ silently pass. `--since` with the default deployment type is refused. Write the next rule when a command needs it; a rule kept alive only by its own test proves nothing. -**Built ahead of use.** Four pieces of production code have no caller yet, on purpose, each held +**Built ahead of use.** Three pieces of production code have no caller yet, on purpose, each held for a named ticket whose shape it already fits. Nothing else in `src` is uncalled; add to this list rather than leave an orphan unexplained. | Code | Held for | Why its API fits | |---|---|---| | `DeploymentsApi.list` | CL-7170 (`deployments:*`) | a `DeploymentScope` plus paging -> `DeploymentsPage` | -| `src/core/redact.ts` | CL-7169 (variables) | see below | | `exactlyOneOf` | the next command that requires one of several flags and cannot prompt for it - `cache:purge` now uses `atMostOneOf` because it asks on a terminal | "exactly one of these flags", judging what the user supplied; `oneOfMessage` is shared with `atMostOneOf` and `cache:purge`'s no-terminal refusal | | `atLeastOneOf` | no ticket yet - its caller, `projects:update`, now prompts for missing fields instead | "at least one of these flags" for the next command that must not prompt - and it judges what the user supplied, not defaults | -**Redaction.** `src/core/redact.ts` (`REDACTED`, `redactedColumn`) has no caller yet; it is kept -ahead of its first use on purpose, so the easy path for the first presenter that renders an -environment variable's value in a table or a detail block is the redacted one. Confirmation text -and error text are not covered: nothing stops a future `variables:*` command from interpolating a -value straight into `this.confirm(...)` or a thrown error's message. Building that guard needs a -debug logger and an in-flight secret registry to redact against, neither of which exists yet - until -one does, a command handling variable values must redact them itself before they reach `confirm()` -or an error message. +**Redaction.** `src/core/redact.ts` has `REDACTED`, `redactedColumn` and `withoutValues`. +`variable.presenter.ts` renders a variable's value through `redactedColumn`, so a table never prints it. +`withoutValues(text, values)` masks every value in a text in its raw, trimmed, JSON-escaped and +URL-encoded forms, longest form first; a form shorter than `MASK_ANYWHERE_MIN_LENGTH` (6) characters +matches whole tokens only (letters, digits and underscore are word characters), so a short secret does not +mask the digits and words around it. `asRedactedFailure` (`environment.errors.ts`) runs it +over a failure before `EnvironmentsApi.create` and `ProjectsApi.create` rethrow it: it keeps the error's +class, name, redacted stack and redacted cause. A `LaunchApiError` is rebuilt with its entries redacted +(its `rawErrors` become those redacted entries) and carries the original's redacted stack, so the printed +frames are the original's, not `asRedactedFailure`'s. Every other own field is dropped, as is a cause that is +neither text nor an `Error`; a `LaunchError` that is not an API or network failure passes through unchanged. Confirmation +text is not covered: nothing stops a command from interpolating a value straight into `this.confirm(...)`, +so a command handling variable values must redact them itself before they reach `confirm()`. **The environment commands (CL-7168).** `launch:env:list`, `:get`, `:create`, `:update` and `:delete` - `launch:env:*` by product decision, not the `launch:environments:*` the Commands Details diff --git a/README.md b/README.md index 8b57d48e..920edc7c 100644 --- a/README.md +++ b/README.md @@ -311,8 +311,8 @@ Create an environment in a Launch project and follow its first deployment USAGE $ csdx launch:env:create [--config ] [-d ] [--org ] [--project ] [--name ] [--branch ] [--framework ] [--build-cmd ] [--server-cmd ] [--output-dir ] - [--res-mode ] [--auto-deploy ] [--cs-auth ] [--var ...] [--dotenv ...] - [--from-stack] [-a ] + [--res-mode ] [--auto-deploy ] [--cs-auth ] [--var ...] [--dotenv ...] [--secret + ...] [--from-stack] [-a ] FLAGS -a, --alias= Alias of a delivery token saved with csdx auth:tokens:add, used with --from-stack without a @@ -333,6 +333,9 @@ FLAGS --output-dir= Output directory --project= Project name or UID --res-mode= Response mode (buffered | streaming) + --secret=... Secret key only, repeatable or comma separated: --secret A --secret B or --secret A,B. The + value is read from a masked prompt, or from standard input when piped, never from the + command line --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 @@ -344,6 +347,10 @@ EXAMPLES $ csdx launch:env:create --org --project --name staging --branch develop --framework NextJs --build-cmd "npm run build" --output-dir .next --res-mode buffered $ csdx launch:env:create --org --project --name staging --data-dir ./site # a FileUpload project uploads the folder + + $ csdx launch:env:create --org --project --name staging --var API_URL=https://api.example.test --secret STRIPE_KEY,DB_PASSWORD # each secret value is asked at a masked prompt + + $ printf '%s' "$STRIPE_KEY" | csdx launch:env:create --org --project --name staging --branch --framework NextJs --secret STRIPE_KEY # a single secret can be piped in ``` _See code: [src/commands/launch/env/create.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/env/create.ts)_ @@ -608,7 +615,7 @@ USAGE $ csdx launch:projects:create [--config ] [-d ] [--org ] [--type ] [--name ] [--description ] [--env-name ] [--branch ] [--framework ] [--build-cmd ] [--server-cmd ] [--output-dir ] [--res-mode ] [--auto-deploy ] [--cs-auth ] - [--var ...] [--dotenv ...] [--from-stack] [-a ] + [--var ...] [--dotenv ...] [--secret ...] [--from-stack] [-a ] FLAGS -a, --alias= Alias of a delivery token saved with csdx auth:tokens:add, used with --from-stack without a @@ -630,6 +637,9 @@ FLAGS --org= Organization UID --output-dir= Output directory --res-mode= Response mode (buffered | streaming) + --secret=... Secret key only, repeatable or comma separated: --secret A --secret B or --secret A,B. The + value is read from a masked prompt, or from standard input when piped, never from the + command line --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 @@ -644,6 +654,10 @@ EXAMPLES $ csdx launch:projects:create --org --type FileUpload --name --env-name --data-dir ./site --framework Other --build-cmd "npm run build" --output-dir ./ --res-mode buffered $ csdx launch:projects:create --org --type GitHub --data-dir ./my-clone # the repository comes from the folder's GitHub remote + + $ csdx launch:projects:create --org --type GitHub --name --env-name --var API_URL=https://api.example.test --secret STRIPE_KEY,DB_PASSWORD # each secret value is asked at a masked prompt + + $ printf '%s' "$STRIPE_KEY" | csdx launch:projects:create --org --type GitHub --name --env-name --branch --framework NextJs --secret STRIPE_KEY # a single secret can be piped in ``` _See code: [src/commands/launch/projects/create.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/projects/create.ts)_