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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ dist
/.eslintcache
.vscode/
manually-test-on-heroku.js
*.tsbuildinfo
2 changes: 1 addition & 1 deletion packages/pg-native/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
},
"homepage": "https://github.com/supabase/node-postgres/tree/master/packages/pg-native",
"dependencies": {
"libpq": "^1.11.0",
"libpq": "^1.8.15",
"pg-types": "2.2.0"
},
"devDependencies": {
Expand Down
30 changes: 29 additions & 1 deletion packages/pg/lib/crypto/sasl.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,34 @@
const crypto = require('./utils')
const { signatureAlgorithmHashFromCertificate } = require('./cert-signatures')

// SASLprep (RFC 4013) — minimal in-tree implementation.
//
// Per RFC 5802 §2.2, the SCRAM-SHA-256 client must normalize the password via
// SASLprep before feeding it into PBKDF2. PostgreSQL's server applies the same
// SASLprep when computing the stored verifier, and libpq does the same client
// side, so passwords whose NFKC form differs from the raw form
// would otherwise authenticate against psql/libpq but fail against pg with `28P01`.
//
// We deliberately implement only the three steps that change the byte content:
// 1. RFC 3454 Table C.1.2 (non-ASCII space) → U+0020 SPACE.
// 2. RFC 3454 Table B.1 (commonly mapped to nothing) → empty.
// 3. NFKC normalization.
// We skip the prohibition (RFC 4013 §2.3) and bidi (RFC 3454 §6) checks.
// libpq is forgiving on those paths and Postgres's own SASLprep matches that
// leniency for legacy roles, so omitting the rejection logic keeps existing
// roles working without adding complexity.
function saslprep(password) {
// RFC 3454 Table C.1.2 — non-ASCII space characters, mapped to U+0020.
const nonAsciiSpace = /[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g
// RFC 3454 Table B.1 — "commonly mapped to nothing". The set intentionally
// contains zero-width joiners and variation selectors — the very characters
// ESLint's no-misleading-character-class warns about — because they combine
// with their neighbors and the RFC strips them for that reason.
// eslint-disable-next-line no-misleading-character-class
const mappedToNothing = /[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g
return password.replace(nonAsciiSpace, ' ').replace(mappedToNothing, '').normalize('NFKC')
}

function startSession(mechanisms, stream) {
const candidates = ['SCRAM-SHA-256']
if (stream) candidates.unshift('SCRAM-SHA-256-PLUS') // higher-priority, so placed first
Expand Down Expand Up @@ -70,7 +98,7 @@ async function continueSession(session, password, serverData, stream) {
const authMessage = clientFirstMessageBare + ',' + serverFirstMessage + ',' + clientFinalMessageWithoutProof

const saltBytes = Buffer.from(sv.salt, 'base64')
const saltedPassword = await crypto.deriveKey(password, saltBytes, sv.iteration)
const saltedPassword = await crypto.deriveKey(saslprep(password), saltBytes, sv.iteration)
const clientKey = await crypto.hmacSha256(saltedPassword, 'Client Key')
const storedKey = await crypto.sha256(clientKey)
const clientSignature = await crypto.hmacSha256(storedKey, authMessage)
Expand Down
2 changes: 1 addition & 1 deletion packages/pg/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@supabase/pg",
"version": "8.21.0",
"version": "8.21.1",
"description": "PostgreSQL client - pure javascript & libpq with the same API",
"keywords": [
"database",
Expand Down
29 changes: 2 additions & 27 deletions packages/pg/test/integration/client/promise-api-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,6 @@ suite.test('valid connection completes promise', () => {
})
})

suite.test('valid connection completes promise', () => {
const client = new pg.Client()
return client.connect().then(() => {
return client.end().then(() => {})
})
})

suite.test('valid connection returns the client in a promise', () => {
const client = new pg.Client()
return client.connect().then((clientInside) => {
Expand All @@ -28,25 +21,7 @@ suite.test('valid connection returns the client in a promise', () => {
})
})

suite.test('invalid connection rejects promise', (done) => {
suite.test('invalid connection rejects promise', async () => {
const client = new pg.Client({ host: 'alksdjflaskdfj', port: 1234 })
return client.connect().catch((e) => {
assert(e instanceof Error)
done()
})
})

suite.test('connected client does not reject promise after connection', (done) => {
const client = new pg.Client()
return client.connect().then(() => {
setTimeout(() => {
client.on('error', (e) => {
assert(e instanceof Error)
client.end()
done()
})
// manually kill the connection
client.emit('error', new Error('something bad happened...but not really'))
}, 50)
})
await assert.rejects(client.connect(), Error)
})
79 changes: 79 additions & 0 deletions packages/pg/test/integration/client/sasl-scram-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,82 @@ suite.test('sasl/scram fails when password is empty', async () => {
)
assert.ok(usingSasl, 'Should be using SASL for authentication')
})

/**
* SASLprep regression coverage. RFC 5802 / RFC 4013 require the SCRAM client
* to normalize the password (B.1 mapping → NFKC → prohibition + bidi check)
* before feeding it into PBKDF2. PostgreSQL's server applies the same
* SASLprep when computing the verifier, so any password whose NFKC form
* differs from the raw form would otherwise authenticate against psql/libpq
* but fail against pg with `28P01`.
*
* To exercise these tests, provision a role whose password contains an
* NFKC-asymmetric character. For example, in psql:
*
* SET password_encryption = 'scram-sha-256';
* CREATE ROLE scram_unicode_test LOGIN PASSWORD U&'IX-\2168';
*
* `\2168` is ROMAN NUMERAL IX; the server SASLprep-normalizes this to
* `IX-IX` when computing the verifier. Then export:
*
* SCRAM_TEST_PGUSER_UNICODE=scram_unicode_test
* SCRAM_TEST_PGPASSWORD_UNICODE='IX-\u2168' (i.e. the raw form)
*
* If either env var is unset the suite is skipped, matching the convention
* of the ASCII SCRAM block above.
*/
const unicodeConfig = {
user: process.env.SCRAM_TEST_PGUSER_UNICODE,
password: process.env.SCRAM_TEST_PGPASSWORD_UNICODE,
host: process.env.SCRAM_TEST_PGHOST,
port: process.env.SCRAM_TEST_PGPORT,
database: process.env.SCRAM_TEST_PGDATABASE,
}

if (!unicodeConfig.user || !unicodeConfig.password) {
suite.test('skipping SCRAM unicode tests (missing env)', () => {})
} else {
suite.test('sasl/scram authenticates a password requiring SASLprep (raw form)', async () => {
const client = new pg.Client(unicodeConfig)
let usingSasl = false
client.connection.once('authenticationSASL', () => {
usingSasl = true
})
await client.connect()
assert.ok(usingSasl, 'Should be using SASL for authentication')
await client.end()
})

suite.test('sasl/scram authenticates the NFKC-equivalent ASCII form of the same password', async () => {
// The unicode password contains a codepoint that NFKC-decomposes to ASCII
// (e.g. U+2168 → "IX"). The server stored the verifier from the
// SASLprep'd ASCII form, so feeding the client the ASCII form directly
// must also authenticate. This proves that the prep step is symmetric:
// any NFKC-equivalent representation reaches the same PBKDF2 input.
const client = new pg.Client({
...unicodeConfig,
password: unicodeConfig.password.normalize('NFKC'),
})
await client.connect()
await client.end()
})

suite.test('sasl/scram fails when unicode password is wrong', async () => {
const client = new pg.Client({
...unicodeConfig,
password: unicodeConfig.password + 'append-something-to-make-it-bad',
})
let usingSasl = false
client.connection.once('authenticationSASL', () => {
usingSasl = true
})
await assert.rejects(
() => client.connect(),
{
code: '28P01',
},
'Error code should be for a password error'
)
assert.ok(usingSasl, 'Should be using SASL for authentication')
})
}
8 changes: 6 additions & 2 deletions packages/pg/test/integration/gh-issues/3174-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ const testErrorBuffer = (bufferName, errorBuffer) => {
if (!cli.native) {
assert(errorHit)
// further queries on the client should fail since its in an invalid state
await assert.rejects(() => client.query('SELECTR NOW()'), 'Further queries on the client should reject')
await assert.rejects(client.query('SELECT NOW()'), {
message: 'Client has encountered a connection error and is not queryable',
})
}

await closeServer()
Expand All @@ -129,7 +131,9 @@ const testErrorBuffer = (bufferName, errorBuffer) => {
if (!cli.native) {
assert(errorHit)
// further queries on the client should fail since its in an invalid state
await assert.rejects(() => client.query('SELECTR NOW()'), 'Further queries on the client should reject')
await assert.rejects(client.query('SELECT NOW()'), {
message: 'Client has encountered a connection error and is not queryable',
})
}

await client.end()
Expand Down
Loading