Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
5c17048
PER-16493: log only the PDP and API URL when the client starts
EliMoshkovich Oct 27, 2026
bf111a5
PER-16493: review follow-ups: structured init fields, URL origins, pi…
EliMoshkovich Oct 27, 2026
3223122
PER-16493: second review pass: log axios errors without their config,…
EliMoshkovich Oct 28, 2026
8913b83
PER-16493: checkAllTenants sends its query as the body; API errors ke…
EliMoshkovich Oct 28, 2026
d17b3c5
PER-16493: redact the raw Authorization header line by line, not by r…
EliMoshkovich Oct 28, 2026
7aacac9
PER-16493: checkAllTenants errors keep no Authorization header; API e…
EliMoshkovich Oct 29, 2026
d8ad051
PER-16493: test that the SDK logger uses its err serializer and redac…
EliMoshkovich Oct 29, 2026
9801dc1
PER-16493: redactUrl drops the user info before the query; the init l…
EliMoshkovich Oct 29, 2026
e9d7882
PER-16493: checkAllTenants logs a failure once; error.request becomes…
EliMoshkovich Oct 29, 2026
943d546
PER-16493: the err serializer redacts a URL in an error's input field…
EliMoshkovich Oct 29, 2026
08494f3
PER-16493: redactUrl reads a valid URL as Node's parser does
EliMoshkovich Oct 29, 2026
1b9cc5a
PER-16493: redactUrl rebuilds an http(s) URL from the parsed URL
EliMoshkovich Oct 29, 2026
1e527da
PER-16493: the err serializer redacts input on a copy
EliMoshkovich Oct 29, 2026
f215370
PER-16493: HTTP debug lines log the URL a request goes to; pin the la…
EliMoshkovich Oct 30, 2026
f1f375c
PER-16493: build the logged URL without params, default it to ''; tes…
EliMoshkovich Oct 30, 2026
7441f37
PER-16493: the logged URL is always a string, and the HTTP lines are …
EliMoshkovich Oct 30, 2026
70591e2
PER-16493: the err serializer makes config.url a string too
EliMoshkovich Oct 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 62 additions & 2 deletions src/api/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,69 @@ interface FormattedAxiosError<T> {
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 live Node request object. Replace that header's value in
// 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<string, unknown> | 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') {
// 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');
}
for (const holder of [error, error.response]) {
Comment thread
EliMoshkovich marked this conversation as resolved.
Resolved
if (holder?.request !== undefined) {
let held: unknown = holder.request;
Object.defineProperty(holder, 'request', {
get: () => held,
set: (value: unknown) => {
held = value;
},
enumerable: false,
configurable: true,
});
}
}
}

export class PermitApiError<T> extends Error {
constructor(message: string, public originalError: AxiosError<T>) {
super(message);
// Not enumerable, so logging or inspecting the error prints the message, not the whole
// axios error. Still readable and writable as before; its Authorization header is redacted.
public originalError!: AxiosError<T>;

constructor(message: string, originalError: AxiosError<T>) {
// 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,
writable: true,
configurable: true,
});
}

public get formattedAxiosError(): FormattedAxiosError<T> {
Expand Down
10 changes: 7 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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',
Expand Down
37 changes: 25 additions & 12 deletions src/enforcement/enforcer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ 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';
import { redactUrl } from '../utils/redact-url';
import { resolveRetryConfig } from '../utils/retry';
import { AxiosRetryInterceptor } from '../utils/retry-interceptor';

Expand Down Expand Up @@ -253,7 +255,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`);
});
}
Expand Down Expand Up @@ -350,7 +352,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`);
});
}
Expand All @@ -362,22 +364,31 @@ export class Enforcer implements IEnforcer {
context: Context = {}, // default to empty context if not provided
sdk = 'node', // default to "node" if not provided
): Promise<TenantDetails[]> {
// 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<AllTenantsResponse>('/allowed/all-tenants', {
const response = await this.client.post<AllTenantsResponse>('allowed/all-tenants', input, {
Comment thread
EliMoshkovich marked this conversation as resolved.
Resolved
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);
// 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');
Comment thread
EliMoshkovich marked this conversation as resolved.
Resolved
throw error;
}
}
Expand Down Expand Up @@ -454,7 +465,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`);
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/enforcement/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export interface AllTenantsCheckResponse {
}

export interface AllTenantsResponse {
allowedTenants: AllTenantsCheckResponse[];
allowed_tenants: AllTenantsCheckResponse[];
}

interface TenantPermissions {
Expand Down
30 changes: 21 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string, unknown> {
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.
Expand Down Expand Up @@ -168,9 +186,7 @@ export class Permit implements IPermitClient {
this.enforcer = new Enforcer(this.config, this.logger);
this.elements = new ElementsClient(this.config, this.logger);

this.logger.debug(
`Permit.io SDK initialized with config:\n${JSON.stringify(this.config, undefined, 2)}`,
);
this.logger.debug(initLogFields(this.config), 'Permit.io SDK initialized');
}

/**
Expand Down Expand Up @@ -226,12 +242,8 @@ export class Permit implements IPermitClient {
context?: Context | undefined,
sdk?: string | undefined,
): Promise<TenantDetails[]> {
try {
return await this.enforcer.checkAllTenants(user, action, resource, context, sdk);
} catch (error) {
this.logger.error('Error fetching all tenants:', error);
throw error;
}
// The enforcer logs a failure, once, before rethrowing it.
return await this.enforcer.checkAllTenants(user, action, resource, context, sdk);
}

/**
Expand Down
53 changes: 49 additions & 4 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,65 @@
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 == null ? undefined : redactUrl(String(error.config.url)),
};
}
// 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') {
return { ...serialized, input: redactUrl(serialized.input) };
}
return serialized;
}

export class LoggerFactory {
static createLogger(config: IPermitConfig): pino.Logger {
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,
prettyPrint: config.log.json ? { levelFirst: true } : false,
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 `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',
'*.token',
'headers.Authorization',
'headers.authorization',
'*.headers.Authorization',
Comment thread
EliMoshkovich marked this conversation as resolved.
Resolved
'*.headers.authorization',
],
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);
}
}
Loading
Loading