diff --git a/README.md b/README.md index 85658f7..cee6080 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,9 @@ Each validation function accepts an (optional) object with the following attribu - `example` - An example value for the env var. - `docs` - A URL that leads to more detailed documentation about the env var. - `requiredWhen` - A function (env -> boolean) specifying when this env var is required. Use With default: undefined (optional value). +- `mask` - Redacts this env var's value wherever the library prints it (validation error + messages, including `example`), so secrets don't leak into logs. Accepts `'all'`, + `'last4'`, or a custom `(value) => string` renderer. Without it, behavior is unchanged. ## Custom validators @@ -137,6 +140,10 @@ const env = cleanEnv(process.env, { }) ``` +If a custom validator is used for a secret, pass `mask` to its spec. Any quoted occurrence +of the value in the thrown error is redacted automatically, e.g. a validator that throws +`` `Bad token: "${x}"` `` will log `Bad token: "****wxyz"`. + ### TypeScript users You can use either one of `makeValidator`, `makeExactValidator` and `makeStructuredValidator` diff --git a/src/core.ts b/src/core.ts index 86ae713..4cd5e4a 100644 --- a/src/core.ts +++ b/src/core.ts @@ -1,4 +1,5 @@ import { EnvError, EnvMissingError } from './errors.ts' +import { applyMask } from './mask.ts' import { defaultReporter } from './reporter.ts' import type { CleanOptions, Spec, SpecsOutput, ValidatorSpec } from './types.ts' @@ -26,7 +27,8 @@ function validateVar({ if (!Array.isArray(spec.choices)) { throw new TypeError(`"choices" must be an array (in spec for "${name}")`) } else if (!spec.choices.includes(value)) { - throw new EnvError(`Value "${value}" not in choices [${spec.choices}]`) + const shown = spec.mask ? applyMask(value, spec.mask) : value + throw new EnvError(`Value "${shown}" not in choices [${spec.choices}]`) } } if (value == null) throw new EnvError(`Invalid value for env var "${name}"`) @@ -35,9 +37,11 @@ function validateVar({ // Format a string error message for when a required env var is missing export function formatSpecDescription(spec: Spec) { - const egText = spec.example ? ` (eg. "${spec.example}")` : '' + const example = spec.example + ? ` (eg. "${spec.mask ? applyMask(spec.example, spec.mask) : spec.example}")` + : '' const docsText = spec.docs ? `. See ${spec.docs}` : '' - return `${spec.desc}${egText}${docsText}` + return `${spec.desc}${example}${docsText}` } const readRawEnvValue = ( diff --git a/src/makers.ts b/src/makers.ts index 5f66330..5832725 100644 --- a/src/makers.ts +++ b/src/makers.ts @@ -1,7 +1,25 @@ -import type { Spec, BaseValidator, StructuredValidator, ExactValidator } from './types.ts' +import type { Mask, Spec, BaseValidator, StructuredValidator, ExactValidator } from './types.ts' +import { redactError } from './mask.ts' -const internalMakeValidator = (parseFn: (input: string) => T) => { - return (spec?: Spec) => ({ ...spec, _parse: parseFn }) +// Validators receive the spec's `mask` so they can render values safely. Custom +// parse functions written against the old 1-arg signature still work (they just +// ignore the extra arg), and the maker redacts any quoted raw value as a fallback. +type ParseFn = (input: string, mask?: Mask) => T + +const internalMakeValidator = (parseFn: ParseFn) => { + return (spec?: Spec) => { + const { mask } = spec ?? {} + return { + ...spec, + _parse: (input: string) => { + try { + return parseFn(input, mask) + } catch (err) { + throw mask ? redactError(err, input, mask) : err + } + }, + } + } } /** diff --git a/src/mask.ts b/src/mask.ts new file mode 100644 index 0000000..159fc39 --- /dev/null +++ b/src/mask.ts @@ -0,0 +1,50 @@ +import type { Mask } from './types.ts' + +// ponytail: presets cover the common cases; a custom fn signature is the escape hatch. +// Unknown/misspelled presets fail safe (full redaction) rather than leaking. +const presets: Record string> = { + all: () => '****', + last4: (value: unknown) => { + const s = String(value) + return s.length <= 4 ? '****' : `****${s.slice(-4)}` + }, +} + +/** Render a value the way it's allowed to appear in logs. */ +export const applyMask = (value: unknown, mask: Mask): string => { + if (typeof mask === 'function') return mask(value) + return (presets[mask] ?? presets.all)(value) +} + +/** + * Render `: ""` for a validator error message. Without a mask the raw value is + * shown (backward compatible); with a mask, the masked form is shown instead. + */ +export const displayValue = (value: unknown, mask?: Mask): string => + `: "${mask ? applyMask(value, mask) : String(value)}"` + +/** + * Render `: ""` only when a mask is set, otherwise nothing. Used by validators + * whose messages must never contain the raw value (url, json). + */ +export const displayMasked = (value: unknown, mask?: Mask): string => + mask ? `: "${applyMask(value, mask)}"` : '' + +/** + * Best-effort redaction for validators that render their own message and don't use + * `displayValue`. Only replaces a *quoted* occurrence of the raw value, so short values + * can't corrupt surrounding text (e.g. an input of "a" must not eat the "a" in "Invalid"). + */ +export const redactError = (err: unknown, input: unknown, mask: Mask): unknown => { + const raw = String(input) + if (!raw) return err + const from = `"${raw}"` + const to = `"${applyMask(input, mask)}"` + if (err instanceof Error) { + err.message = err.message.split(from).join(to) + return err + } + if (typeof err === 'string') return err.split(from).join(to) + return err +} + diff --git a/src/types.ts b/src/types.ts index 0316078..3abdbea 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,9 @@ +/** + * How a value is allowed to appear when its env var's value is included in validation + * error output. Either a preset or a function that renders the replacement string. + */ +export type Mask = 'all' | 'last4' | ((value: unknown) => string) + export interface Spec { /** * An Array that lists the admissable parsed values for the env var. @@ -34,6 +40,22 @@ export interface Spec { * conditions are met with the rest of the env object. Use With default: undefined. */ requiredWhen?: (cleanedEnv: Record) => boolean | undefined + + /** + * If set, any occurrence of this env var's value in a validation error message is + * replaced with a masked form, so secrets don't leak into logs. Pass a preset + * ('all' | 'last4') or a custom `(value) => string` renderer. Also masks `example`. + * + * ```ts + * cleanEnv(process.env, { API_KEY: str({ mask: 'last4' }) }) + * // error shows: Not a string: "****wxyz" + * ``` + * + * Note: this only redacts values the library itself prints (error messages). It + * cannot prevent a consumer from logging the resolved value, since primitives + * can't be intercepted. + */ + mask?: Mask } // All the default-providing attributes, each independently optional and allowed diff --git a/src/validators.ts b/src/validators.ts index 03981eb..f052c79 100644 --- a/src/validators.ts +++ b/src/validators.ts @@ -1,5 +1,7 @@ import { EnvError } from './errors.ts' +import { displayMasked, displayValue } from './mask.ts' import { makeExactValidator, makeStructuredValidator, makeValidator } from './makers.ts' +import type { Mask } from './types.ts' // Simplified adaptation of https://github.com/validatorjs/validator.js/blob/master/src/lib/isFQDN.js const isFQDN = (input: string) => { @@ -30,7 +32,7 @@ const EMAIL_REGEX = /^[^@\s]+@[^@\s]+\.[^@\s]+$/ // intentionally non-exhaustive // We use exact validator here because narrowing down to either 'true' or 'false' // makes no sense. -export const bool = makeExactValidator((input: string | boolean) => { +export const bool = makeExactValidator((input: string | boolean, mask?: Mask) => { switch (input) { case true: case 'true': @@ -47,34 +49,34 @@ export const bool = makeExactValidator((input: string | boolean) => { case '0': return false default: - throw new EnvError(`Invalid bool input: "${input}"`) + throw new EnvError(`Invalid bool input${displayValue(input, mask)}`) } }) -export const num = makeValidator((input: string) => { +export const num = makeValidator((input: string, mask?: Mask) => { const coerced = parseFloat(input) - if (Number.isNaN(coerced)) throw new EnvError(`Invalid number input: "${input}"`) + if (Number.isNaN(coerced)) throw new EnvError(`Invalid number input${displayValue(input, mask)}`) return coerced }) -export const str = makeValidator((input: string) => { +export const str = makeValidator((input: string, mask?: Mask) => { if (typeof input === 'string') return input - throw new EnvError(`Not a string: "${input}"`) + throw new EnvError(`Not a string${displayValue(input, mask)}`) }) -export const email = makeValidator((x: string) => { +export const email = makeValidator((x: string, mask?: Mask) => { if (EMAIL_REGEX.test(x)) return x - throw new EnvError(`Invalid email address: "${x}"`) + throw new EnvError(`Invalid email address${displayValue(x, mask)}`) }) -export const host = makeValidator((input: string) => { +export const host = makeValidator((input: string, mask?: Mask) => { if (!isFQDN(input) && !isIP(input)) { - throw new EnvError(`Invalid host (domain or ip): "${input}"`) + throw new EnvError(`Invalid host (domain or ip)${displayValue(input, mask)}`) } return input }) -export const port = makeValidator((input: string) => { +export const port = makeValidator((input: string, mask?: Mask) => { const coerced = +input if ( Number.isNaN(coerced) || @@ -83,18 +85,18 @@ export const port = makeValidator((input: string) => { coerced < 1 || coerced > 65535 ) { - throw new EnvError(`Invalid port input: "${input}"`) + throw new EnvError(`Invalid port input${displayValue(input, mask)}`) } return coerced }) -export const url = makeValidator((x: string) => { +export const url = makeValidator((x: string, mask?: Mask) => { try { new URL(x) return x } catch { - // Not logging the url value as it could contain sensitive data - throw new EnvError(`Invalid url`) + // Not logging the url value unless a mask was provided + throw new EnvError(`Invalid url${displayMasked(x, mask)}`) } }) @@ -109,10 +111,11 @@ export const url = makeValidator((x: string) => { * }) * ``` */ -export const json = makeStructuredValidator((x: string) => { +export const json = makeStructuredValidator((x: string, mask?: Mask) => { try { return JSON.parse(x) - } catch (e) { - throw new EnvError(`Invalid json: "${x}"`) + } catch { + // Not logging the json value unless a mask was provided + throw new EnvError(`Invalid json${displayMasked(x, mask)}`) } }) diff --git a/tests/mask.test.ts b/tests/mask.test.ts new file mode 100644 index 0000000..7a42dc5 --- /dev/null +++ b/tests/mask.test.ts @@ -0,0 +1,161 @@ +import { test, expect } from 'vitest' +import { cleanEnv, makeValidator, str, num, email, url, json } from '../src' + +const silent = { reporter: null } +const thrownMessage = (fn: () => unknown) => { + try { + fn() + } catch (e) { + return e instanceof Error ? e.message : String(e) + } + throw new Error('expected to throw') +} + +test('no mask -> existing behavior (raw value still appears)', () => { + const secret = 'not-an-email' + const msg = thrownMessage(() => cleanEnv({ FOO: secret }, { FOO: email() }, silent)) + expect(msg).toContain(secret) +}) + +test("mask:'last4' hides the value but keeps the tail", () => { + const secret = 'sk-live-0123456789wxyz' + const msg = thrownMessage(() => + cleanEnv({ FOO: secret }, { FOO: email({ mask: 'last4' }) }, silent), + ) + expect(msg).not.toContain(secret) + expect(msg).toContain('****wxyz') +}) + +test("mask:'last4' short value fully masked", () => { + const msg = thrownMessage(() => + cleanEnv({ FOO: 'abc' }, { FOO: email({ mask: 'last4' }) }, silent), + ) + expect(msg).toContain('****') + expect(msg).not.toContain('abc') +}) + +test("mask:'all' fully redacts", () => { + const secret = 'super-secret-token' + const msg = thrownMessage(() => + cleanEnv({ FOO: secret }, { FOO: email({ mask: 'all' }) }, silent), + ) + expect(msg).not.toContain(secret) + expect(msg).toContain('****') +}) + +test('custom mask function', () => { + const secret = 'abcd1234' + const msg = thrownMessage(() => + cleanEnv( + { FOO: secret }, + { FOO: email({ mask: (v) => `<${String(v).length} chars>` }) }, + silent, + ), + ) + expect(msg).not.toContain(secret) + expect(msg).toContain('<8 chars>') +}) + +test('works for custom validators and built-ins', () => { + const upper = makeValidator((x) => { + if (x === x.toUpperCase()) return x + throw new Error(`not upper: "${x}"`) + }) + const secret = 'mixedCaseSecret' + const msg = thrownMessage(() => + cleanEnv({ FOO: secret }, { FOO: upper({ mask: 'last4' }) }, silent), + ) + expect(msg).not.toContain(secret) + expect(msg).toContain('****cret') + + const numMsg = thrownMessage(() => + cleanEnv({ FOO: 'not-a-number' }, { FOO: num({ mask: 'all' }) }, silent), + ) + expect(numMsg).not.toContain('not-a-number') +}) + +test('choices error masks the offending value', () => { + const secret = 'secret-choice' + const msg = thrownMessage(() => + cleanEnv({ FOO: secret }, { FOO: str({ choices: ['a', 'b'], mask: 'last4' }) }, silent), + ) + expect(msg).not.toContain(secret) + expect(msg).toContain('****oice') +}) + +test('redacts thrown strings too', () => { + const thrower = makeValidator((x) => { + throw `bad value: "${x}"` + }) + const secret = 'string-thrown-secret' + const msg = thrownMessage(() => + cleanEnv({ FOO: secret }, { FOO: thrower({ mask: 'all' }) }, silent), + ) + expect(msg).not.toContain(secret) +}) + +test('short values cannot corrupt surrounding text', () => { + // "a" previously replaced every "a" in the message ("Inv****lid ...") + const msg = thrownMessage(() => cleanEnv({ FOO: 'a' }, { FOO: num({ mask: 'all' }) }, silent)) + expect(msg).toBe('Invalid number input: "****"') +}) + +test('json/url show a masked value only when a mask is set', () => { + const secret = 'nope-secret-json' + const masked = thrownMessage(() => + cleanEnv({ FOO: secret }, { FOO: json({ mask: 'last4' }) }, silent), + ) + expect(masked).not.toContain(secret) + expect(masked).toBe('Invalid json: "****json"') + + // default stays value-free (unchanged by this feature) + expect(thrownMessage(() => cleanEnv({ FOO: secret }, { FOO: json() }, silent))).toBe( + 'Invalid json', + ) + + const u = thrownMessage(() => + cleanEnv({ FOO: 'not a url' }, { FOO: url({ mask: 'all' }) }, silent), + ) + expect(u).toBe('Invalid url: "****"') +}) + +test('unknown preset fails safe (full redaction)', () => { + const secret = 'oops-typo-preset' + const msg = thrownMessage(() => + // biome-ignore lint/suspicious/noExplicitAny: simulating untyped JS caller + cleanEnv({ FOO: secret }, { FOO: email({ mask: 'last4x' as any }) }, silent), + ) + expect(msg).not.toContain(secret) +}) + +test('example in missing-var error is masked', () => { + const msg = thrownMessage(() => + cleanEnv( + {}, + { FOO: str({ example: 'sk-example-secret-1234', mask: 'last4' }) }, + silent, + ), + ) + expect(msg).not.toContain('sk-example-secret-1234') + expect(msg).toContain('****1234') +}) + +test('defensive paths: empty input and non-Error, non-string throws', () => { + // empty input skips redaction entirely (must not split char-by-char) + const empty = makeValidator(() => { + throw new Error('bad ""') + }) + expect(() => empty({ mask: 'all' })._parse('')).toThrow('bad ""') + + // a thrown non-Error/non-string passes through untouched + const weird = makeValidator(() => { + throw { weird: true } + }) + let caught: unknown + try { + cleanEnv({ FOO: 'x' }, { FOO: weird({ mask: 'all' }) }, silent) + } catch (e) { + caught = e + } + expect(caught).toEqual({ weird: true }) +}) diff --git a/tests/validators.test.ts b/tests/validators.test.ts index 1ea1d14..6a15e4b 100644 --- a/tests/validators.test.ts +++ b/tests/validators.test.ts @@ -123,6 +123,16 @@ test('json()', () => { expect(() => cleanEnv({ FOO: 'abc' }, { FOO: json() }, makeSilent)).toThrow() + // The error message should not include the raw value, as it could contain sensitive data + let thrownError: unknown + try { + cleanEnv({ FOO: '{"password": "hunter2"' }, { FOO: json() }, makeSilent) + } catch (e) { + thrownError = e + } + expect((thrownError as Error).message).toBe('Invalid json') + expect((thrownError as Error).message).not.toContain('hunter2') + // default value should be passed through without running through JSON.parse() expect( cleanEnv(