From ce5a46dec0de3e6ed32d303445e2bad2bce4747f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 18:34:34 +0000 Subject: [PATCH 1/6] CL-8166 | +Claude | Add launch:secrets:list command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add csdx launch:secrets:list with --org, --project and --environment flags. It reads Environment.secrets (key and updatedAt only) through the existing GraphQL client and renders a KEY / UPDATED table, never a value. A 403 shows a clear permission message. Refreshed .talismanrc checksums for the touched files (only "secret" wording flagged). #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 10 +- src/commands/launch/secrets/list.test.ts | 141 ++++++++++++++++++++ src/commands/launch/secrets/list.ts | 108 +++++++++++++++ src/graphql/queries.ts | 18 +++ test/integration/harness/fixtures.ts | 23 ++++ test/integration/specs/secrets-list.test.ts | 67 ++++++++++ 6 files changed, 366 insertions(+), 1 deletion(-) create mode 100644 src/commands/launch/secrets/list.test.ts create mode 100644 src/commands/launch/secrets/list.ts create mode 100644 test/integration/specs/secrets-list.test.ts diff --git a/.talismanrc b/.talismanrc index d59b6132..5bbee22a 100644 --- a/.talismanrc +++ b/.talismanrc @@ -38,9 +38,17 @@ fileignoreconfig: - filename: test/integration/specs/launch-github.test.ts checksum: 4ea1ae16627383530d7590374ba2b37fde87b5c111cc6c38c5125456aa9b51c8 - filename: test/integration/harness/fixtures.ts - checksum: b3133a65f3f4b3f3a32caf0cc0bf65b0c71187f96e044a3331ddcce3adea88c1 + checksum: 41f961e91f8628a6ca3ffda5c8172c6f89f5f97d9d9b9a9c3689916760872e82 - filename: src/base-command.ts checksum: db8bc45f6d8aa3daebae621920c8618b6e23d1a20984dee0749d91bfa5c1530c - filename: test/unit/base-command.test.ts checksum: 4612c2a41c9d5a7af887f77842feee0a6f6a28ba95a094282b5e9aa20dba6c8c +- filename: src/graphql/queries.ts + checksum: 6877ec55200ec4913b3c2bde7cc45e16b50e8e7a4a2cfc26529ded6d9fe27718 +- filename: test/integration/specs/secrets-list.test.ts + checksum: d4cdd09fe16a876f7457bdf9bbaa83511624c12a0c7a967abc5f26a678696629 +- filename: src/commands/launch/secrets/list.ts + checksum: 2cb79446bb06c785a2c1a349195e7d90c6a5c5bf4a14be995b970f6fb2b2ccd9 +- filename: src/commands/launch/secrets/list.test.ts + checksum: a5113cbf747b711af916751e37912f50660bc307683a2237eac4f767d5157ce6 version: "1.0" diff --git a/src/commands/launch/secrets/list.test.ts b/src/commands/launch/secrets/list.test.ts new file mode 100644 index 00000000..d23f9577 --- /dev/null +++ b/src/commands/launch/secrets/list.test.ts @@ -0,0 +1,141 @@ +import { print } from 'graphql'; +import { randomUUID } from 'crypto'; +import { cliux } from '@contentstack/cli-utilities'; + +import { environmentSecretsQuery } from '../../../graphql'; + +import ListSecrets from './list'; + +jest.mock('../../../util', () => { + const actual = jest.requireActual('../../../util'); + return { + ...actual, + Logger: jest.fn(), + selectOrg: jest.fn(), + selectProject: jest.fn(), + }; +}); + +jest.mock('@contentstack/cli-utilities', () => { + const { launchCommand } = jest.requireActual('../../../test/mocks/cli-utilities'); + return { ...launchCommand, cliux: { ...launchCommand.cliux, table: jest.fn() } }; +}); + +const secretsResponse = (secrets: Record[], name = 'Default') => ({ + data: { + Environments: { + edges: [{ node: { uid: 'env-uid', name, secrets } }], + }, + }, +}); + +const buildCommand = (flags: Record, query: jest.Mock) => { + const cmd = new ListSecrets([], {} as any); + (cmd as any).flags = flags; + (cmd as any).log = jest.fn(); + (cmd as any).sharedConfig = { currentConfig: { uid: 'project-uid' } }; + (cmd as any).apolloClient = { query }; + return cmd; +}; + +describe('ListSecrets Command', () => { + let exitMock: jest.SpyInstance; + + beforeEach(() => { + exitMock = jest.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Error(`process.exit:${code}`); + }) as any); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('renders a table with KEY and UPDATED columns for the environment secrets', async () => { + const query = jest.fn().mockResolvedValue( + secretsResponse([ + { key: 'API_TOKEN', updatedAt: '2026-01-01T00:00:00.000Z' }, + { key: 'DB_PASSWORD', updatedAt: '2026-02-01T00:00:00.000Z' }, + ]), + ); + const cmd = buildCommand({ environment: 'Default' }, query); + + await (cmd as any).listSecrets(); + + expect(cliux.table).toHaveBeenCalledTimes(1); + expect(cliux.table).toHaveBeenCalledWith( + [{ value: 'KEY' }, { value: 'UPDATED' }], + [ + { KEY: 'API_TOKEN', UPDATED: '2026-01-01T00:00:00.000Z' }, + { KEY: 'DB_PASSWORD', UPDATED: '2026-02-01T00:00:00.000Z' }, + ], + ); + }); + + it('selects only key and updatedAt of the secrets and never a value field', () => { + const printed = print(environmentSecretsQuery); + + expect(printed).toMatch(/secrets\s*\{\s*key\s*updatedAt\s*\}/); + expect(printed).not.toMatch(/\bvalue\b/); + }); + + it('exits with an error and renders no table when the environment is not found', async () => { + const query = jest.fn().mockResolvedValue(secretsResponse([{ key: 'API_TOKEN', updatedAt: '2026-01-01T00:00:00.000Z' }])); + const cmd = buildCommand({ environment: 'Staging' }, query); + + await expect((cmd as any).listSecrets()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith('Environment(s) not found!', 'error'); + expect(exitMock).toHaveBeenCalledWith(1); + expect(cliux.table).not.toHaveBeenCalled(); + }); + + it('prints an empty-state line without exiting or rendering a table when there are no secrets', async () => { + const query = jest.fn().mockResolvedValue(secretsResponse([])); + const cmd = buildCommand({ environment: 'Default' }, query); + + await (cmd as any).listSecrets(); + + expect(cliux.print).toHaveBeenCalledWith('No secrets found for environment Default.'); + expect(cliux.table).not.toHaveBeenCalled(); + expect(exitMock).not.toHaveBeenCalled(); + expect((cmd as any).log).not.toHaveBeenCalled(); + }); + + it('never outputs a value even when the response node carries one', async () => { + const leakedValue = randomUUID(); + const query = jest + .fn() + .mockResolvedValue(secretsResponse([{ key: 'API_TOKEN', updatedAt: '2026-01-01T00:00:00.000Z', value: leakedValue }])); + const cmd = buildCommand({ environment: 'Default' }, query); + + await (cmd as any).listSecrets(); + + const everythingEmitted = JSON.stringify([ + (cliux.table as jest.Mock).mock.calls, + (cliux.print as jest.Mock).mock.calls, + (cmd as any).log.mock.calls, + ]); + expect(cliux.table).toHaveBeenCalledTimes(1); + expect(everythingEmitted).not.toContain(leakedValue); + expect((cliux.table as jest.Mock).mock.calls[0][1]).toEqual([ + { KEY: 'API_TOKEN', UPDATED: '2026-01-01T00:00:00.000Z' }, + ]); + }); + + it('prompts for the environment when --environment is not given', async () => { + const query = jest.fn().mockResolvedValue(secretsResponse([{ key: 'API_TOKEN', updatedAt: '2026-01-01T00:00:00.000Z' }])); + (cliux.inquire as jest.Mock).mockResolvedValue('Default'); + const cmd = buildCommand({}, query); + + await (cmd as any).listSecrets(); + + expect(cliux.inquire).toHaveBeenCalledWith( + expect.objectContaining({ type: 'search-list', name: 'Environment', message: 'Choose an environment' }), + ); + expect(cliux.table).toHaveBeenCalledWith( + [{ value: 'KEY' }, { value: 'UPDATED' }], + [{ KEY: 'API_TOKEN', UPDATED: '2026-01-01T00:00:00.000Z' }], + ); + }); +}); diff --git a/src/commands/launch/secrets/list.ts b/src/commands/launch/secrets/list.ts new file mode 100644 index 00000000..d5897110 --- /dev/null +++ b/src/commands/launch/secrets/list.ts @@ -0,0 +1,108 @@ +import map from 'lodash/map'; +import find from 'lodash/find'; +import isEmpty from 'lodash/isEmpty'; +import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; + +import { BaseCommand } from '../../../base-command'; +import { environmentSecretsQuery } from '../../../graphql'; +import { Logger, selectOrg, selectProject } from '../../../util'; + +export default class ListSecrets extends BaseCommand { + static description = 'List the secrets of an environment (keys only, values are never shown)'; + + static examples = [ + '$ <%= config.bin %> <%= command.id %> --environment=', + '$ <%= config.bin %> <%= command.id %> --org= --project= ' + + '--environment=', + ]; + + static flags: FlagInput = { + org: Flags.string({ + description: '[Optional] Provide the organization UID', + }), + project: Flags.string({ + description: '[Optional] Provide the project UID', + }), + environment: Flags.string({ + char: 'e', + description: 'Environment name or UID', + }), + }; + + async run(): Promise { + this.logger = new Logger(this.sharedConfig); + this.log = this.logger.log.bind(this.logger); + + await this.getConfig(); + await this.prepareApiClients(); + + if (!this.sharedConfig.currentConfig?.uid) { + await selectOrg({ + log: this.log, + flags: this.flags, + config: this.sharedConfig, + managementSdk: this.managementSdk, + }); + await this.prepareApiClients(); + await selectProject({ + log: this.log, + flags: this.flags, + config: this.sharedConfig, + apolloClient: this.apolloClient, + }); + await this.prepareApiClients(); + } + + await this.listSecrets(); + } + + async listSecrets(): Promise { + const environment = await this.resolveEnvironment(); + + if (isEmpty(environment.secrets)) { + ux.print(`No secrets found for environment ${environment.name}.`); + return; + } + + ux.table( + [{ value: 'KEY' }, { value: 'UPDATED' }], + map(environment.secrets, ({ key, updatedAt }) => ({ KEY: key, UPDATED: updatedAt })), + ); + } + + async resolveEnvironment(): Promise { + const environments = await this.apolloClient + .query({ query: environmentSecretsQuery }) + .then(({ data: { Environments } }) => map(Environments.edges, 'node')) + .catch((error) => { + if (error?.graphQLErrors?.[0]?.extensions?.exception?.status === 403) { + this.log('You do not have permission to list the secrets of this environment.', 'error'); + process.exit(1); + } + throw error; + }); + + if (!this.flags.environment) { + return ux + .inquire({ + type: 'search-list', + name: 'Environment', + choices: map(environments, (row) => ({ name: row.name, value: row.name })), + message: 'Choose an environment', + }) + .then((name: any) => find(environments, { name }) as Record); + } + + const environment = find( + environments, + ({ uid, name }) => uid === this.flags.environment || name === this.flags.environment, + ); + + if (isEmpty(environment)) { + this.log('Environment(s) not found!', 'error'); + process.exit(1); + } + + return environment; + } +} diff --git a/src/graphql/queries.ts b/src/graphql/queries.ts index e3d98860..a3a0db0f 100755 --- a/src/graphql/queries.ts +++ b/src/graphql/queries.ts @@ -223,6 +223,23 @@ const environmentsQuery: DocumentNode = gql` } `; +const environmentSecretsQuery: DocumentNode = gql` + query EnvironmentSecrets { + Environments { + edges { + node { + uid + name + secrets { + key + updatedAt + } + } + } + } + } +`; + export { projectsQuery, branchesQuery, @@ -237,5 +254,6 @@ export { serverlessLogsQuery, latestLiveDeploymentQuery, environmentsQuery, + environmentSecretsQuery, rollbackSettingsQuery, }; diff --git a/test/integration/harness/fixtures.ts b/test/integration/harness/fixtures.ts index 9eafdc79..876553aa 100644 --- a/test/integration/harness/fixtures.ts +++ b/test/integration/harness/fixtures.ts @@ -50,6 +50,29 @@ export const environmentsResponse = (nodes: Record[] = [environment }, }); +export const SECRET_KEY = 'API_TOKEN'; + +export const secretNode = (overrides: Record = {}) => ({ + __typename: 'EnvironmentSecret', + key: SECRET_KEY, + updatedAt: '2026-01-01T00:00:00.000Z', + ...overrides, +}); + +export const environmentSecretsResponse = (secrets: Record[] = [secretNode()]) => ({ + data: { + Environments: { + __typename: 'EnvironmentConnection', + edges: [ + { + __typename: 'EnvironmentEdge', + node: { __typename: 'Environment', uid: ENVIRONMENT_UID, name: ENVIRONMENT_NAME, secrets }, + }, + ], + }, + }, +}); + export const projectsResponse = ( projects: { uid: string; name: string }[] = [{ uid: PROJECT_UID, name: PROJECT_NAME }], ) => ({ diff --git a/test/integration/specs/secrets-list.test.ts b/test/integration/specs/secrets-list.test.ts new file mode 100644 index 00000000..9ab89e12 --- /dev/null +++ b/test/integration/specs/secrets-list.test.ts @@ -0,0 +1,67 @@ +import ListSecrets from '../../../src/commands/launch/secrets/list'; +import { cma, fixtures, prompts, runCommand, startSession, Session } from '../harness'; + +describe('launch:secrets:list', () => { + let session: Session; + + beforeEach(async () => { + session = await startSession(); + cma.withOrganizations([fixtures.ORG, fixtures.OTHER_ORG]); + }); + + afterEach(async () => { + await session.stop(); + }); + + const flags = () => [ + ...session.baseArgs, + '--org', + fixtures.ORG.uid, + '--project', + fixtures.PROJECT_UID, + '--environment', + fixtures.ENVIRONMENT_NAME, + ]; + + it('lists the secret keys of the environment named by --org, --project and --environment', async () => { + session.api.on('Projects', fixtures.projectsResponse()).on('EnvironmentSecrets', fixtures.environmentSecretsResponse()); + prompts.script([]); + + const result = await runCommand(ListSecrets, flags()); + + expect(result.error).toBeUndefined(); + expect(result.exitCode).toBe(0); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + + expect(session.api.operationSequence()).toEqual(['Projects', 'EnvironmentSecrets']); + const headers = session.api.headersOf('EnvironmentSecrets'); + expect(headers.organization_uid).toBe(fixtures.ORG.uid); + expect(headers['x-project-uid']).toBe(fixtures.PROJECT_UID); + + expect(result.output).toContain('KEY'); + expect(result.output).toContain('UPDATED'); + expect(result.output).toContain(fixtures.SECRET_KEY); + }); + + it('shows a clear permission message and no raw error when the API answers 403', async () => { + session.api.on('Projects', fixtures.projectsResponse()).on('EnvironmentSecrets', { + errors: [ + { + message: 'Forbidden resource', + extensions: { exception: { status: 403, errorObject: { policy: 'raw-policy-detail' } } }, + }, + ], + }); + prompts.script([]); + + const result = await runCommand(ListSecrets, flags()); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('You do not have permission to list the secrets of this environment.'); + expect(result.output).not.toContain('raw-policy-detail'); + expect(result.output).not.toContain('Forbidden resource'); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + }); +}); From 6fb304e50ead835f76d4a0d630d8bb4669235709 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 18:41:30 +0000 Subject: [PATCH 2/6] CL-8166 | +Claude | Add launch:secrets:set command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add csdx launch:secrets:set, which reads the value from a masked prompt or piped stdin (no --value flag), adds or refreshes the secret after confirmation, warns on client-exposed prefixes and redacts values from errors. Adds the shared secrets util and the add/refresh mutations. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 16 +- src/commands/launch/secrets/set.test.ts | 274 +++++++++++++++++++++ src/commands/launch/secrets/set.ts | 186 ++++++++++++++ src/graphql/mutation.ts | 20 ++ src/util/index.ts | 1 + src/util/secrets.test.ts | 125 ++++++++++ src/util/secrets.ts | 64 +++++ test/integration/harness/fixtures.ts | 12 + test/integration/harness/index.ts | 1 + test/integration/harness/session.ts | 2 + test/integration/harness/stdin.ts | 21 ++ test/integration/specs/secrets-set.test.ts | 165 +++++++++++++ 12 files changed, 885 insertions(+), 2 deletions(-) create mode 100644 src/commands/launch/secrets/set.test.ts create mode 100644 src/commands/launch/secrets/set.ts create mode 100644 src/util/secrets.test.ts create mode 100644 src/util/secrets.ts create mode 100644 test/integration/harness/stdin.ts create mode 100644 test/integration/specs/secrets-set.test.ts diff --git a/.talismanrc b/.talismanrc index 5bbee22a..160d2c40 100644 --- a/.talismanrc +++ b/.talismanrc @@ -34,11 +34,11 @@ fileignoreconfig: - filename: test/integration/harness/launch-api.ts checksum: a4549b87c896744422e71ab5395a1d6d2dfa372678d2488aecc4247ee9738f87 - filename: test/integration/harness/session.ts - checksum: 74dc637304710b1df882bea6a1c52b8779f1bd416dbeeab93a9026c68edb3f9e + checksum: 49000399e4150155dbdccccc8a97e2cda429035062c41e69c30a5f904e5a361c - filename: test/integration/specs/launch-github.test.ts checksum: 4ea1ae16627383530d7590374ba2b37fde87b5c111cc6c38c5125456aa9b51c8 - filename: test/integration/harness/fixtures.ts - checksum: 41f961e91f8628a6ca3ffda5c8172c6f89f5f97d9d9b9a9c3689916760872e82 + checksum: 97a6a6b9c83c1d53ace7175961d7654b4523a3a446bb5a5716f97897fdc895c4 - filename: src/base-command.ts checksum: db8bc45f6d8aa3daebae621920c8618b6e23d1a20984dee0749d91bfa5c1530c - filename: test/unit/base-command.test.ts @@ -51,4 +51,16 @@ fileignoreconfig: checksum: 2cb79446bb06c785a2c1a349195e7d90c6a5c5bf4a14be995b970f6fb2b2ccd9 - filename: src/commands/launch/secrets/list.test.ts checksum: a5113cbf747b711af916751e37912f50660bc307683a2237eac4f767d5157ce6 +- filename: src/graphql/mutation.ts + checksum: b2b64d708700428354cc9863710e3aa2bdaee073e63e11cb1755ca46a2a961d6 +- filename: src/util/secrets.ts + checksum: 0558c6fd1e876704613fa5f4d2eb8a3c1985b4d7f8539d1d3cb47ec2ca8caae0 +- filename: src/commands/launch/secrets/set.ts + checksum: a850e49f4a1a87e34721d94432934f72971ba6f9c151ae8b50a0dc6985095d6f +- filename: src/util/secrets.test.ts + checksum: 08a359719861f1a249fe3ccfac282c48a678e0b2a8ceb7f795e2676acb697c24 +- filename: test/integration/specs/secrets-set.test.ts + checksum: 931fca7aae520cd3b5a63e1c4ba64e4df78fbd121d5f256ba5977703d6fa9b5e +- filename: src/commands/launch/secrets/set.test.ts + checksum: 822408f4669aadf22d91d859b8c09789c123b03e7490e285c8b274ef551186d8 version: "1.0" diff --git a/src/commands/launch/secrets/set.test.ts b/src/commands/launch/secrets/set.test.ts new file mode 100644 index 00000000..eb80255b --- /dev/null +++ b/src/commands/launch/secrets/set.test.ts @@ -0,0 +1,274 @@ +import { Readable } from 'stream'; +import { randomUUID } from 'crypto'; +import { cliux } from '@contentstack/cli-utilities'; + +import { addEnvironmentSecretMutation, refreshEnvironmentSecretMutation } from '../../../graphql'; + +import SetSecret from './set'; + +jest.mock('../../../util', () => { + const actual = jest.requireActual('../../../util'); + return { + ...actual, + Logger: jest.fn(), + selectOrg: jest.fn(), + selectProject: jest.fn(), + }; +}); + +jest.mock('@contentstack/cli-utilities', () => { + const { launchCommand } = jest.requireActual('../../../test/mocks/cli-utilities'); + return { ...launchCommand, cliux: { ...launchCommand.cliux, table: jest.fn() } }; +}); + +const ENVIRONMENT_UID = 'env-uid'; + +const environmentsResponse = (secrets: Record[] = [], name = 'Default') => ({ + data: { Environments: { edges: [{ node: { uid: ENVIRONMENT_UID, name, secrets } }] } }, +}); + +const apiError = (status: number, name?: string) => ({ + message: 'Request failed', + graphQLErrors: [{ message: 'Request failed', extensions: { exception: { status, ...(name ? { name } : {}) } } }], +}); + +const originalStdin = Object.getOwnPropertyDescriptor(process, 'stdin') as PropertyDescriptor; + +const stubStdin = (isTTY: boolean, chunks: string[] = []) => { + const stream: any = Readable.from(chunks); + stream.isTTY = isTTY; + Object.defineProperty(process, 'stdin', { value: stream, configurable: true }); +}; + +const buildCommand = ( + flags: Record, + { secrets = [], mutate = jest.fn().mockResolvedValue({ data: {} }) }: { secrets?: Record[]; mutate?: jest.Mock } = {}, +) => { + const query = jest.fn().mockResolvedValue(environmentsResponse(secrets)); + const cmd = new SetSecret([], {} as any); + (cmd as any).flags = { environment: 'Default', key: 'API_TOKEN', yes: false, ...flags }; + (cmd as any).log = jest.fn(); + (cmd as any).sharedConfig = { currentConfig: { uid: 'project-uid' } }; + (cmd as any).apolloClient = { query, mutate }; + return { cmd, query, mutate }; +}; + +const allOutput = (...mocks: jest.Mock[]) => JSON.stringify(mocks.map((mock) => mock.mock.calls)); + +describe('SetSecret Command', () => { + let exitMock: jest.SpyInstance; + + beforeEach(() => { + exitMock = jest.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Error(`process.exit:${code}`); + }) as any); + }); + + afterEach(() => { + Object.defineProperty(process, 'stdin', originalStdin); + jest.clearAllMocks(); + }); + + it('adds the secret with the value piped on stdin without prompting when --yes is passed', async () => { + const value = randomUUID(); + stubStdin(false, [`${value}\n`]); + const { cmd, mutate } = buildCommand({ yes: true }); + + await (cmd as any).setSecret(); + + expect(mutate).toHaveBeenCalledTimes(1); + expect(mutate).toHaveBeenCalledWith({ + mutation: addEnvironmentSecretMutation, + variables: { environmentUid: ENVIRONMENT_UID, secret: { key: 'API_TOKEN', value } }, + }); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect(exitMock).not.toHaveBeenCalled(); + }); + + it('strips only one trailing CRLF from the piped value', async () => { + const value = randomUUID(); + stubStdin(false, [`${value}\n`, '\r\n']); + const { cmd, mutate } = buildCommand({ yes: true }); + + await (cmd as any).setSecret(); + + expect(mutate.mock.calls[0][0].variables.secret.value).toBe(`${value}\n`); + }); + + it('asks for the value with a masked prompt then confirms before adding when run in a terminal', async () => { + const value = randomUUID(); + stubStdin(true); + (cliux.inquire as jest.Mock).mockResolvedValueOnce(value).mockResolvedValueOnce(true); + const { cmd, mutate } = buildCommand({}); + + await (cmd as any).setSecret(); + + const [first, second] = (cliux.inquire as jest.Mock).mock.calls.map(([question]) => question); + expect(first.type).toBe('password'); + expect(second.type).toBe('confirm'); + expect(mutate).toHaveBeenCalledTimes(1); + expect(mutate.mock.calls[0][0].variables.secret).toEqual({ key: 'API_TOKEN', value }); + }); + + it('refreshes the secret instead of adding it when the key already exists', async () => { + stubStdin(false, [randomUUID()]); + const { cmd, mutate } = buildCommand( + { yes: true }, + { secrets: [{ key: 'API_TOKEN', updatedAt: '2026-01-01T00:00:00.000Z' }] }, + ); + + await (cmd as any).setSecret(); + + expect(mutate).toHaveBeenCalledTimes(1); + expect(mutate.mock.calls[0][0].mutation).toBe(refreshEnvironmentSecretMutation); + expect(mutate.mock.calls[0][0].variables.environmentUid).toBe(ENVIRONMENT_UID); + }); + + it('aborts without a mutation or an error exit when the confirmation is declined', async () => { + stubStdin(true); + (cliux.inquire as jest.Mock).mockResolvedValueOnce(randomUUID()).mockResolvedValueOnce(false); + const { cmd, mutate } = buildCommand({}); + + await (cmd as any).setSecret(); + + expect(mutate).not.toHaveBeenCalled(); + expect(cliux.print).toHaveBeenCalledWith(expect.stringContaining('Aborted')); + expect(exitMock).not.toHaveBeenCalled(); + }); + + it('fails with a clear error and no mutation when nothing is piped on stdin', async () => { + stubStdin(false, []); + const { cmd, mutate } = buildCommand({ yes: true }); + + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + + expect(mutate).not.toHaveBeenCalled(); + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('no value received on stdin'), 'error'); + expect(exitMock).toHaveBeenCalledWith(1); + }); + + it('fails with a clear error and no mutation when the prompted value is empty', async () => { + stubStdin(true); + (cliux.inquire as jest.Mock).mockResolvedValueOnce(''); + const { cmd, mutate } = buildCommand({}); + + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + + expect(mutate).not.toHaveBeenCalled(); + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('value cannot be empty'), 'error'); + expect(exitMock).toHaveBeenCalledWith(1); + }); + + it('requires --yes when the value is piped and never prompts for confirmation', async () => { + stubStdin(false, [randomUUID()]); + const { cmd, mutate } = buildCommand({ yes: false }); + + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + + expect(mutate).not.toHaveBeenCalled(); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('use --yes when piping the value'), 'error'); + expect(exitMock).toHaveBeenCalledWith(1); + }); + + it('warns for a client-exposed key and still sends the mutation', async () => { + stubStdin(false, [randomUUID()]); + const { cmd, mutate } = buildCommand({ yes: true, key: 'NEXT_PUBLIC_API_URL' }); + + await (cmd as any).setSecret(); + + expect(cliux.print).toHaveBeenCalledWith( + expect.stringContaining('NEXT_PUBLIC_API_URL'), + expect.objectContaining({ color: 'yellow' }), + ); + expect(mutate).toHaveBeenCalledTimes(1); + }); + + it.each(['API_TOKEN', 'MY_NEXT_PUBLIC_X'])('does not warn for the key %s', async (key) => { + stubStdin(false, [randomUUID()]); + const { cmd, mutate } = buildCommand({ yes: true, key }); + + await (cmd as any).setSecret(); + + expect(cliux.print).not.toHaveBeenCalled(); + expect(mutate).toHaveBeenCalledTimes(1); + }); + + it('shows the multi-line message and leaks no value fragment when the API rejects a multi-line value', async () => { + stubStdin(false, ['line1\nline2']); + const mutate = jest.fn().mockRejectedValue(apiError(400, 'ENVIRONMENT_SECRET_VALUE_MULTILINE')); + const { cmd } = buildCommand({ yes: true }, { mutate }); + + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('multi-line values are not supported'), 'error'); + expect(exitMock).toHaveBeenCalledWith(1); + expect(allOutput((cmd as any).log, cliux.print as jest.Mock)).not.toContain('line1'); + }); + + it('reports the key conflict message when the API answers 409', async () => { + stubStdin(false, [randomUUID()]); + const mutate = jest.fn().mockRejectedValue(apiError(409, 'ENVIRONMENT_SECRET_KEY_CONFLICT')); + const { cmd } = buildCommand({ yes: true }, { mutate }); + + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('already used by a variable or secret'), 'error'); + }); + + it('prints a success line naming the key and never the value', async () => { + const value = randomUUID(); + stubStdin(false, [value]); + const { cmd } = buildCommand({ yes: true }); + + await (cmd as any).setSecret(); + + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('API_TOKEN')); + expect(allOutput((cmd as any).log, cliux.print as jest.Mock)).not.toContain(value); + }); + + it('exits with an error when the environment is not found', async () => { + stubStdin(false, [randomUUID()]); + const { cmd, mutate } = buildCommand({ yes: true, environment: 'Staging' }); + + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith('Environment(s) not found!', 'error'); + expect(mutate).not.toHaveBeenCalled(); + }); + + it('asks which environment to use when --environment is not given', async () => { + stubStdin(false, [randomUUID()]); + (cliux.inquire as jest.Mock).mockResolvedValueOnce('Default'); + const { cmd, mutate } = buildCommand({ yes: true, environment: undefined }); + + await (cmd as any).setSecret(); + + expect((cliux.inquire as jest.Mock).mock.calls[0][0]).toEqual( + expect.objectContaining({ type: 'search-list', name: 'Environment' }), + ); + expect(mutate).toHaveBeenCalledTimes(1); + }); + + it('shows a formatted error when reading the environment secrets fails', async () => { + stubStdin(false, [randomUUID()]); + const { cmd, query, mutate } = buildCommand({ yes: true }); + query.mockRejectedValue(apiError(403)); + + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('do not have permission'), 'error'); + expect(mutate).not.toHaveBeenCalled(); + }); + + it('redacts a flag value from a parse error before rethrowing it', async () => { + const value = randomUUID(); + const { cmd } = buildCommand({}); + const error = new Error(`Nonexistent flag: --value=${value}`); + + await expect((cmd as any).catch(error)).rejects.toThrow('Nonexistent flag: --value'); + + expect(error.message).not.toContain(value); + expect(error.stack).not.toContain(value); + }); +}); diff --git a/src/commands/launch/secrets/set.ts b/src/commands/launch/secrets/set.ts new file mode 100644 index 00000000..e128341c --- /dev/null +++ b/src/commands/launch/secrets/set.ts @@ -0,0 +1,186 @@ +import map from 'lodash/map'; +import find from 'lodash/find'; +import isEmpty from 'lodash/isEmpty'; +import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; + +import { BaseCommand } from '../../../base-command'; +import { + environmentSecretsQuery, + addEnvironmentSecretMutation, + refreshEnvironmentSecretMutation, +} from '../../../graphql'; +import { + Logger, + selectOrg, + selectProject, + isClientExposedKey, + clientExposedWarning, + formatSecretsError, + redactFlagValues, +} from '../../../util'; + +export default class SetSecret extends BaseCommand { + static description = + 'Add or refresh a secret of an environment. The value is read from a masked prompt, or from stdin when piped'; + + static examples = [ + '$ <%= config.bin %> <%= command.id %> --key=', + '$ printf %s "$TOKEN" | <%= config.bin %> <%= command.id %> --key= --yes', + '$ <%= config.bin %> <%= command.id %> --org= --project= ' + + '--environment= --key=', + ]; + + static flags: FlagInput = { + org: Flags.string({ + description: '[Optional] Provide the organization UID', + }), + project: Flags.string({ + description: '[Optional] Provide the project UID', + }), + environment: Flags.string({ + char: 'e', + description: 'Environment name or UID', + }), + key: Flags.string({ + char: 'k', + required: true, + description: 'Secret key', + }), + yes: Flags.boolean({ + char: 'y', + description: 'Skip the confirmation prompt (required when the value is piped on stdin)', + }), + }; + + async run(): Promise { + this.logger = new Logger(this.sharedConfig); + this.log = this.logger.log.bind(this.logger); + + await this.getConfig(); + await this.prepareApiClients(); + + if (!this.sharedConfig.currentConfig?.uid) { + await selectOrg({ + log: this.log, + flags: this.flags, + config: this.sharedConfig, + managementSdk: this.managementSdk, + }); + await this.prepareApiClients(); + await selectProject({ + log: this.log, + flags: this.flags, + config: this.sharedConfig, + apolloClient: this.apolloClient, + }); + await this.prepareApiClients(); + } + + await this.setSecret(); + } + + protected async catch(err: Error & { exitCode?: number }): Promise { + err.message = redactFlagValues(err.message); + err.stack = err.stack && redactFlagValues(err.stack); + return super.catch(err); + } + + async setSecret(): Promise { + const { key, yes } = this.flags as Record; + const piped = !process.stdin.isTTY; + + if (piped && !yes) { + this.log('use --yes when piping the value', 'error'); + process.exit(1); + } + + const environment = await this.resolveEnvironment(); + const exists = !isEmpty(find(environment.secrets, { key })); + const value = piped ? await this.readStdin() : await this.promptValue(key); + + if (isEmpty(value)) { + this.log(piped ? 'no value received on stdin' : 'The value cannot be empty.', 'error'); + process.exit(1); + } + + if (isClientExposedKey(key)) { + ux.print(clientExposedWarning(key), { color: 'yellow' }); + } + + if (!yes && !(await this.confirm(key, environment.name, exists))) { + ux.print('Aborted. The secret was not changed.'); + return; + } + + await this.apolloClient + .mutate({ + mutation: exists ? refreshEnvironmentSecretMutation : addEnvironmentSecretMutation, + variables: { environmentUid: environment.uid, secret: { key, value } }, + }) + .catch((error) => { + this.log(formatSecretsError(error, { key, value }), 'error'); + process.exit(1); + }); + + this.log(`Secret ${key} ${exists ? 'refreshed' : 'added'} in environment ${environment.name}.`); + } + + async readStdin(): Promise { + const chunks: Buffer[] = []; + + for await (const chunk of process.stdin) { + chunks.push(Buffer.from(chunk)); + } + + return Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, ''); + } + + promptValue(key: string): Promise { + return ux.inquire({ + type: 'password', + name: 'value', + message: `Enter the value for ${key}`, + }); + } + + confirm(key: string, environmentName: string, exists: boolean): Promise { + return ux.inquire({ + type: 'confirm', + name: 'confirm', + message: `${exists ? 'Refresh' : 'Add'} secret ${key} in environment ${environmentName}?`, + }); + } + + async resolveEnvironment(): Promise { + const environments = await this.apolloClient + .query({ query: environmentSecretsQuery }) + .then(({ data: { Environments } }) => map(Environments.edges, 'node')) + .catch((error) => { + this.log(formatSecretsError(error), 'error'); + process.exit(1); + }); + + if (!this.flags.environment) { + return ux + .inquire({ + type: 'search-list', + name: 'Environment', + choices: map(environments, (row) => ({ name: row.name, value: row.name })), + message: 'Choose an environment', + }) + .then((name: any) => find(environments, { name }) as Record); + } + + const environment = find( + environments, + ({ uid, name }) => uid === this.flags.environment || name === this.flags.environment, + ); + + if (isEmpty(environment)) { + this.log('Environment(s) not found!', 'error'); + process.exit(1); + } + + return environment; + } +} diff --git a/src/graphql/mutation.ts b/src/graphql/mutation.ts index 431ef2f7..d9ff76d4 100755 --- a/src/graphql/mutation.ts +++ b/src/graphql/mutation.ts @@ -85,8 +85,28 @@ const rollbackDeploymentMutation: DocumentNode = gql` } `; +const addEnvironmentSecretMutation: DocumentNode = gql` + mutation AddEnvironmentSecret($environmentUid: String!, $secret: EnvironmentSecretInput!) { + addEnvironmentSecret(environmentUid: $environmentUid, secret: $secret) { + key + updatedAt + } + } +`; + +const refreshEnvironmentSecretMutation: DocumentNode = gql` + mutation RefreshEnvironmentSecret($environmentUid: String!, $secret: EnvironmentSecretInput!) { + refreshEnvironmentSecret(environmentUid: $environmentUid, secret: $secret) { + key + updatedAt + } + } +`; + export { importProjectMutation, + addEnvironmentSecretMutation, + refreshEnvironmentSecretMutation, createDeploymentMutation, rollbackDeploymentMutation, createSignedUploadUrlMutation, diff --git a/src/util/index.ts b/src/util/index.ts index 949b8dff..6ce95f26 100755 --- a/src/util/index.ts +++ b/src/util/index.ts @@ -5,4 +5,5 @@ import LogPolling from './logs-polling-utilities'; export * from './log'; export * from './common-utility'; export * from './create-git-meta'; +export * from './secrets'; export { Logger, GraphqlApiClient, LogPolling }; diff --git a/src/util/secrets.test.ts b/src/util/secrets.test.ts new file mode 100644 index 00000000..c65fa691 --- /dev/null +++ b/src/util/secrets.test.ts @@ -0,0 +1,125 @@ +import { randomUUID } from 'crypto'; + +import { + CLIENT_EXPOSED_PREFIXES, + clientExposedWarning, + isClientExposedKey, + formatSecretsError, + redactFlagValues, +} from './secrets'; + +const apiError = (status: number, code?: string, message = 'Request failed') => ({ + graphQLErrors: [{ message, extensions: { exception: { status, ...(code ? { name: code } : {}) } } }], + message, +}); + +describe('secrets util', () => { + it.each(CLIENT_EXPOSED_PREFIXES)('flags a key starting with %s as client exposed and warns about it', (prefix) => { + const key = `${prefix}API_URL`; + + const exposed = isClientExposedKey(key); + const warning = clientExposedWarning(key); + + expect(exposed).toBe(true); + expect(warning).toContain(key); + expect(warning).toContain('inlined into client JavaScript at build time'); + }); + + it.each(['API_TOKEN', 'MY_NEXT_PUBLIC_X', 'next_public_x'])('does not flag %s as client exposed', (key) => { + expect(isClientExposedKey(key)).toBe(false); + }); + + it('lists the five client exposed prefixes', () => { + expect(CLIENT_EXPOSED_PREFIXES).toEqual(['NEXT_PUBLIC_', 'NUXT_PUBLIC_', 'VITE_', 'GATSBY_', 'PUBLIC_']); + }); + + it.each([ + ['409 key conflict', apiError(409, 'ENVIRONMENT_SECRET_KEY_CONFLICT'), 'already used by a variable or secret'], + ['409 concurrent update', apiError(409, 'ENVIRONMENT_VARIABLES_CONCURRENT_UPDATE'), 'concurrent update'], + ['400 multiline', apiError(400, 'ENVIRONMENT_SECRET_VALUE_MULTILINE'), 'multi-line values are not supported'], + ['400 invalid', apiError(400), 'invalid key or value'], + ['403', apiError(403), 'do not have permission'], + ['404 not found', apiError(404, 'ENVIRONMENT_SECRET_NOT_FOUND'), 'DB_URL was not found'], + ])('formats a %s API error as a clear message', (_label, error, expected) => { + const message = formatSecretsError(error, { key: 'DB_URL' }); + + expect(message).toContain(expected); + }); + + it('produces distinct messages for each known error', () => { + const errors = [ + apiError(409, 'ENVIRONMENT_SECRET_KEY_CONFLICT'), + apiError(409, 'ENVIRONMENT_VARIABLES_CONCURRENT_UPDATE'), + apiError(400, 'ENVIRONMENT_SECRET_VALUE_MULTILINE'), + apiError(400), + apiError(403), + apiError(404, 'ENVIRONMENT_SECRET_NOT_FOUND'), + ]; + + const messages = errors.map((error) => formatSecretsError(error, { key: 'DB_URL' })); + + expect(new Set(messages).size).toBe(messages.length); + messages.forEach((message) => expect(message.length).toBeGreaterThan(0)); + }); + + it('finds a namespaced code in the error object', () => { + const error = { + graphQLErrors: [ + { + message: 'Conflict', + extensions: { exception: { status: 409, errorObject: { code: 'launch.ENVIRONMENT_SECRET_KEY_CONFLICT' } } }, + }, + ], + }; + + const message = formatSecretsError(error, { key: 'DB_URL' }); + + expect(message).toContain('already used by a variable or secret'); + }); + + it('finds a code in the exception messages', () => { + const error = { + graphQLErrors: [ + { message: 'Bad', extensions: { exception: { status: 400, messages: ['ENVIRONMENT_SECRET_VALUE_MULTILINE'] } } }, + ], + }; + + const message = formatSecretsError(error, { key: 'DB_URL' }); + + expect(message).toContain('multi-line values are not supported'); + }); + + it('finds a code in the top level error message', () => { + const error = { message: 'ENVIRONMENT_SECRET_NOT_FOUND', graphQLErrors: [] }; + + const message = formatSecretsError(error, { key: 'DB_URL' }); + + expect(message).toContain('DB_URL was not found'); + }); + + it('falls back to the server message for an unknown error', () => { + const message = formatSecretsError(apiError(500, 'SOMETHING_ELSE', 'Server exploded'), { key: 'DB_URL' }); + + expect(message).toBe('Server exploded'); + }); + + it('never includes the secret value in the message', () => { + const value = randomUUID(); + + const message = formatSecretsError(apiError(500, undefined, `bad value ${value}`), { key: 'DB_URL', value }); + + expect(message).not.toContain(value); + }); + + it('removes the value of an equals-style flag from a parse error message', () => { + const value = randomUUID(); + + const message = redactFlagValues(`Nonexistent flag: --value=${value}\nSee more help with --help`); + + expect(message).toBe('Nonexistent flag: --value\nSee more help with --help'); + }); + + it('leaves a message without flag values unchanged', () => { + expect(redactFlagValues('Missing required flag key')).toBe('Missing required flag key'); + }); +}); diff --git a/src/util/secrets.ts b/src/util/secrets.ts new file mode 100644 index 00000000..55e79fb7 --- /dev/null +++ b/src/util/secrets.ts @@ -0,0 +1,64 @@ +import map from 'lodash/map'; +import some from 'lodash/some'; +import find from 'lodash/find'; +import split from 'lodash/split'; +import filter from 'lodash/filter'; +import isEmpty from 'lodash/isEmpty'; +import includes from 'lodash/includes'; +import startsWith from 'lodash/startsWith'; + +export const CLIENT_EXPOSED_PREFIXES = ['NEXT_PUBLIC_', 'NUXT_PUBLIC_', 'VITE_', 'GATSBY_', 'PUBLIC_']; + +export const isClientExposedKey = (key: string): boolean => + some(CLIENT_EXPOSED_PREFIXES, (prefix) => startsWith(key, prefix)); + +export const clientExposedWarning = (key: string): string => + `Warning: ${key} starts with a client-exposed prefix, so its value is inlined into client JavaScript ` + + 'at build time and is visible to anyone who loads your site.'; + +type SecretsErrorContext = { key?: string; value?: string }; + +const stringify = (item: unknown): string => { + try { + return JSON.stringify(item) ?? ''; + } catch { + return ''; + } +}; + +const redactValue = (text: string, value?: string): string => { + if (!value) return text; + const fragments = filter(split(value, /\r?\n/), (fragment) => !isEmpty(fragment)); + return fragments.reduce((redacted, fragment) => split(redacted, fragment).join('[redacted]'), text); +}; + +export const formatSecretsError = (error: any, { key, value }: SecretsErrorContext = {}): string => { + const graphQLError = error?.graphQLErrors?.[0]; + const exception = graphQLError?.extensions?.exception; + const status = exception?.status ?? graphQLError?.extensions?.status ?? error?.networkError?.statusCode; + const searchable = map( + [exception?.messages, exception?.name, exception?.errorObject, graphQLError?.message, error?.message], + stringify, + ).join(' '); + const hasCode = (code: string) => includes(searchable, code); + const keyName = key ?? 'the secret'; + + const known: [boolean, string][] = [ + [hasCode('ENVIRONMENT_SECRET_KEY_CONFLICT'), `The key ${keyName} is already used by a variable or secret.`], + [ + hasCode('ENVIRONMENT_VARIABLES_CONCURRENT_UPDATE'), + 'The environment was changed by a concurrent update. Please retry.', + ], + [hasCode('ENVIRONMENT_SECRET_VALUE_MULTILINE'), 'Invalid value: multi-line values are not supported.'], + [hasCode('ENVIRONMENT_SECRET_NOT_FOUND') || status === 404, `The secret ${keyName} was not found.`], + [status === 403, 'You do not have permission to manage the secrets of this environment.'], + [status === 400, 'The API rejected the request: invalid key or value.'], + ]; + + const match = find(known, ([matches]) => matches); + const message = match ? match[1] : (graphQLError?.message ?? error?.message ?? 'Unable to manage the secret.'); + + return redactValue(message, value); +}; + +export const redactFlagValues = (text: string): string => text.replace(/(--[\w-]+)=\S+/g, '$1'); diff --git a/test/integration/harness/fixtures.ts b/test/integration/harness/fixtures.ts index 876553aa..1368acff 100644 --- a/test/integration/harness/fixtures.ts +++ b/test/integration/harness/fixtures.ts @@ -73,6 +73,18 @@ export const environmentSecretsResponse = (secrets: Record[] = [sec }, }); +export const addEnvironmentSecretResponse = (key = SECRET_KEY) => ({ + data: { addEnvironmentSecret: secretNode({ key }) }, +}); + +export const refreshEnvironmentSecretResponse = (key = SECRET_KEY) => ({ + data: { refreshEnvironmentSecret: secretNode({ key }) }, +}); + +export const secretsApiErrorResponse = (status: number, code?: string, message = 'Request failed') => ({ + errors: [{ message, extensions: { exception: { status, ...(code ? { name: code } : {}) } } }], +}); + export const projectsResponse = ( projects: { uid: string; name: string }[] = [{ uid: PROJECT_UID, name: PROJECT_NAME }], ) => ({ diff --git a/test/integration/harness/index.ts b/test/integration/harness/index.ts index 69baa936..c01bcb05 100644 --- a/test/integration/harness/index.ts +++ b/test/integration/harness/index.ts @@ -5,6 +5,7 @@ export { cma } from './cma'; export type { MockOrganization } from './cma'; export { prompts } from './prompts'; export type { ScriptedAnswer } from './prompts'; +export { stdin } from './stdin'; export { runCommand } from './run-command'; export type { CommandResult } from './run-command'; export { Session, startSession } from './session'; diff --git a/test/integration/harness/session.ts b/test/integration/harness/session.ts index f4fc90e2..52abb8eb 100644 --- a/test/integration/harness/session.ts +++ b/test/integration/harness/session.ts @@ -8,6 +8,7 @@ import { GitRepo, GitRepoOptions } from './git-repo'; import { LaunchApiMock } from './launch-api'; import { cma } from './cma'; import { prompts } from './prompts'; +import { stdin } from './stdin'; const CMA_HOST = 'api.contentstack.io'; @@ -77,6 +78,7 @@ export class Session { async stop(): Promise { try { prompts.restore(); + stdin.restore(); prompts.reset(); cma.reset(); this.api.reset(); diff --git a/test/integration/harness/stdin.ts b/test/integration/harness/stdin.ts new file mode 100644 index 00000000..255b45b1 --- /dev/null +++ b/test/integration/harness/stdin.ts @@ -0,0 +1,21 @@ +import { Readable } from 'stream'; + +const original = Object.getOwnPropertyDescriptor(process, 'stdin') as PropertyDescriptor; + +const replace = (isTTY: boolean, chunks: string[]): void => { + const stream: any = Readable.from(chunks); + stream.isTTY = isTTY; + Object.defineProperty(process, 'stdin', { value: stream, configurable: true }); +}; + +export const stdin = { + pipe(value: string): void { + replace(false, [value]); + }, + tty(): void { + replace(true, []); + }, + restore(): void { + Object.defineProperty(process, 'stdin', original); + }, +}; diff --git a/test/integration/specs/secrets-set.test.ts b/test/integration/specs/secrets-set.test.ts new file mode 100644 index 00000000..76a651cc --- /dev/null +++ b/test/integration/specs/secrets-set.test.ts @@ -0,0 +1,165 @@ +import { existsSync, readFileSync } from 'fs'; +import { join } from 'path'; +import { randomUUID } from 'crypto'; + +import SetSecret from '../../../src/commands/launch/secrets/set'; +import { cma, fixtures, prompts, runCommand, startSession, stdin, Session } from '../harness'; + +describe('launch:secrets:set', () => { + let session: Session; + + beforeEach(async () => { + session = await startSession(); + cma.withOrganizations([fixtures.ORG, fixtures.OTHER_ORG]); + }); + + afterEach(async () => { + await session.stop(); + }); + + const scope = () => [ + ...session.baseArgs, + '--org', + fixtures.ORG.uid, + '--project', + fixtures.PROJECT_UID, + '--environment', + fixtures.ENVIRONMENT_NAME, + ]; + + const logFiles = () => + ['info.log', 'error.log'] + .map((name) => join(session.projectDir, 'logs', name)) + .filter((path) => existsSync(path)) + .map((path) => readFileSync(path, 'utf8')) + .join('\n'); + + it('adds a secret from piped stdin without any prompt when --yes is passed', async () => { + const value = randomUUID(); + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse([])) + .on('AddEnvironmentSecret', fixtures.addEnvironmentSecretResponse()); + stdin.pipe(`${value}\n`); + prompts.script([]); + + const result = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, '--yes']); + + expect(result.error).toBeUndefined(); + expect(result.exitCode).toBe(0); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + expect(session.api.operationSequence()).toEqual(['Projects', 'EnvironmentSecrets', 'AddEnvironmentSecret']); + expect(session.api.variablesOf('AddEnvironmentSecret')).toEqual({ + environmentUid: fixtures.ENVIRONMENT_UID, + secret: { key: fixtures.SECRET_KEY, value }, + }); + expect(result.output).not.toContain(value); + }); + + it('refreshes an existing secret after a masked prompt and a confirmation in a terminal', async () => { + const value = randomUUID(); + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse()) + .on('RefreshEnvironmentSecret', fixtures.refreshEnvironmentSecretResponse()); + stdin.tty(); + prompts.script([ + { name: 'value', answer: value }, + { name: 'confirm', answer: true }, + ]); + + const result = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY]); + + expect(result.error).toBeUndefined(); + expect(result.exitCode).toBe(0); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + expect(session.api.operationSequence()).toEqual(['Projects', 'EnvironmentSecrets', 'RefreshEnvironmentSecret']); + expect(session.api.variablesOf('RefreshEnvironmentSecret').secret).toEqual({ key: fixtures.SECRET_KEY, value }); + expect(result.output).not.toContain(value); + }); + + it('rejects --value as a nonexistent flag without sending a mutation or echoing the value', async () => { + const value = randomUUID(); + session.api.on('Projects', fixtures.projectsResponse()); + stdin.tty(); + prompts.script([]); + + const result = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, '--value', value]); + + expect(result.exitCode).not.toBe(0); + expect(result.output).toContain('Nonexistent flag: --value'); + expect(result.output).not.toContain(value); + expect(session.api.calls('AddEnvironmentSecret')).toHaveLength(0); + expect(session.api.calls('RefreshEnvironmentSecret')).toHaveLength(0); + }); + + it('redacts the value when --value is passed with an equals sign', async () => { + const value = randomUUID(); + session.api.on('Projects', fixtures.projectsResponse()); + stdin.tty(); + prompts.script([]); + + const result = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, `--value=${value}`]); + + expect(result.exitCode).not.toBe(0); + expect(result.output).not.toContain(value); + expect(result.error?.message ?? '').not.toContain(value); + expect(session.api.calls('AddEnvironmentSecret')).toHaveLength(0); + expect(session.api.calls('RefreshEnvironmentSecret')).toHaveLength(0); + }); + + it('fails with a missing required flag error and no mutation when --key is absent', async () => { + session.api.on('Projects', fixtures.projectsResponse()); + stdin.tty(); + prompts.script([]); + + const result = await runCommand(SetSecret, [...scope(), '--yes']); + + expect(result.exitCode).not.toBe(0); + expect(result.output).toContain('Missing required flag key'); + expect(session.api.calls('AddEnvironmentSecret')).toHaveLength(0); + expect(session.api.calls('RefreshEnvironmentSecret')).toHaveLength(0); + }); + + it('shows the key conflict message and exits 1 when the API answers 409', async () => { + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse([])) + .on('AddEnvironmentSecret', fixtures.secretsApiErrorResponse(409, 'ENVIRONMENT_SECRET_KEY_CONFLICT')); + stdin.pipe(randomUUID()); + prompts.script([]); + + const result = await runCommand(SetSecret, [...scope(), '--key', 'DB_URL', '--yes']); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('The key DB_URL is already used by a variable or secret.'); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + }); + + it('never writes the value to the output or the log files on success or on a 400', async () => { + const value = randomUUID(); + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse([])) + .on('AddEnvironmentSecret', (_variables, callIndex) => + callIndex === 0 + ? fixtures.addEnvironmentSecretResponse() + : fixtures.secretsApiErrorResponse(400, undefined, `Invalid value ${value}`), + ); + prompts.script([]); + + stdin.pipe(value); + const success = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, '--yes']); + stdin.pipe(value); + const failure = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, '--yes']); + + expect(success.exitCode).toBe(0); + expect(failure.exitCode).toBe(1); + expect(success.output).not.toContain(value); + expect(failure.output).not.toContain(value); + expect(logFiles()).not.toContain(value); + }); +}); From cf9556d80f33b9fa066a18fbbfd1dd7520cba3ab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 18:47:10 +0000 Subject: [PATCH 3/6] CL-8166 | +Claude | Add launch:secrets:unset command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Delete one or more environment secrets with a repeatable --key, after a confirmation unless --yes is passed. A failing key is reported by name and the remaining keys are still deleted, with exit 1 at the end. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 10 +- src/commands/launch/secrets/unset.test.ts | 127 +++++++++++++++++ src/commands/launch/secrets/unset.ts | 139 +++++++++++++++++++ src/graphql/mutation.ts | 7 + test/integration/harness/fixtures.ts | 4 + test/integration/specs/secrets-unset.test.ts | 74 ++++++++++ 6 files changed, 359 insertions(+), 2 deletions(-) create mode 100644 src/commands/launch/secrets/unset.test.ts create mode 100644 src/commands/launch/secrets/unset.ts create mode 100644 test/integration/specs/secrets-unset.test.ts diff --git a/.talismanrc b/.talismanrc index 160d2c40..11248021 100644 --- a/.talismanrc +++ b/.talismanrc @@ -38,7 +38,7 @@ fileignoreconfig: - filename: test/integration/specs/launch-github.test.ts checksum: 4ea1ae16627383530d7590374ba2b37fde87b5c111cc6c38c5125456aa9b51c8 - filename: test/integration/harness/fixtures.ts - checksum: 97a6a6b9c83c1d53ace7175961d7654b4523a3a446bb5a5716f97897fdc895c4 + checksum: 13093443609ee0e542221fd039393a6b1b0243bb321d83146a6bab3c51cc84a7 - filename: src/base-command.ts checksum: db8bc45f6d8aa3daebae621920c8618b6e23d1a20984dee0749d91bfa5c1530c - filename: test/unit/base-command.test.ts @@ -52,7 +52,7 @@ fileignoreconfig: - filename: src/commands/launch/secrets/list.test.ts checksum: a5113cbf747b711af916751e37912f50660bc307683a2237eac4f767d5157ce6 - filename: src/graphql/mutation.ts - checksum: b2b64d708700428354cc9863710e3aa2bdaee073e63e11cb1755ca46a2a961d6 + checksum: 97bd5e5e73e9ed3d661d417a10de35e22b4924bd0002177cee375ee66545ede8 - filename: src/util/secrets.ts checksum: 0558c6fd1e876704613fa5f4d2eb8a3c1985b4d7f8539d1d3cb47ec2ca8caae0 - filename: src/commands/launch/secrets/set.ts @@ -63,4 +63,10 @@ fileignoreconfig: checksum: 931fca7aae520cd3b5a63e1c4ba64e4df78fbd121d5f256ba5977703d6fa9b5e - filename: src/commands/launch/secrets/set.test.ts checksum: 822408f4669aadf22d91d859b8c09789c123b03e7490e285c8b274ef551186d8 +- filename: src/commands/launch/secrets/unset.ts + checksum: a206adcccf86982c889ae604a020b9a4ae3688dbe4333bb4e7f2125eed81f980 +- filename: src/commands/launch/secrets/unset.test.ts + checksum: 0cf333a36acf97949b36dd51c5c8d2fc8b3bb0617c42be1ad2e7f8f7f4c81bca +- filename: test/integration/specs/secrets-unset.test.ts + checksum: 1d52c72ff9a90bd65b0d083b0460ca641e05b257c9ed60c9f296738ab923a873 version: "1.0" diff --git a/src/commands/launch/secrets/unset.test.ts b/src/commands/launch/secrets/unset.test.ts new file mode 100644 index 00000000..b585e61e --- /dev/null +++ b/src/commands/launch/secrets/unset.test.ts @@ -0,0 +1,127 @@ +import { cliux } from '@contentstack/cli-utilities'; + +import { deleteEnvironmentSecretMutation } from '../../../graphql'; + +import UnsetSecret from './unset'; + +jest.mock('../../../util', () => { + const actual = jest.requireActual('../../../util'); + return { + ...actual, + Logger: jest.fn(), + selectOrg: jest.fn(), + selectProject: jest.fn(), + }; +}); + +jest.mock('@contentstack/cli-utilities', () => { + const { launchCommand } = jest.requireActual('../../../test/mocks/cli-utilities'); + return { ...launchCommand, cliux: { ...launchCommand.cliux, table: jest.fn() } }; +}); + +const ENVIRONMENT_UID = 'env-uid'; + +const environmentsResponse = (name = 'Default') => ({ + data: { Environments: { edges: [{ node: { uid: ENVIRONMENT_UID, name, secrets: [] } }] } }, +}); + +const apiError = (status: number, name?: string) => ({ + message: 'Request failed', + graphQLErrors: [{ message: 'Request failed', extensions: { exception: { status, ...(name ? { name } : {}) } } }], +}); + +const buildCommand = ( + flags: Record, + mutate: jest.Mock = jest.fn().mockResolvedValue({ data: { deleteEnvironmentSecret: true } }), +) => { + const query = jest.fn().mockResolvedValue(environmentsResponse()); + const cmd = new UnsetSecret([], {} as any); + (cmd as any).flags = { environment: 'Default', key: ['API_TOKEN'], yes: false, ...flags }; + (cmd as any).log = jest.fn(); + (cmd as any).sharedConfig = { currentConfig: { uid: 'project-uid' } }; + (cmd as any).apolloClient = { query, mutate }; + return { cmd, query, mutate }; +}; + +describe('UnsetSecret Command', () => { + let exitMock: jest.SpyInstance; + + beforeEach(() => { + exitMock = jest.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Error(`process.exit:${code}`); + }) as any); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('deletes every given key in order without prompting when --yes is passed', async () => { + const { cmd, mutate } = buildCommand({ key: ['API_TOKEN', 'DB_PASSWORD'], yes: true }); + + await (cmd as any).unsetSecrets(); + + expect(mutate).toHaveBeenCalledTimes(2); + expect(mutate).toHaveBeenNthCalledWith(1, { + mutation: deleteEnvironmentSecretMutation, + variables: { environmentUid: ENVIRONMENT_UID, key: 'API_TOKEN' }, + }); + expect(mutate).toHaveBeenNthCalledWith(2, { + mutation: deleteEnvironmentSecretMutation, + variables: { environmentUid: ENVIRONMENT_UID, key: 'DB_PASSWORD' }, + }); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('API_TOKEN')); + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('DB_PASSWORD')); + expect(exitMock).not.toHaveBeenCalled(); + }); + + it('asks for confirmation and deletes the key when it is accepted', async () => { + (cliux.inquire as jest.Mock).mockResolvedValueOnce(true); + const { cmd, mutate } = buildCommand({}); + + await (cmd as any).unsetSecrets(); + + const [question] = (cliux.inquire as jest.Mock).mock.calls[0]; + expect(question.type).toBe('confirm'); + expect(question.message).toContain('API_TOKEN'); + expect(mutate).toHaveBeenCalledTimes(1); + expect(mutate.mock.calls[0][0].variables).toEqual({ environmentUid: ENVIRONMENT_UID, key: 'API_TOKEN' }); + expect(exitMock).not.toHaveBeenCalled(); + }); + + it('aborts without a mutation or an error exit when the confirmation is declined', async () => { + (cliux.inquire as jest.Mock).mockResolvedValueOnce(false); + const { cmd, mutate } = buildCommand({ key: ['API_TOKEN', 'DB_PASSWORD'] }); + + await (cmd as any).unsetSecrets(); + + expect(mutate).not.toHaveBeenCalled(); + expect(cliux.print).toHaveBeenCalledWith(expect.stringContaining('Aborted')); + expect(exitMock).not.toHaveBeenCalled(); + }); + + it('shows the permission message and exits 1 when the API answers 403', async () => { + const { cmd } = buildCommand({ yes: true }, jest.fn().mockRejectedValue(apiError(403))); + + await expect((cmd as any).unsetSecrets()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('permission'), 'error'); + expect(exitMock).toHaveBeenCalledWith(1); + }); + + it('keeps deleting the remaining keys after one fails and exits 1 at the end', async () => { + const mutate = jest + .fn() + .mockRejectedValueOnce(apiError(404, 'ENVIRONMENT_SECRET_NOT_FOUND')) + .mockResolvedValueOnce({ data: { deleteEnvironmentSecret: true } }); + const { cmd } = buildCommand({ key: ['MISSING_KEY', 'API_TOKEN'], yes: true }, mutate); + + await expect((cmd as any).unsetSecrets()).rejects.toThrow('process.exit:1'); + + expect(mutate).toHaveBeenCalledTimes(2); + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('MISSING_KEY'), 'error'); + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('API_TOKEN')); + expect(exitMock).toHaveBeenCalledWith(1); + }); +}); diff --git a/src/commands/launch/secrets/unset.ts b/src/commands/launch/secrets/unset.ts new file mode 100644 index 00000000..ccd8b691 --- /dev/null +++ b/src/commands/launch/secrets/unset.ts @@ -0,0 +1,139 @@ +import map from 'lodash/map'; +import find from 'lodash/find'; +import isEmpty from 'lodash/isEmpty'; +import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; + +import { BaseCommand } from '../../../base-command'; +import { environmentSecretsQuery, deleteEnvironmentSecretMutation } from '../../../graphql'; +import { Logger, selectOrg, selectProject, formatSecretsError } from '../../../util'; + +export default class UnsetSecret extends BaseCommand { + static description = 'Delete one or more secrets of an environment'; + + static examples = [ + '$ <%= config.bin %> <%= command.id %> --key=', + '$ <%= config.bin %> <%= command.id %> --key= --key= --yes', + '$ <%= config.bin %> <%= command.id %> --org= --project= ' + + '--environment= --key=', + ]; + + static flags: FlagInput = { + org: Flags.string({ + description: '[Optional] Provide the organization UID', + }), + project: Flags.string({ + description: '[Optional] Provide the project UID', + }), + environment: Flags.string({ + char: 'e', + description: 'Environment name or UID', + }), + key: Flags.string({ + char: 'k', + required: true, + multiple: true, + description: 'Secret key to delete. Repeat the flag to delete several secrets', + }), + yes: Flags.boolean({ + char: 'y', + description: 'Skip the confirmation prompt', + }), + }; + + async run(): Promise { + this.logger = new Logger(this.sharedConfig); + this.log = this.logger.log.bind(this.logger); + + await this.getConfig(); + await this.prepareApiClients(); + + if (!this.sharedConfig.currentConfig?.uid) { + await selectOrg({ + log: this.log, + flags: this.flags, + config: this.sharedConfig, + managementSdk: this.managementSdk, + }); + await this.prepareApiClients(); + await selectProject({ + log: this.log, + flags: this.flags, + config: this.sharedConfig, + apolloClient: this.apolloClient, + }); + await this.prepareApiClients(); + } + + await this.unsetSecrets(); + } + + async unsetSecrets(): Promise { + const { key: keys, yes } = this.flags as Record; + const environment = await this.resolveEnvironment(); + + if (!yes && !(await this.confirm(keys, environment.name))) { + ux.print('Aborted. No secret was deleted.'); + return; + } + + let failed = false; + + for (const key of keys) { + try { + await this.apolloClient.mutate({ + mutation: deleteEnvironmentSecretMutation, + variables: { environmentUid: environment.uid, key }, + }); + this.log(`Secret ${key} deleted from environment ${environment.name}.`); + } catch (error) { + this.log(formatSecretsError(error, { key }), 'error'); + failed = true; + } + } + + if (failed) { + process.exit(1); + } + } + + confirm(keys: string[], environmentName: string): Promise { + return ux.inquire({ + type: 'confirm', + name: 'confirm', + message: `Delete secret ${keys.join(', ')} from environment ${environmentName}?`, + }); + } + + async resolveEnvironment(): Promise { + const environments = await this.apolloClient + .query({ query: environmentSecretsQuery }) + .then(({ data: { Environments } }) => map(Environments.edges, 'node')) + .catch((error) => { + this.log(formatSecretsError(error), 'error'); + process.exit(1); + }); + + if (!this.flags.environment) { + return ux + .inquire({ + type: 'search-list', + name: 'Environment', + choices: map(environments, (row) => ({ name: row.name, value: row.name })), + message: 'Choose an environment', + }) + .then((name: any) => find(environments, { name }) as Record); + } + + const environment = find( + environments, + ({ uid, name }) => uid === this.flags.environment || name === this.flags.environment, + ); + + if (isEmpty(environment)) { + this.log('Environment(s) not found!', 'error'); + process.exit(1); + } + + return environment; + } +} diff --git a/src/graphql/mutation.ts b/src/graphql/mutation.ts index d9ff76d4..2c488086 100755 --- a/src/graphql/mutation.ts +++ b/src/graphql/mutation.ts @@ -103,10 +103,17 @@ const refreshEnvironmentSecretMutation: DocumentNode = gql` } `; +const deleteEnvironmentSecretMutation: DocumentNode = gql` + mutation DeleteEnvironmentSecret($environmentUid: String!, $key: String!) { + deleteEnvironmentSecret(environmentUid: $environmentUid, key: $key) + } +`; + export { importProjectMutation, addEnvironmentSecretMutation, refreshEnvironmentSecretMutation, + deleteEnvironmentSecretMutation, createDeploymentMutation, rollbackDeploymentMutation, createSignedUploadUrlMutation, diff --git a/test/integration/harness/fixtures.ts b/test/integration/harness/fixtures.ts index 1368acff..8cd1cfa3 100644 --- a/test/integration/harness/fixtures.ts +++ b/test/integration/harness/fixtures.ts @@ -81,6 +81,10 @@ export const refreshEnvironmentSecretResponse = (key = SECRET_KEY) => ({ data: { refreshEnvironmentSecret: secretNode({ key }) }, }); +export const deleteEnvironmentSecretResponse = () => ({ + data: { deleteEnvironmentSecret: true }, +}); + export const secretsApiErrorResponse = (status: number, code?: string, message = 'Request failed') => ({ errors: [{ message, extensions: { exception: { status, ...(code ? { name: code } : {}) } } }], }); diff --git a/test/integration/specs/secrets-unset.test.ts b/test/integration/specs/secrets-unset.test.ts new file mode 100644 index 00000000..f06b595c --- /dev/null +++ b/test/integration/specs/secrets-unset.test.ts @@ -0,0 +1,74 @@ +import UnsetSecret from '../../../src/commands/launch/secrets/unset'; +import { cma, fixtures, prompts, runCommand, startSession, stdin, Session } from '../harness'; + +describe('launch:secrets:unset', () => { + let session: Session; + + beforeEach(async () => { + session = await startSession(); + cma.withOrganizations([fixtures.ORG, fixtures.OTHER_ORG]); + }); + + afterEach(async () => { + await session.stop(); + }); + + const scope = () => [ + ...session.baseArgs, + '--org', + fixtures.ORG.uid, + '--project', + fixtures.PROJECT_UID, + '--environment', + fixtures.ENVIRONMENT_NAME, + ]; + + it('deletes every given key in order without any prompt when --yes is passed', async () => { + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse()) + .on('DeleteEnvironmentSecret', fixtures.deleteEnvironmentSecretResponse()); + stdin.tty(); + prompts.script([]); + + const result = await runCommand(UnsetSecret, [...scope(), '--key', 'API_TOKEN', '--key', 'DB_PASSWORD', '--yes']); + + expect(result.error).toBeUndefined(); + expect(result.exitCode).toBe(0); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + expect(session.api.operationSequence()).toEqual(['Projects', 'EnvironmentSecrets', 'DeleteEnvironmentSecret']); + expect(session.api.calls('DeleteEnvironmentSecret').map((call) => call.variables)).toEqual([ + { environmentUid: fixtures.ENVIRONMENT_UID, key: 'API_TOKEN' }, + { environmentUid: fixtures.ENVIRONMENT_UID, key: 'DB_PASSWORD' }, + ]); + }); + + it('shows a not-found message naming the key and exits 1 when the API answers 404', async () => { + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse()) + .on('DeleteEnvironmentSecret', fixtures.secretsApiErrorResponse(404, 'ENVIRONMENT_SECRET_NOT_FOUND')); + stdin.tty(); + prompts.script([]); + + const result = await runCommand(UnsetSecret, [...scope(), '--key', 'MISSING_KEY', '--yes']); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('The secret MISSING_KEY was not found.'); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + }); + + it('fails with a missing required flag error and no delete when --key is absent', async () => { + session.api.on('Projects', fixtures.projectsResponse()); + stdin.tty(); + prompts.script([]); + + const result = await runCommand(UnsetSecret, [...scope(), '--yes']); + + expect(result.exitCode).not.toBe(0); + expect(result.output).toContain('Missing required flag key'); + expect(session.api.calls('DeleteEnvironmentSecret')).toHaveLength(0); + }); +}); From 2c6ad4dcd1e9ea8351fa0d3c22aa527d63be472f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 18:52:12 +0000 Subject: [PATCH 4/6] CL-8166 | +Claude | Fix review findings in launch:secrets commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Read a piped secret from stdin before getConfig and any org, project, environment or branch prompt, and require --org, --project and --environment when piping. Redact whole flag values (spaced and short form) from parse errors, and format every list query failure instead of rethrowing the raw error. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 8 +- src/commands/launch/secrets/list.test.ts | 17 +++ src/commands/launch/secrets/list.ts | 9 +- src/commands/launch/secrets/set.test.ts | 112 +++++++++++++++++++- src/commands/launch/secrets/set.ts | 73 ++++++++++++- src/util/secrets.test.ts | 16 +++ src/util/secrets.ts | 2 +- test/integration/specs/secrets-list.test.ts | 2 +- test/integration/specs/secrets-set.test.ts | 37 ++++++- 9 files changed, 256 insertions(+), 20 deletions(-) diff --git a/.talismanrc b/.talismanrc index 11248021..37d9404a 100644 --- a/.talismanrc +++ b/.talismanrc @@ -48,19 +48,19 @@ fileignoreconfig: - filename: test/integration/specs/secrets-list.test.ts checksum: d4cdd09fe16a876f7457bdf9bbaa83511624c12a0c7a967abc5f26a678696629 - filename: src/commands/launch/secrets/list.ts - checksum: 2cb79446bb06c785a2c1a349195e7d90c6a5c5bf4a14be995b970f6fb2b2ccd9 + checksum: e33958ccf580f32e6869690f1409ab40bb429f699623dc0a009a62e9e6f204d7 - filename: src/commands/launch/secrets/list.test.ts - checksum: a5113cbf747b711af916751e37912f50660bc307683a2237eac4f767d5157ce6 + checksum: 2405b5f40b03d5ed888466bedb4444cba244f0565785ac9b3a0ab4d0876d4567 - filename: src/graphql/mutation.ts checksum: 97bd5e5e73e9ed3d661d417a10de35e22b4924bd0002177cee375ee66545ede8 - filename: src/util/secrets.ts checksum: 0558c6fd1e876704613fa5f4d2eb8a3c1985b4d7f8539d1d3cb47ec2ca8caae0 - filename: src/commands/launch/secrets/set.ts - checksum: a850e49f4a1a87e34721d94432934f72971ba6f9c151ae8b50a0dc6985095d6f + checksum: 04374d713f871999adc0d6ea3916951c3fd93a8067e4a045420ae00fdde448c6 - filename: src/util/secrets.test.ts checksum: 08a359719861f1a249fe3ccfac282c48a678e0b2a8ceb7f795e2676acb697c24 - filename: test/integration/specs/secrets-set.test.ts - checksum: 931fca7aae520cd3b5a63e1c4ba64e4df78fbd121d5f256ba5977703d6fa9b5e + checksum: 0729bef6ec4b7a5c579ced56c0dfb3da32b9d29b9779a934b8bb1e2690d6f601 - filename: src/commands/launch/secrets/set.test.ts checksum: 822408f4669aadf22d91d859b8c09789c123b03e7490e285c8b274ef551186d8 - filename: src/commands/launch/secrets/unset.ts diff --git a/src/commands/launch/secrets/list.test.ts b/src/commands/launch/secrets/list.test.ts index d23f9577..56e9263b 100644 --- a/src/commands/launch/secrets/list.test.ts +++ b/src/commands/launch/secrets/list.test.ts @@ -90,6 +90,23 @@ describe('ListSecrets Command', () => { expect(cliux.table).not.toHaveBeenCalled(); }); + it.each([[404], [400]])('shows the formatted message and exits 1 when the secrets query fails with %i', async (status) => { + const raw = randomUUID(); + const query = jest.fn().mockRejectedValue({ + message: raw, + graphQLErrors: [{ message: raw, extensions: { exception: { status } } }], + }); + const cmd = buildCommand({ environment: 'Default' }, query); + + await expect((cmd as any).listSecrets()).rejects.toThrow('process.exit:1'); + + const expected = status === 404 ? 'was not found' : 'invalid key or value'; + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining(expected), 'error'); + expect(JSON.stringify((cmd as any).log.mock.calls)).not.toContain(raw); + expect(exitMock).toHaveBeenCalledWith(1); + expect(cliux.table).not.toHaveBeenCalled(); + }); + it('prints an empty-state line without exiting or rendering a table when there are no secrets', async () => { const query = jest.fn().mockResolvedValue(secretsResponse([])); const cmd = buildCommand({ environment: 'Default' }, query); diff --git a/src/commands/launch/secrets/list.ts b/src/commands/launch/secrets/list.ts index d5897110..bd4b176f 100644 --- a/src/commands/launch/secrets/list.ts +++ b/src/commands/launch/secrets/list.ts @@ -5,7 +5,7 @@ import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; import { BaseCommand } from '../../../base-command'; import { environmentSecretsQuery } from '../../../graphql'; -import { Logger, selectOrg, selectProject } from '../../../util'; +import { Logger, selectOrg, selectProject, formatSecretsError } from '../../../util'; export default class ListSecrets extends BaseCommand { static description = 'List the secrets of an environment (keys only, values are never shown)'; @@ -75,11 +75,8 @@ export default class ListSecrets extends BaseCommand { .query({ query: environmentSecretsQuery }) .then(({ data: { Environments } }) => map(Environments.edges, 'node')) .catch((error) => { - if (error?.graphQLErrors?.[0]?.extensions?.exception?.status === 403) { - this.log('You do not have permission to list the secrets of this environment.', 'error'); - process.exit(1); - } - throw error; + this.log(formatSecretsError(error), 'error'); + process.exit(1); }); if (!this.flags.environment) { diff --git a/src/commands/launch/secrets/set.test.ts b/src/commands/launch/secrets/set.test.ts index eb80255b..1af04aa1 100644 --- a/src/commands/launch/secrets/set.test.ts +++ b/src/commands/launch/secrets/set.test.ts @@ -1,9 +1,14 @@ +import { tmpdir } from 'os'; +import { join } from 'path'; import { Readable } from 'stream'; +import { mkdtempSync, writeFileSync } from 'fs'; import { randomUUID } from 'crypto'; import { cliux } from '@contentstack/cli-utilities'; import { addEnvironmentSecretMutation, refreshEnvironmentSecretMutation } from '../../../graphql'; +import { Logger } from '../../../util'; + import SetSecret from './set'; jest.mock('../../../util', () => { @@ -238,8 +243,8 @@ describe('SetSecret Command', () => { }); it('asks which environment to use when --environment is not given', async () => { - stubStdin(false, [randomUUID()]); - (cliux.inquire as jest.Mock).mockResolvedValueOnce('Default'); + stubStdin(true); + (cliux.inquire as jest.Mock).mockResolvedValueOnce('Default').mockResolvedValueOnce(randomUUID()); const { cmd, mutate } = buildCommand({ yes: true, environment: undefined }); await (cmd as any).setSecret(); @@ -250,6 +255,109 @@ describe('SetSecret Command', () => { expect(mutate).toHaveBeenCalledTimes(1); }); + it('reads the piped value before any prompt and keeps it for the mutation', async () => { + const value = randomUUID(); + stubStdin(false, [`${value}\n`]); + const { cmd, mutate } = buildCommand({ yes: true }); + + await (cmd as any).preparePipedInput(); + await (cmd as any).setSecret(); + + expect(mutate).toHaveBeenCalledTimes(1); + expect(mutate.mock.calls[0][0].variables.secret.value).toBe(value); + expect(cliux.inquire).not.toHaveBeenCalled(); + }); + + it('fails without prompting or mutating when the value is piped and --environment is missing', async () => { + const value = randomUUID(); + stubStdin(false, [value]); + const { cmd, query, mutate } = buildCommand({ yes: true, environment: undefined }); + + await expect((cmd as any).preparePipedInput()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith( + '--org, --project and --environment are required when the value is piped', + 'error', + ); + expect(exitMock).toHaveBeenCalledWith(1); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect(query).not.toHaveBeenCalled(); + expect(mutate).not.toHaveBeenCalled(); + expect(allOutput((cmd as any).log, cliux.inquire as jest.Mock)).not.toContain(value); + }); + + it('fails without prompting when the value is piped and no project is configured or given', async () => { + stubStdin(false, [randomUUID()]); + const { cmd, mutate } = buildCommand({ yes: true, org: undefined, project: undefined }); + (cmd as any).sharedConfig = { currentConfig: {} }; + + await expect((cmd as any).assertPipedScope()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith( + '--org, --project and --environment are required when the value is piped', + 'error', + ); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect(mutate).not.toHaveBeenCalled(); + }); + + it('does not require --org and --project when a project is already configured', async () => { + stubStdin(false, [randomUUID()]); + const { cmd } = buildCommand({ yes: true }); + + await expect((cmd as any).assertPipedScope()).resolves.toBeUndefined(); + + expect(exitMock).not.toHaveBeenCalled(); + }); + + it('reads the piped value before the config is loaded so no prompt can consume it', async () => { + stubStdin(false, [randomUUID()]); + (Logger as unknown as jest.Mock).mockImplementation(() => ({ log: jest.fn() })); + const { cmd } = buildCommand({ yes: true }); + const getConfig = jest.spyOn(cmd as any, 'getConfig').mockResolvedValue(undefined); + jest.spyOn(cmd as any, 'prepareApiClients').mockResolvedValue(undefined); + const readStdin = jest.spyOn(cmd as any, 'readStdin'); + jest.spyOn(cmd as any, 'setSecret').mockResolvedValue(undefined); + + await cmd.run(); + + expect(readStdin).toHaveBeenCalledTimes(1); + expect(readStdin.mock.invocationCallOrder[0]).toBeLessThan(getConfig.mock.invocationCallOrder[0]); + }); + + it('fails without prompting or reading stdin when the value is piped and a branch would have to be chosen', async () => { + stubStdin(false, [randomUUID()]); + const { cmd, mutate } = buildCommand({ yes: true }); + const dir = mkdtempSync(join(tmpdir(), 'secrets-branch-')); + const configPath = join(dir, '.cs-launch.json'); + writeFileSync(configPath, JSON.stringify({ main: { uid: 'a' }, develop: { uid: 'b' } })); + (cmd as any).sharedConfig = { config: configPath, currentConfig: {} }; + const readStdin = jest.spyOn(cmd as any, 'readStdin'); + + await expect((cmd as any).preparePipedInput()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith( + 'Multiple branches are configured; pass --branch when the value is piped', + 'error', + ); + expect(readStdin).not.toHaveBeenCalled(); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect(mutate).not.toHaveBeenCalled(); + }); + + it('does not refuse a piped value when --branch names a configured branch', async () => { + stubStdin(false, [randomUUID()]); + const { cmd } = buildCommand({ yes: true, branch: 'main' }); + const dir = mkdtempSync(join(tmpdir(), 'secrets-branch-')); + const configPath = join(dir, '.cs-launch.json'); + writeFileSync(configPath, JSON.stringify({ main: { uid: 'a' }, develop: { uid: 'b' } })); + (cmd as any).sharedConfig = { config: configPath, currentConfig: {} }; + + await expect((cmd as any).preparePipedInput()).resolves.toBeUndefined(); + + expect(exitMock).not.toHaveBeenCalled(); + }); + it('shows a formatted error when reading the environment secrets fails', async () => { stubStdin(false, [randomUUID()]); const { cmd, query, mutate } = buildCommand({ yes: true }); diff --git a/src/commands/launch/secrets/set.ts b/src/commands/launch/secrets/set.ts index e128341c..e634cfd5 100644 --- a/src/commands/launch/secrets/set.ts +++ b/src/commands/launch/secrets/set.ts @@ -1,4 +1,8 @@ +import { existsSync, readFileSync } from 'fs'; import map from 'lodash/map'; +import keys from 'lodash/keys'; +import filter from 'lodash/filter'; +import includes from 'lodash/includes'; import find from 'lodash/find'; import isEmpty from 'lodash/isEmpty'; import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; @@ -20,6 +24,8 @@ import { } from '../../../util'; export default class SetSecret extends BaseCommand { + private pipedValue?: string; + static description = 'Add or refresh a secret of an environment. The value is read from a masked prompt, or from stdin when piped'; @@ -41,6 +47,10 @@ export default class SetSecret extends BaseCommand { char: 'e', description: 'Environment name or UID', }), + branch: Flags.string({ + hidden: true, + description: '[Optional] GitHub branch name', + }), key: Flags.string({ char: 'k', required: true, @@ -56,7 +66,9 @@ export default class SetSecret extends BaseCommand { this.logger = new Logger(this.sharedConfig); this.log = this.logger.log.bind(this.logger); + await this.preparePipedInput(); await this.getConfig(); + await this.assertPipedScope(); await this.prepareApiClients(); if (!this.sharedConfig.currentConfig?.uid) { @@ -85,18 +97,69 @@ export default class SetSecret extends BaseCommand { return super.catch(err); } + requireYesWhenPiped(): void { + if (!process.stdin.isTTY && !this.flags.yes) { + this.log('use --yes when piping the value', 'error'); + process.exit(1); + } + } + + async preparePipedInput(): Promise { + if (process.stdin.isTTY) return; + + this.requireYesWhenPiped(); + + if (!this.flags.environment) { + this.failPipedScope(); + } + + if (this.branchPromptRequired()) { + this.log('Multiple branches are configured; pass --branch when the value is piped', 'error'); + process.exit(1); + } + + this.pipedValue = await this.readStdin(); + } + + async assertPipedScope(): Promise { + if (process.stdin.isTTY) return; + + const { org, project } = this.flags as Record; + + if (!this.sharedConfig.currentConfig?.uid && !(org && project)) { + this.failPipedScope(); + } + } + + failPipedScope(): never { + this.log('--org, --project and --environment are required when the value is piped', 'error'); + return process.exit(1); + } + + branchPromptRequired(): boolean { + const path = this.sharedConfig.config; + + if (!path || !existsSync(path)) return false; + + const configKeys = keys(JSON.parse(readFileSync(path, 'utf-8'))); + const { branch } = this.flags as Record; + + if (branch && includes(configKeys, branch)) { + return false; + } + + return filter(configKeys, (configKey) => configKey !== 'project').length > 1; + } + async setSecret(): Promise { const { key, yes } = this.flags as Record; const piped = !process.stdin.isTTY; - if (piped && !yes) { - this.log('use --yes when piping the value', 'error'); - process.exit(1); - } + this.requireYesWhenPiped(); const environment = await this.resolveEnvironment(); const exists = !isEmpty(find(environment.secrets, { key })); - const value = piped ? await this.readStdin() : await this.promptValue(key); + const value = piped ? (this.pipedValue ?? (await this.readStdin())) : await this.promptValue(key); if (isEmpty(value)) { this.log(piped ? 'no value received on stdin' : 'The value cannot be empty.', 'error'); diff --git a/src/util/secrets.test.ts b/src/util/secrets.test.ts index c65fa691..83a7f0a4 100644 --- a/src/util/secrets.test.ts +++ b/src/util/secrets.test.ts @@ -119,6 +119,22 @@ describe('secrets util', () => { expect(message).toBe('Nonexistent flag: --value\nSee more help with --help'); }); + it('removes a spaced value of an equals-style flag up to the end of the line', () => { + const value = `${randomUUID()} ${randomUUID()}`; + + const message = redactFlagValues(`Nonexistent flag: --value=${value}\nSee more help with --help`); + + expect(message).toBe('Nonexistent flag: --value\nSee more help with --help'); + }); + + it('removes the value of a short equals-style flag', () => { + const value = `${randomUUID()} ${randomUUID()}`; + + const message = redactFlagValues(`Nonexistent flag: -v=${value}`); + + expect(message).toBe('Nonexistent flag: -v'); + }); + it('leaves a message without flag values unchanged', () => { expect(redactFlagValues('Missing required flag key')).toBe('Missing required flag key'); }); diff --git a/src/util/secrets.ts b/src/util/secrets.ts index 55e79fb7..43cc557c 100644 --- a/src/util/secrets.ts +++ b/src/util/secrets.ts @@ -61,4 +61,4 @@ export const formatSecretsError = (error: any, { key, value }: SecretsErrorConte return redactValue(message, value); }; -export const redactFlagValues = (text: string): string => text.replace(/(--[\w-]+)=\S+/g, '$1'); +export const redactFlagValues = (text: string): string => text.replace(/(? { const result = await runCommand(ListSecrets, flags()); expect(result.exitCode).toBe(1); - expect(result.output).toContain('You do not have permission to list the secrets of this environment.'); + expect(result.output).toContain('You do not have permission to manage the secrets of this environment.'); expect(result.output).not.toContain('raw-policy-detail'); expect(result.output).not.toContain('Forbidden resource'); session.api.assertNoUnhandledOperations(); diff --git a/test/integration/specs/secrets-set.test.ts b/test/integration/specs/secrets-set.test.ts index 76a651cc..a3c07d03 100644 --- a/test/integration/specs/secrets-set.test.ts +++ b/test/integration/specs/secrets-set.test.ts @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from 'fs'; +import { existsSync, readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; import { randomUUID } from 'crypto'; @@ -57,6 +57,41 @@ describe('launch:secrets:set', () => { expect(result.output).not.toContain(value); }); + it('fails without any prompt or mutation when the value is piped and --environment is missing', async () => { + const value = randomUUID(); + stdin.pipe(`${value}\n`); + prompts.script([]); + const args = [...session.baseArgs, '--org', fixtures.ORG.uid, '--project', fixtures.PROJECT_UID]; + + const result = await runCommand(SetSecret, [...args, '--key', fixtures.SECRET_KEY, '--yes']); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('--org, --project and --environment are required when the value is piped'); + expect(result.output).not.toContain(value); + expect(session.api.operationSequence()).toEqual([]); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + }); + + it('fails without any prompt or mutation when the value is piped and a branch would have to be chosen', async () => { + const value = randomUUID(); + writeFileSync( + session.launchConfigPath, + JSON.stringify({ main: { uid: fixtures.PROJECT_UID }, develop: { uid: fixtures.PROJECT_UID } }), + ); + stdin.pipe(`${value}\n`); + prompts.script([]); + + const result = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, '--yes']); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('Multiple branches are configured; pass --branch when the value is piped'); + expect(result.output).not.toContain(value); + expect(session.api.operationSequence()).toEqual([]); + session.api.assertNoUnhandledOperations(); + prompts.assertScriptFullyConsumed(); + }); + it('refreshes an existing secret after a masked prompt and a confirmation in a terminal', async () => { const value = randomUUID(); session.api From 5d9585ed0c3fff237c09bcc8b7d894cf476fc023 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 19:12:38 +0000 Subject: [PATCH 5/6] CL-8166 | +Claude | Match secrets operations to the management-service schema MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Send addEnvironmentSecret, refreshEnvironmentSecret and deleteEnvironmentSecret with the environment and secret input objects the schema defines, and recognise the real FormError enum values (status 400) in formatSecretsError. Fixtures and specs now reproduce the real error shape and assert the exact variables sent. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 24 +++---- src/commands/launch/secrets/list.test.ts | 5 +- src/commands/launch/secrets/set.test.ts | 29 +++++++-- src/commands/launch/secrets/set.ts | 2 +- src/commands/launch/secrets/unset.test.ts | 29 +++++++-- src/commands/launch/secrets/unset.ts | 2 +- src/graphql/mutation.ts | 12 ++-- src/graphql/secrets-mutations.test.ts | 22 +++++++ src/util/secrets.test.ts | 67 ++++++++++++++------ src/util/secrets.ts | 26 ++++++-- test/integration/harness/fixtures.ts | 21 +++++- test/integration/specs/secrets-set.test.ts | 13 ++-- test/integration/specs/secrets-unset.test.ts | 8 +-- 13 files changed, 189 insertions(+), 71 deletions(-) create mode 100644 src/graphql/secrets-mutations.test.ts diff --git a/.talismanrc b/.talismanrc index 37d9404a..b25cceba 100644 --- a/.talismanrc +++ b/.talismanrc @@ -38,7 +38,7 @@ fileignoreconfig: - filename: test/integration/specs/launch-github.test.ts checksum: 4ea1ae16627383530d7590374ba2b37fde87b5c111cc6c38c5125456aa9b51c8 - filename: test/integration/harness/fixtures.ts - checksum: 13093443609ee0e542221fd039393a6b1b0243bb321d83146a6bab3c51cc84a7 + checksum: e22bc8ab6f0c266b1f53700bd3611a934f7469b1995bf451cad2115f86ca4b3e - filename: src/base-command.ts checksum: db8bc45f6d8aa3daebae621920c8618b6e23d1a20984dee0749d91bfa5c1530c - filename: test/unit/base-command.test.ts @@ -50,23 +50,25 @@ fileignoreconfig: - filename: src/commands/launch/secrets/list.ts checksum: e33958ccf580f32e6869690f1409ab40bb429f699623dc0a009a62e9e6f204d7 - filename: src/commands/launch/secrets/list.test.ts - checksum: 2405b5f40b03d5ed888466bedb4444cba244f0565785ac9b3a0ab4d0876d4567 + checksum: 1569c7d0feeb55ab1425bf0f8f22aa8550030560dbda83d017de34f09bcff3f2 - filename: src/graphql/mutation.ts - checksum: 97bd5e5e73e9ed3d661d417a10de35e22b4924bd0002177cee375ee66545ede8 + checksum: c420996deea097d6125ccd9648d0b87806bf7edeb4eda5604a068eee3e669542 - filename: src/util/secrets.ts - checksum: 0558c6fd1e876704613fa5f4d2eb8a3c1985b4d7f8539d1d3cb47ec2ca8caae0 + checksum: caf8a13cd8147e8a50667fc7b84a5db073f41e130b6d5996d6a57e3dc0b2bc1c - filename: src/commands/launch/secrets/set.ts - checksum: 04374d713f871999adc0d6ea3916951c3fd93a8067e4a045420ae00fdde448c6 + checksum: 30814bd285d9fe4b9a21206f0c2d2fc530447a5cb276ba152265885ca1a36e56 - filename: src/util/secrets.test.ts - checksum: 08a359719861f1a249fe3ccfac282c48a678e0b2a8ceb7f795e2676acb697c24 + checksum: 608f9187faf1cd312860ca3c15e324bc3d74d492d571194f5062f327dd2be2c4 - filename: test/integration/specs/secrets-set.test.ts - checksum: 0729bef6ec4b7a5c579ced56c0dfb3da32b9d29b9779a934b8bb1e2690d6f601 + checksum: ed46f1b15a450e07ed6da7ce0474fa3b404a4d687113d06de7a40c49283d377d - filename: src/commands/launch/secrets/set.test.ts - checksum: 822408f4669aadf22d91d859b8c09789c123b03e7490e285c8b274ef551186d8 + checksum: 2953250cb9353eaa298a30e480badf5b12a6e8a9851355e3a9055e7a1bbaa98f - filename: src/commands/launch/secrets/unset.ts - checksum: a206adcccf86982c889ae604a020b9a4ae3688dbe4333bb4e7f2125eed81f980 + checksum: 1260b3ee447042bfdc0ec2bafbeeeca0d65e966fc1ffd30c1acb38bf4392229a - filename: src/commands/launch/secrets/unset.test.ts - checksum: 0cf333a36acf97949b36dd51c5c8d2fc8b3bb0617c42be1ad2e7f8f7f4c81bca + checksum: 89449d31e20184f2f32619f75bca546c088f8f75e3a0e9e7c1735fc4cec1882f - filename: test/integration/specs/secrets-unset.test.ts - checksum: 1d52c72ff9a90bd65b0d083b0460ca641e05b257c9ed60c9f296738ab923a873 + checksum: 840417baf15d5f8b2437fd77b48996b85fcc81677fc820dd67b9959787efff8d +- filename: src/graphql/secrets-mutations.test.ts + checksum: e812adf5638b6f55bd4986abc7cedd6707895191dc409e8cfe5de3dc87e5b338 version: "1.0" diff --git a/src/commands/launch/secrets/list.test.ts b/src/commands/launch/secrets/list.test.ts index 56e9263b..7d750a86 100644 --- a/src/commands/launch/secrets/list.test.ts +++ b/src/commands/launch/secrets/list.test.ts @@ -90,7 +90,7 @@ describe('ListSecrets Command', () => { expect(cliux.table).not.toHaveBeenCalled(); }); - it.each([[404], [400]])('shows the formatted message and exits 1 when the secrets query fails with %i', async (status) => { + it.each([[404], [400]])('shows the server message and exits 1 when the secrets query fails with %i', async (status) => { const raw = randomUUID(); const query = jest.fn().mockRejectedValue({ message: raw, @@ -100,9 +100,8 @@ describe('ListSecrets Command', () => { await expect((cmd as any).listSecrets()).rejects.toThrow('process.exit:1'); - const expected = status === 404 ? 'was not found' : 'invalid key or value'; + const expected = status === 400 ? 'invalid key or value' : raw; expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining(expected), 'error'); - expect(JSON.stringify((cmd as any).log.mock.calls)).not.toContain(raw); expect(exitMock).toHaveBeenCalledWith(1); expect(cliux.table).not.toHaveBeenCalled(); }); diff --git a/src/commands/launch/secrets/set.test.ts b/src/commands/launch/secrets/set.test.ts index 1af04aa1..54c4c0e7 100644 --- a/src/commands/launch/secrets/set.test.ts +++ b/src/commands/launch/secrets/set.test.ts @@ -32,9 +32,24 @@ const environmentsResponse = (secrets: Record[] = [], name = 'Defau data: { Environments: { edges: [{ node: { uid: ENVIRONMENT_UID, name, secrets } }] } }, }); -const apiError = (status: number, name?: string) => ({ +const SECRET_CODES = { + conflict: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT', + multiline: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.VALUE.MULTILINE', +}; + +const apiError = (status: number) => ({ message: 'Request failed', - graphQLErrors: [{ message: 'Request failed', extensions: { exception: { status, ...(name ? { name } : {}) } } }], + graphQLErrors: [{ message: 'Request failed', extensions: { exception: { status } } }], +}); + +const formError = (code: string) => ({ + message: 'Bad request', + graphQLErrors: [ + { + message: 'Bad request', + extensions: { exception: { status: 400, messages: [code], errorObject: { secret: [{ code }] } } }, + }, + ], }); const originalStdin = Object.getOwnPropertyDescriptor(process, 'stdin') as PropertyDescriptor; @@ -84,7 +99,7 @@ describe('SetSecret Command', () => { expect(mutate).toHaveBeenCalledTimes(1); expect(mutate).toHaveBeenCalledWith({ mutation: addEnvironmentSecretMutation, - variables: { environmentUid: ENVIRONMENT_UID, secret: { key: 'API_TOKEN', value } }, + variables: { environment: { uid: ENVIRONMENT_UID }, secret: { key: 'API_TOKEN', value } }, }); expect(cliux.inquire).not.toHaveBeenCalled(); expect(exitMock).not.toHaveBeenCalled(); @@ -126,7 +141,7 @@ describe('SetSecret Command', () => { expect(mutate).toHaveBeenCalledTimes(1); expect(mutate.mock.calls[0][0].mutation).toBe(refreshEnvironmentSecretMutation); - expect(mutate.mock.calls[0][0].variables.environmentUid).toBe(ENVIRONMENT_UID); + expect(mutate.mock.calls[0][0].variables.environment).toEqual({ uid: ENVIRONMENT_UID }); }); it('aborts without a mutation or an error exit when the confirmation is declined', async () => { @@ -201,7 +216,7 @@ describe('SetSecret Command', () => { it('shows the multi-line message and leaks no value fragment when the API rejects a multi-line value', async () => { stubStdin(false, ['line1\nline2']); - const mutate = jest.fn().mockRejectedValue(apiError(400, 'ENVIRONMENT_SECRET_VALUE_MULTILINE')); + const mutate = jest.fn().mockRejectedValue(formError(SECRET_CODES.multiline)); const { cmd } = buildCommand({ yes: true }, { mutate }); await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); @@ -211,9 +226,9 @@ describe('SetSecret Command', () => { expect(allOutput((cmd as any).log, cliux.print as jest.Mock)).not.toContain('line1'); }); - it('reports the key conflict message when the API answers 409', async () => { + it('reports the key conflict message when the API reports a key conflict', async () => { stubStdin(false, [randomUUID()]); - const mutate = jest.fn().mockRejectedValue(apiError(409, 'ENVIRONMENT_SECRET_KEY_CONFLICT')); + const mutate = jest.fn().mockRejectedValue(formError(SECRET_CODES.conflict)); const { cmd } = buildCommand({ yes: true }, { mutate }); await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); diff --git a/src/commands/launch/secrets/set.ts b/src/commands/launch/secrets/set.ts index e634cfd5..71aea4d2 100644 --- a/src/commands/launch/secrets/set.ts +++ b/src/commands/launch/secrets/set.ts @@ -178,7 +178,7 @@ export default class SetSecret extends BaseCommand { await this.apolloClient .mutate({ mutation: exists ? refreshEnvironmentSecretMutation : addEnvironmentSecretMutation, - variables: { environmentUid: environment.uid, secret: { key, value } }, + variables: { environment: { uid: environment.uid }, secret: { key, value } }, }) .catch((error) => { this.log(formatSecretsError(error, { key, value }), 'error'); diff --git a/src/commands/launch/secrets/unset.test.ts b/src/commands/launch/secrets/unset.test.ts index b585e61e..22968d17 100644 --- a/src/commands/launch/secrets/unset.test.ts +++ b/src/commands/launch/secrets/unset.test.ts @@ -25,9 +25,23 @@ const environmentsResponse = (name = 'Default') => ({ data: { Environments: { edges: [{ node: { uid: ENVIRONMENT_UID, name, secrets: [] } }] } }, }); -const apiError = (status: number, name?: string) => ({ +const NOT_FOUND_CODE = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND'; + +const apiError = (status: number) => ({ message: 'Request failed', - graphQLErrors: [{ message: 'Request failed', extensions: { exception: { status, ...(name ? { name } : {}) } } }], + graphQLErrors: [{ message: 'Request failed', extensions: { exception: { status } } }], +}); + +const notFoundError = () => ({ + message: 'Bad request', + graphQLErrors: [ + { + message: 'Bad request', + extensions: { + exception: { status: 400, messages: [NOT_FOUND_CODE], errorObject: { secret: [{ code: NOT_FOUND_CODE }] } }, + }, + }, + ], }); const buildCommand = ( @@ -64,11 +78,11 @@ describe('UnsetSecret Command', () => { expect(mutate).toHaveBeenCalledTimes(2); expect(mutate).toHaveBeenNthCalledWith(1, { mutation: deleteEnvironmentSecretMutation, - variables: { environmentUid: ENVIRONMENT_UID, key: 'API_TOKEN' }, + variables: { environment: { uid: ENVIRONMENT_UID }, secret: { key: 'API_TOKEN' } }, }); expect(mutate).toHaveBeenNthCalledWith(2, { mutation: deleteEnvironmentSecretMutation, - variables: { environmentUid: ENVIRONMENT_UID, key: 'DB_PASSWORD' }, + variables: { environment: { uid: ENVIRONMENT_UID }, secret: { key: 'DB_PASSWORD' } }, }); expect(cliux.inquire).not.toHaveBeenCalled(); expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('API_TOKEN')); @@ -86,7 +100,10 @@ describe('UnsetSecret Command', () => { expect(question.type).toBe('confirm'); expect(question.message).toContain('API_TOKEN'); expect(mutate).toHaveBeenCalledTimes(1); - expect(mutate.mock.calls[0][0].variables).toEqual({ environmentUid: ENVIRONMENT_UID, key: 'API_TOKEN' }); + expect(mutate.mock.calls[0][0].variables).toEqual({ + environment: { uid: ENVIRONMENT_UID }, + secret: { key: 'API_TOKEN' }, + }); expect(exitMock).not.toHaveBeenCalled(); }); @@ -113,7 +130,7 @@ describe('UnsetSecret Command', () => { it('keeps deleting the remaining keys after one fails and exits 1 at the end', async () => { const mutate = jest .fn() - .mockRejectedValueOnce(apiError(404, 'ENVIRONMENT_SECRET_NOT_FOUND')) + .mockRejectedValueOnce(notFoundError()) .mockResolvedValueOnce({ data: { deleteEnvironmentSecret: true } }); const { cmd } = buildCommand({ key: ['MISSING_KEY', 'API_TOKEN'], yes: true }, mutate); diff --git a/src/commands/launch/secrets/unset.ts b/src/commands/launch/secrets/unset.ts index ccd8b691..82370d61 100644 --- a/src/commands/launch/secrets/unset.ts +++ b/src/commands/launch/secrets/unset.ts @@ -82,7 +82,7 @@ export default class UnsetSecret extends BaseCommand { try { await this.apolloClient.mutate({ mutation: deleteEnvironmentSecretMutation, - variables: { environmentUid: environment.uid, key }, + variables: { environment: { uid: environment.uid }, secret: { key } }, }); this.log(`Secret ${key} deleted from environment ${environment.name}.`); } catch (error) { diff --git a/src/graphql/mutation.ts b/src/graphql/mutation.ts index 2c488086..3e852745 100755 --- a/src/graphql/mutation.ts +++ b/src/graphql/mutation.ts @@ -86,8 +86,8 @@ const rollbackDeploymentMutation: DocumentNode = gql` `; const addEnvironmentSecretMutation: DocumentNode = gql` - mutation AddEnvironmentSecret($environmentUid: String!, $secret: EnvironmentSecretInput!) { - addEnvironmentSecret(environmentUid: $environmentUid, secret: $secret) { + mutation AddEnvironmentSecret($environment: EnvironmentInput!, $secret: EnvironmentSecretInput!) { + addEnvironmentSecret(environment: $environment, secret: $secret) { key updatedAt } @@ -95,8 +95,8 @@ const addEnvironmentSecretMutation: DocumentNode = gql` `; const refreshEnvironmentSecretMutation: DocumentNode = gql` - mutation RefreshEnvironmentSecret($environmentUid: String!, $secret: EnvironmentSecretInput!) { - refreshEnvironmentSecret(environmentUid: $environmentUid, secret: $secret) { + mutation RefreshEnvironmentSecret($environment: EnvironmentInput!, $secret: EnvironmentSecretInput!) { + refreshEnvironmentSecret(environment: $environment, secret: $secret) { key updatedAt } @@ -104,8 +104,8 @@ const refreshEnvironmentSecretMutation: DocumentNode = gql` `; const deleteEnvironmentSecretMutation: DocumentNode = gql` - mutation DeleteEnvironmentSecret($environmentUid: String!, $key: String!) { - deleteEnvironmentSecret(environmentUid: $environmentUid, key: $key) + mutation DeleteEnvironmentSecret($environment: EnvironmentInput!, $secret: EnvironmentSecretKeyInput!) { + deleteEnvironmentSecret(environment: $environment, secret: $secret) } `; diff --git a/src/graphql/secrets-mutations.test.ts b/src/graphql/secrets-mutations.test.ts new file mode 100644 index 00000000..bedc15fc --- /dev/null +++ b/src/graphql/secrets-mutations.test.ts @@ -0,0 +1,22 @@ +import { print } from 'graphql'; + +import { + addEnvironmentSecretMutation, + refreshEnvironmentSecretMutation, + deleteEnvironmentSecretMutation, +} from './mutation'; + +describe('environment secret mutations', () => { + it.each([ + ['addEnvironmentSecret', addEnvironmentSecretMutation, '$secret: EnvironmentSecretInput!'], + ['refreshEnvironmentSecret', refreshEnvironmentSecretMutation, '$secret: EnvironmentSecretInput!'], + ['deleteEnvironmentSecret', deleteEnvironmentSecretMutation, '$secret: EnvironmentSecretKeyInput!'], + ])('declares %s with the environment and secret input arguments of the schema', (name, document, secretVariable) => { + const printed = print(document); + + expect(printed).toContain('$environment: EnvironmentInput!'); + expect(printed).toContain(secretVariable); + expect(printed).toContain(`${name}(environment: $environment, secret: $secret)`); + expect(printed).not.toContain('environmentUid'); + }); +}); diff --git a/src/util/secrets.test.ts b/src/util/secrets.test.ts index 83a7f0a4..a01e2ba4 100644 --- a/src/util/secrets.test.ts +++ b/src/util/secrets.test.ts @@ -8,8 +8,31 @@ import { redactFlagValues, } from './secrets'; -const apiError = (status: number, code?: string, message = 'Request failed') => ({ - graphQLErrors: [{ message, extensions: { exception: { status, ...(code ? { name: code } : {}) } } }], +const CODES = { + conflict: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT', + notFound: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND', + multiline: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.VALUE.MULTILINE', + concurrent: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE', + keyEmpty: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.NOT_EMPTY', + keyTooLong: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.TOO_LONG', + valueEmpty: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.VALUE.NOT_EMPTY', + valueTooLong: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.VALUE.TOO_LONG', +}; + +const formError = (code: string, key = 'secret') => ({ + message: 'Bad request', + graphQLErrors: [ + { + message: 'Bad request', + extensions: { + exception: { status: 400, messages: [code], errorObject: { [key]: [{ code }] } }, + }, + }, + ], +}); + +const apiError = (status: number, message = 'Request failed') => ({ + graphQLErrors: [{ message, extensions: { exception: { status } } }], message, }); @@ -34,12 +57,16 @@ describe('secrets util', () => { }); it.each([ - ['409 key conflict', apiError(409, 'ENVIRONMENT_SECRET_KEY_CONFLICT'), 'already used by a variable or secret'], - ['409 concurrent update', apiError(409, 'ENVIRONMENT_VARIABLES_CONCURRENT_UPDATE'), 'concurrent update'], - ['400 multiline', apiError(400, 'ENVIRONMENT_SECRET_VALUE_MULTILINE'), 'multi-line values are not supported'], - ['400 invalid', apiError(400), 'invalid key or value'], + ['key conflict', formError(CODES.conflict), 'already used by a variable or secret'], + ['concurrent update', formError(CODES.concurrent, 'environmentVariables'), 'concurrent update'], + ['multiline', formError(CODES.multiline), 'multi-line values are not supported'], + ['not found', formError(CODES.notFound), 'DB_URL was not found'], + ['empty key', formError(CODES.keyEmpty), 'key cannot be empty'], + ['too long key', formError(CODES.keyTooLong), 'key is too long'], + ['empty value', formError(CODES.valueEmpty), 'value cannot be empty'], + ['too long value', formError(CODES.valueTooLong), 'value is too long'], + ['plain 400 validation', apiError(400), 'invalid key or value'], ['403', apiError(403), 'do not have permission'], - ['404 not found', apiError(404, 'ENVIRONMENT_SECRET_NOT_FOUND'), 'DB_URL was not found'], ])('formats a %s API error as a clear message', (_label, error, expected) => { const message = formatSecretsError(error, { key: 'DB_URL' }); @@ -48,12 +75,16 @@ describe('secrets util', () => { it('produces distinct messages for each known error', () => { const errors = [ - apiError(409, 'ENVIRONMENT_SECRET_KEY_CONFLICT'), - apiError(409, 'ENVIRONMENT_VARIABLES_CONCURRENT_UPDATE'), - apiError(400, 'ENVIRONMENT_SECRET_VALUE_MULTILINE'), + formError(CODES.conflict), + formError(CODES.concurrent), + formError(CODES.multiline), + formError(CODES.notFound), + formError(CODES.keyEmpty), + formError(CODES.keyTooLong), + formError(CODES.valueEmpty), + formError(CODES.valueTooLong), apiError(400), apiError(403), - apiError(404, 'ENVIRONMENT_SECRET_NOT_FOUND'), ]; const messages = errors.map((error) => formatSecretsError(error, { key: 'DB_URL' })); @@ -62,12 +93,12 @@ describe('secrets util', () => { messages.forEach((message) => expect(message.length).toBeGreaterThan(0)); }); - it('finds a namespaced code in the error object', () => { + it('finds a code in the error object only', () => { const error = { graphQLErrors: [ { - message: 'Conflict', - extensions: { exception: { status: 409, errorObject: { code: 'launch.ENVIRONMENT_SECRET_KEY_CONFLICT' } } }, + message: 'Bad request', + extensions: { exception: { status: 400, errorObject: { secret: [{ code: CODES.conflict }] } } }, }, ], }; @@ -80,7 +111,7 @@ describe('secrets util', () => { it('finds a code in the exception messages', () => { const error = { graphQLErrors: [ - { message: 'Bad', extensions: { exception: { status: 400, messages: ['ENVIRONMENT_SECRET_VALUE_MULTILINE'] } } }, + { message: 'Bad', extensions: { exception: { status: 400, messages: [CODES.multiline] } } }, ], }; @@ -90,7 +121,7 @@ describe('secrets util', () => { }); it('finds a code in the top level error message', () => { - const error = { message: 'ENVIRONMENT_SECRET_NOT_FOUND', graphQLErrors: [] }; + const error = { message: CODES.notFound, graphQLErrors: [] }; const message = formatSecretsError(error, { key: 'DB_URL' }); @@ -98,7 +129,7 @@ describe('secrets util', () => { }); it('falls back to the server message for an unknown error', () => { - const message = formatSecretsError(apiError(500, 'SOMETHING_ELSE', 'Server exploded'), { key: 'DB_URL' }); + const message = formatSecretsError(apiError(500, 'Server exploded'), { key: 'DB_URL' }); expect(message).toBe('Server exploded'); }); @@ -106,7 +137,7 @@ describe('secrets util', () => { it('never includes the secret value in the message', () => { const value = randomUUID(); - const message = formatSecretsError(apiError(500, undefined, `bad value ${value}`), { key: 'DB_URL', value }); + const message = formatSecretsError(apiError(500, `bad value ${value}`), { key: 'DB_URL', value }); expect(message).not.toContain(value); }); diff --git a/src/util/secrets.ts b/src/util/secrets.ts index 43cc557c..c86d4a30 100644 --- a/src/util/secrets.ts +++ b/src/util/secrets.ts @@ -16,6 +16,17 @@ export const clientExposedWarning = (key: string): string => `Warning: ${key} starts with a client-exposed prefix, so its value is inlined into client JavaScript ` + 'at build time and is visible to anyone who loads your site.'; +const ERROR_CODES = { + keyConflict: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT', + notFound: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND', + multiline: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.VALUE.MULTILINE', + concurrentUpdate: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.CONCURRENT_UPDATE', + keyEmpty: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.NOT_EMPTY', + keyTooLong: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.KEY.TOO_LONG', + valueEmpty: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.VALUE.NOT_EMPTY', + valueTooLong: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.VALUE.TOO_LONG', +}; + type SecretsErrorContext = { key?: string; value?: string }; const stringify = (item: unknown): string => { @@ -44,13 +55,14 @@ export const formatSecretsError = (error: any, { key, value }: SecretsErrorConte const keyName = key ?? 'the secret'; const known: [boolean, string][] = [ - [hasCode('ENVIRONMENT_SECRET_KEY_CONFLICT'), `The key ${keyName} is already used by a variable or secret.`], - [ - hasCode('ENVIRONMENT_VARIABLES_CONCURRENT_UPDATE'), - 'The environment was changed by a concurrent update. Please retry.', - ], - [hasCode('ENVIRONMENT_SECRET_VALUE_MULTILINE'), 'Invalid value: multi-line values are not supported.'], - [hasCode('ENVIRONMENT_SECRET_NOT_FOUND') || status === 404, `The secret ${keyName} was not found.`], + [hasCode(ERROR_CODES.keyConflict), `The key ${keyName} is already used by a variable or secret.`], + [hasCode(ERROR_CODES.concurrentUpdate), 'The environment was changed by a concurrent update. Please retry.'], + [hasCode(ERROR_CODES.multiline), 'Invalid value: multi-line values are not supported.'], + [hasCode(ERROR_CODES.notFound), `The secret ${keyName} was not found.`], + [hasCode(ERROR_CODES.keyEmpty), 'Invalid key: the key cannot be empty.'], + [hasCode(ERROR_CODES.keyTooLong), 'Invalid key: the key is too long (maximum 10000 characters).'], + [hasCode(ERROR_CODES.valueEmpty), 'Invalid value: the value cannot be empty.'], + [hasCode(ERROR_CODES.valueTooLong), 'Invalid value: the value is too long (maximum 10000 characters).'], [status === 403, 'You do not have permission to manage the secrets of this environment.'], [status === 400, 'The API rejected the request: invalid key or value.'], ]; diff --git a/test/integration/harness/fixtures.ts b/test/integration/harness/fixtures.ts index 8cd1cfa3..e0d87ee7 100644 --- a/test/integration/harness/fixtures.ts +++ b/test/integration/harness/fixtures.ts @@ -85,8 +85,25 @@ export const deleteEnvironmentSecretResponse = () => ({ data: { deleteEnvironmentSecret: true }, }); -export const secretsApiErrorResponse = (status: number, code?: string, message = 'Request failed') => ({ - errors: [{ message, extensions: { exception: { status, ...(code ? { name: code } : {}) } } }], +export const SECRET_ERROR_CODES = { + keyConflict: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.CONFLICT', + notFound: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND', + multiline: 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.VALUE.MULTILINE', +}; + +export const secretsFormErrorResponse = (code: string, key = 'secret') => ({ + errors: [ + { + message: 'Bad request', + extensions: { + exception: { errorObject: { [key]: [{ code }] }, key, message: 'Bad request', messages: [code], status: 400 }, + }, + }, + ], +}); + +export const secretsApiErrorResponse = (status: number, message = 'Request failed') => ({ + errors: [{ message, extensions: { exception: { status } } }], }); export const projectsResponse = ( diff --git a/test/integration/specs/secrets-set.test.ts b/test/integration/specs/secrets-set.test.ts index a3c07d03..6e79714d 100644 --- a/test/integration/specs/secrets-set.test.ts +++ b/test/integration/specs/secrets-set.test.ts @@ -51,7 +51,7 @@ describe('launch:secrets:set', () => { prompts.assertScriptFullyConsumed(); expect(session.api.operationSequence()).toEqual(['Projects', 'EnvironmentSecrets', 'AddEnvironmentSecret']); expect(session.api.variablesOf('AddEnvironmentSecret')).toEqual({ - environmentUid: fixtures.ENVIRONMENT_UID, + environment: { uid: fixtures.ENVIRONMENT_UID }, secret: { key: fixtures.SECRET_KEY, value }, }); expect(result.output).not.toContain(value); @@ -111,7 +111,10 @@ describe('launch:secrets:set', () => { session.api.assertNoUnhandledOperations(); prompts.assertScriptFullyConsumed(); expect(session.api.operationSequence()).toEqual(['Projects', 'EnvironmentSecrets', 'RefreshEnvironmentSecret']); - expect(session.api.variablesOf('RefreshEnvironmentSecret').secret).toEqual({ key: fixtures.SECRET_KEY, value }); + expect(session.api.variablesOf('RefreshEnvironmentSecret')).toEqual({ + environment: { uid: fixtures.ENVIRONMENT_UID }, + secret: { key: fixtures.SECRET_KEY, value }, + }); expect(result.output).not.toContain(value); }); @@ -158,11 +161,11 @@ describe('launch:secrets:set', () => { expect(session.api.calls('RefreshEnvironmentSecret')).toHaveLength(0); }); - it('shows the key conflict message and exits 1 when the API answers 409', async () => { + it('shows the key conflict message and exits 1 when the API reports a key conflict', async () => { session.api .on('Projects', fixtures.projectsResponse()) .on('EnvironmentSecrets', fixtures.environmentSecretsResponse([])) - .on('AddEnvironmentSecret', fixtures.secretsApiErrorResponse(409, 'ENVIRONMENT_SECRET_KEY_CONFLICT')); + .on('AddEnvironmentSecret', fixtures.secretsFormErrorResponse(fixtures.SECRET_ERROR_CODES.keyConflict)); stdin.pipe(randomUUID()); prompts.script([]); @@ -182,7 +185,7 @@ describe('launch:secrets:set', () => { .on('AddEnvironmentSecret', (_variables, callIndex) => callIndex === 0 ? fixtures.addEnvironmentSecretResponse() - : fixtures.secretsApiErrorResponse(400, undefined, `Invalid value ${value}`), + : fixtures.secretsApiErrorResponse(400, `Invalid value ${value}`), ); prompts.script([]); diff --git a/test/integration/specs/secrets-unset.test.ts b/test/integration/specs/secrets-unset.test.ts index f06b595c..fb623668 100644 --- a/test/integration/specs/secrets-unset.test.ts +++ b/test/integration/specs/secrets-unset.test.ts @@ -39,16 +39,16 @@ describe('launch:secrets:unset', () => { prompts.assertScriptFullyConsumed(); expect(session.api.operationSequence()).toEqual(['Projects', 'EnvironmentSecrets', 'DeleteEnvironmentSecret']); expect(session.api.calls('DeleteEnvironmentSecret').map((call) => call.variables)).toEqual([ - { environmentUid: fixtures.ENVIRONMENT_UID, key: 'API_TOKEN' }, - { environmentUid: fixtures.ENVIRONMENT_UID, key: 'DB_PASSWORD' }, + { environment: { uid: fixtures.ENVIRONMENT_UID }, secret: { key: 'API_TOKEN' } }, + { environment: { uid: fixtures.ENVIRONMENT_UID }, secret: { key: 'DB_PASSWORD' } }, ]); }); - it('shows a not-found message naming the key and exits 1 when the API answers 404', async () => { + it('shows a not-found message naming the key and exits 1 when the API reports the secret missing', async () => { session.api .on('Projects', fixtures.projectsResponse()) .on('EnvironmentSecrets', fixtures.environmentSecretsResponse()) - .on('DeleteEnvironmentSecret', fixtures.secretsApiErrorResponse(404, 'ENVIRONMENT_SECRET_NOT_FOUND')); + .on('DeleteEnvironmentSecret', fixtures.secretsFormErrorResponse(fixtures.SECRET_ERROR_CODES.notFound)); stdin.tty(); prompts.script([]); From 9c6d25b485d3517602339a01c604e24f7b2931ed Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 19:17:39 +0000 Subject: [PATCH 6/6] CL-8166 | +Claude | Make launch:secrets commands non-interactive safe and share scope setup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the org, project, branch and environment setup of list, set and unset into SecretsBaseCommand. Explicit --org and --project now override the stored project, and when stdin is not a terminal nothing can prompt: unresolved scope, branch ambiguity and a missing --yes fail with exit 1. BaseCommand.getConfig gains an opt-in non-interactive mode. Parse errors no longer echo argv, piped stdin reads are bounded, and read failures use read-context wording. #claude_code# 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 22 +- src/base-command.ts | 15 +- src/base-secrets-command.test.ts | 284 +++++++++++++++++++ src/base-secrets-command.ts | 184 ++++++++++++ src/commands/launch/secrets/list.test.ts | 8 +- src/commands/launch/secrets/list.ts | 80 +----- src/commands/launch/secrets/set.test.ts | 83 +----- src/commands/launch/secrets/set.ts | 192 +++---------- src/commands/launch/secrets/unset.test.ts | 21 ++ src/commands/launch/secrets/unset.ts | 85 +----- src/util/secrets.test.ts | 16 ++ src/util/secrets.ts | 9 +- test/integration/specs/secrets-set.test.ts | 71 ++++- test/integration/specs/secrets-unset.test.ts | 35 +++ 14 files changed, 712 insertions(+), 393 deletions(-) create mode 100644 src/base-secrets-command.test.ts create mode 100644 src/base-secrets-command.ts diff --git a/.talismanrc b/.talismanrc index b25cceba..e187ec07 100644 --- a/.talismanrc +++ b/.talismanrc @@ -40,7 +40,7 @@ fileignoreconfig: - filename: test/integration/harness/fixtures.ts checksum: e22bc8ab6f0c266b1f53700bd3611a934f7469b1995bf451cad2115f86ca4b3e - filename: src/base-command.ts - checksum: db8bc45f6d8aa3daebae621920c8618b6e23d1a20984dee0749d91bfa5c1530c + checksum: 3f7bcb2dff516aa166c7e721d3d60bf1b14db4bb1fc22a339ed21afba4d86a13 - filename: test/unit/base-command.test.ts checksum: 4612c2a41c9d5a7af887f77842feee0a6f6a28ba95a094282b5e9aa20dba6c8c - filename: src/graphql/queries.ts @@ -48,27 +48,31 @@ fileignoreconfig: - filename: test/integration/specs/secrets-list.test.ts checksum: d4cdd09fe16a876f7457bdf9bbaa83511624c12a0c7a967abc5f26a678696629 - filename: src/commands/launch/secrets/list.ts - checksum: e33958ccf580f32e6869690f1409ab40bb429f699623dc0a009a62e9e6f204d7 + checksum: da14a738f37a9610ab9dec7978de81cbb778ed0da9e73c4df4806c6e3c4c00cf - filename: src/commands/launch/secrets/list.test.ts - checksum: 1569c7d0feeb55ab1425bf0f8f22aa8550030560dbda83d017de34f09bcff3f2 + checksum: af09c894e3c21b061078a614f599e642b3db11e6f2145cb588e14e2476ff612a - filename: src/graphql/mutation.ts checksum: c420996deea097d6125ccd9648d0b87806bf7edeb4eda5604a068eee3e669542 - filename: src/util/secrets.ts - checksum: caf8a13cd8147e8a50667fc7b84a5db073f41e130b6d5996d6a57e3dc0b2bc1c + checksum: 9ccc5fdb18cb3c4ea637d6834c5b91e860c374abd01d808d002b3862d2f0c67a - filename: src/commands/launch/secrets/set.ts - checksum: 30814bd285d9fe4b9a21206f0c2d2fc530447a5cb276ba152265885ca1a36e56 + checksum: 80b805d6f746b6cfbef06690f4219fe7b810d58755dcc4fd3042092922b497b6 - filename: src/util/secrets.test.ts - checksum: 608f9187faf1cd312860ca3c15e324bc3d74d492d571194f5062f327dd2be2c4 + checksum: acadbf4e3b1a62d2ebd81f203bdb673c314d1534a7598d95d675a27905c7c8cb - filename: test/integration/specs/secrets-set.test.ts - checksum: ed46f1b15a450e07ed6da7ce0474fa3b404a4d687113d06de7a40c49283d377d + checksum: 0975c0277d2643273d61d2f194ff7e1599f79f21fe4372367746f0fbd5b14d4b - filename: src/commands/launch/secrets/set.test.ts checksum: 2953250cb9353eaa298a30e480badf5b12a6e8a9851355e3a9055e7a1bbaa98f - filename: src/commands/launch/secrets/unset.ts - checksum: 1260b3ee447042bfdc0ec2bafbeeeca0d65e966fc1ffd30c1acb38bf4392229a + checksum: 3c7d81a01ccfbd32fd2060ed88ef14fba525fded736604b4302c68ca9bc2d966 - filename: src/commands/launch/secrets/unset.test.ts checksum: 89449d31e20184f2f32619f75bca546c088f8f75e3a0e9e7c1735fc4cec1882f - filename: test/integration/specs/secrets-unset.test.ts - checksum: 840417baf15d5f8b2437fd77b48996b85fcc81677fc820dd67b9959787efff8d + checksum: 363d8fbfb996395eb89c355b623a337143d5049f99bf20bf45c8c076eeefe06e - filename: src/graphql/secrets-mutations.test.ts checksum: e812adf5638b6f55bd4986abc7cedd6707895191dc409e8cfe5de3dc87e5b338 +- filename: src/base-secrets-command.ts + checksum: 21b5c6d1d69c1dc72979b53fa706eda50874536b32c1549879ea83b38f54d375 +- filename: src/base-secrets-command.test.ts + checksum: 71613e5e8abe20656130e85de53539ebbaa16c23cd050c4b1fac5fda676c8dd1 version: "1.0" diff --git a/src/base-command.ts b/src/base-command.ts index 4cbab1de..e3c8d68a 100755 --- a/src/base-command.ts +++ b/src/base-command.ts @@ -151,7 +151,7 @@ export abstract class BaseCommand extends Command { * @return {*} {Promise} * @memberof BaseCommand */ - async getConfig(): Promise { + async getConfig(options: { interactive?: boolean } = {}): Promise { if (this.sharedConfig.config && existsSync(this.sharedConfig.config)) { const config: Record = JSON.parse(readFileSync(this.sharedConfig.config, 'utf-8')); const configKeys = keys(config); @@ -160,7 +160,7 @@ export abstract class BaseCommand extends Command { if (this.flags.branch && includes(configKeys, this.flags.branch)) { this.sharedConfig.currentConfig = config[this.flags.branch]; } else if (configKeys?.length > 1) { - await this.handleBranchSelection(config, configKeys); + await this.handleBranchSelection(config, configKeys, options.interactive !== false); } else { // By default there is only one configuration ("project"), set it as the default this.sharedConfig.currentConfig = config[configKeys[0]]; @@ -172,11 +172,20 @@ export abstract class BaseCommand extends Command { } } - private async handleBranchSelection(config: Record, configKeys: string[]): Promise { + private async handleBranchSelection( + config: Record, + configKeys: string[], + interactive = true, + ): Promise { // Filter out the "project" key from the branch choices const branchChoices = configKeys.filter((key) => key !== 'project'); // If there are multiple keys (branches), excluding "project", prompt user to choose + if (branchChoices.length > 1 && !interactive) { + this.log('Multiple branches are configured; pass --branch to choose one.', 'error'); + process.exit(1); + } + if (branchChoices.length > 1) { this.sharedConfig.currentConfig = await ux .inquire({ diff --git a/src/base-secrets-command.test.ts b/src/base-secrets-command.test.ts new file mode 100644 index 00000000..2624476a --- /dev/null +++ b/src/base-secrets-command.test.ts @@ -0,0 +1,284 @@ +import { tmpdir } from 'os'; +import { join } from 'path'; +import { Readable } from 'stream'; +import { randomUUID } from 'crypto'; +import { cliux } from '@contentstack/cli-utilities'; +import { mkdtempSync, writeFileSync } from 'fs'; + +import { selectOrg, selectProject, getOrganizations } from './util'; + +import { SecretsBaseCommand } from './base-secrets-command'; +import ListSecrets from './commands/launch/secrets/list'; +import SetSecret from './commands/launch/secrets/set'; +import UnsetSecret from './commands/launch/secrets/unset'; + +jest.mock('./util', () => { + const actual = jest.requireActual('./util'); + return { + ...actual, + Logger: jest.fn().mockImplementation(() => ({ log: jest.fn() })), + selectOrg: jest.fn(), + selectProject: jest.fn(), + getOrganizations: jest.fn(), + }; +}); + +jest.mock('@contentstack/cli-utilities', () => { + const { launchCommand } = jest.requireActual('./test/mocks/cli-utilities'); + return launchCommand; +}); + +class Probe extends SecretsBaseCommand { + async run(): Promise {} +} + +class UnexpectedArgsError extends Error { + parse = {}; +} + +class NonExistentFlagsError extends Error { + parse = {}; +} + +class FailedFlagValidationError extends Error { + parse = {}; +} + +const originalStdin = Object.getOwnPropertyDescriptor(process, 'stdin') as PropertyDescriptor; + +const stubStdin = (isTTY: boolean) => { + const stream: any = Readable.from([]); + stream.isTTY = isTTY; + Object.defineProperty(process, 'stdin', { value: stream, configurable: true }); +}; + +const projectsResponse = (uids: string[]) => ({ + data: { + projects: { edges: uids.map((uid) => ({ node: { uid, name: `name-${uid}` } })) }, + }, +}); + +const writeConfig = (content: Record) => { + const path = join(mkdtempSync(join(tmpdir(), 'secrets-base-')), '.cs-launch.json'); + writeFileSync(path, JSON.stringify(content)); + return path; +}; + +const buildProbe = (flags: Record = {}, currentConfig: Record = {}, extra: any = {}) => { + const cmd = new Probe([], {} as any); + const query = jest.fn().mockResolvedValue(projectsResponse(['P1', 'P2'])); + (cmd as any).flags = flags; + (cmd as any).log = jest.fn(); + (cmd as any).sharedConfig = { currentConfig: { ...currentConfig }, ...extra }; + (cmd as any).apolloClient = { query }; + (cmd as any).managementSdk = {}; + jest.spyOn(cmd as any, 'prepareApiClients').mockResolvedValue(undefined); + return { cmd: cmd as any, query }; +}; + +describe('SecretsBaseCommand', () => { + let exitMock: jest.SpyInstance; + + beforeEach(() => { + exitMock = jest.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Error(`process.exit:${code}`); + }) as any); + }); + + afterEach(() => { + Object.defineProperty(process, 'stdin', originalStdin); + jest.clearAllMocks(); + }); + + it('selects the organization and project again in a terminal when --org or --project override the stored project', async () => { + stubStdin(true); + const { cmd } = buildProbe({ org: 'O2', project: 'P2', environment: 'Default' }, { uid: 'P1' }); + jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await cmd.setupScope(); + + expect(selectOrg).toHaveBeenCalledTimes(1); + expect(selectProject).toHaveBeenCalledTimes(1); + }); + + it('keeps the stored project without selecting in a terminal when no scope flag is given', async () => { + stubStdin(true); + const { cmd } = buildProbe({ environment: 'Default' }, { uid: 'P1' }); + jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await cmd.setupScope(); + + expect(selectOrg).not.toHaveBeenCalled(); + expect(selectProject).not.toHaveBeenCalled(); + }); + + it('overrides the stored project with --project and --org when not in a terminal', async () => { + stubStdin(false); + (getOrganizations as jest.Mock).mockResolvedValue([{ uid: 'O1' }, { uid: 'O2' }]); + const { cmd, query } = buildProbe({ org: 'O2', project: 'P2', environment: 'Default' }, { uid: 'P1', organizationUid: 'O1' }); + jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await cmd.setupScope(); + + expect(cmd.sharedConfig.currentConfig).toEqual(expect.objectContaining({ uid: 'P2', organizationUid: 'O2' })); + expect(query).toHaveBeenCalledTimes(1); + expect(cmd.prepareApiClients).toHaveBeenCalledTimes(3); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect(selectOrg).not.toHaveBeenCalled(); + expect(selectProject).not.toHaveBeenCalled(); + }); + + it('keeps the stored project without any lookup when not in a terminal and no scope flag is given', async () => { + stubStdin(false); + const { cmd, query } = buildProbe({ environment: 'Default' }, { uid: 'P1', organizationUid: 'O1' }); + jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await cmd.setupScope(); + + expect(cmd.sharedConfig.currentConfig.uid).toBe('P1'); + expect(query).not.toHaveBeenCalled(); + expect(getOrganizations).not.toHaveBeenCalled(); + }); + + it('fails without prompting when not in a terminal and --org does not match an organization', async () => { + stubStdin(false); + (getOrganizations as jest.Mock).mockResolvedValue([{ uid: 'O1' }]); + const { cmd } = buildProbe({ org: 'WRONG', project: 'P1', environment: 'Default' }); + jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await expect(cmd.setupScope()).rejects.toThrow('process.exit:1'); + + expect(cmd.log).toHaveBeenCalledWith('Organization UID not found!', 'error'); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect(exitMock).toHaveBeenCalledWith(1); + }); + + it('fails without prompting when not in a terminal and --project does not match a project', async () => { + stubStdin(false); + (getOrganizations as jest.Mock).mockResolvedValue([{ uid: 'O1' }]); + const { cmd } = buildProbe({ org: 'O1', project: 'WRONG', environment: 'Default' }); + jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await expect(cmd.setupScope()).rejects.toThrow('process.exit:1'); + + expect(cmd.log).toHaveBeenCalledWith('Project not found!', 'error'); + expect(cliux.inquire).not.toHaveBeenCalled(); + }); + + it('fails before loading the config when not in a terminal and --environment is missing', async () => { + stubStdin(false); + const { cmd } = buildProbe({ org: 'O1', project: 'P1' }); + const getConfig = jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await expect(cmd.setupScope()).rejects.toThrow('process.exit:1'); + + expect(cmd.log).toHaveBeenCalledWith(expect.stringContaining('--org, --project and --environment are required'), 'error'); + expect(getConfig).not.toHaveBeenCalled(); + expect(cliux.inquire).not.toHaveBeenCalled(); + }); + + it('fails without prompting when not in a terminal and no project is stored or given', async () => { + stubStdin(false); + const { cmd } = buildProbe({ environment: 'Default' }); + jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await expect(cmd.setupScope()).rejects.toThrow('process.exit:1'); + + expect(cmd.log).toHaveBeenCalledWith(expect.stringContaining('--org, --project and --environment are required'), 'error'); + expect(cliux.inquire).not.toHaveBeenCalled(); + }); + + it('loads the config non-interactively when not in a terminal', async () => { + stubStdin(false); + const { cmd } = buildProbe({ environment: 'Default' }, { uid: 'P1' }); + const getConfig = jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined); + + await cmd.setupScope(); + + expect(getConfig).toHaveBeenCalledWith({ interactive: false }); + }); + + it('fails without prompting when a branch must be chosen and the config is loaded non-interactively', async () => { + const config = writeConfig({ main: { uid: 'P1' }, develop: { uid: 'P1' } }); + const { cmd } = buildProbe({}, {}, { config }); + + await expect(cmd.getConfig({ interactive: false })).rejects.toThrow('process.exit:1'); + + expect(cmd.log).toHaveBeenCalledWith('Multiple branches are configured; pass --branch to choose one.', 'error'); + expect(cliux.inquire).not.toHaveBeenCalled(); + }); + + it('uses the branch given with --branch without prompting when the config is loaded non-interactively', async () => { + const config = writeConfig({ main: { uid: 'P1' }, develop: { uid: 'P2' } }); + const { cmd } = buildProbe({ branch: 'develop' }, {}, { config, providerMapper: {} }); + + await cmd.getConfig({ interactive: false }); + + expect(cmd.sharedConfig.currentConfig.uid).toBe('P2'); + expect(cliux.inquire).not.toHaveBeenCalled(); + }); + + it('still prompts for the branch by default', async () => { + const config = writeConfig({ main: { uid: 'P1' }, develop: { uid: 'P2' } }); + (cliux.inquire as jest.Mock).mockResolvedValueOnce('develop'); + const { cmd } = buildProbe({}, {}, { config, providerMapper: {} }); + + await cmd.getConfig(); + + expect(cmd.sharedConfig.currentConfig.uid).toBe('P2'); + expect((cliux.inquire as jest.Mock).mock.calls[0][0]).toEqual(expect.objectContaining({ name: 'branch' })); + }); + + it('fails without prompting when not in a terminal and no environment is given to resolveEnvironment', async () => { + stubStdin(false); + const { cmd, query } = buildProbe({}); + query.mockResolvedValue({ data: { Environments: { edges: [] } } }); + + await expect(cmd.resolveEnvironment()).rejects.toThrow('process.exit:1'); + + expect(cliux.inquire).not.toHaveBeenCalled(); + }); + + it('shows read-context wording when the environments query fails with 404', async () => { + stubStdin(true); + const { cmd, query } = buildProbe({ environment: 'Default' }); + query.mockRejectedValue({ message: 'x', graphQLErrors: [{ message: 'x', extensions: { exception: { status: 404 } } }] }); + + await expect(cmd.resolveEnvironment()).rejects.toThrow('process.exit:1'); + + expect(cmd.log).toHaveBeenCalledWith('The project or environment was not found.', 'error'); + }); + + it.each([ + ['unexpected argument', new UnexpectedArgsError('Unexpected argument: SECRETVALUE')], + ['short flag glued to a value', new NonExistentFlagsError('Nonexistent flag: -vSECRETVALUE')], + ])('replaces the message of a parse error with a generic one for a %s', async (_label, error) => { + const value = randomUUID(); + error.message = error.message.replace('SECRETVALUE', value); + error.stack = `${error.message}\n at parse`; + const { cmd } = buildProbe(); + + await expect(cmd.catch(error)).rejects.toThrow(/Invalid arguments/); + + expect(error.message).not.toContain(value); + expect(error.stack).not.toContain(value); + }); + + it('keeps the message of a missing required flag error', async () => { + const error = new FailedFlagValidationError('Missing required flag key'); + const { cmd } = buildProbe(); + + await expect(cmd.catch(error)).rejects.toThrow('Missing required flag key'); + }); + + it.each([ + ['list', ListSecrets], + ['set', SetSecret], + ['unset', UnsetSecret], + ])('declares the hidden --branch flag and the shared scope flags on %s', (_name, command) => { + const flags = command.flags as Record; + + expect(flags.branch.hidden).toBe(true); + expect(Object.keys(flags)).toEqual(expect.arrayContaining(['org', 'project', 'environment', 'branch'])); + }); +}); diff --git a/src/base-secrets-command.ts b/src/base-secrets-command.ts new file mode 100644 index 00000000..3bc8d7f0 --- /dev/null +++ b/src/base-secrets-command.ts @@ -0,0 +1,184 @@ +import map from 'lodash/map'; +import find from 'lodash/find'; +import isEmpty from 'lodash/isEmpty'; +import includes from 'lodash/includes'; +import { Command } from '@contentstack/cli-command'; +import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; + +import { BaseCommand } from './base-command'; +import { projectsQuery, environmentSecretsQuery } from './graphql'; +import { Logger, selectOrg, selectProject, getOrganizations, formatSecretsError, redactFlagValues } from './util'; + +const GENERIC_PARSE_ERROR_NAMES = [ + 'UnexpectedArgsError', + 'NonExistentFlagsError', + 'FlagInvalidOptionError', + 'ArgInvalidOptionError', +]; + +export const secretsScopeFlags: FlagInput = { + org: Flags.string({ + description: '[Optional] Provide the organization UID', + }), + project: Flags.string({ + description: '[Optional] Provide the project UID', + }), + environment: Flags.string({ + char: 'e', + description: 'Environment name or UID', + }), + branch: Flags.string({ + hidden: true, + description: '[Optional] GitHub branch name', + }), +}; + +export abstract class SecretsBaseCommand extends BaseCommand { + protected scopeRequiredMessage = '--org, --project and --environment are required when not running in a terminal'; + + protected get interactive(): boolean { + return Boolean(process.stdin.isTTY); + } + + protected async catch(err: Error & { exitCode?: number; parse?: unknown }): Promise { + if (err?.parse && includes(GENERIC_PARSE_ERROR_NAMES, err.constructor?.name)) { + err.message = 'Invalid arguments. See --help for the flags this command takes.'; + err.stack = err.message; + } else { + err.message = redactFlagValues(err.message); + err.stack = err.stack && redactFlagValues(err.stack); + } + + return super.catch(err); + } + + protected initLogger(): void { + this.logger = new Logger(this.sharedConfig); + this.log = this.logger.log.bind(this.logger); + } + + protected failScope(message = this.scopeRequiredMessage): never { + this.log(message, 'error'); + return process.exit(1); + } + + async setupScope(): Promise { + const interactive = this.interactive; + + if (!interactive && !this.flags.environment) { + this.failScope(); + } + + await this.getConfig({ interactive }); + await this.prepareApiClients(); + + if (interactive) { + await this.selectScope(); + } else { + await this.resolveScopeFromFlags(); + } + } + + private async selectScope(): Promise { + const { org, project } = this.flags as Record; + + if (!org && !project && this.sharedConfig.currentConfig?.uid) return; + + await selectOrg({ + log: this.log, + flags: this.flags, + config: this.sharedConfig, + managementSdk: this.managementSdk, + }); + await this.prepareApiClients(); + await selectProject({ + log: this.log, + flags: this.flags, + config: this.sharedConfig, + apolloClient: this.apolloClient, + }); + await this.prepareApiClients(); + } + + private async resolveScopeFromFlags(): Promise { + const { org, project } = this.flags as Record; + const current = this.sharedConfig.currentConfig; + + if (org) { + const organizations = await getOrganizations({ log: this.log, managementSdk: this.managementSdk }); + const match = find(organizations, { uid: org }); + + if (!match) { + this.log('Organization UID not found!', 'error'); + process.exit(1); + } + + current.organizationUid = match.uid; + await this.prepareApiClients(); + } + + if (project) { + if (!current.organizationUid) { + this.failScope(); + } + + const projects = await this.apolloClient + .query({ query: projectsQuery, variables: { query: {} } }) + .then(({ data }) => map(data.projects.edges, 'node')) + .catch((error) => { + this.log(formatSecretsError(error, { operation: 'read' }), 'error'); + process.exit(1); + }); + const match = find(projects, { uid: project }) || find(projects, { name: project }); + + if (!match) { + this.log('Project not found!', 'error'); + process.exit(1); + } + + current.uid = match.uid; + await this.prepareApiClients(); + } + + if (!current.uid) { + this.failScope(); + } + } + + async resolveEnvironment(): Promise { + const environments = await this.apolloClient + .query({ query: environmentSecretsQuery }) + .then(({ data: { Environments } }) => map(Environments.edges, 'node')) + .catch((error) => { + this.log(formatSecretsError(error, { operation: 'read' }), 'error'); + process.exit(1); + }); + + if (!this.flags.environment) { + if (!this.interactive) { + this.failScope(); + } + + return ux + .inquire({ + type: 'search-list', + name: 'Environment', + choices: map(environments, (row) => ({ name: row.name, value: row.name })), + message: 'Choose an environment', + }) + .then((name: any) => find(environments, { name }) as Record); + } + + const environment = find( + environments, + ({ uid, name }) => uid === this.flags.environment || name === this.flags.environment, + ); + + if (isEmpty(environment)) { + this.log('Environment(s) not found!', 'error'); + process.exit(1); + } + + return environment; + } +} diff --git a/src/commands/launch/secrets/list.test.ts b/src/commands/launch/secrets/list.test.ts index 7d750a86..1c6b476d 100644 --- a/src/commands/launch/secrets/list.test.ts +++ b/src/commands/launch/secrets/list.test.ts @@ -29,6 +29,8 @@ const secretsResponse = (secrets: Record[], name = 'Default') => ({ }, }); +const originalStdin = Object.getOwnPropertyDescriptor(process, 'stdin') as PropertyDescriptor; + const buildCommand = (flags: Record, query: jest.Mock) => { const cmd = new ListSecrets([], {} as any); (cmd as any).flags = flags; @@ -48,6 +50,7 @@ describe('ListSecrets Command', () => { }); afterEach(() => { + Object.defineProperty(process, 'stdin', originalStdin); jest.clearAllMocks(); }); @@ -90,7 +93,7 @@ describe('ListSecrets Command', () => { expect(cliux.table).not.toHaveBeenCalled(); }); - it.each([[404], [400]])('shows the server message and exits 1 when the secrets query fails with %i', async (status) => { + it.each([[404], [400]])('shows the read-context message and exits 1 when the secrets query fails with %i', async (status) => { const raw = randomUUID(); const query = jest.fn().mockRejectedValue({ message: raw, @@ -100,7 +103,7 @@ describe('ListSecrets Command', () => { await expect((cmd as any).listSecrets()).rejects.toThrow('process.exit:1'); - const expected = status === 400 ? 'invalid key or value' : raw; + const expected = status === 400 ? 'The API rejected the request.' : 'The project or environment was not found.'; expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining(expected), 'error'); expect(exitMock).toHaveBeenCalledWith(1); expect(cliux.table).not.toHaveBeenCalled(); @@ -140,6 +143,7 @@ describe('ListSecrets Command', () => { }); it('prompts for the environment when --environment is not given', async () => { + Object.defineProperty(process, 'stdin', { value: { isTTY: true }, configurable: true }); const query = jest.fn().mockResolvedValue(secretsResponse([{ key: 'API_TOKEN', updatedAt: '2026-01-01T00:00:00.000Z' }])); (cliux.inquire as jest.Mock).mockResolvedValue('Default'); const cmd = buildCommand({}, query); diff --git a/src/commands/launch/secrets/list.ts b/src/commands/launch/secrets/list.ts index bd4b176f..7de08a84 100644 --- a/src/commands/launch/secrets/list.ts +++ b/src/commands/launch/secrets/list.ts @@ -1,13 +1,10 @@ import map from 'lodash/map'; -import find from 'lodash/find'; import isEmpty from 'lodash/isEmpty'; -import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; +import { FlagInput, cliux as ux } from '@contentstack/cli-utilities'; -import { BaseCommand } from '../../../base-command'; -import { environmentSecretsQuery } from '../../../graphql'; -import { Logger, selectOrg, selectProject, formatSecretsError } from '../../../util'; +import { SecretsBaseCommand, secretsScopeFlags } from '../../../base-secrets-command'; -export default class ListSecrets extends BaseCommand { +export default class ListSecrets extends SecretsBaseCommand { static description = 'List the secrets of an environment (keys only, values are never shown)'; static examples = [ @@ -16,43 +13,11 @@ export default class ListSecrets extends BaseCommand { '--environment=', ]; - static flags: FlagInput = { - org: Flags.string({ - description: '[Optional] Provide the organization UID', - }), - project: Flags.string({ - description: '[Optional] Provide the project UID', - }), - environment: Flags.string({ - char: 'e', - description: 'Environment name or UID', - }), - }; + static flags: FlagInput = { ...secretsScopeFlags }; async run(): Promise { - this.logger = new Logger(this.sharedConfig); - this.log = this.logger.log.bind(this.logger); - - await this.getConfig(); - await this.prepareApiClients(); - - if (!this.sharedConfig.currentConfig?.uid) { - await selectOrg({ - log: this.log, - flags: this.flags, - config: this.sharedConfig, - managementSdk: this.managementSdk, - }); - await this.prepareApiClients(); - await selectProject({ - log: this.log, - flags: this.flags, - config: this.sharedConfig, - apolloClient: this.apolloClient, - }); - await this.prepareApiClients(); - } - + this.initLogger(); + await this.setupScope(); await this.listSecrets(); } @@ -69,37 +34,4 @@ export default class ListSecrets extends BaseCommand { map(environment.secrets, ({ key, updatedAt }) => ({ KEY: key, UPDATED: updatedAt })), ); } - - async resolveEnvironment(): Promise { - const environments = await this.apolloClient - .query({ query: environmentSecretsQuery }) - .then(({ data: { Environments } }) => map(Environments.edges, 'node')) - .catch((error) => { - this.log(formatSecretsError(error), 'error'); - process.exit(1); - }); - - if (!this.flags.environment) { - return ux - .inquire({ - type: 'search-list', - name: 'Environment', - choices: map(environments, (row) => ({ name: row.name, value: row.name })), - message: 'Choose an environment', - }) - .then((name: any) => find(environments, { name }) as Record); - } - - const environment = find( - environments, - ({ uid, name }) => uid === this.flags.environment || name === this.flags.environment, - ); - - if (isEmpty(environment)) { - this.log('Environment(s) not found!', 'error'); - process.exit(1); - } - - return environment; - } } diff --git a/src/commands/launch/secrets/set.test.ts b/src/commands/launch/secrets/set.test.ts index 54c4c0e7..86155e5d 100644 --- a/src/commands/launch/secrets/set.test.ts +++ b/src/commands/launch/secrets/set.test.ts @@ -1,7 +1,4 @@ -import { tmpdir } from 'os'; -import { join } from 'path'; import { Readable } from 'stream'; -import { mkdtempSync, writeFileSync } from 'fs'; import { randomUUID } from 'crypto'; import { cliux } from '@contentstack/cli-utilities'; @@ -183,7 +180,7 @@ describe('SetSecret Command', () => { stubStdin(false, [randomUUID()]); const { cmd, mutate } = buildCommand({ yes: false }); - await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + await expect((cmd as any).preparePipedInput()).rejects.toThrow('process.exit:1'); expect(mutate).not.toHaveBeenCalled(); expect(cliux.inquire).not.toHaveBeenCalled(); @@ -283,48 +280,6 @@ describe('SetSecret Command', () => { expect(cliux.inquire).not.toHaveBeenCalled(); }); - it('fails without prompting or mutating when the value is piped and --environment is missing', async () => { - const value = randomUUID(); - stubStdin(false, [value]); - const { cmd, query, mutate } = buildCommand({ yes: true, environment: undefined }); - - await expect((cmd as any).preparePipedInput()).rejects.toThrow('process.exit:1'); - - expect((cmd as any).log).toHaveBeenCalledWith( - '--org, --project and --environment are required when the value is piped', - 'error', - ); - expect(exitMock).toHaveBeenCalledWith(1); - expect(cliux.inquire).not.toHaveBeenCalled(); - expect(query).not.toHaveBeenCalled(); - expect(mutate).not.toHaveBeenCalled(); - expect(allOutput((cmd as any).log, cliux.inquire as jest.Mock)).not.toContain(value); - }); - - it('fails without prompting when the value is piped and no project is configured or given', async () => { - stubStdin(false, [randomUUID()]); - const { cmd, mutate } = buildCommand({ yes: true, org: undefined, project: undefined }); - (cmd as any).sharedConfig = { currentConfig: {} }; - - await expect((cmd as any).assertPipedScope()).rejects.toThrow('process.exit:1'); - - expect((cmd as any).log).toHaveBeenCalledWith( - '--org, --project and --environment are required when the value is piped', - 'error', - ); - expect(cliux.inquire).not.toHaveBeenCalled(); - expect(mutate).not.toHaveBeenCalled(); - }); - - it('does not require --org and --project when a project is already configured', async () => { - stubStdin(false, [randomUUID()]); - const { cmd } = buildCommand({ yes: true }); - - await expect((cmd as any).assertPipedScope()).resolves.toBeUndefined(); - - expect(exitMock).not.toHaveBeenCalled(); - }); - it('reads the piped value before the config is loaded so no prompt can consume it', async () => { stubStdin(false, [randomUUID()]); (Logger as unknown as jest.Mock).mockImplementation(() => ({ log: jest.fn() })); @@ -340,37 +295,19 @@ describe('SetSecret Command', () => { expect(readStdin.mock.invocationCallOrder[0]).toBeLessThan(getConfig.mock.invocationCallOrder[0]); }); - it('fails without prompting or reading stdin when the value is piped and a branch would have to be chosen', async () => { - stubStdin(false, [randomUUID()]); + it('gives up with a clear error and no mutation when no data and no end arrive on stdin in time', async () => { + const stream: any = new Readable({ read() {} }); + stream.isTTY = false; + Object.defineProperty(process, 'stdin', { value: stream, configurable: true }); const { cmd, mutate } = buildCommand({ yes: true }); - const dir = mkdtempSync(join(tmpdir(), 'secrets-branch-')); - const configPath = join(dir, '.cs-launch.json'); - writeFileSync(configPath, JSON.stringify({ main: { uid: 'a' }, develop: { uid: 'b' } })); - (cmd as any).sharedConfig = { config: configPath, currentConfig: {} }; - const readStdin = jest.spyOn(cmd as any, 'readStdin'); + (cmd as any).stdinTimeoutMs = 20; - await expect((cmd as any).preparePipedInput()).rejects.toThrow('process.exit:1'); + await (cmd as any).preparePipedInput(); + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); - expect((cmd as any).log).toHaveBeenCalledWith( - 'Multiple branches are configured; pass --branch when the value is piped', - 'error', - ); - expect(readStdin).not.toHaveBeenCalled(); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('no value received on stdin'), 'error'); expect(mutate).not.toHaveBeenCalled(); - }); - - it('does not refuse a piped value when --branch names a configured branch', async () => { - stubStdin(false, [randomUUID()]); - const { cmd } = buildCommand({ yes: true, branch: 'main' }); - const dir = mkdtempSync(join(tmpdir(), 'secrets-branch-')); - const configPath = join(dir, '.cs-launch.json'); - writeFileSync(configPath, JSON.stringify({ main: { uid: 'a' }, develop: { uid: 'b' } })); - (cmd as any).sharedConfig = { config: configPath, currentConfig: {} }; - - await expect((cmd as any).preparePipedInput()).resolves.toBeUndefined(); - - expect(exitMock).not.toHaveBeenCalled(); + expect(cliux.inquire).not.toHaveBeenCalled(); }); it('shows a formatted error when reading the environment secrets fails', async () => { diff --git a/src/commands/launch/secrets/set.ts b/src/commands/launch/secrets/set.ts index 71aea4d2..30214dca 100644 --- a/src/commands/launch/secrets/set.ts +++ b/src/commands/launch/secrets/set.ts @@ -1,31 +1,20 @@ -import { existsSync, readFileSync } from 'fs'; -import map from 'lodash/map'; -import keys from 'lodash/keys'; -import filter from 'lodash/filter'; -import includes from 'lodash/includes'; import find from 'lodash/find'; import isEmpty from 'lodash/isEmpty'; import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; -import { BaseCommand } from '../../../base-command'; -import { - environmentSecretsQuery, - addEnvironmentSecretMutation, - refreshEnvironmentSecretMutation, -} from '../../../graphql'; -import { - Logger, - selectOrg, - selectProject, - isClientExposedKey, - clientExposedWarning, - formatSecretsError, - redactFlagValues, -} from '../../../util'; - -export default class SetSecret extends BaseCommand { +import { SecretsBaseCommand, secretsScopeFlags } from '../../../base-secrets-command'; +import { addEnvironmentSecretMutation, refreshEnvironmentSecretMutation } from '../../../graphql'; +import { isClientExposedKey, clientExposedWarning, formatSecretsError } from '../../../util'; + +const STDIN_TIMEOUT_MS = 30000; + +export default class SetSecret extends SecretsBaseCommand { private pipedValue?: string; + protected scopeRequiredMessage = '--org, --project and --environment are required when the value is piped'; + + stdinTimeoutMs = STDIN_TIMEOUT_MS; + static description = 'Add or refresh a secret of an environment. The value is read from a masked prompt, or from stdin when piped'; @@ -37,20 +26,7 @@ export default class SetSecret extends BaseCommand { ]; static flags: FlagInput = { - org: Flags.string({ - description: '[Optional] Provide the organization UID', - }), - project: Flags.string({ - description: '[Optional] Provide the project UID', - }), - environment: Flags.string({ - char: 'e', - description: 'Environment name or UID', - }), - branch: Flags.string({ - hidden: true, - description: '[Optional] GitHub branch name', - }), + ...secretsScopeFlags, key: Flags.string({ char: 'k', required: true, @@ -63,99 +39,29 @@ export default class SetSecret extends BaseCommand { }; async run(): Promise { - this.logger = new Logger(this.sharedConfig); - this.log = this.logger.log.bind(this.logger); - + this.initLogger(); await this.preparePipedInput(); - await this.getConfig(); - await this.assertPipedScope(); - await this.prepareApiClients(); - - if (!this.sharedConfig.currentConfig?.uid) { - await selectOrg({ - log: this.log, - flags: this.flags, - config: this.sharedConfig, - managementSdk: this.managementSdk, - }); - await this.prepareApiClients(); - await selectProject({ - log: this.log, - flags: this.flags, - config: this.sharedConfig, - apolloClient: this.apolloClient, - }); - await this.prepareApiClients(); - } - + await this.setupScope(); await this.setSecret(); } - protected async catch(err: Error & { exitCode?: number }): Promise { - err.message = redactFlagValues(err.message); - err.stack = err.stack && redactFlagValues(err.stack); - return super.catch(err); - } - - requireYesWhenPiped(): void { - if (!process.stdin.isTTY && !this.flags.yes) { - this.log('use --yes when piping the value', 'error'); - process.exit(1); - } - } - async preparePipedInput(): Promise { - if (process.stdin.isTTY) return; + if (this.interactive) return; this.requireYesWhenPiped(); - - if (!this.flags.environment) { - this.failPipedScope(); - } - - if (this.branchPromptRequired()) { - this.log('Multiple branches are configured; pass --branch when the value is piped', 'error'); - process.exit(1); - } - this.pipedValue = await this.readStdin(); } - async assertPipedScope(): Promise { - if (process.stdin.isTTY) return; - - const { org, project } = this.flags as Record; - - if (!this.sharedConfig.currentConfig?.uid && !(org && project)) { - this.failPipedScope(); - } - } - - failPipedScope(): never { - this.log('--org, --project and --environment are required when the value is piped', 'error'); - return process.exit(1); - } - - branchPromptRequired(): boolean { - const path = this.sharedConfig.config; - - if (!path || !existsSync(path)) return false; - - const configKeys = keys(JSON.parse(readFileSync(path, 'utf-8'))); - const { branch } = this.flags as Record; - - if (branch && includes(configKeys, branch)) { - return false; + requireYesWhenPiped(): void { + if (!this.interactive && !this.flags.yes) { + this.log('use --yes when piping the value', 'error'); + process.exit(1); } - - return filter(configKeys, (configKey) => configKey !== 'project').length > 1; } async setSecret(): Promise { const { key, yes } = this.flags as Record; - const piped = !process.stdin.isTTY; - - this.requireYesWhenPiped(); + const piped = !this.interactive; const environment = await this.resolveEnvironment(); const exists = !isEmpty(find(environment.secrets, { key })); @@ -188,14 +94,23 @@ export default class SetSecret extends BaseCommand { this.log(`Secret ${key} ${exists ? 'refreshed' : 'added'} in environment ${environment.name}.`); } - async readStdin(): Promise { - const chunks: Buffer[] = []; - - for await (const chunk of process.stdin) { - chunks.push(Buffer.from(chunk)); - } - - return Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, ''); + readStdin(): Promise { + return new Promise((resolve) => { + const chunks: Buffer[] = []; + const timer = setTimeout(() => { + process.stdin.removeAllListeners('data'); + resolve(''); + }, this.stdinTimeoutMs); + + process.stdin.on('data', (chunk) => { + clearTimeout(timer); + chunks.push(Buffer.from(chunk)); + }); + process.stdin.on('end', () => { + clearTimeout(timer); + resolve(Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, '')); + }); + }); } promptValue(key: string): Promise { @@ -213,37 +128,4 @@ export default class SetSecret extends BaseCommand { message: `${exists ? 'Refresh' : 'Add'} secret ${key} in environment ${environmentName}?`, }); } - - async resolveEnvironment(): Promise { - const environments = await this.apolloClient - .query({ query: environmentSecretsQuery }) - .then(({ data: { Environments } }) => map(Environments.edges, 'node')) - .catch((error) => { - this.log(formatSecretsError(error), 'error'); - process.exit(1); - }); - - if (!this.flags.environment) { - return ux - .inquire({ - type: 'search-list', - name: 'Environment', - choices: map(environments, (row) => ({ name: row.name, value: row.name })), - message: 'Choose an environment', - }) - .then((name: any) => find(environments, { name }) as Record); - } - - const environment = find( - environments, - ({ uid, name }) => uid === this.flags.environment || name === this.flags.environment, - ); - - if (isEmpty(environment)) { - this.log('Environment(s) not found!', 'error'); - process.exit(1); - } - - return environment; - } } diff --git a/src/commands/launch/secrets/unset.test.ts b/src/commands/launch/secrets/unset.test.ts index 22968d17..09ef1c26 100644 --- a/src/commands/launch/secrets/unset.test.ts +++ b/src/commands/launch/secrets/unset.test.ts @@ -44,6 +44,12 @@ const notFoundError = () => ({ ], }); +const originalStdin = Object.getOwnPropertyDescriptor(process, 'stdin') as PropertyDescriptor; + +const stubStdin = (isTTY: boolean) => { + Object.defineProperty(process, 'stdin', { value: { isTTY }, configurable: true }); +}; + const buildCommand = ( flags: Record, mutate: jest.Mock = jest.fn().mockResolvedValue({ data: { deleteEnvironmentSecret: true } }), @@ -67,6 +73,7 @@ describe('UnsetSecret Command', () => { }); afterEach(() => { + Object.defineProperty(process, 'stdin', originalStdin); jest.clearAllMocks(); }); @@ -90,7 +97,20 @@ describe('UnsetSecret Command', () => { expect(exitMock).not.toHaveBeenCalled(); }); + it('fails fast without a prompt or mutation when --yes is missing and not running in a terminal', async () => { + stubStdin(false); + const { cmd, mutate } = buildCommand({}); + + await expect((cmd as any).unsetSecrets()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith('use --yes when not running in a terminal', 'error'); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect(mutate).not.toHaveBeenCalled(); + expect(exitMock).toHaveBeenCalledWith(1); + }); + it('asks for confirmation and deletes the key when it is accepted', async () => { + stubStdin(true); (cliux.inquire as jest.Mock).mockResolvedValueOnce(true); const { cmd, mutate } = buildCommand({}); @@ -108,6 +128,7 @@ describe('UnsetSecret Command', () => { }); it('aborts without a mutation or an error exit when the confirmation is declined', async () => { + stubStdin(true); (cliux.inquire as jest.Mock).mockResolvedValueOnce(false); const { cmd, mutate } = buildCommand({ key: ['API_TOKEN', 'DB_PASSWORD'] }); diff --git a/src/commands/launch/secrets/unset.ts b/src/commands/launch/secrets/unset.ts index 82370d61..f0a04913 100644 --- a/src/commands/launch/secrets/unset.ts +++ b/src/commands/launch/secrets/unset.ts @@ -1,13 +1,10 @@ -import map from 'lodash/map'; -import find from 'lodash/find'; -import isEmpty from 'lodash/isEmpty'; import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; -import { BaseCommand } from '../../../base-command'; -import { environmentSecretsQuery, deleteEnvironmentSecretMutation } from '../../../graphql'; -import { Logger, selectOrg, selectProject, formatSecretsError } from '../../../util'; +import { SecretsBaseCommand, secretsScopeFlags } from '../../../base-secrets-command'; +import { deleteEnvironmentSecretMutation } from '../../../graphql'; +import { formatSecretsError } from '../../../util'; -export default class UnsetSecret extends BaseCommand { +export default class UnsetSecret extends SecretsBaseCommand { static description = 'Delete one or more secrets of an environment'; static examples = [ @@ -18,16 +15,7 @@ export default class UnsetSecret extends BaseCommand { ]; static flags: FlagInput = { - org: Flags.string({ - description: '[Optional] Provide the organization UID', - }), - project: Flags.string({ - description: '[Optional] Provide the project UID', - }), - environment: Flags.string({ - char: 'e', - description: 'Environment name or UID', - }), + ...secretsScopeFlags, key: Flags.string({ char: 'k', required: true, @@ -41,29 +29,8 @@ export default class UnsetSecret extends BaseCommand { }; async run(): Promise { - this.logger = new Logger(this.sharedConfig); - this.log = this.logger.log.bind(this.logger); - - await this.getConfig(); - await this.prepareApiClients(); - - if (!this.sharedConfig.currentConfig?.uid) { - await selectOrg({ - log: this.log, - flags: this.flags, - config: this.sharedConfig, - managementSdk: this.managementSdk, - }); - await this.prepareApiClients(); - await selectProject({ - log: this.log, - flags: this.flags, - config: this.sharedConfig, - apolloClient: this.apolloClient, - }); - await this.prepareApiClients(); - } - + this.initLogger(); + await this.setupScope(); await this.unsetSecrets(); } @@ -71,6 +38,11 @@ export default class UnsetSecret extends BaseCommand { const { key: keys, yes } = this.flags as Record; const environment = await this.resolveEnvironment(); + if (!yes && !this.interactive) { + this.log('use --yes when not running in a terminal', 'error'); + process.exit(1); + } + if (!yes && !(await this.confirm(keys, environment.name))) { ux.print('Aborted. No secret was deleted.'); return; @@ -103,37 +75,4 @@ export default class UnsetSecret extends BaseCommand { message: `Delete secret ${keys.join(', ')} from environment ${environmentName}?`, }); } - - async resolveEnvironment(): Promise { - const environments = await this.apolloClient - .query({ query: environmentSecretsQuery }) - .then(({ data: { Environments } }) => map(Environments.edges, 'node')) - .catch((error) => { - this.log(formatSecretsError(error), 'error'); - process.exit(1); - }); - - if (!this.flags.environment) { - return ux - .inquire({ - type: 'search-list', - name: 'Environment', - choices: map(environments, (row) => ({ name: row.name, value: row.name })), - message: 'Choose an environment', - }) - .then((name: any) => find(environments, { name }) as Record); - } - - const environment = find( - environments, - ({ uid, name }) => uid === this.flags.environment || name === this.flags.environment, - ); - - if (isEmpty(environment)) { - this.log('Environment(s) not found!', 'error'); - process.exit(1); - } - - return environment; - } } diff --git a/src/util/secrets.test.ts b/src/util/secrets.test.ts index a01e2ba4..2534b1c3 100644 --- a/src/util/secrets.test.ts +++ b/src/util/secrets.test.ts @@ -73,6 +73,22 @@ describe('secrets util', () => { expect(message).toContain(expected); }); + it.each([ + [404, 'The project or environment was not found.'], + [400, 'The API rejected the request.'], + ])('uses read-context wording without a key for a %i on a read operation', (status, expected) => { + const message = formatSecretsError(apiError(status), { operation: 'read' }); + + expect(message).toBe(expected); + expect(message).not.toContain('the secret'); + }); + + it('keeps the key-specific wording for a write operation', () => { + const message = formatSecretsError(formError(CODES.notFound), { key: 'DB_URL', operation: 'write' }); + + expect(message).toBe('The secret DB_URL was not found.'); + }); + it('produces distinct messages for each known error', () => { const errors = [ formError(CODES.conflict), diff --git a/src/util/secrets.ts b/src/util/secrets.ts index c86d4a30..e5e6e5f6 100644 --- a/src/util/secrets.ts +++ b/src/util/secrets.ts @@ -27,7 +27,7 @@ const ERROR_CODES = { valueTooLong: 'launch.ENVIRONMENT.ENVIRONMENT_VARIABLES.VALUE.TOO_LONG', }; -type SecretsErrorContext = { key?: string; value?: string }; +type SecretsErrorContext = { key?: string; value?: string; operation?: 'read' | 'write' }; const stringify = (item: unknown): string => { try { @@ -43,7 +43,10 @@ const redactValue = (text: string, value?: string): string => { return fragments.reduce((redacted, fragment) => split(redacted, fragment).join('[redacted]'), text); }; -export const formatSecretsError = (error: any, { key, value }: SecretsErrorContext = {}): string => { +export const formatSecretsError = ( + error: any, + { key, value, operation = 'write' }: SecretsErrorContext = {}, +): string => { const graphQLError = error?.graphQLErrors?.[0]; const exception = graphQLError?.extensions?.exception; const status = exception?.status ?? graphQLError?.extensions?.status ?? error?.networkError?.statusCode; @@ -64,6 +67,8 @@ export const formatSecretsError = (error: any, { key, value }: SecretsErrorConte [hasCode(ERROR_CODES.valueEmpty), 'Invalid value: the value cannot be empty.'], [hasCode(ERROR_CODES.valueTooLong), 'Invalid value: the value is too long (maximum 10000 characters).'], [status === 403, 'You do not have permission to manage the secrets of this environment.'], + [operation === 'read' && status === 404, 'The project or environment was not found.'], + [operation === 'read' && status === 400, 'The API rejected the request.'], [status === 400, 'The API rejected the request: invalid key or value.'], ]; diff --git a/test/integration/specs/secrets-set.test.ts b/test/integration/specs/secrets-set.test.ts index 6e79714d..f031d8ac 100644 --- a/test/integration/specs/secrets-set.test.ts +++ b/test/integration/specs/secrets-set.test.ts @@ -85,7 +85,7 @@ describe('launch:secrets:set', () => { const result = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, '--yes']); expect(result.exitCode).toBe(1); - expect(result.output).toContain('Multiple branches are configured; pass --branch when the value is piped'); + expect(result.output).toContain('Multiple branches are configured; pass --branch to choose one.'); expect(result.output).not.toContain(value); expect(session.api.operationSequence()).toEqual([]); session.api.assertNoUnhandledOperations(); @@ -127,12 +127,79 @@ describe('launch:secrets:set', () => { const result = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, '--value', value]); expect(result.exitCode).not.toBe(0); - expect(result.output).toContain('Nonexistent flag: --value'); + expect(result.output).toContain('Invalid arguments'); expect(result.output).not.toContain(value); expect(session.api.calls('AddEnvironmentSecret')).toHaveLength(0); expect(session.api.calls('RefreshEnvironmentSecret')).toHaveLength(0); }); + it.each([ + ['a positional argument', (value: string) => [value]], + ['a short flag glued to the value', (value: string) => [`-v${value}`]], + ])('never echoes the value when it is given as %s', async (_label, extra) => { + const value = randomUUID(); + session.api.on('Projects', fixtures.projectsResponse()); + stdin.tty(); + prompts.script([]); + + const result = await runCommand(SetSecret, [...scope(), '--key', fixtures.SECRET_KEY, ...extra(value)]); + + expect(result.exitCode).not.toBe(0); + expect(result.output).not.toContain(value); + expect(result.error?.message ?? '').not.toContain(value); + expect(result.error?.stack ?? '').not.toContain(value); + expect(session.api.calls('AddEnvironmentSecret')).toHaveLength(0); + }); + + it('fails without any prompt or mutation when the value is piped and --org matches no organization', async () => { + const value = randomUUID(); + stdin.pipe(`${value}\n`); + prompts.script([]); + const args = [...session.baseArgs, '--org', 'WRONG', '--project', fixtures.PROJECT_UID, '-e', fixtures.ENVIRONMENT_NAME]; + + const result = await runCommand(SetSecret, [...args, '--key', fixtures.SECRET_KEY, '--yes']); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('Organization UID not found!'); + expect(result.output).not.toContain(value); + expect(session.api.operationSequence()).toEqual([]); + prompts.assertScriptFullyConsumed(); + }); + + it('fails without any prompt or mutation when the value is piped and --project matches no project', async () => { + const value = randomUUID(); + session.api.on('Projects', fixtures.projectsResponse()); + stdin.pipe(`${value}\n`); + prompts.script([]); + const args = [...session.baseArgs, '--org', fixtures.ORG.uid, '--project', 'WRONG', '-e', fixtures.ENVIRONMENT_NAME]; + + const result = await runCommand(SetSecret, [...args, '--key', fixtures.SECRET_KEY, '--yes']); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('Project not found!'); + expect(result.output).not.toContain(value); + expect(session.api.operationSequence()).toEqual(['Projects']); + prompts.assertScriptFullyConsumed(); + }); + + it('writes to the project named by --project instead of the one stored in .cs-launch.json', async () => { + const value = randomUUID(); + writeFileSync(session.launchConfigPath, JSON.stringify(fixtures.existingProjectConfigFile())); + session.api + .on('Projects', fixtures.projectsResponse([{ uid: 'other-project-uid', name: 'Other project' }])) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse([])) + .on('AddEnvironmentSecret', fixtures.addEnvironmentSecretResponse()); + stdin.pipe(`${value}\n`); + prompts.script([]); + const args = [...session.baseArgs, '--org', fixtures.ORG.uid, '--project', 'other-project-uid', '-e', fixtures.ENVIRONMENT_NAME]; + + const result = await runCommand(SetSecret, [...args, '--key', fixtures.SECRET_KEY, '--yes']); + + expect(result.exitCode).toBe(0); + expect(session.api.headersOf('AddEnvironmentSecret')['x-project-uid']).toBe('other-project-uid'); + prompts.assertScriptFullyConsumed(); + }); + it('redacts the value when --value is passed with an equals sign', async () => { const value = randomUUID(); session.api.on('Projects', fixtures.projectsResponse()); diff --git a/test/integration/specs/secrets-unset.test.ts b/test/integration/specs/secrets-unset.test.ts index fb623668..709b5369 100644 --- a/test/integration/specs/secrets-unset.test.ts +++ b/test/integration/specs/secrets-unset.test.ts @@ -1,3 +1,5 @@ +import { writeFileSync } from 'fs'; + import UnsetSecret from '../../../src/commands/launch/secrets/unset'; import { cma, fixtures, prompts, runCommand, startSession, stdin, Session } from '../harness'; @@ -71,4 +73,37 @@ describe('launch:secrets:unset', () => { expect(result.output).toContain('Missing required flag key'); expect(session.api.calls('DeleteEnvironmentSecret')).toHaveLength(0); }); + + it('fails fast without a prompt or delete when --yes is missing and stdin is not a terminal', async () => { + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse()); + prompts.script([]); + + const result = await runCommand(UnsetSecret, [...scope(), '--key', 'API_TOKEN']); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('use --yes when not running in a terminal'); + expect(session.api.calls('DeleteEnvironmentSecret')).toHaveLength(0); + prompts.assertScriptFullyConsumed(); + }); + + it('uses --branch to pick the configuration of a multi-branch .cs-launch.json without prompting', async () => { + const config = { + ...fixtures.existingProjectConfigFile({}, 'main'), + ...fixtures.existingProjectConfigFile({}, 'develop'), + }; + writeFileSync(session.launchConfigPath, JSON.stringify(config)); + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse()) + .on('DeleteEnvironmentSecret', fixtures.deleteEnvironmentSecretResponse()); + stdin.tty(); + prompts.script([]); + + const result = await runCommand(UnsetSecret, [...scope(), '--branch', 'develop', '--key', 'API_TOKEN', '--yes']); + + expect(result.exitCode).toBe(0); + prompts.assertScriptFullyConsumed(); + }); });