diff --git a/.speakeasy/gen.yaml b/.speakeasy/gen.yaml index 3e469677c0..cbc079a8fb 100644 --- a/.speakeasy/gen.yaml +++ b/.speakeasy/gen.yaml @@ -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 diff --git a/.speakeasy/patches/src/lib/sdks.ts.patch b/.speakeasy/patches/src/lib/sdks.ts.patch new file mode 100644 index 0000000000..b3e1d73e7e --- /dev/null +++ b/.speakeasy/patches/src/lib/sdks.ts.patch @@ -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( diff --git a/package.json b/package.json index a091fc2e15..ef0502dd0a 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/hooks/debug-logger.ts b/src/hooks/debug-logger.ts new file mode 100644 index 0000000000..e92b03acce --- /dev/null +++ b/src/hooks/debug-logger.ts @@ -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 = {}; + 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)), + }; +} diff --git a/src/lib/sdks.ts b/src/lib/sdks.ts index 19d9cf8ea0..759c95f7a6 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( diff --git a/tests/debug-logger-redaction.test.mjs b/tests/debug-logger-redaction.test.mjs new file mode 100644 index 0000000000..0f6ceacc73 --- /dev/null +++ b/tests/debug-logger-redaction.test.mjs @@ -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/); +});