From 5c170488254d323c9b25c8dab8eb23bf14283559 Mon Sep 17 00:00:00 2001 From: eli Date: Tue, 27 Oct 2026 18:03:17 -0500 Subject: [PATCH 01/17] PER-16493: log only the PDP and API URL when the client starts The constructor's debug line printed the whole config. It now names the PDP and the API URL, which is what the line is for. Co-Authored-By: Claude Opus 5.5 --- src/index.ts | 3 ++- src/tests/unit/init-log.spec.ts | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/tests/unit/init-log.spec.ts diff --git a/src/index.ts b/src/index.ts index a96af183..78ff6fd6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -168,8 +168,9 @@ export class Permit implements IPermitClient { this.enforcer = new Enforcer(this.config, this.logger); this.elements = new ElementsClient(this.config, this.logger); + // The endpoints only, not the whole config. this.logger.debug( - `Permit.io SDK initialized with config:\n${JSON.stringify(this.config, undefined, 2)}`, + `Permit.io SDK initialized: pdp=${this.config.pdp}, apiUrl=${this.config.apiUrl}`, ); } diff --git a/src/tests/unit/init-log.spec.ts b/src/tests/unit/init-log.spec.ts new file mode 100644 index 00000000..b9869bda --- /dev/null +++ b/src/tests/unit/init-log.spec.ts @@ -0,0 +1,36 @@ +import { spawnSync } from 'child_process'; +import path from 'path'; + +import test from 'ava'; + +// A token value that only this test uses. +const TOKEN = 'permit_key_init_log_test_0123456789abcdef'; + +// The SDK's logger writes to the process's stdout file descriptor, so run a client in a +// child process and read what it printed. +function initLogOutput(level: string): string { + const sdk = path.resolve(__dirname, '../../index.js'); + const script = ` + const { Permit } = require(${JSON.stringify(sdk)}); + new Permit({ token: ${JSON.stringify(TOKEN)}, log: { level: ${JSON.stringify(level)} } }); + `; + const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8' }); + if (result.status !== 0) { + throw new Error(`the client failed to start: ${result.stderr}`); + } + return result.stdout + result.stderr; +} + +test('the debug init log carries the PDP and API URL only', (t) => { + const output = initLogOutput('debug'); + + t.true(output.includes('Permit.io SDK initialized'), output); + t.true(output.includes('http://localhost:7766'), output); + t.false(output.includes(TOKEN)); +}); + +test('no log level prints the configured token', (t) => { + for (const level of ['trace', 'debug', 'info', 'warn', 'error']) { + t.false(initLogOutput(level).includes(TOKEN), level); + } +}); From bf111a5840c38d9987147eac231b14a670fdc1e3 Mon Sep 17 00:00:00 2001 From: eli Date: Tue, 27 Oct 2026 18:13:19 -0500 Subject: [PATCH 02/17] PER-16493: review follow-ups: structured init fields, URL origins, pino options - The init line passes its fields to pino as an object: the PDP and API URL origins (no user, password, path or query) and the settings that change the SDK's behaviour (timeout, throwOnError, multiTenancy, proxyFactsViaPdp, the facts-sync and retry settings). - LoggerFactory no longer passes prettyPrint, which pino 8 rejects, so log.json / PERMIT_LOG_JSON=true no longer stop the client from starting; the output stays JSON either way, as it was by default. - pino redacts token and Authorization fields as a backstop. - Tests run the child without PERMIT_* variables, check the exact fields, cover log.json, and report a failed spawn's cause. Co-Authored-By: Claude Opus 5.5 --- src/index.ts | 32 +++++++++++-- src/logger.ts | 15 ++++++- src/tests/unit/init-log.spec.ts | 79 ++++++++++++++++++++++++++------- 3 files changed, 105 insertions(+), 21 deletions(-) diff --git a/src/index.ts b/src/index.ts index 78ff6fd6..40e7c1a6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -92,6 +92,33 @@ export interface IPermitClient extends IEnforcer { * } * ``` */ +// The URL's scheme, host and port: no user, password, path or query, which can carry +// credentials. +function urlOrigin(url: string): string { + try { + return new URL(url).origin; + } catch { + return ''; + } +} + +// What the init line logs: the endpoints' origins and the settings that change the SDK's +// behaviour. Not the config itself, whose token and axios instances stay out of logs. +function initLogFields(config: IPermitConfig): Record { + return { + pdp: urlOrigin(config.pdp), + apiUrl: urlOrigin(config.apiUrl), + timeout: config.timeout, + throwOnError: config.throwOnError, + multiTenancy: config.multiTenancy, + proxyFactsViaPdp: config.proxyFactsViaPdp, + factsSyncTimeout: config.factsSyncTimeout, + factsSyncTimeoutPolicy: config.factsSyncTimeoutPolicy, + retry: config.retry, + pdpRetry: config.pdpRetry, + }; +} + export class Permit implements IPermitClient { private logger: pino.Logger; private enforcer: IEnforcer; @@ -168,10 +195,7 @@ export class Permit implements IPermitClient { this.enforcer = new Enforcer(this.config, this.logger); this.elements = new ElementsClient(this.config, this.logger); - // The endpoints only, not the whole config. - this.logger.debug( - `Permit.io SDK initialized: pdp=${this.config.pdp}, apiUrl=${this.config.apiUrl}`, - ); + this.logger.debug(initLogFields(this.config), 'Permit.io SDK initialized'); } /** diff --git a/src/logger.ts b/src/logger.ts index 48a13c25..e9321d7f 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -10,11 +10,24 @@ export function prettyConsoleLog(label: string, data: any) { export class LoggerFactory { static createLogger(config: IPermitConfig): pino.Logger { + // pino 8 has no prettyPrint option and throws on a truthy one, so `log.json` no longer + // reaches pino: the output is JSON whatever it says, as it already was by default. return pino({ level: config.log.level, - prettyPrint: config.log.json ? { levelFirst: true } : false, base: { label: config.log.label }, timestamp: pino.stdTimeFunctions.isoTime, + // A backstop for a credential that a log call passes in an object. + redact: { + paths: [ + 'token', + '*.token', + 'headers.Authorization', + 'headers.authorization', + '*.headers.Authorization', + '*.headers.authorization', + ], + censor: '[REDACTED]', + }, }); } } diff --git a/src/tests/unit/init-log.spec.ts b/src/tests/unit/init-log.spec.ts index b9869bda..b099036f 100644 --- a/src/tests/unit/init-log.spec.ts +++ b/src/tests/unit/init-log.spec.ts @@ -7,30 +7,77 @@ import test from 'ava'; const TOKEN = 'permit_key_init_log_test_0123456789abcdef'; // The SDK's logger writes to the process's stdout file descriptor, so run a client in a -// child process and read what it printed. -function initLogOutput(level: string): string { +// child process and read what it printed. The child gets no PERMIT_* variables, so the +// shell running the tests can't change the client's config. +function initLog(config: Record, env: Record = {}) { const sdk = path.resolve(__dirname, '../../index.js'); const script = ` const { Permit } = require(${JSON.stringify(sdk)}); - new Permit({ token: ${JSON.stringify(TOKEN)}, log: { level: ${JSON.stringify(level)} } }); + new Permit(${JSON.stringify({ token: TOKEN, ...config })}); `; - const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8' }); - if (result.status !== 0) { - throw new Error(`the client failed to start: ${result.stderr}`); + const childEnv: NodeJS.ProcessEnv = {}; + for (const [name, value] of Object.entries(process.env)) { + if (!name.startsWith('PERMIT_')) { + childEnv[name] = value; + } } - return result.stdout + result.stderr; + const result = spawnSync(process.execPath, ['-e', script], { + encoding: 'utf8', + env: { ...childEnv, ...env }, + }); + if (result.error || result.status !== 0) { + throw new Error( + `the client failed to start (status ${result.status}, signal ${result.signal}): ${ + result.error ?? result.stderr + }`, + ); + } + const output = result.stdout + result.stderr; + const records = result.stdout + .split('\n') + .filter((line) => line.trim().startsWith('{')) + .map((line) => JSON.parse(line)); + return { output, records }; } -test('the debug init log carries the PDP and API URL only', (t) => { - const output = initLogOutput('debug'); +test('the debug init line carries the endpoint origins and settings, nothing else', (t) => { + const { output, records } = initLog({ + pdp: 'http://pdp-user:pdp-password@pdp.example.com:7766/path?key=query-secret', + apiUrl: 'https://api.example.com/?sig=query-secret', + log: { level: 'debug' }, + }); - t.true(output.includes('Permit.io SDK initialized'), output); - t.true(output.includes('http://localhost:7766'), output); - t.false(output.includes(TOKEN)); + const init = records.find((record) => record.msg === 'Permit.io SDK initialized'); + t.truthy(init, output); + t.is(init.pdp, 'http://pdp.example.com:7766'); + t.is(init.apiUrl, 'https://api.example.com'); + t.deepEqual( + Object.keys(init) + .filter((key) => !['level', 'time', 'label', 'msg'].includes(key)) + .sort(), + [ + 'apiUrl', + 'factsSyncTimeout', + 'factsSyncTimeoutPolicy', + 'multiTenancy', + 'pdp', + 'pdpRetry', + 'proxyFactsViaPdp', + 'retry', + 'throwOnError', + 'timeout', + ].filter((key) => key in init), + ); + for (const secret of [TOKEN, 'pdp-password', 'pdp-user', 'query-secret']) { + t.false(output.includes(secret), secret); + } }); -test('no log level prints the configured token', (t) => { - for (const level of ['trace', 'debug', 'info', 'warn', 'error']) { - t.false(initLogOutput(level).includes(TOKEN), level); - } +test('the trace level does not print the token either', (t) => { + t.false(initLog({ log: { level: 'trace' } }).output.includes(TOKEN)); +}); + +test('log.json no longer stops the client from starting', (t) => { + t.notThrows(() => initLog({ log: { json: true } })); + t.notThrows(() => initLog({}, { PERMIT_LOG_JSON: 'true' })); }); From 322312215dea2d01d684d8ef8e8148bc2548f399 Mon Sep 17 00:00:00 2001 From: eli Date: Wed, 28 Oct 2026 13:07:48 -0500 Subject: [PATCH 03/17] PER-16493: second review pass: log axios errors without their config, URLs without credentials - The logger's err serializer turns an axios error into its type, message, code, status, method and URL. pino's standard serializer copied its config, request and response, which hold the Authorization header; the redact paths stay as a second layer. - redactUrl drops a URL's user, password, query and fragment. PDP connection errors and the HTTP debug lines show URLs through it. - PERMIT_LOG_JSON is read leniently ('true'/'1', any case), so no value stops the client from starting; log.json is documented as having no effect. - The init-log test's child process has a 20s timeout. - Tests: an axios error with the token in its headers, raw request and URL serializes without them; PERMIT_LOG_JSON values that JSON.parse rejected. Co-Authored-By: Claude Opus 5.5 --- src/config.ts | 10 ++++--- src/enforcement/enforcer.ts | 9 ++++--- src/logger.ts | 20 ++++++++++++++ src/tests/unit/init-log.spec.ts | 6 ++++- src/tests/unit/logger.spec.ts | 48 +++++++++++++++++++++++++++++++++ src/utils/http-logger.ts | 14 +++++++--- src/utils/redact-url.ts | 8 ++++++ 7 files changed, 104 insertions(+), 11 deletions(-) create mode 100644 src/tests/unit/logger.spec.ts create mode 100644 src/utils/redact-url.ts diff --git a/src/config.ts b/src/config.ts index fa6b06d7..c5ccdc4c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -19,7 +19,9 @@ interface ILoggerConfig { label: string; /** - * Sets whether the SDK log output should be in JSON format. + * Has no effect: the SDK log output is always JSON. + * + * @deprecated pino 8 dropped the pretty-print option this used to set. */ json: boolean; } @@ -154,8 +156,10 @@ export class ConfigFactory { level: _.get(process.env, 'PERMIT_LOG_LEVEL', 'warn'), // Label added to logs label: _.get(process.env, 'PERMIT_LOG_LABEL', 'Permit.io'), - // When logging - dump full data to console as JSON - json: JSON.parse(_.get(process.env, 'PERMIT_LOG_JSON', 'false')), + // Read leniently: the option has no effect, so no value may stop the client starting. + json: ['true', '1'].includes( + _.get(process.env, 'PERMIT_LOG_JSON', 'false').trim().toLowerCase(), + ), }, multiTenancy: { defaultTenant: 'default', diff --git a/src/enforcement/enforcer.ts b/src/enforcement/enforcer.ts index f5218daf..80e66764 100644 --- a/src/enforcement/enforcer.ts +++ b/src/enforcement/enforcer.ts @@ -5,6 +5,7 @@ import URL from 'url-parse'; import { IPermitConfig } from '../config'; import { CheckConfig, Context, ContextStore } from '../utils/context'; import { AxiosLoggingInterceptor } from '../utils/http-logger'; +import { redactUrl } from '../utils/redact-url'; import { resolveRetryConfig } from '../utils/retry'; import { AxiosRetryInterceptor } from '../utils/retry-interceptor'; @@ -253,7 +254,7 @@ export class Enforcer implements IEnforcer { } throw new PermitConnectionError(`Permit SDK got error: \n ${error.message} \n and cannot connect to the PDP, please check your configuration and make sure the - PDP is running at ${this.config.pdp} and accepting requests. \n + PDP is running at ${redactUrl(this.config.pdp)} and accepting requests. \n Read more about setting up the PDP at https://docs.permit.io`); }); } @@ -350,7 +351,7 @@ export class Enforcer implements IEnforcer { } throw new PermitConnectionError(`Permit SDK got error: \n ${error.message} \n and cannot connect to the PDP, please check your configuration and make sure the - PDP is running at ${this.config.pdp} and accepting requests. \n + PDP is running at ${redactUrl(this.config.pdp)} and accepting requests. \n Read more about setting up the PDP at https://docs.permit.io`); }); } @@ -454,7 +455,9 @@ export class Enforcer implements IEnforcer { this.logger.error(`${errorMessage}\n${error}`); } throw new PermitConnectionError(`Permit SDK got error: \n ${error.message} \n - and cannot connect to the PDP, please check your configuration and make sure the PDP is running at ${this.config.pdp} and accepting requests. \n + and cannot connect to the PDP, please check your configuration and make sure the PDP is running at ${redactUrl( + this.config.pdp, + )} and accepting requests. \n Read more about setting up the PDP at https://docs.permit.io`); }); } diff --git a/src/logger.ts b/src/logger.ts index e9321d7f..371ec7aa 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,13 +1,32 @@ import util from 'util'; +import axios from 'axios'; import pino from 'pino'; import { IPermitConfig } from './config'; +import { redactUrl } from './utils/redact-url'; export function prettyConsoleLog(label: string, data: any) { console.log(label, util.inspect(data, false, 12, true)); } +// pino's standard error serializer copies every field of an error, and an axios error's +// config, request and response hold the Authorization header (the request even as raw +// header text). An axios error is logged as what identifies the failure, and nothing else. +export function serializeError(error: unknown): unknown { + if (axios.isAxiosError(error)) { + return { + type: error.name, + message: error.message, + code: error.code, + status: error.response?.status, + method: error.config?.method?.toUpperCase(), + url: error.config?.url === undefined ? undefined : redactUrl(error.config.url), + }; + } + return pino.stdSerializers.err(error as Error); +} + export class LoggerFactory { static createLogger(config: IPermitConfig): pino.Logger { // pino 8 has no prettyPrint option and throws on a truthy one, so `log.json` no longer @@ -16,6 +35,7 @@ export class LoggerFactory { level: config.log.level, base: { label: config.log.label }, timestamp: pino.stdTimeFunctions.isoTime, + serializers: { err: serializeError }, // A backstop for a credential that a log call passes in an object. redact: { paths: [ diff --git a/src/tests/unit/init-log.spec.ts b/src/tests/unit/init-log.spec.ts index b099036f..76655168 100644 --- a/src/tests/unit/init-log.spec.ts +++ b/src/tests/unit/init-log.spec.ts @@ -24,6 +24,8 @@ function initLog(config: Record, env: Record = const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8', env: { ...childEnv, ...env }, + // A hung child fails here, with the reason, rather than at ava's inactivity timeout. + timeout: 20000, }); if (result.error || result.status !== 0) { throw new Error( @@ -79,5 +81,7 @@ test('the trace level does not print the token either', (t) => { test('log.json no longer stops the client from starting', (t) => { t.notThrows(() => initLog({ log: { json: true } })); - t.notThrows(() => initLog({}, { PERMIT_LOG_JSON: 'true' })); + for (const value of ['true', 'True', '', 'yes', '1']) { + t.notThrows(() => initLog({}, { PERMIT_LOG_JSON: value }), value); + } }); diff --git a/src/tests/unit/logger.spec.ts b/src/tests/unit/logger.spec.ts new file mode 100644 index 00000000..14ebf994 --- /dev/null +++ b/src/tests/unit/logger.spec.ts @@ -0,0 +1,48 @@ +import test from 'ava'; +import { AxiosError, AxiosHeaders, InternalAxiosRequestConfig } from 'axios'; + +import { serializeError } from '../../logger'; + +// A token value that only this test uses. +const TOKEN = 'permit_key_logger_test_0123456789abcdef'; + +function axiosErrorWithTheToken(): AxiosError { + const config = { + method: 'post', + url: 'http://user:password@pdp.example.com:7766/allowed?sig=query-secret', + headers: new AxiosHeaders({ Authorization: `Bearer ${TOKEN}` }), + } as InternalAxiosRequestConfig; + const request = { _header: `POST /allowed HTTP/1.1\r\nAuthorization: Bearer ${TOKEN}\r\n` }; + const response = { + status: 502, + statusText: 'Bad Gateway', + data: 'bad gateway', + headers: {}, + config, + }; + return new AxiosError('Request failed', 'ERR_BAD_RESPONSE', config, request, response as never); +} + +test('an axios error is logged without its config, request or response', (t) => { + const serialized = serializeError(axiosErrorWithTheToken()); + + const text = JSON.stringify(serialized); + for (const secret of [TOKEN, 'password', 'query-secret']) { + t.false(text.includes(secret), secret); + } + t.deepEqual(serialized, { + type: 'AxiosError', + message: 'Request failed', + code: 'ERR_BAD_RESPONSE', + status: 502, + method: 'POST', + url: 'http://pdp.example.com:7766/allowed', + }); +}); + +test('any other error is logged as pino logs it', (t) => { + const serialized = serializeError(new TypeError('boom')) as Record; + + t.is(serialized.type, 'TypeError'); + t.is(serialized.message, 'boom'); +}); diff --git a/src/utils/http-logger.ts b/src/utils/http-logger.ts index 8606cbfb..7d524658 100644 --- a/src/utils/http-logger.ts +++ b/src/utils/http-logger.ts @@ -1,13 +1,19 @@ import { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'; import pino from 'pino'; +import { redactUrl } from './redact-url'; + export class AxiosLoggingInterceptor { static setupInterceptor(axiosInstance: AxiosInstance, logger: pino.Logger): void { // Add a request interceptor axiosInstance.interceptors.request.use( function (request: InternalAxiosRequestConfig) { request.headers = request.headers || {}; // Ensure headers are not undefined - logger.debug(`Sending HTTP request: ${request?.method?.toUpperCase()} ${request?.url}`); + logger.debug( + `Sending HTTP request: ${request?.method?.toUpperCase()} ${redactUrl( + request?.url ?? '', + )}`, + ); return request; }, function (error: any) { @@ -20,9 +26,9 @@ export class AxiosLoggingInterceptor { axiosInstance.interceptors.response.use( function (response: AxiosResponse) { logger.debug( - `Received HTTP response: ${response?.config?.method?.toUpperCase()} ${ - response?.config?.url - }, status: ${response?.status}`, + `Received HTTP response: ${response?.config?.method?.toUpperCase()} ${redactUrl( + response?.config?.url ?? '', + )}, status: ${response?.status}`, ); return response; }, diff --git a/src/utils/redact-url.ts b/src/utils/redact-url.ts new file mode 100644 index 00000000..8f3ba06a --- /dev/null +++ b/src/utils/redact-url.ts @@ -0,0 +1,8 @@ +// A URL fit for a log line or an error message: the user, password, query and fragment are +// dropped, since any of them can carry a credential, and the scheme, host, port and path stay, +// so a misconfigured URL is still recognisable. A string that isn't a URL, such as +// `localhost:7766`, is kept as it is, less any of those parts. +export function redactUrl(url: string): string { + const withoutQuery = url.split(/[?#]/, 1)[0]; + return withoutQuery.replace(/^([a-z][a-z0-9+.-]*:\/\/)?[^/]*@/i, '$1'); +} From 8913b8333327e197e1210afd2bf0361a9548b7d0 Mon Sep 17 00:00:00 2001 From: eli Date: Wed, 28 Oct 2026 14:02:01 -0500 Subject: [PATCH 04/17] PER-16493: checkAllTenants sends its query as the body; API errors keep no Authorization header - checkAllTenants posted an object holding the Authorization header and the query as the request body, so the PDP got the key in the body and no query. It now posts the query (user, action, resource, merged context) as the body, with the key in the Authorization header, and reads allowed_tenants, the field the PDP returns. The resource keeps only the tenant it names. - PermitApiError redacts the Authorization header in the axios error it carries (config, response config, raw request header text), and keeps originalError non-enumerable, so logging or inspecting the error does not print the key. originalError, response and request still work. - Tests: the all-tenants request's body and header; an API error inspected at depth prints no key. Co-Authored-By: Claude Opus 5.5 --- src/api/base.ts | 29 +++++++++- src/enforcement/enforcer.ts | 21 +++++--- src/enforcement/interfaces.ts | 2 +- src/tests/unit/key-exposure.spec.ts | 84 +++++++++++++++++++++++++++++ 4 files changed, 126 insertions(+), 10 deletions(-) create mode 100644 src/tests/unit/key-exposure.spec.ts diff --git a/src/api/base.ts b/src/api/base.ts index 569acd18..a7beebba 100644 --- a/src/api/base.ts +++ b/src/api/base.ts @@ -13,9 +13,36 @@ interface FormattedAxiosError { error?: T; status?: number; } +// An axios error keeps the request's headers, the Authorization header with the API key +// included, in its config and in the raw request's header text. Replace that header's value +// in place, so neither the error nor anything logging it shows the key. +export function redactAuthorization(error: AxiosError): void { + for (const config of [error.config, error.response?.config]) { + const headers = config?.headers as Record | undefined; + if (!headers) { + continue; + } + for (const name of Object.keys(headers)) { + if (name.toLowerCase() === 'authorization') { + headers[name] = '[REDACTED]'; + } + } + } + const request = error.request as { _header?: unknown } | undefined; + if (request && typeof request._header === 'string') { + request._header = request._header.replace(/^(authorization:[ \t]*).*$/gim, '$1[REDACTED]'); + } +} + export class PermitApiError extends Error { - constructor(message: string, public originalError: AxiosError) { + // Not enumerable, so logging or inspecting the error prints the message, not the whole + // axios error. Still readable as before; its Authorization header is redacted. + public readonly originalError!: AxiosError; + + constructor(message: string, originalError: AxiosError) { super(message); + redactAuthorization(originalError); + Object.defineProperty(this, 'originalError', { value: originalError, enumerable: false }); } public get formattedAxiosError(): FormattedAxiosError { diff --git a/src/enforcement/enforcer.ts b/src/enforcement/enforcer.ts index 80e66764..f4281440 100644 --- a/src/enforcement/enforcer.ts +++ b/src/enforcement/enforcer.ts @@ -363,20 +363,25 @@ export class Enforcer implements IEnforcer { context: Context = {}, // default to empty context if not provided sdk = 'node', // default to "node" if not provided ): Promise { + // The query goes in the body, as for check(), and the key in the Authorization header. + // The resource keeps the tenant it names: the answer lists every tenant it is allowed in, + // so the default tenant is not filled in. + const resourceObj = isString(resource) ? Enforcer.resourceFromString(resource) : resource; + const input: ICheckInput = { + user: isString(user) ? { key: user } : user, + action, + resource: resourceObj, + context: this.contextStore.getDerivedContext(context), + }; try { - const response = await this.client.post('/allowed/all-tenants', { + const response = await this.client.post('allowed/all-tenants', input, { headers: { Authorization: `Bearer ${this.config.token}`, 'X-Permit-Sdk-Language': sdk, }, - params: { - user, - action, - resource, - context, - }, + timeout: this.config.timeout, }); - return response.data.allowedTenants.map((item) => item.tenant); + return response.data.allowed_tenants.map((item) => item.tenant); } catch (error) { this.logger.error('Error fetching all tenants:', error); throw error; diff --git a/src/enforcement/interfaces.ts b/src/enforcement/interfaces.ts index ad963e04..d27d5673 100644 --- a/src/enforcement/interfaces.ts +++ b/src/enforcement/interfaces.ts @@ -142,7 +142,7 @@ export interface AllTenantsCheckResponse { } export interface AllTenantsResponse { - allowedTenants: AllTenantsCheckResponse[]; + allowed_tenants: AllTenantsCheckResponse[]; } interface TenantPermissions { diff --git a/src/tests/unit/key-exposure.spec.ts b/src/tests/unit/key-exposure.spec.ts new file mode 100644 index 00000000..6109dfd2 --- /dev/null +++ b/src/tests/unit/key-exposure.spec.ts @@ -0,0 +1,84 @@ +import util from 'util'; + +import test from 'ava'; +import { AxiosError, AxiosHeaders, AxiosInstance, InternalAxiosRequestConfig } from 'axios'; + +import { PermitApiError } from '../../api/base'; + +// A token value that only this test uses. +const TOKEN = 'permit_key_exposure_test_0123456789abcdef'; + +interface PermitInternals { + enforcer: { client: AxiosInstance }; + checkAllTenants: ( + user: string, + action: string, + resource: string, + context?: Record, + ) => Promise>; +} + +test('checkAllTenants sends the query in the body and the key only in the header', async (t) => { + const { Permit } = await import('../../index'); + const permit = new Permit({ token: TOKEN }) as unknown as PermitInternals; + let sent: InternalAxiosRequestConfig | undefined; + permit.enforcer.client.defaults.adapter = async (config: InternalAxiosRequestConfig) => { + sent = config; + return { + status: 200, + statusText: 'OK', + headers: {}, + config, + data: { allowed_tenants: [{ tenant: { key: 'tenant-1', attributes: {} } }] }, + }; + }; + + const tenants = await permit.checkAllTenants('user-1', 'read', 'document', { ip: '1.2.3.4' }); + + t.deepEqual( + tenants.map((tenant) => tenant.key), + ['tenant-1'], + ); + t.truthy(sent); + t.true(sent?.url?.endsWith('allowed/all-tenants')); + t.is(AxiosHeaders.from(sent?.headers).get('Authorization'), `Bearer ${TOKEN}`); + const body = JSON.parse(String(sent?.data)); + t.deepEqual(body, { + user: { key: 'user-1' }, + action: 'read', + resource: { type: 'document' }, + context: { ip: '1.2.3.4' }, + }); + t.false(String(sent?.data).includes(TOKEN)); +}); + +test('an API error neither prints nor keeps the key', (t) => { + const config = { + method: 'get', + url: 'https://api.example.com/v2/facts/p/e/users/u', + headers: new AxiosHeaders({ Authorization: `Bearer ${TOKEN}` }), + } as InternalAxiosRequestConfig; + const request = { _header: `GET /v2 HTTP/1.1\r\nAuthorization: Bearer ${TOKEN}\r\nHost: x\r\n` }; + const response = { + status: 500, + statusText: 'Error', + data: { message: 'boom' }, + headers: {}, + config, + }; + const axiosError = new AxiosError( + 'failed', + 'ERR_BAD_RESPONSE', + config, + request, + response as never, + ); + + const error = new PermitApiError('boom', axiosError); + + t.false(util.inspect(error, { depth: 10 }).includes(TOKEN)); + t.false(util.inspect(error.originalError, { depth: 10 }).includes(TOKEN)); + t.false(JSON.stringify(error.formattedAxiosError).includes(TOKEN)); + t.is(error.originalError, axiosError); + t.is(error.response?.status, 500); +}); From d17b3c5f428290707da2ab4dfa3ec946d8d5a5dd Mon Sep 17 00:00:00 2001 From: eli Date: Wed, 28 Oct 2026 14:06:13 -0500 Subject: [PATCH 05/17] PER-16493: redact the raw Authorization header line by line, not by regex CodeQL flagged the pattern's two adjacent wildcards as polynomial on long header text. A line scan does the same replacement in linear time. Co-Authored-By: Claude Opus 5.5 --- src/api/base.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/api/base.ts b/src/api/base.ts index a7beebba..b74cb788 100644 --- a/src/api/base.ts +++ b/src/api/base.ts @@ -30,7 +30,16 @@ export function redactAuthorization(error: AxiosError): void { } const request = error.request as { _header?: unknown } | undefined; if (request && typeof request._header === 'string') { - request._header = request._header.replace(/^(authorization:[ \t]*).*$/gim, '$1[REDACTED]'); + // Line by line, not by regex: a pattern with two adjacent wildcards can backtrack + // polynomially on long header text. + request._header = request._header + .split('\n') + .map((line) => + line.toLowerCase().startsWith('authorization:') + ? `Authorization: [REDACTED]${line.endsWith('\r') ? '\r' : ''}` + : line, + ) + .join('\n'); } } From 7aacac945999db9541465a9c638a75a0195d04f2 Mon Sep 17 00:00:00 2001 From: eli Date: Thu, 29 Oct 2026 13:18:26 -0500 Subject: [PATCH 06/17] PER-16493: checkAllTenants errors keep no Authorization header; API errors hide the request and say why - checkAllTenants redacts the axios error it rethrows, as PermitApiError does, and logs it through the err serializer (pino ignored the extra argument). - The axios error's request (the live Node request, which holds the headers) is no longer enumerable on the error or its response, so printing or inspecting the error doesn't reach it. It stays readable. - A PermitApiError without an API message (a refused connection, a timeout) takes axios's message instead of an empty one. - originalError stays writable, as the public field was; only enumerability changes. - Tests use real errors from a 127.0.0.1 server and a refused port, and cover the checkAllTenants URL, timeout and context store, and the PDP URL in connection errors. Co-Authored-By: Claude Opus 5.5 --- src/api/base.ts | 32 ++++- src/enforcement/enforcer.ts | 7 +- src/index.ts | 2 +- src/tests/unit/key-exposure.spec.ts | 180 +++++++++++++++++++++++++++- 4 files changed, 208 insertions(+), 13 deletions(-) diff --git a/src/api/base.ts b/src/api/base.ts index b74cb788..1cf15f8c 100644 --- a/src/api/base.ts +++ b/src/api/base.ts @@ -14,8 +14,11 @@ interface FormattedAxiosError { status?: number; } // An axios error keeps the request's headers, the Authorization header with the API key -// included, in its config and in the raw request's header text. Replace that header's value -// in place, so neither the error nor anything logging it shows the key. +// included, in its config and in the live Node request object. Replace that header's value in +// the configs and in the request's raw header text, and make `request` non-enumerable on the +// error and its response, as axios's own toJSON() already leaves it out: printing, inspecting +// or serializing the error then doesn't show the key. `error.request` stays readable, and +// inspecting that object itself still shows the headers Node keeps inside it. export function redactAuthorization(error: AxiosError): void { for (const config of [error.config, error.response?.config]) { const headers = config?.headers as Record | undefined; @@ -41,17 +44,34 @@ export function redactAuthorization(error: AxiosError): void { ) .join('\n'); } + for (const holder of [error, error.response]) { + if (holder?.request !== undefined) { + Object.defineProperty(holder, 'request', { + value: holder.request, + enumerable: false, + writable: true, + configurable: true, + }); + } + } } export class PermitApiError extends Error { // Not enumerable, so logging or inspecting the error prints the message, not the whole - // axios error. Still readable as before; its Authorization header is redacted. - public readonly originalError!: AxiosError; + // axios error. Still readable and writable as before; its Authorization header is redacted. + public originalError!: AxiosError; constructor(message: string, originalError: AxiosError) { - super(message); + // A failure without a response (a refused connection, a timeout) has no API message: + // axios's message says what happened, and carries no header. + super(message || originalError.message); redactAuthorization(originalError); - Object.defineProperty(this, 'originalError', { value: originalError, enumerable: false }); + Object.defineProperty(this, 'originalError', { + value: originalError, + enumerable: false, + writable: true, + configurable: true, + }); } public get formattedAxiosError(): FormattedAxiosError { diff --git a/src/enforcement/enforcer.ts b/src/enforcement/enforcer.ts index f4281440..95bba0d7 100644 --- a/src/enforcement/enforcer.ts +++ b/src/enforcement/enforcer.ts @@ -2,6 +2,7 @@ import axios, { AxiosInstance } from 'axios'; import { Logger } from 'pino'; import URL from 'url-parse'; +import { redactAuthorization } from '../api/base'; import { IPermitConfig } from '../config'; import { CheckConfig, Context, ContextStore } from '../utils/context'; import { AxiosLoggingInterceptor } from '../utils/http-logger'; @@ -383,7 +384,11 @@ export class Enforcer implements IEnforcer { }); return response.data.allowed_tenants.map((item) => item.tenant); } catch (error) { - this.logger.error('Error fetching all tenants:', error); + // Rethrown as it is, so callers keep the error type they get today, less the key. + if (axios.isAxiosError(error)) { + redactAuthorization(error); + } + this.logger.error({ err: error }, 'Error fetching all tenants'); throw error; } } diff --git a/src/index.ts b/src/index.ts index 40e7c1a6..eab50b83 100644 --- a/src/index.ts +++ b/src/index.ts @@ -254,7 +254,7 @@ export class Permit implements IPermitClient { try { return await this.enforcer.checkAllTenants(user, action, resource, context, sdk); } catch (error) { - this.logger.error('Error fetching all tenants:', error); + this.logger.error({ err: error }, 'Error fetching all tenants'); throw error; } } diff --git a/src/tests/unit/key-exposure.spec.ts b/src/tests/unit/key-exposure.spec.ts index 6109dfd2..e628fb24 100644 --- a/src/tests/unit/key-exposure.spec.ts +++ b/src/tests/unit/key-exposure.spec.ts @@ -1,7 +1,9 @@ +import http from 'http'; +import { AddressInfo } from 'net'; import util from 'util'; import test from 'ava'; -import { AxiosError, AxiosHeaders, AxiosInstance, InternalAxiosRequestConfig } from 'axios'; +import axios, { AxiosError, AxiosHeaders, AxiosInstance, InternalAxiosRequestConfig } from 'axios'; import { PermitApiError } from '../../api/base'; @@ -9,18 +11,56 @@ import { PermitApiError } from '../../api/base'; const TOKEN = 'permit_key_exposure_test_0123456789abcdef'; interface PermitInternals { - enforcer: { client: AxiosInstance }; + enforcer: { + client: AxiosInstance; + contextStore: { add: (context: Record) => void }; + }; checkAllTenants: ( user: string, action: string, resource: string, context?: Record, ) => Promise>; + api: { users: { get: (key: string) => Promise } }; +} + +// A server on 127.0.0.1 that answers with `handler`, so the errors below are the ones the +// Node http adapter really builds, request objects included. +async function withServer( + handler: http.RequestListener, + run: (url: string) => Promise, +): Promise { + const server = http.createServer(handler); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + await run(`http://127.0.0.1:${(server.address() as AddressInfo).port}`); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +} + +// A 127.0.0.1 URL that refuses connections: a port that was just free. +async function refusedUrl(): Promise { + let url = ''; + await withServer( + (_req, res) => res.end(), + async (serverUrl) => { + url = serverUrl; + }, + ); + return url; +} + +function assertNoToken(t: { false: (actual: boolean, message?: string) => void }, err: unknown) { + t.false(util.inspect(err, { depth: 10 }).includes(TOKEN), 'util.inspect'); + t.false(JSON.stringify(err).includes(TOKEN), 'JSON.stringify'); + t.false(String(err).includes(TOKEN), 'String'); } test('checkAllTenants sends the query in the body and the key only in the header', async (t) => { const { Permit } = await import('../../index'); - const permit = new Permit({ token: TOKEN }) as unknown as PermitInternals; + const permit = new Permit({ token: TOKEN, timeout: 4321 }) as unknown as PermitInternals; + permit.enforcer.contextStore.add({ region: 'eu' }); let sent: InternalAxiosRequestConfig | undefined; permit.enforcer.client.defaults.adapter = async (config: InternalAxiosRequestConfig) => { sent = config; @@ -40,18 +80,127 @@ test('checkAllTenants sends the query in the body and the key only in the header ['tenant-1'], ); t.truthy(sent); - t.true(sent?.url?.endsWith('allowed/all-tenants')); + t.is(axios.getUri(sent), 'http://localhost:7766/allowed/all-tenants'); + t.is(sent?.method, 'post'); + t.is(sent?.timeout, 4321); t.is(AxiosHeaders.from(sent?.headers).get('Authorization'), `Bearer ${TOKEN}`); const body = JSON.parse(String(sent?.data)); t.deepEqual(body, { user: { key: 'user-1' }, action: 'read', resource: { type: 'document' }, - context: { ip: '1.2.3.4' }, + // The context store's context, merged with the call's. + context: { region: 'eu', ip: '1.2.3.4' }, }); t.false(String(sent?.data).includes(TOKEN)); }); +for (const failure of ['an error status', 'a refused connection']) { + test(`checkAllTenants rethrows ${failure} without the key`, async (t) => { + const { Permit } = await import('../../index'); + const check = async (pdp: string) => { + const permit = new Permit({ token: TOKEN, pdp }) as unknown as PermitInternals; + const err = await t.throwsAsync(permit.checkAllTenants('user-1', 'read', 'document')); + // The error callers got before: the axios error itself. + t.true(axios.isAxiosError(err)); + assertNoToken(t, err); + }; + if (failure === 'an error status') { + await withServer((_req, res) => { + res.statusCode = 500; + res.end('{}'); + }, check); + } else { + await check(await refusedUrl()); + } + }); +} + +test('a PDP connection error names the PDP URL without its credentials', async (t) => { + const { Permit, PermitConnectionError } = await import('../../index'); + const refused = new URL(await refusedUrl()); + const permit = new Permit({ + token: TOKEN, + pdp: `http://pdp-user:pdp-password@${refused.host}/prefix?sig=query-secret`, + throwOnError: true, + }); + + for (const call of [ + () => permit.check('user-1', 'read', 'document'), + () => permit.bulkCheck([{ user: 'user-1', action: 'read', resource: 'document' }]), + () => permit.getUserPermissions('user-1'), + ]) { + const err = await t.throwsAsync(call(), { instanceOf: PermitConnectionError }); + t.true(err.message.includes(`PDP is running at http://${refused.host}/prefix and`)); + for (const secret of [TOKEN, 'pdp-user', 'pdp-password', 'query-secret']) { + t.false(err.message.includes(secret), secret); + } + } +}); + +// A REST API that grants an environment-level scope, and fails the call that follows with +// `fail`. +function apiServer(fail: (res: http.ServerResponse) => void): http.RequestListener { + return (req, res) => { + if (req.url === '/v2/api-key/scope') { + res.setHeader('Content-Type', 'application/json'); + res.end( + JSON.stringify({ organization_id: 'org', project_id: 'proj', environment_id: 'env' }), + ); + return; + } + fail(res); + }; +} + +async function apiError(t: { true: (actual: boolean) => void }, apiUrl: string) { + const { Permit } = await import('../../index'); + const permit = new Permit({ token: TOKEN, apiUrl }) as unknown as PermitInternals; + let caught: unknown; + try { + await permit.api.users.get('user-1'); + } catch (err) { + caught = err; + } + t.true(caught instanceof PermitApiError); + return caught as PermitApiError; +} + +test('a real API error status neither prints nor keeps the key', async (t) => { + await withServer( + apiServer((res) => { + res.statusCode = 500; + res.setHeader('Content-Type', 'application/json'); + res.end('{"message":"boom"}'); + }), + async (apiUrl) => { + const error = await apiError(t, apiUrl); + + t.is(error.message, 'boom'); + t.is(error.response?.status, 500); + assertNoToken(t, error); + assertNoToken(t, error.originalError); + t.false(JSON.stringify(error.formattedAxiosError).includes(TOKEN)); + }, + ); +}); + +test('a network failure surfaces as a PermitApiError that says why, without the key', async (t) => { + await withServer( + // The connection drops before any response. + apiServer((res) => res.socket?.destroy()), + async (apiUrl) => { + const error = await apiError(t, apiUrl); + + t.is(error.response, undefined); + t.truthy(error.message); + t.is(error.message, error.originalError.message); + assertNoToken(t, error); + assertNoToken(t, error.originalError); + }, + ); +}); + test('an API error neither prints nor keeps the key', (t) => { const config = { method: 'get', @@ -65,6 +214,7 @@ test('an API error neither prints nor keeps the key', (t) => { data: { message: 'boom' }, headers: {}, config, + request, }; const axiosError = new AxiosError( 'failed', @@ -79,6 +229,26 @@ test('an API error neither prints nor keeps the key', (t) => { t.false(util.inspect(error, { depth: 10 }).includes(TOKEN)); t.false(util.inspect(error.originalError, { depth: 10 }).includes(TOKEN)); t.false(JSON.stringify(error.formattedAxiosError).includes(TOKEN)); + t.false(request._header.includes(TOKEN)); + // Still there, only not enumerable, so printing the error doesn't print the axios error. t.is(error.originalError, axiosError); + t.is(error.request, request); t.is(error.response?.status, 500); + t.false(Object.prototype.propertyIsEnumerable.call(error, 'originalError')); + t.false(Object.prototype.propertyIsEnumerable.call(axiosError, 'request')); + t.false(Object.prototype.propertyIsEnumerable.call(axiosError.response, 'request')); + // And writable, as a public field was before. + const other = new AxiosError('other'); + error.originalError = other; + t.is(error.originalError, other); + t.false(Object.prototype.propertyIsEnumerable.call(error, 'originalError')); +}); + +test('a PermitApiError without an API message falls back to the axios message', (t) => { + const error = new PermitApiError( + undefined as unknown as string, + new AxiosError('timeout of 1ms'), + ); + + t.is(error.message, 'timeout of 1ms'); }); From d8ad0519ddbe4b45bcd574eb403a8671dd2ccb07 Mon Sep 17 00:00:00 2001 From: eli Date: Thu, 29 Oct 2026 13:18:36 -0500 Subject: [PATCH 07/17] PER-16493: test that the SDK logger uses its err serializer and redact paths LoggerFactory.createLogger takes an optional destination (stdout by default), so a test can read what the SDK's own logger writes: an axios error through the err serializer, the redact paths, and the HTTP debug lines without a URL's credentials or query. The redact comment now says exactly which paths it covers. Co-Authored-By: Claude Opus 5.5 --- src/logger.ts | 17 +++++--- src/tests/unit/logger.spec.ts | 76 ++++++++++++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 8 deletions(-) diff --git a/src/logger.ts b/src/logger.ts index 371ec7aa..3adca8dd 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -28,15 +28,17 @@ export function serializeError(error: unknown): unknown { } export class LoggerFactory { - static createLogger(config: IPermitConfig): pino.Logger { - // pino 8 has no prettyPrint option and throws on a truthy one, so `log.json` no longer - // reaches pino: the output is JSON whatever it says, as it already was by default. - return pino({ + // `destination` defaults to stdout, as before; tests pass a stream to read the output. + static createLogger(config: IPermitConfig, destination?: pino.DestinationStream): pino.Logger { + const options: pino.LoggerOptions = { level: config.log.level, base: { label: config.log.label }, timestamp: pino.stdTimeFunctions.isoTime, serializers: { err: serializeError }, - // A backstop for a credential that a log call passes in an object. + // A backstop for a credential that a log call passes in an object: a `token` field, or + // an `Authorization` / `authorization` header in a `headers` field, at the top level of + // that object or one level down. fast-redact has no recursive wildcard, so deeper fields + // and other spellings aren't covered; errors go through `serializeError` instead. redact: { paths: [ 'token', @@ -48,6 +50,9 @@ export class LoggerFactory { ], censor: '[REDACTED]', }, - }); + }; + // pino 8 has no prettyPrint option and throws on a truthy one, so `log.json` no longer + // reaches pino: the output is JSON whatever it says, as it already was by default. + return destination ? pino(options, destination) : pino(options); } } diff --git a/src/tests/unit/logger.spec.ts b/src/tests/unit/logger.spec.ts index 14ebf994..4104b404 100644 --- a/src/tests/unit/logger.spec.ts +++ b/src/tests/unit/logger.spec.ts @@ -1,7 +1,9 @@ import test from 'ava'; -import { AxiosError, AxiosHeaders, InternalAxiosRequestConfig } from 'axios'; +import axios, { AxiosError, AxiosHeaders, InternalAxiosRequestConfig } from 'axios'; -import { serializeError } from '../../logger'; +import { IPermitConfig } from '../../config'; +import { LoggerFactory, serializeError } from '../../logger'; +import { AxiosLoggingInterceptor } from '../../utils/http-logger'; // A token value that only this test uses. const TOKEN = 'permit_key_logger_test_0123456789abcdef'; @@ -46,3 +48,73 @@ test('any other error is logged as pino logs it', (t) => { t.is(serialized.type, 'TypeError'); t.is(serialized.message, 'boom'); }); + +// The SDK's logger, writing its JSON lines to an array instead of stdout. +function capturingLogger(level = 'info') { + const lines: string[] = []; + const logger = LoggerFactory.createLogger( + { log: { level, label: 'test', json: false } } as IPermitConfig, + { write: (line: string) => lines.push(line) }, + ); + return { logger, lines, records: () => lines.map((line) => JSON.parse(line)) }; +} + +test('the SDK logger serializes an axios error without its config, request or response', (t) => { + const { logger, lines, records } = capturingLogger(); + + logger.error({ err: axiosErrorWithTheToken() }, 'failed'); + + for (const secret of [TOKEN, 'password', 'query-secret']) { + t.false(lines.join('').includes(secret), secret); + } + t.deepEqual(records()[0].err, { + type: 'AxiosError', + message: 'Request failed', + code: 'ERR_BAD_RESPONSE', + status: 502, + method: 'POST', + url: 'http://pdp.example.com:7766/allowed', + }); +}); + +test('the SDK logger redacts a token or Authorization header passed in an object', (t) => { + const { logger, lines, records } = capturingLogger(); + + logger.info({ token: TOKEN }); + logger.info({ client: { token: TOKEN } }); + logger.info({ headers: { Authorization: `Bearer ${TOKEN}` } }); + logger.info({ request: { headers: { authorization: `Bearer ${TOKEN}` } } }); + + t.false(lines.join('').includes(TOKEN)); + const [top, nested, header, nestedHeader] = records(); + t.is(top.token, '[REDACTED]'); + t.is(nested.client.token, '[REDACTED]'); + t.is(header.headers.Authorization, '[REDACTED]'); + t.is(nestedHeader.request.headers.authorization, '[REDACTED]'); +}); + +test('the HTTP debug lines show a URL without its credentials or query', async (t) => { + const { logger, lines, records } = capturingLogger('debug'); + const client = axios.create(); + AxiosLoggingInterceptor.setupInterceptor(client, logger); + client.defaults.adapter = async (config: InternalAxiosRequestConfig) => ({ + status: 200, + statusText: 'OK', + headers: {}, + config, + data: {}, + }); + + await client.get('http://user:password@pdp.example.com:7766/allowed?sig=query-secret'); + + for (const secret of ['user', 'password', 'query-secret']) { + t.false(lines.join('').includes(secret), secret); + } + t.deepEqual( + records().map((record) => record.msg), + [ + 'Sending HTTP request: GET http://pdp.example.com:7766/allowed', + 'Received HTTP response: GET http://pdp.example.com:7766/allowed, status: 200', + ], + ); +}); From 9801dc18ef7d9ff6b666c39629a1c8c65d288b34 Mon Sep 17 00:00:00 2001 From: eli Date: Thu, 29 Oct 2026 13:18:36 -0500 Subject: [PATCH 08/17] PER-16493: redactUrl drops the user info before the query; the init line logs redacted URLs - redactUrl removes the user info first, up to the last '@' before the path, so a '?' or '#' in a password can't hide the '@', then the query and fragment. - The init line logs redactUrl(pdp) and redactUrl(apiUrl) instead of the URL origin, which is "null" for a value without a scheme such as localhost:7766. - initLogFields sits above the Permit class's TSDoc block again, so the class keeps its docs in index.d.ts. - The init-log test sets timeout, retry and pdpRetry and expects all ten keys. Co-Authored-By: Claude Opus 5.5 --- src/index.ts | 45 +++++++++++++------------------ src/tests/unit/init-log.spec.ts | 27 ++++++++++++++++--- src/tests/unit/redact-url.spec.ts | 26 ++++++++++++++++++ src/utils/redact-url.ts | 12 +++++++-- 4 files changed, 77 insertions(+), 33 deletions(-) create mode 100644 src/tests/unit/redact-url.spec.ts diff --git a/src/index.ts b/src/index.ts index eab50b83..b8137394 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,7 @@ import { import { LoggerFactory } from './logger'; import { CheckConfig, Context } from './utils/context'; import { AxiosLoggingInterceptor } from './utils/http-logger'; +import { redactUrl } from './utils/redact-url'; import { resolveRetryConfig } from './utils/retry'; import { AxiosRetryInterceptor } from './utils/retry-interceptor'; import { RecursivePartial } from './utils/types'; @@ -47,6 +48,23 @@ export interface IPermitClient extends IEnforcer { elements: IPermitElementsApi; } +// What the init line logs: the endpoints, without credentials, and the settings that change +// the SDK's behaviour. Not the config itself, whose token and axios instances stay out of logs. +function initLogFields(config: IPermitConfig): Record { + return { + pdp: redactUrl(config.pdp), + apiUrl: redactUrl(config.apiUrl), + timeout: config.timeout, + throwOnError: config.throwOnError, + multiTenancy: config.multiTenancy, + proxyFactsViaPdp: config.proxyFactsViaPdp, + factsSyncTimeout: config.factsSyncTimeout, + factsSyncTimeoutPolicy: config.factsSyncTimeoutPolicy, + retry: config.retry, + pdpRetry: config.pdpRetry, + }; +} + /** * The `Permit` class represents the main entry point for interacting with the Permit.io SDK. * The SDK constructor expects an object implementing the {@link IPermitConfig} interface. @@ -92,33 +110,6 @@ export interface IPermitClient extends IEnforcer { * } * ``` */ -// The URL's scheme, host and port: no user, password, path or query, which can carry -// credentials. -function urlOrigin(url: string): string { - try { - return new URL(url).origin; - } catch { - return ''; - } -} - -// What the init line logs: the endpoints' origins and the settings that change the SDK's -// behaviour. Not the config itself, whose token and axios instances stay out of logs. -function initLogFields(config: IPermitConfig): Record { - return { - pdp: urlOrigin(config.pdp), - apiUrl: urlOrigin(config.apiUrl), - timeout: config.timeout, - throwOnError: config.throwOnError, - multiTenancy: config.multiTenancy, - proxyFactsViaPdp: config.proxyFactsViaPdp, - factsSyncTimeout: config.factsSyncTimeout, - factsSyncTimeoutPolicy: config.factsSyncTimeoutPolicy, - retry: config.retry, - pdpRetry: config.pdpRetry, - }; -} - export class Permit implements IPermitClient { private logger: pino.Logger; private enforcer: IEnforcer; diff --git a/src/tests/unit/init-log.spec.ts b/src/tests/unit/init-log.spec.ts index 76655168..d63b28e5 100644 --- a/src/tests/unit/init-log.spec.ts +++ b/src/tests/unit/init-log.spec.ts @@ -42,17 +42,24 @@ function initLog(config: Record, env: Record = return { output, records }; } -test('the debug init line carries the endpoint origins and settings, nothing else', (t) => { +test('the debug init line carries the endpoints and settings, nothing else', (t) => { const { output, records } = initLog({ pdp: 'http://pdp-user:pdp-password@pdp.example.com:7766/path?key=query-secret', apiUrl: 'https://api.example.com/?sig=query-secret', log: { level: 'debug' }, + // Set, so that every field the line carries is present. + timeout: 1234, + retry: { maxRetries: 2 }, + pdpRetry: { maxRetries: 1 }, }); const init = records.find((record) => record.msg === 'Permit.io SDK initialized'); t.truthy(init, output); - t.is(init.pdp, 'http://pdp.example.com:7766'); - t.is(init.apiUrl, 'https://api.example.com'); + t.is(init.pdp, 'http://pdp.example.com:7766/path'); + t.is(init.apiUrl, 'https://api.example.com/'); + t.is(init.timeout, 1234); + t.deepEqual(init.retry, { maxRetries: 2 }); + t.deepEqual(init.pdpRetry, { maxRetries: 1 }); t.deepEqual( Object.keys(init) .filter((key) => !['level', 'time', 'label', 'msg'].includes(key)) @@ -68,13 +75,25 @@ test('the debug init line carries the endpoint origins and settings, nothing els 'retry', 'throwOnError', 'timeout', - ].filter((key) => key in init), + ], ); for (const secret of [TOKEN, 'pdp-password', 'pdp-user', 'query-secret']) { t.false(output.includes(secret), secret); } }); +test('the init line keeps a PDP value without a scheme recognisable', (t) => { + const { output, records } = initLog({ + pdp: 'pdp-user:pdp-password@localhost:7766', + log: { level: 'debug' }, + }); + + const init = records.find((record) => record.msg === 'Permit.io SDK initialized'); + t.truthy(init, output); + t.is(init.pdp, 'localhost:7766'); + t.false(output.includes('pdp-password')); +}); + test('the trace level does not print the token either', (t) => { t.false(initLog({ log: { level: 'trace' } }).output.includes(TOKEN)); }); diff --git a/src/tests/unit/redact-url.spec.ts b/src/tests/unit/redact-url.spec.ts new file mode 100644 index 00000000..8e30c661 --- /dev/null +++ b/src/tests/unit/redact-url.spec.ts @@ -0,0 +1,26 @@ +import test from 'ava'; + +import { redactUrl } from '../../utils/redact-url'; + +for (const [url, expected] of [ + ['http://localhost:7766', 'http://localhost:7766'], + ['https://api.example.com/v2/facts?page=2#top', 'https://api.example.com/v2/facts'], + ['http://user:password@pdp.example.com:7766/path?sig=secret', 'http://pdp.example.com:7766/path'], + ['HTTP://User:Password@Host:7766', 'HTTP://Host:7766'], + ['http://user:password@[::1]:7766/x', 'http://[::1]:7766/x'], + // A '?' or '#' in the password doesn't stop the user info being removed. + ['http://user:pa#ss@host:7766', 'http://host:7766'], + ['http://user:pa?ss@host:7766/path', 'http://host:7766/path'], + ['http://user:p@ss@host:7766', 'http://host:7766'], + // An '@' after the host belongs to the path or query, not to user info. + ['http://host:7766/users/a@example.com', 'http://host:7766/users/a@example.com'], + ['http://host:7766/path?email=a@example.com', 'http://host:7766/path'], + // Not a URL, but recognisable. + ['localhost:7766', 'localhost:7766'], + ['user:password@localhost:7766', 'localhost:7766'], + ['', ''], +]) { + test(`redactUrl(${JSON.stringify(url)})`, (t) => { + t.is(redactUrl(url), expected); + }); +} diff --git a/src/utils/redact-url.ts b/src/utils/redact-url.ts index 8f3ba06a..d7a4188d 100644 --- a/src/utils/redact-url.ts +++ b/src/utils/redact-url.ts @@ -3,6 +3,14 @@ // so a misconfigured URL is still recognisable. A string that isn't a URL, such as // `localhost:7766`, is kept as it is, less any of those parts. export function redactUrl(url: string): string { - const withoutQuery = url.split(/[?#]/, 1)[0]; - return withoutQuery.replace(/^([a-z][a-z0-9+.-]*:\/\/)?[^/]*@/i, '$1'); + const scheme = /^[a-z][a-z0-9+.-]*:\/\//i.exec(url)?.[0] ?? ''; + let rest = url.slice(scheme.length); + // The user info first, up to the last '@' before the path, so that a '?' or '#' in a + // password can't hide the '@'; then the query and fragment. + const slash = rest.indexOf('/'); + const at = rest.lastIndexOf('@', slash === -1 ? rest.length : slash); + if (at !== -1) { + rest = rest.slice(at + 1); + } + return scheme + rest.split(/[?#]/, 1)[0]; } From e9d788217340b8c98a02c85811a61584e517d87b Mon Sep 17 00:00:00 2001 From: eli Date: Thu, 29 Oct 2026 14:26:46 -0500 Subject: [PATCH 09/17] PER-16493: checkAllTenants logs a failure once; error.request becomes an accessor - Permit.checkAllTenants no longer logs the failure the enforcer has already logged, so a failure gives one error line. - `request` on an axios error and its response is a non-enumerable accessor rather than a data property, so inspection modes that list hidden properties show [Getter/Setter] instead of the request. It stays readable and writable. - The checkAllTenants failure tests capture the SDK logger, assert one record with the error's code (and status), and make a further call on the same client to check it still sends the key. - The tests use a server that drops each connection instead of a port that was just released, which another listener could take in between. Co-Authored-By: Claude Opus 5.5 --- src/api/base.ts | 16 +++-- src/index.ts | 8 +-- src/tests/unit/key-exposure.spec.ts | 104 ++++++++++++++++++++-------- 3 files changed, 87 insertions(+), 41 deletions(-) diff --git a/src/api/base.ts b/src/api/base.ts index 1cf15f8c..e5531ec6 100644 --- a/src/api/base.ts +++ b/src/api/base.ts @@ -15,10 +15,11 @@ interface FormattedAxiosError { } // An axios error keeps the request's headers, the Authorization header with the API key // included, in its config and in the live Node request object. Replace that header's value in -// the configs and in the request's raw header text, and make `request` non-enumerable on the -// error and its response, as axios's own toJSON() already leaves it out: printing, inspecting -// or serializing the error then doesn't show the key. `error.request` stays readable, and -// inspecting that object itself still shows the headers Node keeps inside it. +// the configs and in the request's raw header text, and turn `request` on the error and its +// response into a non-enumerable accessor (axios's own toJSON() already leaves it out). Printing, +// inspecting (with hidden properties too: an accessor shows as [Getter/Setter] without being +// called) or serializing the error then doesn't show the key. `error.request` stays readable +// and writable, and inspecting that object itself still shows the headers Node keeps inside it. export function redactAuthorization(error: AxiosError): void { for (const config of [error.config, error.response?.config]) { const headers = config?.headers as Record | undefined; @@ -46,10 +47,13 @@ export function redactAuthorization(error: AxiosError): void { } for (const holder of [error, error.response]) { if (holder?.request !== undefined) { + let held: unknown = holder.request; Object.defineProperty(holder, 'request', { - value: holder.request, + get: () => held, + set: (value: unknown) => { + held = value; + }, enumerable: false, - writable: true, configurable: true, }); } diff --git a/src/index.ts b/src/index.ts index b8137394..5968f5f0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -242,12 +242,8 @@ export class Permit implements IPermitClient { context?: Context | undefined, sdk?: string | undefined, ): Promise { - try { - return await this.enforcer.checkAllTenants(user, action, resource, context, sdk); - } catch (error) { - this.logger.error({ err: error }, 'Error fetching all tenants'); - throw error; - } + // The enforcer logs a failure, once, before rethrowing it. + return await this.enforcer.checkAllTenants(user, action, resource, context, sdk); } /** diff --git a/src/tests/unit/key-exposure.spec.ts b/src/tests/unit/key-exposure.spec.ts index e628fb24..c00e2afd 100644 --- a/src/tests/unit/key-exposure.spec.ts +++ b/src/tests/unit/key-exposure.spec.ts @@ -6,13 +6,17 @@ import test from 'ava'; import axios, { AxiosError, AxiosHeaders, AxiosInstance, InternalAxiosRequestConfig } from 'axios'; import { PermitApiError } from '../../api/base'; +import { IPermitConfig } from '../../config'; +import { LoggerFactory } from '../../logger'; // A token value that only this test uses. const TOKEN = 'permit_key_exposure_test_0123456789abcdef'; interface PermitInternals { + logger: unknown; enforcer: { client: AxiosInstance; + logger: unknown; contextStore: { add: (context: Record) => void }; }; checkAllTenants: ( @@ -39,20 +43,23 @@ async function withServer( } } -// A 127.0.0.1 URL that refuses connections: a port that was just free. -async function refusedUrl(): Promise { - let url = ''; - await withServer( - (_req, res) => res.end(), - async (serverUrl) => { - url = serverUrl; - }, - ); - return url; +// A 127.0.0.1 server that drops every connection before any response. It stays listening +// while `run` uses it, so no other listener can take the port in between. +async function withDroppingServer(run: (url: string) => Promise): Promise { + const server = http.createServer(); + server.on('connection', (socket) => socket.destroy()); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + await run(`http://127.0.0.1:${(server.address() as AddressInfo).port}`); + } finally { + await new Promise((resolve) => server.close(resolve)); + } } function assertNoToken(t: { false: (actual: boolean, message?: string) => void }, err: unknown) { t.false(util.inspect(err, { depth: 10 }).includes(TOKEN), 'util.inspect'); + // Hidden (non-enumerable) properties too, as some inspection modes show them. + t.false(util.inspect(err, { depth: 10, showHidden: true }).includes(TOKEN), 'showHidden'); t.false(JSON.stringify(err).includes(TOKEN), 'JSON.stringify'); t.false(String(err).includes(TOKEN), 'String'); } @@ -95,15 +102,48 @@ test('checkAllTenants sends the query in the body and the key only in the header t.false(String(sent?.data).includes(TOKEN)); }); -for (const failure of ['an error status', 'a refused connection']) { - test(`checkAllTenants rethrows ${failure} without the key`, async (t) => { +for (const failure of ['an error status', 'a dropped connection']) { + test(`checkAllTenants rethrows ${failure} without the key, and logs it once`, async (t) => { const { Permit } = await import('../../index'); + const lines: string[] = []; + const logger = LoggerFactory.createLogger( + { log: { level: 'info', label: 'test', json: false } } as IPermitConfig, + { write: (line: string) => lines.push(line) }, + ); const check = async (pdp: string) => { const permit = new Permit({ token: TOKEN, pdp }) as unknown as PermitInternals; + permit.logger = logger; + permit.enforcer.logger = logger; const err = await t.throwsAsync(permit.checkAllTenants('user-1', 'read', 'document')); // The error callers got before: the axios error itself. t.true(axios.isAxiosError(err)); assertNoToken(t, err); + + const logged = lines + .map((line) => JSON.parse(line)) + .filter((record) => record.msg === 'Error fetching all tenants'); + t.is(logged.length, 1); + if (failure === 'an error status') { + t.is(logged[0].err.status, 500); + } + t.truthy(logged[0].err.code); + t.false(lines.join('').includes(TOKEN)); + + // The redaction edits that failed request's config, not the client's: the next call + // still sends the key. + let authorization: string | undefined; + await withServer( + (req, res) => { + authorization = req.headers.authorization; + res.setHeader('Content-Type', 'application/json'); + res.end('{"allowed_tenants":[]}'); + }, + async (url) => { + permit.enforcer.client.defaults.baseURL = `${url}/`; + t.deepEqual(await permit.checkAllTenants('user-1', 'read', 'document'), []); + }, + ); + t.is(authorization, `Bearer ${TOKEN}`); }; if (failure === 'an error status') { await withServer((_req, res) => { @@ -111,31 +151,33 @@ for (const failure of ['an error status', 'a refused connection']) { res.end('{}'); }, check); } else { - await check(await refusedUrl()); + await withDroppingServer(check); } }); } test('a PDP connection error names the PDP URL without its credentials', async (t) => { const { Permit, PermitConnectionError } = await import('../../index'); - const refused = new URL(await refusedUrl()); - const permit = new Permit({ - token: TOKEN, - pdp: `http://pdp-user:pdp-password@${refused.host}/prefix?sig=query-secret`, - throwOnError: true, - }); + await withDroppingServer(async (url) => { + const { host } = new URL(url); + const permit = new Permit({ + token: TOKEN, + pdp: `http://pdp-user:pdp-password@${host}/prefix?sig=query-secret`, + throwOnError: true, + }); - for (const call of [ - () => permit.check('user-1', 'read', 'document'), - () => permit.bulkCheck([{ user: 'user-1', action: 'read', resource: 'document' }]), - () => permit.getUserPermissions('user-1'), - ]) { - const err = await t.throwsAsync(call(), { instanceOf: PermitConnectionError }); - t.true(err.message.includes(`PDP is running at http://${refused.host}/prefix and`)); - for (const secret of [TOKEN, 'pdp-user', 'pdp-password', 'query-secret']) { - t.false(err.message.includes(secret), secret); + for (const call of [ + () => permit.check('user-1', 'read', 'document'), + () => permit.bulkCheck([{ user: 'user-1', action: 'read', resource: 'document' }]), + () => permit.getUserPermissions('user-1'), + ]) { + const err = await t.throwsAsync(call(), { instanceOf: PermitConnectionError }); + t.true(err.message.includes(`PDP is running at http://${host}/prefix and`)); + for (const secret of [TOKEN, 'pdp-user', 'pdp-password', 'query-secret']) { + t.false(err.message.includes(secret), secret); + } } - } + }); }); // A REST API that grants an environment-level scope, and fails the call that follows with @@ -237,6 +279,10 @@ test('an API error neither prints nor keeps the key', (t) => { t.false(Object.prototype.propertyIsEnumerable.call(error, 'originalError')); t.false(Object.prototype.propertyIsEnumerable.call(axiosError, 'request')); t.false(Object.prototype.propertyIsEnumerable.call(axiosError.response, 'request')); + // An accessor, so even inspecting hidden properties doesn't print the request. + t.false(util.inspect(axiosError, { depth: 10, showHidden: true }).includes('GET /v2')); + axiosError.request = { replaced: true }; + t.deepEqual(axiosError.request, { replaced: true }); // And writable, as a public field was before. const other = new AxiosError('other'); error.originalError = other; From 943d546b587d8c6cd491137f06debbe818d7e5f7 Mon Sep 17 00:00:00 2001 From: eli Date: Thu, 29 Oct 2026 14:26:47 -0500 Subject: [PATCH 10/17] PER-16493: the err serializer redacts a URL in an error's input field; pin each redact path - For an error that isn't an axios error, the serializer passes a string `input` (Node's ERR_INVALID_URL carries the whole URL there) through redactUrl. - The redact test is table-driven, one case per path. Co-Authored-By: Claude Opus 5.5 --- src/logger.ts | 8 ++++- src/tests/unit/logger.spec.ts | 63 ++++++++++++++++++++++++++++------- 2 files changed, 58 insertions(+), 13 deletions(-) diff --git a/src/logger.ts b/src/logger.ts index 3adca8dd..495b1182 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -24,7 +24,13 @@ export function serializeError(error: unknown): unknown { url: error.config?.url === undefined ? undefined : redactUrl(error.config.url), }; } - return pino.stdSerializers.err(error as Error); + // Any other error is copied field by field. Node's ERR_INVALID_URL, which axios rejects with + // for a URL it can't parse, carries that whole URL in `input`. + const serialized = pino.stdSerializers.err(error as Error); + if (typeof serialized?.input === 'string') { + serialized.input = redactUrl(serialized.input); + } + return serialized; } export class LoggerFactory { diff --git a/src/tests/unit/logger.spec.ts b/src/tests/unit/logger.spec.ts index 4104b404..442417e0 100644 --- a/src/tests/unit/logger.spec.ts +++ b/src/tests/unit/logger.spec.ts @@ -77,20 +77,59 @@ test('the SDK logger serializes an axios error without its config, request or re }); }); -test('the SDK logger redacts a token or Authorization header passed in an object', (t) => { +// One case per redact path, so each path is pinned: the logged object, and where the +// censored value ends up in the record. +for (const [path, logged, read] of [ + ['token', { token: TOKEN }, (r: any) => r.token], + ['*.token', { client: { token: TOKEN } }, (r: any) => r.client.token], + [ + 'headers.Authorization', + { headers: { Authorization: `Bearer ${TOKEN}` } }, + (r: any) => r.headers.Authorization, + ], + [ + 'headers.authorization', + { headers: { authorization: `Bearer ${TOKEN}` } }, + (r: any) => r.headers.authorization, + ], + [ + '*.headers.Authorization', + { request: { headers: { Authorization: `Bearer ${TOKEN}` } } }, + (r: any) => r.request.headers.Authorization, + ], + [ + '*.headers.authorization', + { request: { headers: { authorization: `Bearer ${TOKEN}` } } }, + (r: any) => r.request.headers.authorization, + ], +] as Array<[string, Record, (record: any) => unknown]>) { + test(`the SDK logger redacts ${path}`, (t) => { + const { logger, lines, records } = capturingLogger(); + + logger.info(logged); + + t.false(lines.join('').includes(TOKEN)); + t.is(read(records()[0]), '[REDACTED]'); + }); +} + +test('any other error keeps no URL credentials in its input field', (t) => { + let invalid: unknown; + try { + new URL('http://user:password@host:bad/path?sig=query-secret'); + } catch (err) { + invalid = err; + } + t.is((invalid as { code?: string }).code, 'ERR_INVALID_URL'); const { logger, lines, records } = capturingLogger(); - logger.info({ token: TOKEN }); - logger.info({ client: { token: TOKEN } }); - logger.info({ headers: { Authorization: `Bearer ${TOKEN}` } }); - logger.info({ request: { headers: { authorization: `Bearer ${TOKEN}` } } }); - - t.false(lines.join('').includes(TOKEN)); - const [top, nested, header, nestedHeader] = records(); - t.is(top.token, '[REDACTED]'); - t.is(nested.client.token, '[REDACTED]'); - t.is(header.headers.Authorization, '[REDACTED]'); - t.is(nestedHeader.request.headers.authorization, '[REDACTED]'); + logger.error({ err: invalid }, 'failed'); + + for (const secret of ['user:', 'password', 'query-secret']) { + t.false(lines.join('').includes(secret), secret); + } + t.is(records()[0].err.input, 'http://host:bad/path'); + t.is(records()[0].err.code, 'ERR_INVALID_URL'); }); test('the HTTP debug lines show a URL without its credentials or query', async (t) => { From 08494f30608f7ecdbc1a226a88e42038c3318468 Mon Sep 17 00:00:00 2001 From: eli Date: Thu, 29 Oct 2026 14:26:48 -0500 Subject: [PATCH 11/17] PER-16493: redactUrl reads a valid URL as Node's parser does - The input is trimmed, and one or more slashes after the scheme are accepted, as Node's URL parser (which axios uses) accepts both. - For a valid URL, a '?' or '#' starts the query or fragment, so an '@' after it is not taken as the end of the user info. - For a URL with a scheme that doesn't parse, everything up to the last '@' is removed, which also covers a '/' in a password. Co-Authored-By: Claude Opus 5.5 --- src/tests/unit/redact-url.spec.ts | 9 +++++++ src/utils/redact-url.ts | 45 ++++++++++++++++++++++++------- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/src/tests/unit/redact-url.spec.ts b/src/tests/unit/redact-url.spec.ts index 8e30c661..62df80b6 100644 --- a/src/tests/unit/redact-url.spec.ts +++ b/src/tests/unit/redact-url.spec.ts @@ -15,6 +15,15 @@ for (const [url, expected] of [ // An '@' after the host belongs to the path or query, not to user info. ['http://host:7766/users/a@example.com', 'http://host:7766/users/a@example.com'], ['http://host:7766/path?email=a@example.com', 'http://host:7766/path'], + // An '@' in the query or fragment of a URL without a path isn't user info. + ['http://host:7766?a=b@c', 'http://host:7766'], + ['http://pdp?sig=a@b/c', 'http://pdp'], + ['http://host#x@y', 'http://host'], + // A '/' in the password: not a valid URL, so everything up to the last '@' goes. + ['http://user:pa/ss@host:7766', 'http://host:7766'], + // What Node's URL parser accepts: surrounding whitespace, and one slash after the scheme. + [' http://user:pass@pdp:7766\n', 'http://pdp:7766'], + ['http:/user:pass@pdp:7766', 'http:/pdp:7766'], // Not a URL, but recognisable. ['localhost:7766', 'localhost:7766'], ['user:password@localhost:7766', 'localhost:7766'], diff --git a/src/utils/redact-url.ts b/src/utils/redact-url.ts index d7a4188d..a08d8bd8 100644 --- a/src/utils/redact-url.ts +++ b/src/utils/redact-url.ts @@ -3,14 +3,41 @@ // so a misconfigured URL is still recognisable. A string that isn't a URL, such as // `localhost:7766`, is kept as it is, less any of those parts. export function redactUrl(url: string): string { - const scheme = /^[a-z][a-z0-9+.-]*:\/\//i.exec(url)?.[0] ?? ''; - let rest = url.slice(scheme.length); - // The user info first, up to the last '@' before the path, so that a '?' or '#' in a - // password can't hide the '@'; then the query and fragment. - const slash = rest.indexOf('/'); - const at = rest.lastIndexOf('@', slash === -1 ? rest.length : slash); - if (at !== -1) { - rest = rest.slice(at + 1); + const trimmed = url.trim(); + // One or more slashes, as Node's URL parser (which axios uses) accepts `http:/host`. + const scheme = /^[a-z][a-z0-9+.-]*:\/+/i.exec(trimmed)?.[0] ?? ''; + let rest = trimmed.slice(scheme.length); + if (scheme && isValidUrl(trimmed)) { + // Read as the parser reads it, which is where requests go: a '?' or '#' starts the query + // or fragment, so an '@' after one isn't user info. + rest = withoutQuery(rest); + rest = rest.slice(rest.lastIndexOf('@', authorityEnd(rest)) + 1); + } else if (scheme) { + // Not a valid URL, so remove more rather than less: everything up to the last '@', which + // also covers a '/', '?' or '#' in a password. + rest = withoutQuery(rest.slice(rest.lastIndexOf('@') + 1)); + } else { + // No scheme, such as `user:pass@localhost:7766`: the user info up to the last '@' before + // the path, then the query and fragment. + rest = withoutQuery(rest.slice(rest.lastIndexOf('@', authorityEnd(rest)) + 1)); + } + return scheme + rest; +} + +function isValidUrl(url: string): boolean { + try { + new URL(url); + return true; + } catch { + return false; } - return scheme + rest.split(/[?#]/, 1)[0]; +} + +function authorityEnd(rest: string): number { + const slash = rest.indexOf('/'); + return slash === -1 ? rest.length : slash; +} + +function withoutQuery(rest: string): string { + return rest.split(/[?#]/, 1)[0]; } From 1b9cc5ab52d4456304adfacca6a970978431adca Mon Sep 17 00:00:00 2001 From: eli Date: Thu, 29 Oct 2026 16:23:44 -0500 Subject: [PATCH 12/17] PER-16493: redactUrl rebuilds an http(s) URL from the parsed URL - An input that Node's URL parser accepts as http: or https: is rebuilt from the parsed URL (scheme, host, path), so the parser's own clean-up (tabs and newlines dropped, '\' read as '/') applies before anything is removed. - Anything else has everything up to the last '@' removed, whether or not a scheme was found, then the query and fragment; a scheme in front is kept. - The scheme and host now come back lowercased, and `http:/host` as `http://host`; a URL with an empty path drops its trailing '/'. Co-Authored-By: Claude Opus 5.5 --- src/tests/unit/init-log.spec.ts | 2 +- src/tests/unit/redact-url.spec.ts | 14 +++++++-- src/utils/redact-url.ts | 47 +++++++++---------------------- 3 files changed, 27 insertions(+), 36 deletions(-) diff --git a/src/tests/unit/init-log.spec.ts b/src/tests/unit/init-log.spec.ts index d63b28e5..cd2f64d5 100644 --- a/src/tests/unit/init-log.spec.ts +++ b/src/tests/unit/init-log.spec.ts @@ -56,7 +56,7 @@ test('the debug init line carries the endpoints and settings, nothing else', (t) const init = records.find((record) => record.msg === 'Permit.io SDK initialized'); t.truthy(init, output); t.is(init.pdp, 'http://pdp.example.com:7766/path'); - t.is(init.apiUrl, 'https://api.example.com/'); + t.is(init.apiUrl, 'https://api.example.com'); t.is(init.timeout, 1234); t.deepEqual(init.retry, { maxRetries: 2 }); t.deepEqual(init.pdpRetry, { maxRetries: 1 }); diff --git a/src/tests/unit/redact-url.spec.ts b/src/tests/unit/redact-url.spec.ts index 62df80b6..22a279f6 100644 --- a/src/tests/unit/redact-url.spec.ts +++ b/src/tests/unit/redact-url.spec.ts @@ -6,7 +6,8 @@ for (const [url, expected] of [ ['http://localhost:7766', 'http://localhost:7766'], ['https://api.example.com/v2/facts?page=2#top', 'https://api.example.com/v2/facts'], ['http://user:password@pdp.example.com:7766/path?sig=secret', 'http://pdp.example.com:7766/path'], - ['HTTP://User:Password@Host:7766', 'HTTP://Host:7766'], + // The parser lowercases the scheme and host. + ['HTTP://User:Password@Host:7766', 'http://host:7766'], ['http://user:password@[::1]:7766/x', 'http://[::1]:7766/x'], // A '?' or '#' in the password doesn't stop the user info being removed. ['http://user:pa#ss@host:7766', 'http://host:7766'], @@ -23,10 +24,19 @@ for (const [url, expected] of [ ['http://user:pa/ss@host:7766', 'http://host:7766'], // What Node's URL parser accepts: surrounding whitespace, and one slash after the scheme. [' http://user:pass@pdp:7766\n', 'http://pdp:7766'], - ['http:/user:pass@pdp:7766', 'http:/pdp:7766'], + ['http:/user:pass@pdp:7766', 'http://pdp:7766'], + // What the parser cleans up before it parses: a tab or newline inside the text, a '\\' + // read as '/'. axios still sends these with the user info, so it is removed. + ['ht\ttp://user:pass@pdp:7766', 'http://pdp:7766'], + ['http://pdp:7766/a\nb', 'http://pdp:7766/ab'], + ['http:\\\\user:pass@pdp:7766\\path', 'http://pdp:7766/path'], + // No scheme the parser accepts, and a '/' before the '@': everything up to the last '@'. + ['http//user:pass@pdp:7766', 'pdp:7766'], + ['htp:/x/user:pass@pdp:7766/path', 'htp:/pdp:7766/path'], // Not a URL, but recognisable. ['localhost:7766', 'localhost:7766'], ['user:password@localhost:7766', 'localhost:7766'], + ['localhost:7766/a/user:pass@pdp', 'pdp'], ['', ''], ]) { test(`redactUrl(${JSON.stringify(url)})`, (t) => { diff --git a/src/utils/redact-url.ts b/src/utils/redact-url.ts index a08d8bd8..ee1a5540 100644 --- a/src/utils/redact-url.ts +++ b/src/utils/redact-url.ts @@ -4,40 +4,21 @@ // `localhost:7766`, is kept as it is, less any of those parts. export function redactUrl(url: string): string { const trimmed = url.trim(); - // One or more slashes, as Node's URL parser (which axios uses) accepts `http:/host`. - const scheme = /^[a-z][a-z0-9+.-]*:\/+/i.exec(trimmed)?.[0] ?? ''; - let rest = trimmed.slice(scheme.length); - if (scheme && isValidUrl(trimmed)) { - // Read as the parser reads it, which is where requests go: a '?' or '#' starts the query - // or fragment, so an '@' after one isn't user info. - rest = withoutQuery(rest); - rest = rest.slice(rest.lastIndexOf('@', authorityEnd(rest)) + 1); - } else if (scheme) { - // Not a valid URL, so remove more rather than less: everything up to the last '@', which - // also covers a '/', '?' or '#' in a password. - rest = withoutQuery(rest.slice(rest.lastIndexOf('@') + 1)); - } else { - // No scheme, such as `user:pass@localhost:7766`: the user info up to the last '@' before - // the path, then the query and fragment. - rest = withoutQuery(rest.slice(rest.lastIndexOf('@', authorityEnd(rest)) + 1)); - } - return scheme + rest; -} - -function isValidUrl(url: string): boolean { try { - new URL(url); - return true; + // An http(s) URL, the only kind axios requests, is rebuilt from what Node's URL parser + // (which axios uses) reads, after its own clean-up of the text: where requests go, without + // the user info, query or fragment. + const parsed = new URL(trimmed); + if (parsed.protocol === 'http:' || parsed.protocol === 'https:') { + const path = parsed.pathname === '/' ? '' : parsed.pathname; + return `${parsed.protocol}//${parsed.host}${path}`; + } } catch { - return false; + // Not a URL the parser accepts: handled below. } -} - -function authorityEnd(rest: string): number { - const slash = rest.indexOf('/'); - return slash === -1 ? rest.length : slash; -} - -function withoutQuery(rest: string): string { - return rest.split(/[?#]/, 1)[0]; + // Anything else removes more rather than less: everything up to the last '@', then the + // query and fragment. A scheme in front is kept, so the value stays recognisable. + const scheme = /^[a-z][a-z0-9+.-]*:\/+/i.exec(trimmed)?.[0] ?? ''; + const rest = trimmed.slice(scheme.length); + return scheme + rest.slice(rest.lastIndexOf('@') + 1).split(/[?#]/, 1)[0]; } From 1e527da79c9f3204a20bd08277b4d272eaa31f97 Mon Sep 17 00:00:00 2001 From: eli Date: Thu, 29 Oct 2026 16:23:45 -0500 Subject: [PATCH 13/17] PER-16493: the err serializer redacts input on a copy pino returns a value that isn't error-like as the caller's own object, so the redacted input goes on a copy and the logged value is never written to (a frozen one no longer makes the log call throw). Co-Authored-By: Claude Opus 5.5 --- src/logger.ts | 3 ++- src/tests/unit/logger.spec.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/logger.ts b/src/logger.ts index 495b1182..74bf5f07 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -27,8 +27,9 @@ export function serializeError(error: unknown): unknown { // Any other error is copied field by field. Node's ERR_INVALID_URL, which axios rejects with // for a URL it can't parse, carries that whole URL in `input`. const serialized = pino.stdSerializers.err(error as Error); + // A copy: for a value that isn't error-like, pino returns the caller's own object. if (typeof serialized?.input === 'string') { - serialized.input = redactUrl(serialized.input); + return { ...serialized, input: redactUrl(serialized.input) }; } return serialized; } diff --git a/src/tests/unit/logger.spec.ts b/src/tests/unit/logger.spec.ts index 442417e0..1a7f1a29 100644 --- a/src/tests/unit/logger.spec.ts +++ b/src/tests/unit/logger.spec.ts @@ -132,6 +132,19 @@ test('any other error keeps no URL credentials in its input field', (t) => { t.is(records()[0].err.code, 'ERR_INVALID_URL'); }); +test('the input redaction never writes to the logged value', (t) => { + // Not error-like (no message), so pino hands back this same object; frozen, so a write + // would throw. + const value = Object.freeze({ code: 'X', input: 'http://user:password@host:7766/path' }); + const { logger, lines, records } = capturingLogger(); + + t.notThrows(() => logger.error({ err: value }, 'failed')); + + t.is(value.input, 'http://user:password@host:7766/path'); + t.false(lines.join('').includes('password')); + t.is(records()[0].err.input, 'http://host:7766/path'); +}); + test('the HTTP debug lines show a URL without its credentials or query', async (t) => { const { logger, lines, records } = capturingLogger('debug'); const client = axios.create(); From f215370e36396488e70272528215430d5cd34d8a Mon Sep 17 00:00:00 2001 From: eli Date: Fri, 30 Oct 2026 08:08:56 -0500 Subject: [PATCH 14/17] PER-16493: HTTP debug lines log the URL a request goes to; pin the last-@ cut; redactUrl comments match Co-Authored-By: Claude Opus 5.5 --- src/tests/unit/logger.spec.ts | 26 ++++++++++++++++++++++++++ src/tests/unit/redact-url.spec.ts | 6 ++++-- src/utils/http-logger.ts | 20 ++++++++++++++++++-- src/utils/redact-url.ts | 8 ++++---- 4 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/tests/unit/logger.spec.ts b/src/tests/unit/logger.spec.ts index 1a7f1a29..c72e31cc 100644 --- a/src/tests/unit/logger.spec.ts +++ b/src/tests/unit/logger.spec.ts @@ -170,3 +170,29 @@ test('the HTTP debug lines show a URL without its credentials or query', async ( ], ); }); + +test('the HTTP debug lines show the URL a relative path goes to, an @ in its path kept', async (t) => { + const { logger, lines, records } = capturingLogger('debug'); + const client = axios.create({ baseURL: 'http://user:password@pdp.example.com:7766/' }); + AxiosLoggingInterceptor.setupInterceptor(client, logger); + client.defaults.adapter = async (config: InternalAxiosRequestConfig) => ({ + status: 200, + statusText: 'OK', + headers: {}, + config, + data: {}, + }); + + await client.get('/users/a@example.com/x', { params: { sig: 'query-secret' } }); + + for (const secret of ['user:', 'password', 'query-secret']) { + t.false(lines.join('').includes(secret), secret); + } + t.deepEqual( + records().map((record) => record.msg), + [ + 'Sending HTTP request: GET http://pdp.example.com:7766/users/a@example.com/x', + 'Received HTTP response: GET http://pdp.example.com:7766/users/a@example.com/x, status: 200', + ], + ); +}); diff --git a/src/tests/unit/redact-url.spec.ts b/src/tests/unit/redact-url.spec.ts index 22a279f6..48076eb4 100644 --- a/src/tests/unit/redact-url.spec.ts +++ b/src/tests/unit/redact-url.spec.ts @@ -30,13 +30,15 @@ for (const [url, expected] of [ ['ht\ttp://user:pass@pdp:7766', 'http://pdp:7766'], ['http://pdp:7766/a\nb', 'http://pdp:7766/ab'], ['http:\\\\user:pass@pdp:7766\\path', 'http://pdp:7766/path'], - // No scheme the parser accepts, and a '/' before the '@': everything up to the last '@'. + // Not an http(s) URL to the parser, and a '/' before the '@': everything up to the last '@'. ['http//user:pass@pdp:7766', 'pdp:7766'], + ['http//user:p@ss@pdp:7766', 'pdp:7766'], ['htp:/x/user:pass@pdp:7766/path', 'htp:/pdp:7766/path'], + ['localhost:7766/a/user:pass@pdp', 'pdp'], // Not a URL, but recognisable. ['localhost:7766', 'localhost:7766'], ['user:password@localhost:7766', 'localhost:7766'], - ['localhost:7766/a/user:pass@pdp', 'pdp'], + ['user:p@ss@localhost:7766/path?x=y', 'localhost:7766/path'], ['', ''], ]) { test(`redactUrl(${JSON.stringify(url)})`, (t) => { diff --git a/src/utils/http-logger.ts b/src/utils/http-logger.ts index 7d524658..39764c38 100644 --- a/src/utils/http-logger.ts +++ b/src/utils/http-logger.ts @@ -3,6 +3,22 @@ import pino from 'pino'; import { redactUrl } from './redact-url'; +// The URL a request goes to, `baseURL` included: a relative `url` on its own isn't a URL, so +// redactUrl would cut it at its last '@' (e.g. `/users/a@example.com/x`). +function requestedUrl( + axiosInstance: AxiosInstance, + config: InternalAxiosRequestConfig | undefined, +): string { + if (config === undefined) { + return ''; + } + try { + return axiosInstance.getUri(config); + } catch { + return config.url ?? ''; + } +} + export class AxiosLoggingInterceptor { static setupInterceptor(axiosInstance: AxiosInstance, logger: pino.Logger): void { // Add a request interceptor @@ -11,7 +27,7 @@ export class AxiosLoggingInterceptor { request.headers = request.headers || {}; // Ensure headers are not undefined logger.debug( `Sending HTTP request: ${request?.method?.toUpperCase()} ${redactUrl( - request?.url ?? '', + requestedUrl(axiosInstance, request), )}`, ); return request; @@ -27,7 +43,7 @@ export class AxiosLoggingInterceptor { function (response: AxiosResponse) { logger.debug( `Received HTTP response: ${response?.config?.method?.toUpperCase()} ${redactUrl( - response?.config?.url ?? '', + requestedUrl(axiosInstance, response?.config), )}, status: ${response?.status}`, ); return response; diff --git a/src/utils/redact-url.ts b/src/utils/redact-url.ts index ee1a5540..873119c4 100644 --- a/src/utils/redact-url.ts +++ b/src/utils/redact-url.ts @@ -1,7 +1,7 @@ -// A URL fit for a log line or an error message: the user, password, query and fragment are -// dropped, since any of them can carry a credential, and the scheme, host, port and path stay, -// so a misconfigured URL is still recognisable. A string that isn't a URL, such as -// `localhost:7766`, is kept as it is, less any of those parts. +// A URL fit for a log line or an error message, without the user, password, query or +// fragment, since any of them can carry a credential. An http(s) URL is rebuilt from what +// Node's URL parser reads (scheme, host, port, path); anything else, such as +// `localhost:7766`, loses everything up to its last '@', then its query and fragment. export function redactUrl(url: string): string { const trimmed = url.trim(); try { From f1f375c3a9cf8d989e7dcbedc20c2fd5401b53e3 Mon Sep 17 00:00:00 2001 From: eli Date: Fri, 30 Oct 2026 09:54:08 -0500 Subject: [PATCH 15/17] PER-16493: build the logged URL without params, default it to ''; test the getUri fallback Co-Authored-By: Claude Opus 5.5 --- src/tests/unit/logger.spec.ts | 72 ++++++++++++++++++++++++++++++++++- src/utils/http-logger.ts | 7 +++- 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/src/tests/unit/logger.spec.ts b/src/tests/unit/logger.spec.ts index c72e31cc..5439c466 100644 --- a/src/tests/unit/logger.spec.ts +++ b/src/tests/unit/logger.spec.ts @@ -1,5 +1,12 @@ import test from 'ava'; -import axios, { AxiosError, AxiosHeaders, InternalAxiosRequestConfig } from 'axios'; +import axios, { + AxiosError, + AxiosHeaders, + AxiosInstance, + CreateAxiosDefaults, + InternalAxiosRequestConfig, +} from 'axios'; +import pino from 'pino'; import { IPermitConfig } from '../../config'; import { LoggerFactory, serializeError } from '../../logger'; @@ -196,3 +203,66 @@ test('the HTTP debug lines show the URL a relative path goes to, an @ in its pat ], ); }); + +function stubbedClient(logger: pino.Logger, config: CreateAxiosDefaults = {}): AxiosInstance { + const client = axios.create(config); + AxiosLoggingInterceptor.setupInterceptor(client, logger); + client.defaults.adapter = async (sent: InternalAxiosRequestConfig) => ({ + status: 200, + statusText: 'OK', + headers: {}, + config: sent, + data: {}, + }); + return client; +} + +test('the HTTP debug lines show config.url, redacted, when getUri throws', async (t) => { + const { logger, records } = capturingLogger('debug'); + const client = stubbedClient(logger); + client.getUri = () => { + throw new Error('getUri'); + }; + + await client.get('http://user:password@pdp.example.com:7766/allowed?sig=query-secret'); + + t.deepEqual( + records().map((record) => record.msg), + [ + 'Sending HTTP request: GET http://pdp.example.com:7766/allowed', + 'Received HTTP response: GET http://pdp.example.com:7766/allowed, status: 200', + ], + ); +}); + +test('the HTTP debug lines build their URL without the params', async (t) => { + const { logger, records } = capturingLogger('debug'); + let serialized = 0; + const client = stubbedClient(logger, { + params: { sig: 'query-secret' }, + paramsSerializer: { + serialize: () => { + serialized += 1; + return 'sig=query-secret'; + }, + }, + }); + + await client.get('http://pdp.example.com:7766/allowed'); + + // The stub adapter never builds the URL, so any call is the debug lines'. + t.is(serialized, 0); + t.is(records().length, 2); +}); + +test('a request with neither url nor baseURL logs an empty URL', async (t) => { + const { logger, records } = capturingLogger('debug'); + const client = stubbedClient(logger); + + await client.request({ method: 'get' }); + + t.deepEqual( + records().map((record) => record.msg), + ['Sending HTTP request: GET ', 'Received HTTP response: GET , status: 200'], + ); +}); diff --git a/src/utils/http-logger.ts b/src/utils/http-logger.ts index 39764c38..610d8be8 100644 --- a/src/utils/http-logger.ts +++ b/src/utils/http-logger.ts @@ -4,7 +4,10 @@ import pino from 'pino'; import { redactUrl } from './redact-url'; // The URL a request goes to, `baseURL` included: a relative `url` on its own isn't a URL, so -// redactUrl would cut it at its last '@' (e.g. `/users/a@example.com/x`). +// redactUrl would cut it at its last '@' (e.g. `/users/a@example.com/x`). Built without +// `params` (`null`: `undefined` falls back to the instance's), which the line doesn't show, +// so an app's `paramsSerializer` doesn't run for it. `getUri` returns undefined for a +// request with neither `url` nor `baseURL`, whatever its type says. function requestedUrl( axiosInstance: AxiosInstance, config: InternalAxiosRequestConfig | undefined, @@ -13,7 +16,7 @@ function requestedUrl( return ''; } try { - return axiosInstance.getUri(config); + return (axiosInstance.getUri({ ...config, params: null }) as string | undefined) ?? ''; } catch { return config.url ?? ''; } From 7441f37d4fd8794e1eeadc38a8ab0851d7dbe46a Mon Sep 17 00:00:00 2001 From: eli Date: Fri, 30 Oct 2026 10:37:41 -0500 Subject: [PATCH 16/17] PER-16493: the logged URL is always a string, and the HTTP lines are built only at debug Co-Authored-By: Claude Opus 5.5 --- src/tests/unit/logger.spec.ts | 36 +++++++++++++++++++++++++++++++++++ src/utils/http-logger.ts | 36 +++++++++++++++++++++-------------- 2 files changed, 58 insertions(+), 14 deletions(-) diff --git a/src/tests/unit/logger.spec.ts b/src/tests/unit/logger.spec.ts index 5439c466..949ab92a 100644 --- a/src/tests/unit/logger.spec.ts +++ b/src/tests/unit/logger.spec.ts @@ -266,3 +266,39 @@ test('a request with neither url nor baseURL logs an empty URL', async (t) => { ['Sending HTTP request: GET ', 'Received HTTP response: GET , status: 200'], ); }); + +for (const level of ['warn', 'debug']) { + test(`a url given as a URL object is sent and logged (level ${level})`, async (t) => { + const { logger, records } = capturingLogger(level); + const client = stubbedClient(logger); + + const response = await client.get( + new URL('http://user:password@pdp.example.com:7766/allowed') as unknown as string, + ); + + t.is(response.status, 200); + t.deepEqual( + records().map((record) => record.msg), + level === 'debug' + ? [ + 'Sending HTTP request: GET http://pdp.example.com:7766/allowed', + 'Received HTTP response: GET http://pdp.example.com:7766/allowed, status: 200', + ] + : [], + ); + }); +} + +test('the HTTP lines are not built when debug is off', async (t) => { + const { logger } = capturingLogger('info'); + const client = stubbedClient(logger); + let built = 0; + client.getUri = () => { + built += 1; + return 'http://pdp.example.com:7766/allowed'; + }; + + await client.get('http://pdp.example.com:7766/allowed'); + + t.is(built, 0); +}); diff --git a/src/utils/http-logger.ts b/src/utils/http-logger.ts index 610d8be8..4b8acadb 100644 --- a/src/utils/http-logger.ts +++ b/src/utils/http-logger.ts @@ -6,8 +6,9 @@ import { redactUrl } from './redact-url'; // The URL a request goes to, `baseURL` included: a relative `url` on its own isn't a URL, so // redactUrl would cut it at its last '@' (e.g. `/users/a@example.com/x`). Built without // `params` (`null`: `undefined` falls back to the instance's), which the line doesn't show, -// so an app's `paramsSerializer` doesn't run for it. `getUri` returns undefined for a -// request with neither `url` nor `baseURL`, whatever its type says. +// so an app's `paramsSerializer` doesn't run for it. Whatever `getUri` returns, its type +// aside, is made a string: undefined for a request with neither `url` nor `baseURL`, and a +// `url` given as a `URL` object as it is. function requestedUrl( axiosInstance: AxiosInstance, config: InternalAxiosRequestConfig | undefined, @@ -15,11 +16,13 @@ function requestedUrl( if (config === undefined) { return ''; } + let uri: unknown; try { - return (axiosInstance.getUri({ ...config, params: null }) as string | undefined) ?? ''; + uri = axiosInstance.getUri({ ...config, params: null }); } catch { - return config.url ?? ''; + uri = config.url; } + return uri == null ? '' : String(uri); } export class AxiosLoggingInterceptor { @@ -28,11 +31,14 @@ export class AxiosLoggingInterceptor { axiosInstance.interceptors.request.use( function (request: InternalAxiosRequestConfig) { request.headers = request.headers || {}; // Ensure headers are not undefined - logger.debug( - `Sending HTTP request: ${request?.method?.toUpperCase()} ${redactUrl( - requestedUrl(axiosInstance, request), - )}`, - ); + // Built only when it's logged, so a request at another level pays nothing for it. + if (logger.isLevelEnabled('debug')) { + logger.debug( + `Sending HTTP request: ${request?.method?.toUpperCase()} ${redactUrl( + requestedUrl(axiosInstance, request), + )}`, + ); + } return request; }, function (error: any) { @@ -44,11 +50,13 @@ export class AxiosLoggingInterceptor { // Add a response interceptor axiosInstance.interceptors.response.use( function (response: AxiosResponse) { - logger.debug( - `Received HTTP response: ${response?.config?.method?.toUpperCase()} ${redactUrl( - requestedUrl(axiosInstance, response?.config), - )}, status: ${response?.status}`, - ); + if (logger.isLevelEnabled('debug')) { + logger.debug( + `Received HTTP response: ${response?.config?.method?.toUpperCase()} ${redactUrl( + requestedUrl(axiosInstance, response?.config), + )}, status: ${response?.status}`, + ); + } return response; }, function (error) { From 70591e26eaad6e25a18bde9e0ba208cfe64bb92f Mon Sep 17 00:00:00 2001 From: eli Date: Fri, 30 Oct 2026 13:48:11 -0500 Subject: [PATCH 17/17] PER-16493: the err serializer makes config.url a string too Co-Authored-By: Claude Opus 5.5 --- src/logger.ts | 2 +- src/tests/unit/logger.spec.ts | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/logger.ts b/src/logger.ts index 74bf5f07..0170ae5e 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -21,7 +21,7 @@ export function serializeError(error: unknown): unknown { code: error.code, status: error.response?.status, method: error.config?.method?.toUpperCase(), - url: error.config?.url === undefined ? undefined : redactUrl(error.config.url), + url: error.config?.url == null ? undefined : redactUrl(String(error.config.url)), }; } // Any other error is copied field by field. Node's ERR_INVALID_URL, which axios rejects with diff --git a/src/tests/unit/logger.spec.ts b/src/tests/unit/logger.spec.ts index 949ab92a..4f6e4fb6 100644 --- a/src/tests/unit/logger.spec.ts +++ b/src/tests/unit/logger.spec.ts @@ -302,3 +302,23 @@ test('the HTTP lines are not built when debug is off', async (t) => { t.is(built, 0); }); + +for (const [name, url, expected] of [ + [ + 'a URL object', + new URL('http://user:password@pdp.example.com:7766/allowed?sig=query-secret'), + 'http://pdp.example.com:7766/allowed', + ], + ['a number', 42, '42'], + ['null', null, undefined], +] as const) { + test(`an axios error whose config.url is ${name} is still logged`, (t) => { + const error = axiosErrorWithTheToken(); + (error.config as { url?: unknown }).url = url; + + const serialized = serializeError(error) as Record; + + t.is(serialized.url, expected); + t.false(JSON.stringify(serialized).includes('password')); + }); +}