Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(src/clients): improved error handling #28

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 30 additions & 8 deletions src/clients.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,12 @@ function log(text: string = '') {
}

function getRepositoryName(): string {
const output = spawnSync('gh', ['repo', 'view', '--json', 'nameWithOwner'], { stdio: ['ignore', 'pipe', 'inherit'] }).stdout.toString('utf-8');

const spawn = spawnSync('gh', ['repo', 'view', '--json', 'nameWithOwner'], { stdio: ['ignore', 'pipe', 'pipe'] });
const stderr = spawn.stderr?.toString();
if (stderr) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a fan of this. Can’t we get an exit code?

Copy link
Author

@ryparker ryparker Nov 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure. We can throw on non 0 exit codes. Are you cool with keeping the stderr output in the message or would you rather not 'pipe' it?

const spawn = spawnSync('gh', args, { input: value, stdio: ['pipe', 'inherit', 'pipe'] });
  if (spawn.status !== 0) {
    throw new Error(`Failed to store secret '${name}' in repository '${repository}'. ${spawn.stderr?.toString()}`);
  }

throw new Error(`Failed to get repository name: ${stderr}`);
}
const output = spawn.stdout.toString('utf-8');
try {
const repo = JSON.parse(output);
return repo.nameWithOwner;
Expand All @@ -56,18 +60,30 @@ function getRepositoryName(): string {

function storeSecret(repository: string, name: string, value: string): void {
const args = ['secret', 'set', '--repo', repository, name];
spawnSync('gh', args, { input: value, stdio: ['pipe', 'inherit', 'inherit'] });
const spawn = spawnSync('gh', args, { input: value, stdio: ['pipe', 'inherit', 'pipe'] });
const stderr = spawn.stderr?.toString();
if (stderr) {
throw new Error(`Failed to store secret '${name}' in repository '${repository}': ${stderr}`);
}
}

function listSecrets(repository: string): string[] {
const args = ['secret', 'list', '--repo', repository];
const stdout = spawnSync('gh', args, { stdio: ['ignore', 'pipe', 'inherit'] }).stdout.toString('utf-8').trim();
return stdout.split('\n').map(line => line.split('\t')[0]);
const spawn = spawnSync('gh', args, { stdio: ['ignore', 'pipe', 'pipe'] });
const stderr = spawn.stderr?.toString();
if (stderr) {
throw new Error(`Failed to list secrets in repository '${repository}': ${stderr}`);
}
return spawn.stdout.toString('utf-8').trim().split('\n').map(line => line.split('\t')[0]);
}

function removeSecret(repository: string, key: string): void {
const args = ['secret', 'remove', '--repo', repository, key];
spawnSync('gh', args, { stdio: ['ignore', 'inherit', 'inherit'] });
const spawn = spawnSync('gh', args, { stdio: ['ignore', 'inherit', 'pipe'] });
const stderr = spawn.stderr?.toString();
if (stderr) {
throw new Error(`Failed to remove secret '${key}' from repository '${repository}': ${stderr}`);
}
}

function confirmPrompt(): Promise<boolean> {
Expand Down Expand Up @@ -96,7 +112,13 @@ async function getSecret(secretId: string, options: SecretOptions = {}): Promise
customUserAgent: `${PKG.name}/${PKG.version}`,
});

const result = await client.getSecretValue({ SecretId: secretId }).promise();
let result;
try {
result = await client.getSecretValue({ SecretId: secretId }).promise();
} catch (error) {
throw new Error(`Failed to retrieve secret '${secretId}' from SecretsManager: ${error}`);
}

let json;
try {
json = JSON.parse(result.SecretString!);
Expand All @@ -113,4 +135,4 @@ async function getSecret(secretId: string, options: SecretOptions = {}): Promise
export interface Secret {
readonly json: Record<string, string>;
readonly arn: string;
}
}
2 changes: 1 addition & 1 deletion src/update-secrets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export async function updateSecrets(options: UpdateSecretsOptions) {

c.log(`FROM : ${secret.arn}`);
c.log(`REPO : ${repository}`);
c.log(`UDPATE: ${keys.join(',')}`);
c.log(`UPDATE: ${keys.join(',')}`);

if (pruneCandidates.length > 0) {
if (prune) {
Expand Down
38 changes: 38 additions & 0 deletions test/clients.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { DEFAULTS as clients } from '../src/clients';

jest.mock('child_process', () => {
const actual = jest.requireActual('child_process');
return {
spawnSync: (_a: any, _b: any, options: any) => {
return actual.spawnSync('node', ['--eval', "throw new Error('Nope');"], options);
},
};
});

afterEach(() => {
jest.resetAllMocks();
});

test('throws error, when getRepositoryName() sub process fails', async () => {
expect(
() => clients.getRepositoryName(),
).toThrowError(/Failed to get repository name: .*/);
});

test('throws error, when storeSecret() sub process fails', async () => {
expect(
() => clients.storeSecret('repo', 'name', 'value'),
).toThrowError(/Failed to store secret 'name' in repository 'repo': .*/);
});

test('throws error, when listSecrets() sub process fails', async () => {
expect(
() => clients.listSecrets('repo'),
).toThrowError(/Failed to list secrets in repository 'repo': .*/);
});

test('throws error, when removeSecret() sub process fails', async () => {
expect(
() => clients.removeSecret('repo', 'key'),
).toThrowError(/Failed to remove secret 'key' from repository 'repo': .*/);
});