Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .speakeasy/gen.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ typescript:
additionalPackageJSON:
license: Apache-2.0
additionalScripts:
test: npm run test:connect-environments
test: npm run test:connect-environments && npm run test:debug-logger
test:connect-environments: npm run build && node --test tests/connect-integration-resource-to-project.test.mjs
test:debug-logger: npm run build && node --test tests/debug-logger-redaction.test.mjs
alwaysIncludeInboundAndOutbound: false
apiPromiseHelpers: false
author: Speakeasy
Expand Down
21 changes: 21 additions & 0 deletions .speakeasy/patches/src/lib/sdks.ts.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
diff --git a/src/lib/sdks.ts b/src/lib/sdks.ts
index 19d9cf8ea..759c95f7a 100644
--- a/src/lib/sdks.ts
+++ b/src/lib/sdks.ts
@@ -2,6 +2,7 @@
* Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
*/

+import { redactDebugLogger } from "../hooks/debug-logger.js";
import { SDKHooks } from "../hooks/hooks.js";
import { HookContext } from "../hooks/types.js";
import {
@@ -110,7 +111,7 @@ export class ClientSDK {

this._options = { ...options, hooks: this.#hooks };

- this.#logger = this._options.debugLogger;
+ this.#logger = redactDebugLogger(this._options.debugLogger);
}

public _createRequest(
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@
"lint": "oxlint --max-warnings=0 --deny-warnings --no-error-on-unmatched-pattern src",
"build": "tsgo",
"prepublishOnly": "npm run build",
"test": "npm run test:connect-environments",
"test:connect-environments": "npm run build && node --test tests/connect-integration-resource-to-project.test.mjs"
"test": "npm run test:connect-environments && npm run test:debug-logger",
"test:connect-environments": "npm run build && node --test tests/connect-integration-resource-to-project.test.mjs",
"test:debug-logger": "npm run build && node --test tests/debug-logger-redaction.test.mjs"
},
"peerDependencies": {

Expand Down
84 changes: 84 additions & 0 deletions src/hooks/debug-logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { Logger } from "../lib/logger.js";

/*
* This file is not generated. `.speakeasy/patches/src/lib/sdks.ts.patch`
* wraps the caller's `debugLogger` with `redactDebugLogger` so the request and
* response logging in `src/lib/sdks.ts` never prints credentials.
*/

const REDACTED = "[REDACTED]";

const SENSITIVE_HEADERS = new Set([
"authorization",
"cookie",
"proxy-authorization",
"set-cookie",
"x-api-key",
]);

const SENSITIVE_KEY_SUFFIXES = [
"apikey",
"password",
"privatekey",
"secret",
"token",
];

// Header and multipart field lines are logged as a single "name: value" string.
const NAME_VALUE_LINE = /^([A-Za-z0-9_.-]+):\s/;

function isSensitiveKey(key: string): boolean {
const normalized = key.toLowerCase().replace(/[-_]/g, "");
return SENSITIVE_KEY_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
}

function redactLine(line: string): string {
const match = NAME_VALUE_LINE.exec(line);
const name = match?.[1];
if (!name) {
return line;
}
if (SENSITIVE_HEADERS.has(name.toLowerCase()) || isSensitiveKey(name)) {
return `${name}: ${REDACTED}`;
}
return line;
}

function redactValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(redactValue);
}
if (value === null || typeof value !== "object") {
return value;
}
const prototype = Object.getPrototypeOf(value);
if (prototype !== Object.prototype && prototype !== null) {
return value;
}
const redacted: Record<string, unknown> = {};
for (const [key, entry] of Object.entries(value)) {
redacted[key] = entry != null && isSensitiveKey(key)
? REDACTED
: redactValue(entry);
}
return redacted;
}

function redactArg(arg: unknown): unknown {
return typeof arg === "string" ? redactLine(arg) : redactValue(arg);
}

export function redactDebugLogger(
logger: Logger | undefined,
): Logger | undefined {
if (!logger) {
return undefined;
}
return {
group: (label?: string) =>
logger.group(label === undefined ? label : redactLine(label)),
groupEnd: () => logger.groupEnd(),
log: (message: any, ...args: any[]) =>
logger.log(redactArg(message), ...args.map(redactArg)),
};
}
3 changes: 2 additions & 1 deletion src/lib/sdks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
*/

import { redactDebugLogger } from "../hooks/debug-logger.js";
import { SDKHooks } from "../hooks/hooks.js";
import { HookContext } from "../hooks/types.js";
import {
Expand Down Expand Up @@ -110,7 +111,7 @@ export class ClientSDK {

this._options = { ...options, hooks: this.#hooks };

this.#logger = this._options.debugLogger;
this.#logger = redactDebugLogger(this._options.debugLogger);
}

public _createRequest(
Expand Down
118 changes: 118 additions & 0 deletions tests/debug-logger-redaction.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { inspect } from "node:util";
import test from "node:test";
import { Vercel } from "../esm/index.js";
import { HTTPClient } from "../esm/lib/http.js";

const API_TOKEN = "vercel_api_token_1234567890";
const WEBHOOK_SECRET = "webhook_signing_secret_1234567890";

function captureLogger() {
const lines = [];
const record = (...args) => {
lines.push(args.map((arg) => inspect(arg, { depth: null })).join(" "));
};
return {
lines,
logger: { group: record, groupEnd: () => {}, log: record },
};
}

function webhookClient() {
return new HTTPClient({
fetcher: async () =>
new Response(
JSON.stringify({
id: "account_hook_1234567890",
url: "https://example.com/webhook",
events: ["deployment.created"],
ownerId: "team_1234567890",
createdAt: 1234567890123,
updatedAt: 1234567890123,
secret: WEBHOOK_SECRET,
}),
{
status: 200,
headers: {
"content-type": "application/json",
"set-cookie": `session=${API_TOKEN}`,
},
},
),
});
}

test("redacts the API token and webhook secret from debug logs", async () => {
const { lines, logger } = captureLogger();
const vercel = new Vercel({
bearerToken: API_TOKEN,
httpClient: webhookClient(),
debugLogger: logger,
});

const result = await vercel.webhooks.createWebhook({
teamId: "team_1234567890",
requestBody: {
url: "https://example.com/webhook",
events: ["deployment.created"],
},
});

assert.equal(result.secret, WEBHOOK_SECRET);

const output = lines.join("\n");
assert.match(output, /authorization: \[REDACTED\]/i);
assert.match(output, /set-cookie: \[REDACTED\]/i);
assert.match(output, /secret: '\[REDACTED\]'/);
assert.match(output, /https:\/\/example\.com\/webhook/);
assert.doesNotMatch(output, new RegExp(API_TOKEN));
assert.doesNotMatch(output, new RegExp(WEBHOOK_SECRET));
});

test("redacts non-string values under secret-like keys", async () => {
const { lines, logger } = captureLogger();
const vercel = new Vercel({
bearerToken: API_TOKEN,
httpClient: new HTTPClient({
fetcher: async () =>
new Response(
JSON.stringify({
secret: 9876543210,
token: ["token_value_1", "token_value_2"],
clientSecret: { value: "nested_secret_value_1" },
url: "https://example.com/webhook",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
}),
debugLogger: logger,
});

await vercel.webhooks
.createWebhook({
teamId: "team_1234567890",
requestBody: {
url: "https://example.com/webhook",
events: ["deployment.created"],
},
})
.catch(() => {});

const output = lines.join("\n");
assert.match(output, /https:\/\/example\.com\/webhook/);
assert.doesNotMatch(output, /9876543210/);
assert.doesNotMatch(output, /token_value_/);
assert.doesNotMatch(output, /nested_secret_value_1/);
});

test("preserves the debug logger redaction across generations", async () => {
const patch = await readFile(
".speakeasy/patches/src/lib/sdks.ts.patch",
"utf8",
);
assert.match(patch, /redactDebugLogger\(this\._options\.debugLogger\)/);

const generatorConfig = await readFile(".speakeasy/gen.yaml", "utf8");
assert.match(generatorConfig, /tests\/debug-logger-redaction\.test\.mjs/);
});
Loading