Skip to content

Commit

Permalink
Redact diagnostics file
Browse files Browse the repository at this point in the history
  • Loading branch information
ghengeveld committed Oct 13, 2023
1 parent 10ce1d3 commit 32815e8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
25 changes: 25 additions & 0 deletions node-src/lib/writeChromaticDiagnostics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, it, expect } from 'vitest';
import { getDiagnostics } from './writeChromaticDiagnostics';

describe('getDiagnostics', () => {
it('returns context object', () => {
const ctx = { build: { number: 1 } };
expect(getDiagnostics(ctx as any)).toEqual(ctx);
});

it('omits certain fields', () => {
const ctx = { argv: [], client: {}, env: {}, log: {}, pkg: {}, title: {} };
expect(getDiagnostics(ctx as any)).toEqual({});
});

it('redacts sensitive fields', () => {
const ctx = {
build: { number: 1, reportToken: 'foo' },
flags: { projectToken: 'bar' },
};
expect(getDiagnostics(ctx as any)).toEqual({
build: { number: 1, reportToken: undefined },
flags: { projectToken: undefined },
});
});
});
16 changes: 14 additions & 2 deletions node-src/lib/writeChromaticDiagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,23 @@ const { writeFile } = jsonfile;

export const CHROMATIC_DIAGNOSTICS_FILE = 'chromatic-diagnostics.json';

const redact = <T>(value: T, ...fields: string[]): T => {
if (value === null || typeof value !== 'object') return value;
if (Array.isArray(value)) return value.map((item) => redact(item, ...fields)) as T;
const obj = { ...value };
for (const key in obj) obj[key] = fields.includes(key) ? undefined : redact(obj[key], ...fields);
return obj;
};

export function getDiagnostics(ctx: Context) {
// Drop some fields that are not useful to have and redact sensitive fields
const { argv, client, env, help, http, log, pkg, title, ...rest } = ctx;
return Object.keys(rest)
const data = redact(rest, 'projectToken', 'reportToken');

// Sort top-level fields alphabetically
return Object.keys(data)
.sort((a, b) => a.localeCompare(b))
.reduce((acc, key) => ({ ...acc, [key]: rest[key] }), {});
.reduce((acc, key) => ({ ...acc, [key]: data[key] }), {});
}

// Extract important information from ctx, sort it and output into a json file
Expand Down
2 changes: 1 addition & 1 deletion node-src/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ describe('runAll', () => {
diagnostics: true,
}),
options: expect.objectContaining({
projectToken: 'asdf1234',
projectToken: undefined, // redacted
}),
}),
{ spaces: 2 }
Expand Down

0 comments on commit 32815e8

Please sign in to comment.