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
1 change: 1 addition & 0 deletions docs/pages/features/_meta.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export default {
transactions: 'Transactions',
types: 'Data Types',
ssl: 'SSL',
kerberos: 'Kerberos and GSS',
native: 'Native',
esm: 'ESM',
callbacks: 'Callbacks',
Expand Down
102 changes: 102 additions & 0 deletions docs/pages/features/kerberos.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
title: Kerberos and GSS authentication
---

The JavaScript driver can answer PostgreSQL GSSAPI and SSPI authentication requests
using the optional native `kerberos` package. The server selects the authentication
method; a database password is not required for ticket-based authentication.

This is **authentication support, not GSS transport encryption**. Configure TLS
with certificate verification to protect queries and results.

## Requirements

The `kerberos` native binding must be installed and loadable in the application
runtime. Linux and macOS use the system GSSAPI implementation; Windows uses SSPI.
If the package or native binding is unavailable, the connection rejects with an
actionable error. Ordinary password connections do not load the binding.

The OS must have appropriate credentials, such as a ticket acquired with `kinit`
on a GSSAPI system or the logged-in identity on Windows. PostgreSQL must map the
authenticated identity to the requested database role.

## Connection

```js
import fs from 'node:fs'
import pg from 'pg'

const client = new pg.Client({
host: 'database.example.test',
user: 'database_role',
database: 'app',
ssl: {
ca: fs.readFileSync('trusted-ca.pem', 'utf8'),
rejectUnauthorized: true,
},
connectionTimeoutMillis: 5000,
})

await client.connect()
console.log(await client.query('SELECT current_database()'))
await client.end()
```

Clients and pools use the same authentication implementation. Connections that
are already authenticated remain associated with that identity; new connections
use the credentials available when authentication starts. Close or replace a pool
when switching identities.

## Service identity and options

| Option | Environment default | Behavior |
| ------------ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `krbsrvname` | `PGKRBSRVNAME`, then `postgres` | Kerberos service name. |
| `gssHost` | Connection `host` | Database hostname used for the service identity. |
| `gsslib` | `PGGSSLIB` | Only the platform's binding is available: `sspi` on Windows and `gssapi` elsewhere. Alternate libraries are rejected. |
| `gssencmode` | `PGGSSENCMODE` | `require` rejects before connecting because the JavaScript driver does not implement GSS encryption. `prefer` does not enable GSS encryption; configure verified TLS separately. |

Explicit connection options override their environment defaults. This does not
implement all libpq environment variables, service files, or host-resolution
rules.

For an SSH tunnel or TCP proxy, the socket endpoint may be loopback while the
database service identity is not:

```js
const client = new pg.Client({
host: '127.0.0.1',
port: 15432,
gssHost: 'database.example.test',
user: 'database_role',
ssl: {
ca: fs.readFileSync('trusted-ca.pem', 'utf8'),
servername: 'database.example.test',
rejectUnauthorized: true,
},
})
```

The binding receives the platform-specific service identity derived from the
database hostname, not the tunnel address.

## GSSAPI versus SSPI

PostgreSQL AuthenticationGSS selects the Kerberos mechanism. AuthenticationSSPI
selects SPNEGO/Negotiate, which may negotiate Kerberos or NTLM on Windows. These
are distinct methods; SSPI success alone is not proof that Kerberos was used.

The driver serializes opaque binary continuation tokens and waits for both the
security context to finish and the server to accept authentication before
resolving `connect()`. It does not request credential delegation.

## Errors and cancellation

Unsupported or malformed protocol messages fail the connection, not the process.
Errors raised by application message callbacks, `connect()` callbacks or `connect`
event listeners remain application errors.

Use `connectionTimeoutMillis` to bound connection waiting. Ending or failing a
connecting client invalidates the GSS session, closes the socket, and suppresses
late authentication results. The native binding does not expose cancellation of
an OS security call already running; that work may finish later.
75 changes: 75 additions & 0 deletions packages/pg-protocol/src/inbound-parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -582,4 +582,79 @@ describe('PgPacketStream', function () {
parser.parse(oneFieldBuf, () => {})
assert.strictEqual((parser as any).reader.buffer.byteLength, 0)
})

for (const code of [2, 1234]) {
it(`closes the stream on unsupported authentication ${code}, including a split packet`, async function () {
const stream = new PassThrough()
const messages: BackendMessage[] = []
const errors: Error[] = []
stream.on('error', (error) => errors.push(error))
const closed = new Promise<void>((resolve) => stream.once('close', resolve))
parse(stream, (message) => messages.push(message))
const response = new BufferList().addInt32(code).join(true, 'R')

stream.write(Buffer.concat([authOkBuffer, response.subarray(0, 3)]))
stream.write(Buffer.concat([response.subarray(3), readyForQueryBuffer]))
await closed

assert.strictEqual(messages.length, 1)
assert.strictEqual(errors.length, 1)
assert.match(errors[0].message, new RegExp(`Unknown authenticationOk message type ${code}`))
assert.strictEqual(stream.destroyed, true)
})
}

it('does not catch exceptions thrown by the message callback', function () {
const stream = new PassThrough()
const failure = new Error('caller callback failed')
const errors: Error[] = []
stream.on('error', (error) => errors.push(error))
parse(stream, () => {
throw failure
})

assert.throws(
() => stream.emit('data', authOkBuffer),
(error) => error === failure
)
assert.strictEqual(errors.length, 0)
assert.strictEqual(stream.destroyed, false)
stream.destroy()
})

for (const [code, name] of [
[7, 'authenticationGSS'],
[9, 'authenticationSSPI'],
] as const) {
it(`parses the ${name} initiation message`, async function () {
const messages = await parseBuffers([new BufferList().addInt32(code).join(true, 'R')])
assert.deepStrictEqual(messages, [{ name, length: 8 }])
})
}

it('preserves non-UTF8 binary continuation tokens across every packet split', async function () {
const token = Buffer.from([0, 128, 255, 1, 0])
const response = new BufferList().addInt32(8).add(token).join(true, 'R')
for (let split = 1; split < response.length; split++) {
const messages = await parseBuffers([response.subarray(0, split), response.subarray(split)])
assert.strictEqual(messages.length, 1)
assert.strictEqual(messages[0].name, 'authenticationGSSContinue')
assert.strictEqual(messages[0].length, token.length + 8)
assert.ok('data' in messages[0])
assert.deepStrictEqual(messages[0].data, token)
}
})

it('fails a malformed GSS initiation packet without reporting authentication success', async function () {
const stream = new PassThrough()
const errors: Error[] = []
const messages: BackendMessage[] = []
stream.on('error', (error) => errors.push(error))
const closed = new Promise<void>((resolve) => stream.once('close', resolve))
parse(stream, (message) => messages.push(message))
stream.write(new BufferList().addInt32(7).addInt32(0).join(true, 'R'))
await closed
assert.strictEqual(messages.length, 0)
assert.match(errors[0].message, /Invalid PostgreSQL GSS authentication message length/)
})
})
25 changes: 24 additions & 1 deletion packages/pg-protocol/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,30 @@ import { Parser, MessageCallback } from './parser'

export function parse(stream: NodeJS.ReadableStream, callback: MessageCallback): Promise<void> {
const parser = new Parser()
stream.on('data', (buffer: Buffer) => parser.parse(buffer, callback))
stream.on('data', (buffer: Buffer) => {
let callbackThrew = false
try {
parser.parse(buffer, (message) => {
try {
callback(message)
} catch (error) {
callbackThrew = true
throw error
}
})
} catch (error) {
// A caller's callback error is not a malformed PostgreSQL message.
if (callbackThrew) {
throw error
}
const failure = error instanceof Error ? error : new Error(String(error))
if ('destroy' in stream && typeof stream.destroy === 'function') {
stream.destroy(failure)
} else {
stream.emit('error', failure)
}
}
})
return new Promise((resolve) => stream.on('end', () => resolve()))
}

Expand Down
11 changes: 11 additions & 0 deletions packages/pg-protocol/src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export type MessageName =
| 'authenticationOk'
| 'authenticationMD5Password'
| 'authenticationCleartextPassword'
| 'authenticationGSS'
| 'authenticationGSSContinue'
| 'authenticationSSPI'
| 'authenticationSASL'
| 'authenticationSASLContinue'
| 'authenticationSASLFinal'
Expand Down Expand Up @@ -191,6 +194,14 @@ export class AuthenticationMD5Password implements BackendMessage {
) {}
}

export class AuthenticationGSSContinue implements BackendMessage {
public readonly name: MessageName = 'authenticationGSSContinue'
constructor(
public readonly length: number,
public readonly data: Buffer
) {}
}

export class BackendKeyDataMessage {
public readonly name: MessageName = 'backendKeyData'
constructor(
Expand Down
7 changes: 7 additions & 0 deletions packages/pg-protocol/src/outbound-serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ describe('serializer', () => {
assert.deepEqual(actual, new BufferList().addString('data').join(true, 'p'))
})

it('serializes a binary GSS token without a C-string terminator or text conversion', function () {
const token = Buffer.from([0, 128, 255, 1, 0])
const actual = serialize.sendGSSResponse(token)
assert.deepStrictEqual(actual, new BufferList().add(token).join(true, 'p'))
assert.strictEqual(actual.readInt32BE(1), token.length + 4)
})

it('builds query message', function () {
const txt = 'select * from boom'
const actual = serialize.query(txt)
Expand Down
16 changes: 16 additions & 0 deletions packages/pg-protocol/src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
BackendMessage,
MessageName,
AuthenticationMD5Password,
AuthenticationGSSContinue,
NoticeMessage,
} from './messages'
import { BufferReader } from './buffer-reader'
Expand Down Expand Up @@ -330,6 +331,9 @@ const parseBackendKeyData = (reader: BufferReader) => {
}

const parseAuthenticationResponse = (reader: BufferReader, length: number) => {
if (length < 8) {
throw new Error('Invalid PostgreSQL authentication message length')
}
const code = reader.int32()
// TODO(bmc): maybe better types here
const message: BackendMessage & any = {
Expand All @@ -352,6 +356,18 @@ const parseAuthenticationResponse = (reader: BufferReader, length: number) => {
return new AuthenticationMD5Password(LATEINIT_LENGTH, salt)
}
break
case 7: // AuthenticationGSS
case 9: // AuthenticationSSPI
if (length !== 8) {
throw new Error('Invalid PostgreSQL GSS authentication message length')
}
message.name = code === 7 ? 'authenticationGSS' : 'authenticationSSPI'
break
case 8: // AuthenticationGSSContinue
if (length > 8 + 65535) {
throw new Error('PostgreSQL GSS authentication token exceeds the protocol limit')
}
return new AuthenticationGSSContinue(length, Buffer.from(reader.bytes(length - 8)))
case 10: // AuthenticationSASL
{
message.name = 'authenticationSASL'
Expand Down
3 changes: 3 additions & 0 deletions packages/pg-protocol/src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,8 @@ const copyData = (chunk: Buffer): Buffer => {
return writer.add(chunk).flush(code.copyFromChunk)
}

const sendGSSResponse = (token: Buffer): Buffer => writer.add(token).flush(code.startup)

const copyFail = (message: string): Buffer => {
return cstringMessage(code.copyFail, message)
}
Expand All @@ -268,6 +270,7 @@ const serialize = {
requestSsl,
sendSASLInitialResponseMessage,
sendSCRAMClientFinalMessage,
sendGSSResponse,
query,
parse,
bind,
Expand Down
Loading
Loading