Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/sql-pg-cache-salted-password.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@effect/sql-pg": patch
---

Reuse SCRAM-SHA-256 salted passwords when the password, salt and iteration count match. A bounded cache avoids repeating PBKDF2 while keeping proofs and server signature verification specific to each exchange.
24 changes: 21 additions & 3 deletions packages/sql/pg/src/PgAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ const textEncoder = new TextEncoder()
const textDecoder = new TextDecoder("utf-8", { fatal: true })
/** Bounds synchronous PBKDF2 work requested by an untrusted server. */
const maxScramIterations = 1_000_000
/** Bounds the SaltedPassword values retained across SCRAM exchanges. */
const maxCachedSaltedPasswords = 16
const saltedPasswords = new Map<string, Uint8Array>()

const bytesOf = (value: Uint8Array): Uint8Array => Uint8Array.from(value)

Expand Down Expand Up @@ -261,9 +264,24 @@ const scramContinueUnsafe = (
return fail(`Invalid SCRAM iteration count: ${iterationText}`)
}

const saltedPassword = bytesOf(
pbkdf2Sync(textEncoder.encode(state.password), salt, iterations, 32, "sha256")
)
// RFC 5802 allows clients to reuse SaltedPassword for the same derivation inputs.
// Prefix the salt with its length and hash the tuple to keep keys fixed-size without storing plaintext passwords.
const password = textEncoder.encode(state.password)
const cacheKey = createHash("sha256")
.update(`${iterations}:${salt.length}:`)
.update(salt)
.update(password)
.digest("hex")
let saltedPassword = saltedPasswords.get(cacheKey)
if (saltedPassword === undefined) {
saltedPassword = bytesOf(pbkdf2Sync(password, salt, iterations, 32, "sha256"))
if (saltedPasswords.size === maxCachedSaltedPasswords) {
const oldest = saltedPasswords.keys().next()
if (!oldest.done) saltedPasswords.delete(oldest.value)
}
saltedPasswords.set(cacheKey, saltedPassword)
}

const clientKey = hmacSha256(saltedPassword, textEncoder.encode("Client Key"))
const storedKey = sha256(clientKey)
const clientFinalMessageWithoutProof = `c=${CHANNEL_BINDING},r=${nonce}`
Expand Down
78 changes: 78 additions & 0 deletions packages/sql/pg/test/PgAuth.cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { PgAuth } from "@effect/sql-pg"
import { beforeEach, describe, expect, it } from "@effect/vitest"
import * as Result from "effect/Result"
import * as Crypto from "node:crypto"
import { vi } from "vitest"

vi.mock("node:crypto", async (importOriginal) => {
const crypto = await importOriginal<typeof Crypto>()
return { ...crypto, pbkdf2Sync: vi.fn(crypto.pbkdf2Sync) }
})

const encoder = new TextEncoder()
const decoder = new TextDecoder()

const exchange = (options: {
readonly password: string
readonly salt: string
readonly iterations: number
readonly nonce?: string
}) => {
const { iterations, nonce = "client", password, salt } = options
const { state } = Result.getOrThrow(PgAuth.scramInit({ password, nonce }))
const challenge = encoder.encode(`r=${nonce}server,s=${salt},i=${iterations}`)
return Result.getOrThrow(PgAuth.scramContinue(state, challenge))
}

describe("PgAuth SCRAM-SHA-256 salted password cache", { concurrent: false }, () => {
beforeEach(() => {
vi.mocked(Crypto.pbkdf2Sync).mockClear()
})

it("reuses the derivation while computing fresh proofs and signatures", () => {
const credentials = { password: "same-password", salt: "AQIDBA==", iterations: 2 }
const first = exchange(credentials)
const second = exchange({ ...credentials, nonce: "another-client" })

expect(Crypto.pbkdf2Sync).toHaveBeenCalledTimes(1)
expect(decoder.decode(second.response)).toContain("r=another-clientserver")
expect(decoder.decode(second.response).split(",p=")[1]).not.toBe(decoder.decode(first.response).split(",p=")[1])
expect(second.state.serverSignature).not.toEqual(first.state.serverSignature)
})

it("derives separately when the password, salt, or iteration count changes", () => {
const credentials = { password: "test:pássword", salt: "AA==", iterations: 2 }
const first = exchange(credentials)

const changed = [
{ ...credentials, password: "test:another-password" },
{ ...credentials, salt: "AQ==" },
{ ...credentials, iterations: 3 }
]
for (const [index, options] of changed.entries()) {
expect(exchange(options).state.serverSignature).not.toEqual(first.state.serverSignature)
expect(Crypto.pbkdf2Sync).toHaveBeenCalledTimes(index + 2)
}

expect(exchange(credentials)).toEqual(first)
expect(Crypto.pbkdf2Sync).toHaveBeenCalledTimes(4)
})

it("evicts the oldest entry when a seventeenth derivation is cached", () => {
const capacity = 16
const credentials = (index: number) => ({ password: `eviction-test:${index}`, salt: "AQIDBA==", iterations: 1 })

for (let index = 0; index < capacity; index++) {
exchange(credentials(index))
}
expect(Crypto.pbkdf2Sync).toHaveBeenCalledTimes(capacity)

exchange(credentials(capacity))
exchange(credentials(1))
exchange(credentials(capacity))
expect(Crypto.pbkdf2Sync).toHaveBeenCalledTimes(capacity + 1)

exchange(credentials(0))
expect(Crypto.pbkdf2Sync).toHaveBeenCalledTimes(capacity + 2)
})
})
Loading