diff --git a/.talismanrc b/.talismanrc index d59b6132..e187ec07 100644 --- a/.talismanrc +++ b/.talismanrc @@ -34,13 +34,45 @@ 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: b3133a65f3f4b3f3a32caf0cc0bf65b0c71187f96e044a3331ddcce3adea88c1 + 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 + checksum: 6877ec55200ec4913b3c2bde7cc45e16b50e8e7a4a2cfc26529ded6d9fe27718 +- filename: test/integration/specs/secrets-list.test.ts + checksum: d4cdd09fe16a876f7457bdf9bbaa83511624c12a0c7a967abc5f26a678696629 +- filename: src/commands/launch/secrets/list.ts + checksum: da14a738f37a9610ab9dec7978de81cbb778ed0da9e73c4df4806c6e3c4c00cf +- filename: src/commands/launch/secrets/list.test.ts + checksum: af09c894e3c21b061078a614f599e642b3db11e6f2145cb588e14e2476ff612a +- filename: src/graphql/mutation.ts + checksum: c420996deea097d6125ccd9648d0b87806bf7edeb4eda5604a068eee3e669542 +- filename: src/util/secrets.ts + checksum: 9ccc5fdb18cb3c4ea637d6834c5b91e860c374abd01d808d002b3862d2f0c67a +- filename: src/commands/launch/secrets/set.ts + checksum: 80b805d6f746b6cfbef06690f4219fe7b810d58755dcc4fd3042092922b497b6 +- filename: src/util/secrets.test.ts + checksum: acadbf4e3b1a62d2ebd81f203bdb673c314d1534a7598d95d675a27905c7c8cb +- filename: test/integration/specs/secrets-set.test.ts + checksum: 0975c0277d2643273d61d2f194ff7e1599f79f21fe4372367746f0fbd5b14d4b +- filename: src/commands/launch/secrets/set.test.ts + checksum: 2953250cb9353eaa298a30e480badf5b12a6e8a9851355e3a9055e7a1bbaa98f +- filename: src/commands/launch/secrets/unset.ts + checksum: 3c7d81a01ccfbd32fd2060ed88ef14fba525fded736604b4302c68ca9bc2d966 +- filename: src/commands/launch/secrets/unset.test.ts + checksum: 89449d31e20184f2f32619f75bca546c088f8f75e3a0e9e7c1735fc4cec1882f +- filename: test/integration/specs/secrets-unset.test.ts + 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 new file mode 100644 index 00000000..1c6b476d --- /dev/null +++ b/src/commands/launch/secrets/list.test.ts @@ -0,0 +1,161 @@ +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 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; + (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(() => { + Object.defineProperty(process, 'stdin', originalStdin); + 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.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, + 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 === 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(); + }); + + 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 () => { + 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); + + 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..7de08a84 --- /dev/null +++ b/src/commands/launch/secrets/list.ts @@ -0,0 +1,37 @@ +import map from 'lodash/map'; +import isEmpty from 'lodash/isEmpty'; +import { FlagInput, cliux as ux } from '@contentstack/cli-utilities'; + +import { SecretsBaseCommand, secretsScopeFlags } from '../../../base-secrets-command'; + +export default class ListSecrets extends SecretsBaseCommand { + 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 = { ...secretsScopeFlags }; + + async run(): Promise { + this.initLogger(); + await this.setupScope(); + 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 })), + ); + } +} diff --git a/src/commands/launch/secrets/set.test.ts b/src/commands/launch/secrets/set.test.ts new file mode 100644 index 00000000..86155e5d --- /dev/null +++ b/src/commands/launch/secrets/set.test.ts @@ -0,0 +1,334 @@ +import { Readable } from 'stream'; +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', () => { + 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 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 } } }], +}); + +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; + +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: { environment: { uid: 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.environment).toEqual({ uid: 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).preparePipedInput()).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(formError(SECRET_CODES.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 reports a key conflict', async () => { + stubStdin(false, [randomUUID()]); + 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'); + + 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(true); + (cliux.inquire as jest.Mock).mockResolvedValueOnce('Default').mockResolvedValueOnce(randomUUID()); + 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('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('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('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 }); + (cmd as any).stdinTimeoutMs = 20; + + await (cmd as any).preparePipedInput(); + await expect((cmd as any).setSecret()).rejects.toThrow('process.exit:1'); + + expect((cmd as any).log).toHaveBeenCalledWith(expect.stringContaining('no value received on stdin'), 'error'); + expect(mutate).not.toHaveBeenCalled(); + expect(cliux.inquire).not.toHaveBeenCalled(); + }); + + 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..30214dca --- /dev/null +++ b/src/commands/launch/secrets/set.ts @@ -0,0 +1,131 @@ +import find from 'lodash/find'; +import isEmpty from 'lodash/isEmpty'; +import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; + +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'; + + 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 = { + ...secretsScopeFlags, + 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.initLogger(); + await this.preparePipedInput(); + await this.setupScope(); + await this.setSecret(); + } + + async preparePipedInput(): Promise { + if (this.interactive) return; + + this.requireYesWhenPiped(); + this.pipedValue = await this.readStdin(); + } + + requireYesWhenPiped(): void { + if (!this.interactive && !this.flags.yes) { + this.log('use --yes when piping the value', 'error'); + process.exit(1); + } + } + + async setSecret(): Promise { + const { key, yes } = this.flags as Record; + const piped = !this.interactive; + + const environment = await this.resolveEnvironment(); + const exists = !isEmpty(find(environment.secrets, { 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'); + 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: { environment: { uid: 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}.`); + } + + 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 { + 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}?`, + }); + } +} diff --git a/src/commands/launch/secrets/unset.test.ts b/src/commands/launch/secrets/unset.test.ts new file mode 100644 index 00000000..09ef1c26 --- /dev/null +++ b/src/commands/launch/secrets/unset.test.ts @@ -0,0 +1,165 @@ +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 NOT_FOUND_CODE = 'launch.ENVIRONMENT.ENVIRONMENT_SECRETS.KEY.NOT_FOUND'; + +const apiError = (status: number) => ({ + message: 'Request failed', + 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 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 } }), +) => { + 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(() => { + Object.defineProperty(process, 'stdin', originalStdin); + 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: { environment: { uid: ENVIRONMENT_UID }, secret: { key: 'API_TOKEN' } }, + }); + expect(mutate).toHaveBeenNthCalledWith(2, { + mutation: deleteEnvironmentSecretMutation, + variables: { environment: { uid: ENVIRONMENT_UID }, secret: { 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('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({}); + + 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({ + environment: { uid: ENVIRONMENT_UID }, + secret: { key: 'API_TOKEN' }, + }); + expect(exitMock).not.toHaveBeenCalled(); + }); + + 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'] }); + + 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(notFoundError()) + .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..f0a04913 --- /dev/null +++ b/src/commands/launch/secrets/unset.ts @@ -0,0 +1,78 @@ +import { FlagInput, Flags, cliux as ux } from '@contentstack/cli-utilities'; + +import { SecretsBaseCommand, secretsScopeFlags } from '../../../base-secrets-command'; +import { deleteEnvironmentSecretMutation } from '../../../graphql'; +import { formatSecretsError } from '../../../util'; + +export default class UnsetSecret extends SecretsBaseCommand { + 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 = { + ...secretsScopeFlags, + 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.initLogger(); + await this.setupScope(); + await this.unsetSecrets(); + } + + async unsetSecrets(): Promise { + 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; + } + + let failed = false; + + for (const key of keys) { + try { + await this.apolloClient.mutate({ + mutation: deleteEnvironmentSecretMutation, + variables: { environment: { uid: environment.uid }, secret: { 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}?`, + }); + } +} diff --git a/src/graphql/mutation.ts b/src/graphql/mutation.ts index 431ef2f7..3e852745 100755 --- a/src/graphql/mutation.ts +++ b/src/graphql/mutation.ts @@ -85,8 +85,35 @@ const rollbackDeploymentMutation: DocumentNode = gql` } `; +const addEnvironmentSecretMutation: DocumentNode = gql` + mutation AddEnvironmentSecret($environment: EnvironmentInput!, $secret: EnvironmentSecretInput!) { + addEnvironmentSecret(environment: $environment, secret: $secret) { + key + updatedAt + } + } +`; + +const refreshEnvironmentSecretMutation: DocumentNode = gql` + mutation RefreshEnvironmentSecret($environment: EnvironmentInput!, $secret: EnvironmentSecretInput!) { + refreshEnvironmentSecret(environment: $environment, secret: $secret) { + key + updatedAt + } + } +`; + +const deleteEnvironmentSecretMutation: DocumentNode = gql` + mutation DeleteEnvironmentSecret($environment: EnvironmentInput!, $secret: EnvironmentSecretKeyInput!) { + deleteEnvironmentSecret(environment: $environment, secret: $secret) + } +`; + export { importProjectMutation, + addEnvironmentSecretMutation, + refreshEnvironmentSecretMutation, + deleteEnvironmentSecretMutation, createDeploymentMutation, rollbackDeploymentMutation, createSignedUploadUrlMutation, 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/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/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..2534b1c3 --- /dev/null +++ b/src/util/secrets.test.ts @@ -0,0 +1,188 @@ +import { randomUUID } from 'crypto'; + +import { + CLIENT_EXPOSED_PREFIXES, + clientExposedWarning, + isClientExposedKey, + formatSecretsError, + redactFlagValues, +} from './secrets'; + +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, +}); + +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([ + ['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'], + ])('formats a %s API error as a clear message', (_label, error, expected) => { + const message = formatSecretsError(error, { key: 'DB_URL' }); + + 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), + 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), + ]; + + 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 code in the error object only', () => { + const error = { + graphQLErrors: [ + { + message: 'Bad request', + extensions: { exception: { status: 400, errorObject: { secret: [{ code: CODES.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: [CODES.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: CODES.notFound, 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, '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, `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('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 new file mode 100644 index 00000000..e5e6e5f6 --- /dev/null +++ b/src/util/secrets.ts @@ -0,0 +1,81 @@ +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.'; + +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; operation?: 'read' | 'write' }; + +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, operation = 'write' }: 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(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.'], + [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.'], + ]; + + 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(/(?[] = [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 addEnvironmentSecretResponse = (key = SECRET_KEY) => ({ + data: { addEnvironmentSecret: secretNode({ key }) }, +}); + +export const refreshEnvironmentSecretResponse = (key = SECRET_KEY) => ({ + data: { refreshEnvironmentSecret: secretNode({ key }) }, +}); + +export const deleteEnvironmentSecretResponse = () => ({ + data: { deleteEnvironmentSecret: true }, +}); + +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 = ( 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-list.test.ts b/test/integration/specs/secrets-list.test.ts new file mode 100644 index 00000000..ebbd5814 --- /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 manage 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(); + }); +}); diff --git a/test/integration/specs/secrets-set.test.ts b/test/integration/specs/secrets-set.test.ts new file mode 100644 index 00000000..f031d8ac --- /dev/null +++ b/test/integration/specs/secrets-set.test.ts @@ -0,0 +1,270 @@ +import { existsSync, readFileSync, writeFileSync } 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({ + environment: { uid: fixtures.ENVIRONMENT_UID }, + secret: { key: fixtures.SECRET_KEY, value }, + }); + 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 to choose one.'); + 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 + .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')).toEqual({ + environment: { uid: fixtures.ENVIRONMENT_UID }, + secret: { 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('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()); + 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 reports a key conflict', async () => { + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse([])) + .on('AddEnvironmentSecret', fixtures.secretsFormErrorResponse(fixtures.SECRET_ERROR_CODES.keyConflict)); + 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, `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); + }); +}); diff --git a/test/integration/specs/secrets-unset.test.ts b/test/integration/specs/secrets-unset.test.ts new file mode 100644 index 00000000..709b5369 --- /dev/null +++ b/test/integration/specs/secrets-unset.test.ts @@ -0,0 +1,109 @@ +import { writeFileSync } from 'fs'; + +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([ + { 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 reports the secret missing', async () => { + session.api + .on('Projects', fixtures.projectsResponse()) + .on('EnvironmentSecrets', fixtures.environmentSecretsResponse()) + .on('DeleteEnvironmentSecret', fixtures.secretsFormErrorResponse(fixtures.SECRET_ERROR_CODES.notFound)); + 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); + }); + + 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(); + }); +});