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
110 changes: 110 additions & 0 deletions packages/drivers/src/snowflake-key.ts
Original file line number Diff line number Diff line change
@@ -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]))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (edge input, not blocking): the first *PRIVATE KEY block wins even when it can't be used. If an unusable private-key block (for example -----BEGIN OPENSSH PRIVATE KEY-----) comes before a valid PKCS#8 key in the same value and a passphrase is set, main's parser skipped it and connected. Head picks the OpenSSH block and throws "could not be parsed". Without a passphrase, main also failed (the SDK only accepts text starting with -----BEGIN PRIVATE KEY-----), so only the passphrase-set case regresses. This needs two private keys pasted into one value, which is an edge case. A possible follow-up: try each private-key block in turn and keep the first one that parses.

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, "")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (edge input, not blocking): extra legacy PEM headers end up in the base64 body. Only Proc-Type and DEK-Info are taken out before whitespace is stripped. Any other RFC 1421 header line before the blank line (for example Comment: hello) gets folded into the body, so decryption fails. Repro: an AES-256-CBC legacy PKCS#1 key with \nComment: hello inserted after DEK-Info, with the correct passphrase. Main decrypts it and returns the matching key; head throws "failed to decrypt the private key". openssl, ssh-keygen and the Snowflake docs commands never write such a header, so this is an edge case. A safe follow-up is to drop any Name: value line in the header area, not just these two.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (edge input, pre-existing, not blocking): a key encrypted with an empty passphrase can't be used. passphrase: "" is treated as no passphrase, so a key encrypted with "" gets "key is encrypted; set the passphrase". crypto.createPrivateKey({ key, passphrase: "" }) would decrypt it. Main fails this case too. It is very rare.

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 })

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (not blocking, same as main): EC (SEC1 and PKCS#8), Ed25519 and DSA keys pass here with no local message. They are converted to PKCS#8 and handed to the SDK. snowflake-sdk 2.x then signs the JWT with RS256 through jsonwebtoken, which rejects a non-RSA key, so the user never sees this module's "use an RSA key" hint. Snowflake accepts only RSA keys. A short keyObject.asymmetricKeyType !== "rsa" check with a fixed message would make this clear. I understand the reply that rejecting key types is out of scope; this is a follow-up, not a block.

return keyObject.export({ type: "pkcs8", format: "pem" }).toString()
} catch {
if (encrypted) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (Node/Bun limitation, not blocking): an unsupported encryption scheme gets the wrong-passphrase message. PKCS#8 encrypted with PBES1 PBE-MD5-DES (openssl pkcs8 -topk8 -v1 PBE-MD5-DES) cannot be decoded by Bun (BoringSSL) or Node 26 (OpenSSL 3.5, legacy provider off). The user gets "The passphrase ... is incorrect, or the key is corrupted or uses an unsupported cipher" even when the passphrase is right. The message does mention an unsupported cipher, but it does not name the scheme. Under Bun, these all decode correctly: PBES2 AES-256/AES-128/DES-EDE3, PBES1 PBE-SHA1-3DES, and legacy AES-128-CBC/AES-256-CBC/DES-EDE3-CBC. A follow-up could suggest re-encrypting with openssl pkcs8 -topk8 -v2 aes-256-cbc.

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.",
)
}
Comment on lines +95 to +109

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: toPkcs8Pem accepts any private key that Node can parse, including EC/DSA keys and RSA keys smaller than 2048 bits. Snowflake key-pair authentication requires at least a 2048-bit RSA key, so these inputs reach SNOWFLAKE_JWT and fail later in the SDK; validate asymmetricKeyType and modulusLength before exporting.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/drivers/src/snowflake-key.ts, line 95:

<comment>`toPkcs8Pem` accepts any private key that Node can parse, including EC/DSA keys and RSA keys smaller than 2048 bits. Snowflake key-pair authentication requires at least a 2048-bit RSA key, so these inputs reach `SNOWFLAKE_JWT` and fail later in the SDK; validate `asymmetricKeyType` and `modulusLength` before exporting.</comment>

<file context>
@@ -0,0 +1,110 @@
+    )
+  }
+
+  try {
+    const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })
+    return keyObject.export({ type: "pkcs8", format: "pem" }).toString()
</file context>
Suggested change
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.",
)
}
let keyObject: crypto.KeyObject
try {
keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })
} 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.",
)
}
const modulusLength = keyObject.asymmetricKeyDetails?.modulusLength ?? 0
if (keyObject.asymmetricKeyType !== "rsa" || modulusLength < 2048) {
throw new Error("Snowflake private key must be an RSA key with at least 2048 bits.")
}
return keyObject.export({ type: "pkcs8", format: "pem" }).toString()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this here: the issue is about reading pasted formats, and rejecting other key types or sizes could break keys that work today. The SDK and Snowflake already report an unsupported key type or size when connecting.

}
31 changes: 4 additions & 27 deletions packages/drivers/src/snowflake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
159 changes: 159 additions & 0 deletions packages/drivers/test/snowflake-key.test.ts
Original file line number Diff line number Diff line change
@@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (test-only, not blocking): the fixtures cover one 2048-bit RSA key and one cipher. No test covers: extra legacy headers, an unusable private-key block before a valid one, 1024/4096-bit keys, other ciphers, or connect() with inline text that has no -----BEGIN. Mutation results: removing the quote-strip loop, or keeping spaces inside the body (removing only newlines), passes all 36 tests. Both are redundant in practice (details in the PR comment). Removing the Proc-Type/DEK-Info handling fails 6-8 tests, removing the literal-escape conversion fails 7, and taking the first PEM block of any kind fails 1.

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<string, string> = { pkcs8, pkcs1 }
for (const [name, pem] of Object.entries(plain)) {
const variants: Record<string, string> = {
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<string, string> = { "encrypted pkcs8": pkcs8Enc, "legacy encrypted pkcs1": pkcs1Enc }
for (const [name, pem] of Object.entries(encrypted)) {
const variants: Record<string, string> = {
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/)
})
})
Loading