diff --git a/packages/drivers/src/snowflake-key.ts b/packages/drivers/src/snowflake-key.ts new file mode 100644 index 0000000000..31d7cefb4b --- /dev/null +++ b/packages/drivers/src/snowflake-key.ts @@ -0,0 +1,110 @@ +/** + * Private-key handling for Snowflake key-pair auth. + * + * Users paste keys in many shapes: real multi-line PEM, single-line values with + * literal `\n` sequences, bodies whose line breaks became spaces, CRLF files, + * values wrapped in quotes. This module normalizes all of them back to a + * canonical PEM and converts every supported key format to the unencrypted + * PKCS#8 PEM that snowflake-sdk expects. Error messages never include key + * material or the underlying OpenSSL text. + */ + +import * as crypto from "crypto" + +const PEM_BLOCK = /-----BEGIN ([A-Z0-9 ]+?)-----([\s\S]*?)-----END \1-----/g + +export interface NormalizedKey { + pem: string + label: string + /** True for legacy PKCS#1 (traditional) PEM encryption headers. */ + legacyEncrypted: boolean +} + +function chunk64(body: string): string { + return body.match(/.{1,64}/g)?.join("\n") ?? "" +} + +/** + * Rebuild a canonical PEM from a pasted value. Returns undefined when no + * BEGIN/END block can be found. + */ +export function normalizePrivateKeyPem(raw: string): NormalizedKey | undefined { + let text = raw.trim() + // Strip surrounding quotes (possibly repeated, e.g. JSON inside env files). + while (text.length >= 2 && (text[0] === '"' || text[0] === "'") && text[text.length - 1] === text[0]) { + text = text.slice(1, -1).trim() + } + text = text.replace(/\\r\\n|\\n|\\r/g, "\n").replace(/\r\n?/g, "\n") + + // A pasted file may hold other blocks (certificates, public key) before the + // private key; use the first block that is a private key. + const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) + if (!match) return undefined + const label = match[1] + let inner = match[2] + + // Legacy encryption headers, either on their own lines or space-joined. + let procType: string | undefined + let dekInfo: string | undefined + inner = inner.replace(/Proc-Type:\s*([^\s]+)/i, (_m, v: string) => { + procType = v + return " " + }) + inner = inner.replace(/DEK-Info:\s*([^\s]+)/i, (_m, v: string) => { + dekInfo = v + return " " + }) + + const body = inner.replace(/\s+/g, "") + const lines = [`-----BEGIN ${label}-----`] + if (procType || dekInfo) { + if (procType) lines.push(`Proc-Type: ${procType}`) + if (dekInfo) lines.push(`DEK-Info: ${dekInfo}`) + lines.push("") + } + lines.push(chunk64(body), `-----END ${label}-----`, "") + return { + pem: lines.join("\n"), + label, + legacyEncrypted: !!procType && /ENCRYPTED/i.test(procType), + } +} + +/** + * Convert any supported private key text into an unencrypted PKCS#8 PEM. + * Supports unencrypted PKCS#1/PKCS#8/SEC1, encrypted PKCS#8, and legacy + * encrypted PKCS#1 (Proc-Type/DEK-Info). + */ +export function toPkcs8Pem(raw: string, passphrase?: string): string { + const normalized = normalizePrivateKeyPem(raw) + if (!normalized || !/PRIVATE KEY$/.test(normalized.label)) { + throw new Error( + "Snowflake private key format is not recognized. Provide a PEM private key " + + "('-----BEGIN PRIVATE KEY-----', '-----BEGIN ENCRYPTED PRIVATE KEY-----' or '-----BEGIN RSA PRIVATE KEY-----').", + ) + } + const pass = passphrase && passphrase.length > 0 ? passphrase : undefined + const encrypted = normalized.label === "ENCRYPTED PRIVATE KEY" || normalized.legacyEncrypted + + if (encrypted && !pass) { + throw new Error( + "Snowflake private key is encrypted; set the passphrase (private_key_passphrase) to decrypt it.", + ) + } + + try { + const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass }) + return keyObject.export({ type: "pkcs8", format: "pem" }).toString() + } catch { + if (encrypted) { + throw new Error( + "Snowflake: failed to decrypt the private key. The passphrase (private_key_passphrase) is incorrect, " + + "or the key is corrupted or uses an unsupported cipher.", + ) + } + throw new Error( + "Snowflake private key could not be parsed. It may be truncated, corrupted, or in an unsupported format; " + + "use an RSA key in PKCS#8 or PKCS#1 PEM form.", + ) + } +} diff --git a/packages/drivers/src/snowflake.ts b/packages/drivers/src/snowflake.ts index ec1caf2277..24aba33688 100644 --- a/packages/drivers/src/snowflake.ts +++ b/packages/drivers/src/snowflake.ts @@ -4,6 +4,7 @@ import * as fs from "fs" import type { ConnectionConfig, Connector, ConnectorResult, ExecuteOptions, SchemaColumn } from "./types" +import { toPkcs8Pem } from "./snowflake-key" import { loadOptionalDriver } from "./resolve" import { emitBrowserSignIn, openInBrowser } from "./sign-in" import { emitReconnect, type ReconnectEvent } from "./reconnect-events" @@ -614,35 +615,11 @@ export async function connect( keyContent = fs.readFileSync(resolvedKeyPath, "utf-8") } else { keyContent = resolvedInlineKey! - // Normalize escaped newlines from env vars / JSON configs - if (keyContent.includes("\\n")) { - keyContent = keyContent.replace(/\\n/g, "\n") - } } - // If key is encrypted, decrypt using Node crypto — - // snowflake-sdk expects unencrypted PKCS#8 PEM. - let privateKey: string - if (keyPassphrase || keyContent.includes("ENCRYPTED")) { - const crypto = await import("crypto") - try { - const keyObject = crypto.createPrivateKey({ - key: keyContent, - format: "pem", - passphrase: keyPassphrase || undefined, - }) - privateKey = keyObject - .export({ type: "pkcs8", format: "pem" }) - .toString() - } catch (e) { - const msg = e instanceof Error ? e.message : String(e) - throw new Error( - `Snowflake: Failed to decrypt private key. Verify the passphrase and key format (must be PEM/PKCS#8). ${msg}`, - ) - } - } else { - privateKey = keyContent - } + // Normalize pasted formats and convert to the unencrypted PKCS#8 PEM + // snowflake-sdk expects. + const privateKey = toPkcs8Pem(keyContent, keyPassphrase) options.authenticator = "SNOWFLAKE_JWT" options.privateKey = privateKey diff --git a/packages/drivers/test/snowflake-key.test.ts b/packages/drivers/test/snowflake-key.test.ts new file mode 100644 index 0000000000..db528c7740 --- /dev/null +++ b/packages/drivers/test/snowflake-key.test.ts @@ -0,0 +1,159 @@ +import { describe, expect, test } from "bun:test" +import { generateKeyPairSync, createPrivateKey } from "node:crypto" +import { normalizePrivateKeyPem, toPkcs8Pem } from "../src/snowflake-key" + +const PASS = "test-pass-phrase" + +const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 }) +const fingerprint = (pem: string) => + createPrivateKey(pem).export({ type: "pkcs8", format: "der" }).toString("base64") +const expected = fingerprint(rsa.privateKey.export({ type: "pkcs8", format: "pem" }) as string) + +const pkcs8 = rsa.privateKey.export({ type: "pkcs8", format: "pem" }) as string +const pkcs1 = rsa.privateKey.export({ type: "pkcs1", format: "pem" }) as string +const pkcs8Enc = rsa.privateKey.export({ type: "pkcs8", format: "pem", cipher: "aes-256-cbc", passphrase: PASS }) as string +const pkcs1Enc = rsa.privateKey.export({ type: "pkcs1", format: "pem", cipher: "aes-256-cbc", passphrase: PASS }) as string + +const spaced = (pem: string) => pem.trim().replace(/\r?\n/g, " ") +const escaped = (pem: string) => pem.trim().replace(/\n/g, "\\n") + +describe("toPkcs8Pem", () => { + const plain: Record = { pkcs8, pkcs1 } + for (const [name, pem] of Object.entries(plain)) { + const variants: Record = { + multiline: pem, + crlf: pem.replace(/\n/g, "\r\n"), + "space-separated": spaced(pem), + "escaped newlines": escaped(pem), + quoted: `"${escaped(pem)}"`, + "single quoted multiline": `'${pem}'`, + } + for (const [variant, text] of Object.entries(variants)) { + test(`unencrypted ${name} (${variant})`, () => { + expect(fingerprint(toPkcs8Pem(text))).toBe(expected) + }) + } + } + + const encrypted: Record = { "encrypted pkcs8": pkcs8Enc, "legacy encrypted pkcs1": pkcs1Enc } + for (const [name, pem] of Object.entries(encrypted)) { + const variants: Record = { + multiline: pem, + crlf: pem.replace(/\n/g, "\r\n"), + "space-separated": spaced(pem), + "escaped newlines": escaped(pem), + } + for (const [variant, text] of Object.entries(variants)) { + test(`${name} with passphrase (${variant})`, () => { + const out = toPkcs8Pem(text, PASS) + expect(out).toContain("-----BEGIN PRIVATE KEY-----") + expect(fingerprint(out)).toBe(expected) + }) + } + + test(`${name} without passphrase gives an actionable error`, () => { + expect(() => toPkcs8Pem(pem)).toThrow(/encrypted; set the passphrase/) + expect(() => toPkcs8Pem(spaced(pem), "")).toThrow(/encrypted; set the passphrase/) + }) + + test(`${name} with wrong passphrase leaks no key material`, () => { + let msg = "" + try { + toPkcs8Pem(pem, "wrong") + } catch (e) { + msg = (e as Error).message + } + expect(msg).toMatch(/passphrase .* incorrect/) + expect(msg).not.toMatch(/DECODER|bad decrypt|wrong/) + const bodyLines = pem.split("\n").filter((l) => /^[A-Za-z0-9+/=]{40,}$/.test(l)) + expect(bodyLines.length).toBeGreaterThan(0) + for (const line of bodyLines) expect(msg).not.toContain(line) + }) + } + + test("unencrypted key with an unneeded passphrase still works", () => { + expect(fingerprint(toPkcs8Pem(pkcs8, PASS))).toBe(expected) + }) + + test("non-PEM text is rejected without echoing it", () => { + expect(() => toPkcs8Pem("super-secret-token")).toThrow(/not recognized/) + try { + toPkcs8Pem("super-secret-token") + } catch (e) { + expect((e as Error).message).not.toContain("super-secret-token") + } + }) + + test("corrupted body gives a parse error without key material", () => { + const bad = "-----BEGIN PRIVATE KEY-----\nQUJDREVGR0hJSktMTU5PUA==\n-----END PRIVATE KEY-----" + expect(() => toPkcs8Pem(bad)).toThrow(/could not be parsed/) + }) + + test("a private key after other PEM blocks is found", () => { + const pub = rsa.publicKey.export({ type: "spki", format: "pem" }) as string + expect(fingerprint(toPkcs8Pem(`${pub}\n${pkcs8}`))).toBe(expected) + expect(fingerprint(toPkcs8Pem(spaced(`${pub}\n${pkcs8}`)))).toBe(expected) + expect(fingerprint(toPkcs8Pem(`${pub}\n${pkcs8Enc}`, PASS))).toBe(expected) + }) + + test("public key PEM is not accepted as a private key", () => { + const pub = rsa.publicKey.export({ type: "spki", format: "pem" }) as string + expect(() => toPkcs8Pem(pub)).toThrow(/not recognized/) + }) +}) + +describe("normalizePrivateKeyPem", () => { + test("rebuilds 64-char lines between markers", () => { + const out = normalizePrivateKeyPem(spaced(pkcs8))!.pem.trim().split("\n") + expect(out[0]).toBe("-----BEGIN PRIVATE KEY-----") + expect(out[out.length - 1]).toBe("-----END PRIVATE KEY-----") + for (const l of out.slice(1, -2)) expect(l.length).toBe(64) + }) + + test("keeps legacy headers on their own lines followed by a blank line", () => { + const out = normalizePrivateKeyPem(spaced(pkcs1Enc))! + expect(out.legacyEncrypted).toBe(true) + expect(out.pem).toMatch(/Proc-Type: 4,ENCRYPTED\nDEK-Info: [^\n]+\n\n/) + }) +}) + +describe("snowflake connect() key-pair wiring", () => { + const { connect } = require("../src/snowflake") as typeof import("../src/snowflake") + function fakeSdk() { + const created: any[] = [] + return { + created, + sdk: { + configure() {}, + createConnection(options: any) { + created.push(options) + return { connect: (cb: (e: Error | null) => void) => cb(null), isUp: () => true, execute() {}, destroy: (cb: any) => cb(null) } + }, + }, + } + } + const base = { type: "snowflake", account: "acme-xy123", user: "u" } as any + + const cases: Array<[string, string, string | undefined]> = [ + ["space-separated pkcs8", spaced(pkcs8), undefined], + ["escaped pkcs1", escaped(pkcs1), undefined], + ["encrypted pkcs8, spaces", spaced(pkcs8Enc), PASS], + ["legacy encrypted pkcs1, spaces", spaced(pkcs1Enc), PASS], + ] + for (const [name, key, pass] of cases) { + test(`passes an unencrypted PKCS#8 key to the SDK: ${name}`, async () => { + const { sdk, created } = fakeSdk() + const c = await connect({ ...base, private_key: key, private_key_passphrase: pass }, sdk as any) + await c.connect() + expect(created[0].authenticator).toBe("SNOWFLAKE_JWT") + expect(fingerprint(created[0].privateKey)).toBe(expected) + expect(created[0].privateKey).toContain("-----BEGIN PRIVATE KEY-----") + }) + } + + test("encrypted key without a passphrase is a clear error", async () => { + const { sdk } = fakeSdk() + const c = await connect({ ...base, private_key: pkcs8Enc }, sdk as any) + await expect(c.connect()).rejects.toThrow(/encrypted; set the passphrase/) + }) +})