diff --git a/docs/pages/features/_meta.js b/docs/pages/features/_meta.js index 7ddd35a5c..1285125f2 100644 --- a/docs/pages/features/_meta.js +++ b/docs/pages/features/_meta.js @@ -6,6 +6,7 @@ export default { transactions: 'Transactions', types: 'Data Types', ssl: 'SSL', + kerberos: 'Kerberos and GSS', native: 'Native', esm: 'ESM', callbacks: 'Callbacks', diff --git a/docs/pages/features/kerberos.mdx b/docs/pages/features/kerberos.mdx new file mode 100644 index 000000000..62ead0811 --- /dev/null +++ b/docs/pages/features/kerberos.mdx @@ -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. diff --git a/packages/pg-protocol/src/inbound-parser.test.ts b/packages/pg-protocol/src/inbound-parser.test.ts index 8687194c3..f86fbbe02 100644 --- a/packages/pg-protocol/src/inbound-parser.test.ts +++ b/packages/pg-protocol/src/inbound-parser.test.ts @@ -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((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((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/) + }) }) diff --git a/packages/pg-protocol/src/index.ts b/packages/pg-protocol/src/index.ts index 703ff2e49..4c1c3b305 100644 --- a/packages/pg-protocol/src/index.ts +++ b/packages/pg-protocol/src/index.ts @@ -4,7 +4,30 @@ import { Parser, MessageCallback } from './parser' export function parse(stream: NodeJS.ReadableStream, callback: MessageCallback): Promise { 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())) } diff --git a/packages/pg-protocol/src/messages.ts b/packages/pg-protocol/src/messages.ts index c3fbbdd9b..13701d603 100644 --- a/packages/pg-protocol/src/messages.ts +++ b/packages/pg-protocol/src/messages.ts @@ -23,6 +23,9 @@ export type MessageName = | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' + | 'authenticationGSS' + | 'authenticationGSSContinue' + | 'authenticationSSPI' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' @@ -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( diff --git a/packages/pg-protocol/src/outbound-serializer.test.ts b/packages/pg-protocol/src/outbound-serializer.test.ts index aac0c57ba..0fca62329 100644 --- a/packages/pg-protocol/src/outbound-serializer.test.ts +++ b/packages/pg-protocol/src/outbound-serializer.test.ts @@ -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) diff --git a/packages/pg-protocol/src/parser.ts b/packages/pg-protocol/src/parser.ts index df48ca4a1..320a7678d 100644 --- a/packages/pg-protocol/src/parser.ts +++ b/packages/pg-protocol/src/parser.ts @@ -24,6 +24,7 @@ import { BackendMessage, MessageName, AuthenticationMD5Password, + AuthenticationGSSContinue, NoticeMessage, } from './messages' import { BufferReader } from './buffer-reader' @@ -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 = { @@ -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' diff --git a/packages/pg-protocol/src/serializer.ts b/packages/pg-protocol/src/serializer.ts index bbd59623e..22b99a9ac 100644 --- a/packages/pg-protocol/src/serializer.ts +++ b/packages/pg-protocol/src/serializer.ts @@ -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) } @@ -268,6 +270,7 @@ const serialize = { requestSsl, sendSASLInitialResponseMessage, sendSCRAMClientFinalMessage, + sendGSSResponse, query, parse, bind, diff --git a/packages/pg/lib/client.js b/packages/pg/lib/client.js index 2b13c1de7..8df0fadad 100644 --- a/packages/pg/lib/client.js +++ b/packages/pg/lib/client.js @@ -2,6 +2,7 @@ const EventEmitter = require('events').EventEmitter const utils = require('./utils') const nodeUtils = require('util') const sasl = require('./crypto/sasl') +const { GssSession, authenticationError } = require('./crypto/gss') const TypeOverrides = require('./type-overrides') const ConnectionParameters = require('./connection-parameters') @@ -83,6 +84,10 @@ class Client extends EventEmitter { this._queryable = true this._activeQuery = null this._txStatus = null + this._gssSession = null + this._gssVerified = false + this._gssReadyPending = false + this._nonGssAuthenticationStarted = false this.enableChannelBinding = Boolean(c.enableChannelBinding) // set true to use SCRAM-SHA-256-PLUS when offered this.scramMaxIterations = coerceNumberOrDefault(c.scramMaxIterations, sasl.DEFAULT_MAX_SCRAM_ITERATIONS) @@ -162,6 +167,12 @@ class Client extends EventEmitter { }) return } + if (this.connectionParameters.gssencmode === 'require') { + const err = new Error('GSS transport encryption is not supported by the JavaScript driver') + err.code = 'PG_GSS_ENCRYPTION_UNSUPPORTED' + process.nextTick(() => callback(err)) + return + } this._connecting = true if (this._connectionTimeoutMillis > 0) { @@ -201,6 +212,7 @@ class Client extends EventEmitter { this._attachListeners(con) con.once('end', () => { + this._gssSession?.dispose() const error = this._ending ? new Error('Connection terminated') : new Error('Connection terminated unexpectedly') clearTimeout(this.connectionTimeoutHandle) @@ -247,6 +259,10 @@ class Client extends EventEmitter { } _attachListeners(con) { + con.on('authenticationGSS', () => this._handleAuthGSS('GSSAPI')) + con.on('authenticationSSPI', () => this._handleAuthGSS('SSPI')) + con.on('authenticationGSSContinue', this._handleAuthGSSContinue.bind(this)) + con.on('authenticationOk', this._handleAuthOk.bind(this)) // password request handling con.on('authenticationCleartextPassword', this._handleAuthCleartextPassword.bind(this)) // password request handling @@ -311,12 +327,16 @@ class Client extends EventEmitter { } _handleAuthCleartextPassword(msg) { + if (!this._allowNonGssAuthentication()) return + this._nonGssAuthenticationStarted = true this._getPassword(() => { this.connection.password(this.password) }) } _handleAuthMD5Password(msg) { + if (!this._allowNonGssAuthentication()) return + this._nonGssAuthenticationStarted = true this._getPassword(async () => { try { const hashedPassword = await crypto.postgresMd5PasswordHash(this.user, this.password, msg.salt) @@ -328,6 +348,8 @@ class Client extends EventEmitter { } _handleAuthSASL(msg) { + if (!this._allowNonGssAuthentication()) return + this._nonGssAuthenticationStarted = true this._getPassword(() => { try { this.saslSession = sasl.startSession( @@ -343,6 +365,7 @@ class Client extends EventEmitter { } async _handleAuthSASLContinue(msg) { + if (!this._allowNonGssAuthentication()) return try { await sasl.continueSession( this.saslSession, @@ -357,6 +380,7 @@ class Client extends EventEmitter { } _handleAuthSASLFinal(msg) { + if (!this._allowNonGssAuthentication()) return try { sasl.finalizeSession(this.saslSession, msg.data) this.saslSession = null @@ -365,12 +389,70 @@ class Client extends EventEmitter { } } + _allowNonGssAuthentication() { + if (!this._gssSession) return true + this._failGSS(authenticationError('The server changed authentication methods during GSS negotiation')) + return false + } + + _handleAuthGSS(method) { + if (!this._connecting || this._gssSession || this._nonGssAuthenticationStarted) { + this._failGSS(authenticationError('Unexpected GSS authentication request')) + return + } + this._gssSession = new GssSession(this.connectionParameters, method, (token) => + this.connection.sendGSSResponse(token) + ) + this._gssSession.start().catch((error) => this._failGSS(error)) + } + + _handleAuthGSSContinue(message) { + if (!this._gssSession) { + this._failGSS(authenticationError('GSS continuation received before authentication started')) + return + } + this._gssSession.continue(message.data).catch((error) => this._failGSS(error)) + } + + _handleAuthOk() { + if (this._gssSession) { + this._gssSession.accept().catch((error) => this._failGSS(error)) + } + } + + _failGSS(error) { + if (this._ending || this._ended || this._connectionError) return + this._gssSession?.dispose() + this.connection.stream.destroy( + error instanceof Error ? error : authenticationError('GSS authentication failed', error) + ) + } + _handleBackendKeyData(msg) { this.processID = msg.processID this.secretKey = msg.secretKey } _handleReadyForQuery(msg) { + if (this._connectionError || this.connection.stream.destroyed) return + if (this._connecting && this._gssSession && !this._gssVerified) { + if (this._gssReadyPending) { + this._failGSS(authenticationError('Duplicate ReadyForQuery during GSS authentication')) + return + } + this._gssReadyPending = true + this._gssSession + .ready() + .then(() => { + process.nextTick(() => { + if (this._ending || this._ended || this._connectionError || this.connection.stream.destroyed) return + this._gssVerified = true + this._handleReadyForQuery(msg) + }) + }) + .catch((error) => this._failGSS(error)) + return + } if (this._connecting) { this._connecting = false this._connected = true @@ -398,6 +480,7 @@ class Client extends EventEmitter { // if we receive an error event or error message // during the connection process we handle it here _handleErrorWhileConnecting(err) { + this._gssSession?.dispose() if (this._connectionError) { // TODO(bmc): this is swallowing errors - we shouldn't do this return @@ -414,6 +497,7 @@ class Client extends EventEmitter { // this means the socket is dead - do a hard abort of all queries and emit // the socket error on the client as well _handleErrorEvent(err) { + this._gssSession?.dispose() if (this._connecting) { return this._handleErrorWhileConnecting(err) } @@ -797,6 +881,10 @@ class Client extends EventEmitter { } end(cb) { + if (this._connecting && this._gssSession && !this._connectionError) { + this._handleErrorWhileConnecting(authenticationError('Connection terminated during GSS authentication')) + } + this._gssSession?.dispose() this._ending = true // if we have never connected, then end is a noop, callback immediately diff --git a/packages/pg/lib/connection-parameters.js b/packages/pg/lib/connection-parameters.js index 37987fd68..86b563a75 100644 --- a/packages/pg/lib/connection-parameters.js +++ b/packages/pg/lib/connection-parameters.js @@ -69,6 +69,13 @@ class ConnectionParameters { this.port = parseInt(val('port', config), 10) this.host = val('host', config) + this.krbsrvname = val('krbsrvname', config, 'PGKRBSRVNAME') + this.gssHost = config.gssHost || this.host + this.gsslib = val('gsslib', config, 'PGGSSLIB') + this.gssencmode = val('gssencmode', config, 'PGGSSENCMODE') + if (this.gssencmode !== undefined && !['disable', 'prefer', 'require'].includes(this.gssencmode)) { + throw new Error('Invalid gssencmode: expected disable, prefer, or require') + } // "hiding" the password so it doesn't show up in stack traces // or if the client is console.logged @@ -157,6 +164,9 @@ class ConnectionParameters { add(params, ssl, 'sslcert') add(params, ssl, 'sslrootcert') add(params, this, 'sslnegotiation') + add(params, this, 'krbsrvname') + add(params, this, 'gsslib') + add(params, this, 'gssencmode') if (this.database) { params.push('dbname=' + quoteParamValue(this.database)) diff --git a/packages/pg/lib/connection.js b/packages/pg/lib/connection.js index 85f3113a1..511c32114 100644 --- a/packages/pg/lib/connection.js +++ b/packages/pg/lib/connection.js @@ -168,6 +168,12 @@ class Connection extends EventEmitter { this._send(serialize.sendSCRAMClientFinalMessage(additionalData)) } + sendGSSResponse(token) { + this._send(serialize.sendGSSResponse(token)) + // Backpressure still accepts the token; only a closed stream is a failure. + return this.stream.writable + } + _send(buffer) { if (!this.stream.writable) { return false diff --git a/packages/pg/lib/crypto/gss.js b/packages/pg/lib/crypto/gss.js new file mode 100644 index 000000000..f294e173e --- /dev/null +++ b/packages/pg/lib/crypto/gss.js @@ -0,0 +1,147 @@ +'use strict' + +function authenticationError(message, cause) { + const error = new Error(message) + error.code = 'PG_GSS_AUTHENTICATION_FAILED' + if (cause !== undefined) error.cause = cause + return error +} + +function serviceName(parameters, platform) { + const service = parameters.krbsrvname || 'postgres' + const host = parameters.gssHost + if (typeof service !== 'string' || !service || /[@/\\\0]/.test(service)) { + throw authenticationError('Invalid Kerberos service name') + } + if (typeof host !== 'string' || !host || /[@/\\\0]/.test(host)) { + throw authenticationError('Kerberos authentication requires a database hostname') + } + if (parameters.gsslib && parameters.gsslib !== (platform === 'win32' ? 'sspi' : 'gssapi')) { + throw authenticationError('The requested GSS library is not supported by the Kerberos binding on this platform') + } + return platform === 'win32' ? `${service}/${host}` : `${service}@${host}` +} + +class GssSession { + constructor(parameters, method, send, binding) { + this.parameters = parameters + this.method = method + this.send = send + this.binding = binding + this.client = null + this.closed = false + this.accepted = false + this.rounds = 0 + this.queue = Promise.resolve() + } + + enqueue(action) { + this.queue = this.queue.then(() => { + if (!this.closed) return action() + }) + return this.queue + } + + loadBinding() { + let binding = this.binding + if (!binding) { + try { + binding = require('kerberos') + } catch (cause) { + throw authenticationError( + 'GSS authentication requires the optional kerberos package and a compatible native binding', + cause + ) + } + } + if (!binding || typeof binding.initializeClient !== 'function') { + throw authenticationError('The Kerberos binding does not provide initializeClient') + } + if ( + typeof binding.GSS_C_MUTUAL_FLAG !== 'number' || + typeof binding.GSS_C_REPLAY_FLAG !== 'number' || + typeof binding.GSS_C_SEQUENCE_FLAG !== 'number' || + typeof binding.GSS_MECH_OID_KRB5 !== 'number' || + typeof binding.GSS_MECH_OID_SPNEGO !== 'number' + ) { + throw authenticationError('The Kerberos binding does not provide the required authentication mechanisms') + } + return binding + } + + start() { + return this.enqueue(async () => { + const service = serviceName(this.parameters, process.platform) + const binding = this.loadBinding() + const flags = binding.GSS_C_MUTUAL_FLAG | binding.GSS_C_REPLAY_FLAG | binding.GSS_C_SEQUENCE_FLAG + const client = await binding.initializeClient(service, { + mechOID: this.method === 'GSSAPI' ? binding.GSS_MECH_OID_KRB5 : binding.GSS_MECH_OID_SPNEGO, + gssFlags: flags, + flags, + }) + if (this.closed) return + if (!client || typeof client.step !== 'function') { + throw authenticationError('The Kerberos binding returned an invalid context') + } + this.client = client + await this.step(Buffer.alloc(0)) + }) + } + + continue(token) { + if (++this.rounds > 32) { + return Promise.reject(authenticationError('GSS authentication exceeded its negotiation limit')) + } + return this.enqueue(() => { + if (!Buffer.isBuffer(token) || this.accepted || !this.client) { + throw authenticationError('Unexpected GSS authentication continuation') + } + return this.step(token) + }) + } + + async step(challenge) { + const token = await this.client.step(challenge.toString('base64')) + if (this.closed) return + if (token === null || token === undefined || token === '') { + if (this.client.contextComplete !== true) { + throw authenticationError('GSS authentication returned no token before context completion') + } + return + } + if (typeof token !== 'string') { + throw authenticationError('The Kerberos binding returned an invalid token') + } + const bytes = Buffer.from(token, 'base64') + if (bytes.length === 0 || bytes.length > 65535 || bytes.toString('base64') !== token) { + throw authenticationError('The Kerberos binding returned an invalid base64 token') + } + if (!this.send(bytes)) { + throw authenticationError('The PostgreSQL connection closed during GSS authentication') + } + } + + accept() { + return this.enqueue(() => { + if (this.accepted || !this.client || this.client.contextComplete !== true) { + throw authenticationError('The server accepted GSS authentication before the client context completed') + } + this.accepted = true + }) + } + + async ready() { + await this.queue + if (this.closed || !this.accepted) { + throw authenticationError('GSS authentication did not complete') + } + } + + dispose() { + this.closed = true + this.client = null + this.binding = null + } +} + +module.exports = { GssSession, serviceName, authenticationError } diff --git a/packages/pg/package.json b/packages/pg/package.json index 0f693e314..e480d7295 100644 --- a/packages/pg/package.json +++ b/packages/pg/package.json @@ -50,6 +50,7 @@ "wrangler": "^3.x" }, "optionalDependencies": { + "kerberos": "^2.2.2", "pg-cloudflare": "^1.4.1" }, "peerDependencies": { diff --git a/packages/pg/test/integration/gh-issues/gss-handshake-tests.js b/packages/pg/test/integration/gh-issues/gss-handshake-tests.js new file mode 100644 index 000000000..73b5f18ab --- /dev/null +++ b/packages/pg/test/integration/gh-issues/gss-handshake-tests.js @@ -0,0 +1,332 @@ +'use strict' + +const assert = require('assert') +const { execFile } = require('child_process') +const net = require('net') +const Module = require('module') +const { Client, Pool } = require('../../../lib') +const { Suite } = require('../../test-helper') + +function authentication(code, data = Buffer.alloc(0)) { + const packet = Buffer.alloc(data.length + 9) + packet[0] = 0x52 + packet.writeInt32BE(data.length + 8, 1) + packet.writeInt32BE(code, 5) + data.copy(packet, 9) + return packet +} + +const ready = Buffer.from([0x5a, 0, 0, 0, 5, 0x49]) +const challenge = Buffer.from([0, 128, 255]) +const response = Buffer.from([255, 128, 0]).toString('base64') +const suite = new Suite() + +async function fixture(reply, onToken) { + const sockets = new Set() + const tokens = [] + const server = net.createServer((socket) => { + sockets.add(socket) + socket.on('close', () => sockets.delete(socket)) + socket.on('error', () => {}) + let startup = true + let buffer = Buffer.alloc(0) + socket.on('data', (data) => { + buffer = Buffer.concat([buffer, data]) + if (startup) { + if (buffer.length < 4 || buffer.length < buffer.readInt32BE(0)) return + buffer = buffer.subarray(buffer.readInt32BE(0)) + startup = false + socket.write(reply) + } + while (buffer.length >= 5 && buffer.length >= buffer.readInt32BE(1) + 1) { + const length = buffer.readInt32BE(1) + 1 + if (buffer[0] === 0x70) { + tokens.push(Buffer.from(buffer.subarray(5, length))) + if (onToken) onToken(socket) + } + if (buffer[0] === 0x58) socket.end() + buffer = buffer.subarray(length) + } + }) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { + tokens, + options: { host: '127.0.0.1', port: server.address().port, gssHost: 'db.example.test', ssl: false }, + close: () => + new Promise((resolve) => { + for (const socket of sockets) socket.destroy() + server.close(resolve) + }), + } +} + +async function withBinding(binding, action) { + const original = Module._load + Module._load = function (name, parent, isMain) { + if (name === 'kerberos') { + if (binding === undefined) { + const error = new Error('fixture native binding unavailable') + error.code = 'MODULE_NOT_FOUND' + throw error + } + return binding + } + return original.call(this, name, parent, isMain) + } + try { + await action() + } finally { + Module._load = original + } +} + +function binding(initializeClient) { + return { + GSS_C_MUTUAL_FLAG: 2, + GSS_C_REPLAY_FLAG: 4, + GSS_C_SEQUENCE_FLAG: 8, + GSS_MECH_OID_KRB5: 9, + GSS_MECH_OID_SPNEGO: 6, + initializeClient, + } +} + +for (const [code, backpressure] of [ + [7, false], + [9, false], + [7, true], +]) { + suite.test(`authentication ${code} waits for the final security step (backpressure: ${backpressure})`, async () => { + const peer = await fixture(authentication(code), (socket) => { + socket.write(Buffer.concat([authentication(8, challenge), authentication(0), ready])) + }) + const context = { + contextComplete: false, + step: async (token) => { + if (!token) return response + assert.strictEqual(token, challenge.toString('base64')) + await new Promise((resolve) => setTimeout(resolve, 10)) + context.contextComplete = true + return null + }, + } + const library = binding(async (_service, options) => { + assert.strictEqual(options.mechOID, code === 7 ? 9 : 6) + return context + }) + const client = new Client(peer.options) + if (backpressure) { + client.connection.once('connect', () => { + const write = client.connection.stream.write.bind(client.connection.stream) + client.connection.stream.write = (...args) => { + write(...args) + return false + } + }) + } + try { + await withBinding(library, async () => { + await client.connect() + assert.strictEqual(context.contextComplete, true) + assert.strictEqual(client._gssVerified, true) + assert.deepStrictEqual(peer.tokens, [Buffer.from(response, 'base64')]) + }) + } finally { + await client.end() + await peer.close() + } + }) +} + +suite.test('premature AuthenticationOk does not produce a successful connection', async () => { + const peer = await fixture(Buffer.concat([authentication(7), authentication(0), ready])) + const client = new Client(peer.options) + try { + await withBinding( + binding(async () => ({ contextComplete: false, step: async () => response })), + async () => { + await assert.rejects(client.connect(), /before the client context completed/) + assert.strictEqual(client._connected, false) + } + ) + } finally { + await client.end() + await peer.close() + } +}) + +for (const order of ['gss-first', 'password-first']) { + suite.test(`mixed authentication closes the connection without sending a password (${order})`, async () => { + const reply = + order === 'gss-first' + ? Buffer.concat([authentication(7), authentication(3)]) + : Buffer.concat([authentication(3), authentication(7)]) + const peer = await fixture(Buffer.concat([reply, authentication(0), ready])) + const client = new Client({ ...peer.options, password: async () => 'must-not-be-sent' }) + const errors = [] + client.on('error', (error) => errors.push(error)) + try { + await withBinding( + binding(async () => ({ contextComplete: false, step: async () => response })), + async () => { + await assert.rejects(client.connect(), /changed authentication|Unexpected GSS/) + await new Promise((resolve) => setTimeout(resolve, 20)) + assert.deepStrictEqual(peer.tokens, []) + assert.strictEqual(client._connected, false) + assert.deepStrictEqual(errors, []) + } + ) + } finally { + await client.end() + await peer.close() + } + }) +} + +for (const api of ['client-promise', 'client-callback', 'pool']) { + suite.test(`${api} rejects an unsolicited GSS continuation followed by server success`, async () => { + const peer = await fixture(Buffer.concat([authentication(8, challenge), authentication(0), ready])) + const target = api === 'pool' ? new Pool(peer.options) : new Client(peer.options) + const errors = [] + target.on('error', (error) => errors.push(error)) + try { + const connecting = + api === 'client-callback' + ? new Promise((resolve, reject) => target.connect((error) => (error ? reject(error) : resolve()))) + : target.connect() + await assert.rejects(connecting, /GSS continuation received before authentication started/) + await new Promise((resolve) => setTimeout(resolve, 20)) + assert.deepStrictEqual(errors, []) + assert.deepStrictEqual(peer.tokens, []) + if (api === 'pool') { + assert.strictEqual(target.totalCount, 0) + assert.strictEqual(target.idleCount, 0) + } else { + assert.strictEqual(target._connected, false) + } + } finally { + await target.end() + await peer.close() + } + }) +} + +for (const kind of ['callback', 'listener']) { + suite.test(`does not classify a throwing connect ${kind} as a GSS authentication failure`, async () => { + const peer = await fixture(authentication(7), (socket) => { + socket.write(Buffer.concat([authentication(0), ready])) + }) + const message = `application connect ${kind} failed` + const script = ` + const { Client } = require(${JSON.stringify(require.resolve('../../../lib'))}) + const { GssSession } = require(${JSON.stringify(require.resolve('../../../lib/crypto/gss'))}) + GssSession.prototype.loadBinding = () => (${binding.toString()})(async () => ({ + contextComplete: true, + step: async () => ${JSON.stringify(response)}, + })) + const client = new Client(${JSON.stringify(peer.options)}) + client.on('error', () => process.exit(2)) + const fail = () => { throw new Error(${JSON.stringify(message)}) } + if (${JSON.stringify(kind)} === 'callback') { + client.connect((error) => { + if (error) process.exit(3) + fail() + }) + } else { + client.once('connect', fail) + client.connect().catch(() => process.exit(3)) + } + ` + try { + const result = await new Promise((resolve) => { + execFile(process.execPath, ['-e', script], { timeout: 3000 }, (error, stdout, stderr) => { + resolve({ error, stderr }) + }) + }) + assert.strictEqual(result.error?.code, 1, result.stderr) + assert.match(result.stderr, new RegExp(message)) + } finally { + await peer.close() + } + }) +} + +for (const kind of ['end', 'timeout']) { + suite.test(`${kind} settles connecting and suppresses a late native initialization result`, async () => { + const peer = await fixture(authentication(7)) + let release + let initialized + const initialization = new Promise((resolve) => { + initialized = resolve + }) + const library = binding(() => { + initialized() + return new Promise((resolve) => { + release = resolve + }) + }) + const client = new Client({ ...peer.options, connectionTimeoutMillis: kind === 'timeout' ? 30 : 0 }) + try { + await withBinding(library, async () => { + const connecting = client.connect() + const rejected = assert.rejects(connecting, kind === 'timeout' ? /timeout expired/ : /terminated during GSS/) + await initialization + if (kind === 'end') await client.end() + await rejected + release({ contextComplete: true, step: async () => response }) + await new Promise((resolve) => setTimeout(resolve, 20)) + assert.deepStrictEqual(peer.tokens, []) + assert.strictEqual(client._connected, false) + }) + } finally { + await client.end() + await peer.close() + } + }) +} + +suite.test('a missing optional binding rejects connect without an uncaught exception', async () => { + const peer = await fixture(authentication(7)) + const client = new Client(peer.options) + try { + await withBinding(undefined, async () => { + await assert.rejects( + client.connect(), + (error) => error.code === 'PG_GSS_AUTHENTICATION_FAILED' && /optional kerberos package/.test(error.message) + ) + }) + } finally { + await client.end() + await peer.close() + } +}) + +for (const source of ['profile', 'environment']) { + suite.test(`required GSS encryption is rejected before opening a socket (${source})`, async () => { + const peer = await fixture(authentication(7)) + const saved = process.env.PGGSSENCMODE + if (source === 'environment') process.env.PGGSSENCMODE = 'require' + const options = source === 'profile' ? { ...peer.options, gssencmode: 'require' } : peer.options + const client = new Client(options) + client.connection.connect = () => assert.fail('Required GSS encryption must not open a socket') + let initialized = false + try { + await withBinding( + binding(async () => { + initialized = true + }), + async () => { + await assert.rejects(client.connect(), (error) => error.code === 'PG_GSS_ENCRYPTION_UNSUPPORTED') + assert.strictEqual(initialized, false) + assert.deepStrictEqual(peer.tokens, []) + } + ) + } finally { + if (saved === undefined) delete process.env.PGGSSENCMODE + else process.env.PGGSSENCMODE = saved + await client.end() + await peer.close() + } + }) +} diff --git a/packages/pg/test/integration/gh-issues/unsupported-authentication-tests.js b/packages/pg/test/integration/gh-issues/unsupported-authentication-tests.js new file mode 100644 index 000000000..136af765b --- /dev/null +++ b/packages/pg/test/integration/gh-issues/unsupported-authentication-tests.js @@ -0,0 +1,69 @@ +'use strict' + +const assert = require('assert') +const net = require('net') +const { Client, Pool } = require('../../../lib') +const { Suite } = require('../../test-helper') + +function authentication(code) { + const packet = Buffer.alloc(9) + packet[0] = 0x52 + packet.writeInt32BE(8, 1) + packet.writeInt32BE(code, 5) + return packet +} + +async function createServer() { + let rejectedConnections = 0 + const sockets = new Set() + const server = net.createServer((socket) => { + sockets.add(socket) + socket.on('close', () => sockets.delete(socket)) + socket.on('error', () => {}) + socket.once('data', () => { + if (rejectedConnections++ === 0) { + const packet = authentication(1234) + socket.write(packet.subarray(0, 3)) + setImmediate(() => socket.write(packet.subarray(3))) + } else { + socket.write(Buffer.concat([authentication(0), Buffer.from([0x5a, 0, 0, 0, 5, 0x49])])) + socket.on('data', (packet) => { + if (packet[0] === 0x58) socket.end() + }) + } + }) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { + options: { host: '127.0.0.1', port: server.address().port, user: 'test', ssl: false }, + sockets, + close: () => + new Promise((resolve) => { + for (const socket of sockets) socket.destroy() + server.close(resolve) + }), + } +} + +const suite = new Suite() + +for (const api of ['client-promise', 'client-callback', 'pool']) { + suite.test(`${api} rejects a split unsupported auth packet and permits a subsequent connection`, async () => { + const fixture = await createServer() + const target = api === 'pool' ? new Pool(fixture.options) : new Client(fixture.options) + try { + const connect = + api === 'client-callback' + ? new Promise((resolve, reject) => target.connect((error) => (error ? reject(error) : resolve()))) + : target.connect() + await assert.rejects(connect, /Unknown authenticationOk message type 1234/) + await target.end() + + const healthy = new Client(fixture.options) + await healthy.connect() + await healthy.end() + } finally { + await fixture.close() + } + }) +} diff --git a/packages/pg/test/integration/gss/Dockerfile b/packages/pg/test/integration/gss/Dockerfile new file mode 100644 index 000000000..8e62ab62d --- /dev/null +++ b/packages/pg/test/integration/gss/Dockerfile @@ -0,0 +1,8 @@ +FROM node@sha256:0e5f906573693feaa1e21057ebdcfdb5bd5021f050b2dc7c9deceb629c7da2a8 + +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + postgresql krb5-kdc krb5-admin-server krb5-user libkrb5-dev \ + openssh-client openssh-server + +WORKDIR /work diff --git a/packages/pg/test/integration/gss/README.md b/packages/pg/test/integration/gss/README.md new file mode 100644 index 000000000..b103b6d30 --- /dev/null +++ b/packages/pg/test/integration/gss/README.md @@ -0,0 +1,35 @@ +# Real GSS authentication checks + +These opt-in checks use a disposable PostgreSQL server and MIT Kerberos KDC. +They generate their own identities, keys and TLS certificates. No production +database, domain configuration, ticket cache or server policy is changed. + +`run-real-checks.js` compares the unmodified source mounted at `/before-source` +with the candidate mounted at `/source`. It verifies ticket authentication, +verified TLS, pool reuse, a real SSH tunnel with the database service hostname, +and clean failure for missing/expired tickets, invalid service names, rejected +identities, invalid CA trust and required GSS encryption. A libpq control must +authenticate before the comparisons run. + +Example: + +```sh +docker build -t pg-gss-fixture packages/pg/test/integration/gss +docker run --name pg-gss-fixture \ + -e NPM_CONFIG_REGISTRY="$NPM_CONFIG_REGISTRY" \ + -v "$PWD:/source:ro" \ + -v "$BASELINE_SOURCE:/before-source:ro" \ + pg-gss-fixture \ + bash -c '/source/packages/pg/test/integration/gss/prepare.sh && /work/current/packages/pg/test/integration/gss/run-fixture.sh' +docker cp pg-gss-fixture:/work/real-authentication-results.json . +docker rm pg-gss-fixture +``` + +Set `NPM_CONFIG_REGISTRY` to the package registry approved for your environment. +The container must be able to download packages and Node build headers while +preparing; authentication servers subsequently bind only to container loopback. +No host ports are published. Use a unique container name when another run exists. + +The generated result records actual outcomes, not an assertion that every +platform works. This Linux fixture does not validate Windows SSPI or Windows +domain Kerberos. Those require separate platform fixtures and results. diff --git a/packages/pg/test/integration/gss/fixture-dependencies.json b/packages/pg/test/integration/gss/fixture-dependencies.json new file mode 100644 index 000000000..b0ec93f73 --- /dev/null +++ b/packages/pg/test/integration/gss/fixture-dependencies.json @@ -0,0 +1,19 @@ +{ + "name": "disposable-node-postgres-gss-fixture", + "private": true, + "dependencies": { + "@types/node": "^16", + "@types/mocha": "^10", + "@types/chai": "^4", + "async": "2.6.4", + "chai": "4.2.0", + "kerberos": "2.2.2", + "mocha": "11.7.5", + "pg-connection-string": "2.14.1", + "pg-cursor": "2.22.0", + "pg-pool": "3.14.0", + "pg-types": "2.2.0", + "pgpass": "1.0.5", + "typescript": "6.0.3" + } +} diff --git a/packages/pg/test/integration/gss/prepare.sh b/packages/pg/test/integration/gss/prepare.sh new file mode 100644 index 000000000..829b277c1 --- /dev/null +++ b/packages/pg/test/integration/gss/prepare.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /work/deps /work/current /work/before +cp /source/packages/pg/test/integration/gss/fixture-dependencies.json /work/deps/package.json +registry=${NPM_CONFIG_REGISTRY:?Set NPM_CONFIG_REGISTRY to your approved package registry} +npm --prefix /work/deps install --ignore-scripts --no-audit --no-fund \ + --registry="$registry" +npm_config_build_from_source=true npm --prefix /work/deps rebuild kerberos --foreground-scripts + +for item in current before; do + origin=/source + if [ "$item" = before ]; then origin=/before-source; fi + (cd "$origin" && tar --exclude=node_modules --exclude=.git -cf - packages/pg packages/pg-protocol) \ + | (cd "/work/$item" && tar -xf -) + ln -s /work/deps/node_modules "/work/$item/node_modules" + mkdir -p "/work/$item/packages/pg/node_modules" + ln -s "/work/$item/packages/pg-protocol" "/work/$item/packages/pg/node_modules/pg-protocol" + /work/deps/node_modules/.bin/tsc --project "/work/$item/packages/pg-protocol/tsconfig.json" +done + +node -e 'const k=require("/work/deps/node_modules/kerberos"); console.log(JSON.stringify({node:process.version,kerberos:k.version,napi:process.versions.napi,platform:process.platform}))' diff --git a/packages/pg/test/integration/gss/probe-real.js b/packages/pg/test/integration/gss/probe-real.js new file mode 100644 index 000000000..ba236f6bb --- /dev/null +++ b/packages/pg/test/integration/gss/probe-real.js @@ -0,0 +1,74 @@ +'use strict' + +const assert = require('assert') +const fs = require('fs') +const { Client, Pool } = require(process.env.PG_GSS_CLIENT_ROOT + '/lib') +const scenario = process.argv[2] +const options = { + host: 'localhost', + port: 55439, + user: scenario === 'rejected-identity' ? 'rejectedrole' : 'pgrepro', + database: 'gssrepro', + connectionTimeoutMillis: 3000, + gssencmode: scenario === 'required-encryption' ? 'require' : 'disable', + krbsrvname: scenario === 'invalid-service' ? 'missing-service' : 'postgres', + ssl: scenario === 'plain' ? false : { ca: fs.readFileSync('/work/fixture/ca.crt', 'utf8'), rejectUnauthorized: true }, +} +if (scenario === 'invalid-ca') options.ssl.ca = '' +if (scenario === 'ssh' || scenario === 'ssh-without-database-host') { + options.host = '127.0.0.1' + options.port = 55440 + if (scenario === 'ssh') options.gssHost = 'localhost' +} + +async function verify(client) { + const result = await client.query( + 'SELECT 42 AS answer, ' + + '(SELECT gss_authenticated FROM pg_catalog.pg_stat_gssapi WHERE pid=pg_backend_pid()) AS gss_auth, ' + + '(SELECT encrypted FROM pg_catalog.pg_stat_gssapi WHERE pid=pg_backend_pid()) AS gss_encrypted, ' + + '(SELECT ssl FROM pg_catalog.pg_stat_ssl WHERE pid=pg_backend_pid()) AS tls' + ) + assert.strictEqual(result.rows[0].answer, 42) + assert.strictEqual(result.rows[0].gss_auth, true) + assert.strictEqual(result.rows[0].gss_encrypted, false) + assert.strictEqual(result.rows[0].tls, scenario !== 'plain') + if (scenario !== 'plain') assert.strictEqual(client.connection.stream.authorized, true) + return result.rows[0] +} + +async function main() { + if (scenario === 'missing-ticket') process.env.KRB5CCNAME = 'FILE:/work/fixture/missing.ccache' + if (scenario === 'expired-ticket') process.env.KRB5CCNAME = 'FILE:/work/fixture/expired.ccache' + let client + let pool + try { + let data + if (scenario === 'pool') { + pool = new Pool({ ...options, max: 1 }) + for (let attempt = 0; attempt < 3; attempt++) { + client = await pool.connect() + try { + data = await verify(client) + } finally { + client.release() + client = null + } + } + } else { + client = new Client(options) + await client.connect() + data = await verify(client) + } + console.log(JSON.stringify({ scenario, status: 'connected', data, node: process.version })) + } catch (error) { + console.log(JSON.stringify({ scenario, status: 'rejected', code: error.code || null, node: process.version })) + } finally { + if (client) await client.end() + if (pool) await pool.end() + } +} + +main().catch((error) => { + console.error(error) + process.exitCode = 70 +}) diff --git a/packages/pg/test/integration/gss/regressions.js b/packages/pg/test/integration/gss/regressions.js new file mode 100644 index 000000000..9c6e7d99d --- /dev/null +++ b/packages/pg/test/integration/gss/regressions.js @@ -0,0 +1,120 @@ +'use strict' + +const assert = require('assert') +const crypto = require('crypto') +const fs = require('fs') +const path = require('path') + +const root = '/work/fixture' +const password = crypto.randomBytes(24).toString('hex') +const Current = require('/work/current/packages/pg/lib') +const results = [] + +async function setup() { + const admin = new Current.Client({ + host: path.join(root, 'socket'), + port: 55439, + user: 'postgres', + database: 'postgres', + }) + await admin.connect() + try { + await admin.query( + `CREATE ROLE passwordrepro LOGIN PASSWORD '${password}'; CREATE ROLE scramrepro LOGIN PASSWORD '${password}';` + ) + fs.writeFileSync( + path.join(root, 'pgdata', 'pg_hba.conf'), + 'local all all trust\n' + + 'hostssl gssrepro passwordrepro 127.0.0.1/32 password\n' + + 'hostssl gssrepro scramrepro 127.0.0.1/32 scram-sha-256\n' + + 'host all all 127.0.0.1/32 gss include_realm=1 map=fixture\n' + ) + await admin.query('SELECT pg_reload_conf()') + } finally { + await admin.end() + } +} + +async function ordinaryAuth(stage, role, invalid) { + const { Client } = require(`/work/${stage}/packages/pg/lib`) + const client = new Client({ + host: 'localhost', + port: 55439, + database: 'gssrepro', + user: role, + password: async () => (invalid ? 'deliberately-invalid' : password), + ssl: { ca: fs.readFileSync(path.join(root, 'ca.crt'), 'utf8'), rejectUnauthorized: true }, + enableChannelBinding: true, + connectionTimeoutMillis: 3000, + }) + try { + if (invalid) { + await assert.rejects(client.connect(), (error) => error.code === '28P01') + return { stage, role, invalid, outcome: 'expected-rejection' } + } + await client.connect() + const query = await client.query('SELECT $1::integer AS answer', [42]) + assert.strictEqual(query.rows[0].answer, 42) + assert.strictEqual(client.connection.stream.authorized, true) + return { stage, role, invalid, outcome: 'passed', answer: 42 } + } finally { + await client.end() + } +} + +async function cursorAndTransactions() { + const Cursor = require('pg-cursor') + const client = new Current.Client({ + host: 'localhost', + port: 55439, + database: 'gssrepro', + user: 'pgrepro', + ssl: { ca: fs.readFileSync(path.join(root, 'ca.crt'), 'utf8'), rejectUnauthorized: true }, + connectionTimeoutMillis: 3000, + }) + await client.connect() + try { + await client.query('BEGIN') + await client.query('CREATE TEMP TABLE session_control(value integer)') + await client.query('INSERT INTO session_control VALUES (42)') + await client.query('COMMIT') + assert.strictEqual((await client.query('SELECT value FROM session_control')).rows[0].value, 42) + const cursor = client.query(new Cursor('SELECT n FROM generate_series(1, 10) AS n ORDER BY n')) + const values = [] + try { + let rows + do { + rows = await new Promise((resolve, reject) => + cursor.read(3, (error, rows) => (error ? reject(error) : resolve(rows))) + ) + values.push(...rows.map((row) => row.n)) + } while (rows.length > 0) + } finally { + await new Promise((resolve, reject) => cursor.close((error) => (error ? reject(error) : resolve()))) + } + assert.deepStrictEqual(values, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + assert.strictEqual((await client.query('SELECT 42 AS answer')).rows[0].answer, 42) + return { stage: 'after', scenario: 'gss-cursor-and-transaction-affinity', outcome: 'passed', rows: values.length } + } finally { + await client.end() + } +} + +async function main() { + await setup() + for (const stage of ['before', 'current']) { + for (const role of ['passwordrepro', 'scramrepro']) { + for (const invalid of [false, true]) { + results.push(await ordinaryAuth(stage, role, invalid)) + } + } + } + results.push(await cursorAndTransactions()) + fs.writeFileSync('/work/ordinary-auth-and-stream-regressions.json', JSON.stringify({ results }, null, 2)) + console.log(JSON.stringify({ ordinaryBeforeAfterCases: 8, gssCursorAndTransactionCase: 1, allPassed: true })) +} + +main().catch((error) => { + console.error(error) + process.exitCode = 1 +}) diff --git a/packages/pg/test/integration/gss/run-fixture.sh b/packages/pg/test/integration/gss/run-fixture.sh new file mode 100644 index 000000000..12bdb9301 --- /dev/null +++ b/packages/pg/test/integration/gss/run-fixture.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 + +root=/work/fixture +mkdir -p "$root/kdc" "$root/socket" "$root/pgdata" +export KRB5_CONFIG="$root/krb5.conf" +export KRB5_KDC_PROFILE="$root/kdc.conf" +export KRB5CCNAME="FILE:$root/valid.ccache" + +cat > "$KRB5_CONFIG" < "$KRB5_KDC_PROFILE" < "$root/kdc-setup.log" +kadmin.local -q "addprinc -pw $ticket_password fixtureuser@PGTEST.INVALID" >> "$root/kdc-setup.log" 2>&1 +kadmin.local -q 'addprinc -randkey postgres/localhost@PGTEST.INVALID' >> "$root/kdc-setup.log" 2>&1 +kadmin.local -q "ktadd -k $root/server.keytab postgres/localhost@PGTEST.INVALID" >> "$root/kdc-setup.log" 2>&1 + +openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj '/CN=Local GSS fixture CA' \ + -keyout "$root/ca.key" -out "$root/ca.crt" > "$root/certificate.log" 2>&1 +openssl req -newkey rsa:2048 -nodes -subj '/CN=localhost' \ + -keyout "$root/server.key" -out "$root/server.csr" >> "$root/certificate.log" 2>&1 +printf 'subjectAltName=DNS:localhost,IP:127.0.0.1\nextendedKeyUsage=serverAuth\n' > "$root/cert.ext" +openssl x509 -req -in "$root/server.csr" -CA "$root/ca.crt" -CAkey "$root/ca.key" \ + -CAcreateserial -days 1 -extfile "$root/cert.ext" -out "$root/server.crt" >> "$root/certificate.log" 2>&1 + +touch "$root/postgres.log" +chown postgres:postgres "$root/postgres.log" "$root/socket" "$root/pgdata" "$root/server.keytab" "$root/server.key" "$root/server.crt" +chmod 755 "$root" +pgbin=$(dirname "$(find /usr/lib/postgresql -name postgres -type f | head -1)") +runuser -u postgres -- "$pgbin/initdb" -D "$root/pgdata" -A trust > "$root/postgres-setup.log" +cat >> "$root/pgdata/postgresql.conf" <> "$root/postgres-setup.log" +kdc_pid= +sshd_pid= +tunnel_pid= +cleanup() { + local status=$? + trap - EXIT + if [ -n "$tunnel_pid" ]; then kill "$tunnel_pid" 2>/dev/null || true; wait "$tunnel_pid" 2>/dev/null || true; fi + if [ -n "$sshd_pid" ]; then kill "$sshd_pid" 2>/dev/null || true; wait "$sshd_pid" 2>/dev/null || true; fi + if ! runuser -u postgres -- "$pgbin/pg_ctl" -D "$root/pgdata" stop -m fast -w >> "$root/postgres-setup.log" 2>&1; then + printf 'PostgreSQL fixture teardown failed; inspect postgres-setup.log\n' >&2 + status=1 + fi + if [ -n "$kdc_pid" ]; then kill "$kdc_pid" 2>/dev/null || true; wait "$kdc_pid" 2>/dev/null || true; fi + exit "$status" +} +trap cleanup EXIT +runuser -u postgres -- psql -h "$root/socket" -p 55439 -d postgres -v ON_ERROR_STOP=1 \ + -c 'CREATE ROLE pgrepro LOGIN; CREATE ROLE rejectedrole LOGIN;' >> "$root/postgres-setup.log" +runuser -u postgres -- createdb -h "$root/socket" -p 55439 -O pgrepro gssrepro +printf 'local all all trust\nhost all all 127.0.0.1/32 gss include_realm=1 map=fixture\n' > "$root/pgdata/pg_hba.conf" +printf 'fixture fixtureuser@PGTEST.INVALID pgrepro\n' > "$root/pgdata/pg_ident.conf" +chown postgres:postgres "$root/pgdata/pg_hba.conf" "$root/pgdata/pg_ident.conf" +runuser -u postgres -- "$pgbin/pg_ctl" -D "$root/pgdata" reload >> "$root/postgres-setup.log" + +krb5kdc -n > "$root/kdc.log" 2>&1 & +kdc_pid=$! +sleep 1 +printf '%s\n' "$ticket_password" | kinit -c "$root/expired.ccache" -l 1s fixtureuser@PGTEST.INVALID > "$root/expired-ticket.log" 2>&1 +sleep 2 +printf '%s\n' "$ticket_password" | kinit -c "$root/valid.ccache" fixtureuser@PGTEST.INVALID > "$root/valid-ticket.log" 2>&1 +unset master ticket_password + +mkdir -p /run/sshd +ssh-keygen -q -t ed25519 -N '' -f "$root/ssh-client" +ssh-keygen -q -t ed25519 -N '' -f "$root/ssh-host" +cat > "$root/sshd.conf" < "$root/known-hosts" +/usr/sbin/sshd -D -f "$root/sshd.conf" > "$root/sshd.log" 2>&1 & +sshd_pid=$! +node <<'JS' +const net = require('net') +const deadline = Date.now() + 5000 +function probe() { + const socket = net.connect(61122, '127.0.0.1', () => socket.end()) + socket.once('error', (error) => { + if (Date.now() < deadline) setTimeout(probe, 50) + else { console.error(error.message); process.exitCode = 1 } + }) +} +probe() +JS +ssh -N -p 61122 -i "$root/ssh-client" -o UserKnownHostsFile="$root/known-hosts" \ + -o StrictHostKeyChecking=yes -o ExitOnForwardFailure=yes \ + -L 127.0.0.1:55440:127.0.0.1:55439 root@127.0.0.1 > "$root/tunnel.log" 2>&1 & +tunnel_pid=$! +sleep 1 +kill -0 "$tunnel_pid" + +export PGHOST=localhost PGPORT=55439 PGUSER=pgrepro PGDATABASE=gssrepro PGGSSENCMODE=disable +psql "sslmode=verify-full sslrootcert=$root/ca.crt" -w -t -A \ + -c "SELECT gss_authenticated, encrypted FROM pg_catalog.pg_stat_gssapi WHERE pid=pg_backend_pid()" \ + > /work/libpq-gss-control.txt +node /work/current/packages/pg/test/integration/gss/run-real-checks.js +node /work/current/packages/pg/test/integration/gss/regressions.js diff --git a/packages/pg/test/integration/gss/run-real-checks.js b/packages/pg/test/integration/gss/run-real-checks.js new file mode 100644 index 000000000..a303bc8b4 --- /dev/null +++ b/packages/pg/test/integration/gss/run-real-checks.js @@ -0,0 +1,67 @@ +'use strict' + +const assert = require('assert') +const fs = require('fs') +const path = require('path') +const { spawnSync } = require('child_process') + +const cases = [ + 'plain', + 'tls', + 'pool', + 'ssh', + 'ssh-without-database-host', + 'missing-ticket', + 'expired-ticket', + 'invalid-service', + 'rejected-identity', + 'invalid-ca', + 'required-encryption', +] +const results = [] +for (const stage of ['before', 'after']) { + for (const scenario of cases) { + const clientRoot = stage === 'before' ? '/work/before/packages/pg' : '/work/current/packages/pg' + const child = spawnSync(process.execPath, [path.join(__dirname, 'probe-real.js'), scenario], { + env: { ...process.env, PG_GSS_CLIENT_ROOT: clientRoot }, + encoding: 'utf8', + timeout: 12000, + }) + let status + let details = null + const lines = child.stdout.trim().split(/\r?\n/).filter(Boolean) + if (lines.length) details = JSON.parse(lines[lines.length - 1]) + if (child.error) status = 'harness-timeout-or-error' + else if (child.status === 1 && /Unknown authenticationOk message type 7/.test(child.stderr)) + status = 'uncaught-parser-exception' + else if (child.status === 0 && details) status = details.status + else status = 'unexpected' + results.push({ stage, scenario, status, exitCode: child.status, details }) + console.log(JSON.stringify(results[results.length - 1])) + } +} +fs.writeFileSync( + '/work/real-authentication-results.json', + JSON.stringify( + { + fixture: 'disposable local PostgreSQL and MIT Kerberos', + kerberosBinding: require('/work/deps/node_modules/kerberos').version, + node: process.version, + libpqControl: fs.readFileSync('/work/libpq-gss-control.txt', 'utf8').trim(), + results, + }, + null, + 2 + ) +) +for (const result of results) { + if (result.stage === 'after') { + const expected = ['plain', 'tls', 'pool', 'ssh'].includes(result.scenario) ? 'connected' : 'rejected' + assert.strictEqual(result.status, expected, `${result.stage}/${result.scenario}`) + } +} +assert.strictEqual( + results.find((result) => result.stage === 'before' && result.scenario === 'tls').status, + 'uncaught-parser-exception' +) +assert.strictEqual(fs.readFileSync('/work/libpq-gss-control.txt', 'utf8').trim(), 't|f') diff --git a/packages/pg/test/unit/client/gss-session-tests.js b/packages/pg/test/unit/client/gss-session-tests.js new file mode 100644 index 000000000..14d2aafb9 --- /dev/null +++ b/packages/pg/test/unit/client/gss-session-tests.js @@ -0,0 +1,175 @@ +'use strict' + +const assert = require('assert') +const { GssSession, serviceName } = require('../../../lib/crypto/gss') +const { Suite } = require('../../test-helper') +const ConnectionParameters = require('../../../lib/connection-parameters') + +const suite = new Suite() +const initial = Buffer.from([0, 128, 255]) +const middle = Buffer.from([255, 0, 128, 1]) +const firstChallenge = Buffer.from([128, 1, 0]) +const finalChallenge = Buffer.from([255, 2, 0]) + +function mockBinding(step) { + const client = { contextComplete: false, step } + return { + GSS_C_MUTUAL_FLAG: 2, + GSS_C_REPLAY_FLAG: 4, + GSS_C_SEQUENCE_FLAG: 8, + GSS_MECH_OID_KRB5: 9, + GSS_MECH_OID_SPNEGO: 6, + initializeClient: async function (service, options) { + this.service = service + this.options = options + return client + }, + client, + } +} + +function createSession(binding, method = 'GSSAPI') { + const sent = [] + const session = new GssSession( + { krbsrvname: 'postgres', gssHost: 'db.example.test' }, + method, + (token) => { + sent.push(token) + return true + }, + binding + ) + return { session, sent } +} + +for (const method of ['GSSAPI', 'SSPI']) { + suite.test( + `${method} serializes multi-round binary tokens and waits for both context and server acceptance`, + async () => { + const challenges = [] + const binding = mockBinding(async (challenge) => { + challenges.push(Buffer.from(challenge, 'base64')) + if (!challenge) return initial.toString('base64') + if (challenge === firstChallenge.toString('base64')) return middle.toString('base64') + assert.strictEqual(challenge, finalChallenge.toString('base64')) + binding.client.contextComplete = true + return null + }) + const { session, sent } = createSession(binding, method) + session.start() + session.continue(firstChallenge) + session.continue(finalChallenge) + session.accept() + await session.ready() + + assert.deepStrictEqual(challenges, [Buffer.alloc(0), firstChallenge, finalChallenge]) + assert.deepStrictEqual(sent, [initial, middle]) + assert.strictEqual(binding.options.mechOID, method === 'GSSAPI' ? 9 : 6) + assert.strictEqual(binding.options.gssFlags & 1, 0, 'do not delegate credentials') + assert.strictEqual(binding.options.flags & 2, 2, 'request mutual authentication') + assert.strictEqual(session.accepted, true) + session.dispose() + } + ) +} + +suite.test('does not accept server success before the security context completes', async () => { + const { session } = createSession(mockBinding(async () => initial.toString('base64'))) + await session.start() + await assert.rejects(session.accept(), /before the client context completed/) + await assert.rejects(session.ready(), /before the client context completed/) + assert.strictEqual(session.accepted, false) + session.dispose() +}) + +suite.test('does not send an initialization result after cancellation', async () => { + let resolveContext + const binding = mockBinding(async () => initial.toString('base64')) + binding.initializeClient = () => + new Promise((resolve) => { + resolveContext = resolve + }) + const { session, sent } = createSession(binding) + const started = session.start() + await Promise.resolve() + session.dispose() + resolveContext(binding.client) + await started + assert.deepStrictEqual(sent, []) + assert.strictEqual(session.client, null) + await assert.rejects(session.ready(), /did not complete/) +}) + +suite.test('does not send a late security token after cancellation', async () => { + let resolveStep + const { session, sent } = createSession( + mockBinding( + () => + new Promise((resolve) => { + resolveStep = resolve + }) + ) + ) + const started = session.start() + for (let tick = 0; tick < 3; tick++) await Promise.resolve() + assert.strictEqual(typeof resolveStep, 'function') + session.dispose() + resolveStep(initial.toString('base64')) + await started + assert.deepStrictEqual(sent, []) + assert.strictEqual(session.client, null) +}) + +for (const token of [null, '', 42, 'not!base64', Buffer.alloc(65536).toString('base64')]) { + suite.test(`rejects invalid or incomplete security tokens (${typeof token})`, async () => { + const { session, sent } = createSession(mockBinding(async () => token)) + await assert.rejects(session.start(), /no token before context completion|invalid.*token/) + assert.deepStrictEqual(sent, []) + session.dispose() + }) +} + +suite.test('rejects a failed transport write', async () => { + const binding = mockBinding(async () => initial.toString('base64')) + const session = new GssSession({ gssHost: 'db.example.test' }, 'GSSAPI', () => false, binding) + await assert.rejects(session.start(), /closed during GSS authentication/) + session.dispose() +}) + +suite.test('bounds excessive continuation requests', async () => { + const { session } = createSession(mockBinding(async () => initial.toString('base64'))) + await session.start() + for (let round = 0; round < 32; round++) await session.continue(firstChallenge) + await assert.rejects(session.continue(firstChallenge), /negotiation limit/) + session.dispose() +}) + +suite.test('preserves the database hostname through a loopback proxy and uses platform SPN syntax', () => { + const parameters = new ConnectionParameters({ host: '127.0.0.1', gssHost: 'db.example.test', krbsrvname: 'postgres' }) + assert.strictEqual(serviceName(parameters, 'win32'), 'postgres/db.example.test') + assert.strictEqual(serviceName(parameters, 'linux'), 'postgres@db.example.test') + assert.throws(() => serviceName({ gssHost: '/tmp/socket' }, 'linux'), /requires a database hostname/) + assert.throws( + () => serviceName({ gssHost: 'db.example.test', krbsrvname: 'postgres/other' }, 'linux'), + /service name/ + ) +}) + +suite.test('profile settings take precedence over libpq-compatible GSS environment options', () => { + const saved = { service: process.env.PGKRBSRVNAME, encryption: process.env.PGGSSENCMODE } + try { + process.env.PGKRBSRVNAME = 'environment-service' + process.env.PGGSSENCMODE = 'require' + const inherited = new ConnectionParameters({}) + assert.strictEqual(inherited.krbsrvname, 'environment-service') + assert.strictEqual(inherited.gssencmode, 'require') + const explicit = new ConnectionParameters({ krbsrvname: 'explicit-service', gssencmode: 'disable' }) + assert.strictEqual(explicit.krbsrvname, 'explicit-service') + assert.strictEqual(explicit.gssencmode, 'disable') + } finally { + if (saved.service === undefined) delete process.env.PGKRBSRVNAME + else process.env.PGKRBSRVNAME = saved.service + if (saved.encryption === undefined) delete process.env.PGGSSENCMODE + else process.env.PGGSSENCMODE = saved.encryption + } +}) diff --git a/yarn.lock b/yarn.lock index b3b512e2a..969a62644 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2808,6 +2808,11 @@ base64-js@0.0.2: resolved "https://registry.npmjs.org/base64-js/-/base64-js-0.0.2.tgz" integrity sha1-Ak8Pcq+iW3X5wO5zzU9V7Bvtl4Q= +base64-js@^1.3.1: + version "1.5.1" + resolved "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" + integrity sha1-GxtEAWClv3rUC2UPCVljSBkDkwo= + base@^0.11.1: version "0.11.2" resolved "https://registry.npmjs.org/base/-/base-0.11.2.tgz" @@ -2845,6 +2850,15 @@ birpc@0.2.14: resolved "https://registry.yarnpkg.com/birpc/-/birpc-0.2.14.tgz#4a5498771e6ff24cf8ae5f47faf90e76ca2fce03" integrity sha512-37FHE8rqsYM5JEKCnXFyHpBCzvgHEExwVVTq+nUmloInU7l8ezD1TpOhKpS8oe1DTYFqEK27rFZVKG43oTqXRA== +bl@^4.0.3: + version "4.1.0" + resolved "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a" + integrity sha1-RRU1JkGCvsL7vIOmKrmM8R2fezo= + dependencies: + buffer "^5.5.0" + inherits "^2.0.4" + readable-stream "^3.4.0" + blake3-wasm@2.1.5: version "2.1.5" resolved "https://registry.yarnpkg.com/blake3-wasm/-/blake3-wasm-2.1.5.tgz#b22dbb84bc9419ed0159caa76af4b1b132e6ba52" @@ -2933,6 +2947,14 @@ buffer-from@^1.0.0: resolved "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz" integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== +buffer@^5.5.0: + version "5.7.1" + resolved "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0" + integrity sha1-umLnwTEzBTWCGXFghRqPZI6Z7tA= + dependencies: + base64-js "^1.3.1" + ieee754 "^1.1.13" + builtins@^1.0.3: version "1.0.3" resolved "https://registry.npmjs.org/builtins/-/builtins-1.0.3.tgz" @@ -3685,6 +3707,13 @@ decode-uri-component@^0.2.0: resolved "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz" integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= +decompress-response@^6.0.0: + version "6.0.0" + resolved "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc" + integrity sha1-yjh2Et234QS9FthaqwDV7PCcZvw= + dependencies: + mimic-response "^3.1.0" + dedent@^0.7.0: version "0.7.0" resolved "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz" @@ -3702,6 +3731,11 @@ deep-eql@^5.0.1: resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-5.0.2.tgz#4b756d8d770a9257300825d52a2c2cff99c3a341" integrity sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q== +deep-extend@^0.6.0: + version "0.6.0" + resolved "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" + integrity sha1-xPp8lUBKF6nD6Mp+FTcxK3NjMKw= + deep-is@^0.1.3: version "0.1.3" resolved "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz" @@ -3780,6 +3814,11 @@ detect-indent@^5.0.0: resolved "https://registry.npmjs.org/detect-indent/-/detect-indent-5.0.0.tgz" integrity sha1-OHHMCmoALow+Wzz38zYmRnXwa50= +detect-libc@^2.0.0: + version "2.1.2" + resolved "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz#689c5dcdc1900ef5583a4cb9f6d7b473742074ad" + integrity sha1-aJxdzcGQDvVYOky59te0c3QgdK0= + detect-libc@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.3.tgz#f0cd503b40f9939b894697d19ad50895e30cf700" @@ -3891,6 +3930,13 @@ end-of-stream@^1.0.0, end-of-stream@^1.1.0: dependencies: once "^1.4.0" +end-of-stream@^1.4.1: + version "1.4.5" + resolved "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz#7344d711dea40e0b74abc2ed49778743ccedb08c" + integrity sha1-c0TXEd6kDgt0q8LtSXeHQ8ztsIw= + dependencies: + once "^1.4.0" + enhanced-resolve@^5.17.1: version "5.18.1" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.18.1.tgz#728ab082f8b7b6836de51f1637aab5d3b9568faf" @@ -4311,6 +4357,11 @@ expand-brackets@^2.1.4: snapdragon "^0.8.1" to-regex "^3.0.1" +expand-template@^2.0.3: + version "2.0.3" + resolved "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz#6e14b3fcee0f3a6340ecb57d2e8918692052a47c" + integrity sha1-bhSz/O4POmNA7LV9LokYaSBSpHw= + expect-type@^1.1.0: version "1.2.1" resolved "https://registry.yarnpkg.com/expect-type/-/expect-type-1.2.1.tgz#af76d8b357cf5fa76c41c09dafb79c549e75f71f" @@ -4593,6 +4644,11 @@ fromentries@^1.2.0: resolved "https://registry.yarnpkg.com/fromentries/-/fromentries-1.3.2.tgz#e4bca6808816bf8f93b52750f1127f5a6fd86e3a" integrity sha512-cHEpEQHUg0f8XdtZCc2ZAhrHzKzT0MrFUTcvx+hfxYu7rGMDc5SKoXFh+n4YigxsHXRzc6OrCshdR1bWH6HHyg== +fs-constants@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz#6be0de9be998ce16af8afc24497b9ee9b7ccd9ad" + integrity sha1-a+Dem+mYzhavivwkSXue6bfM2a0= + fs-extra@^8.1.0: version "8.1.0" resolved "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz" @@ -4799,6 +4855,11 @@ gitconfiglocal@^1.0.0: dependencies: ini "^1.3.2" +github-from-package@0.0.0: + version "0.0.0" + resolved "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz#97fb5d96bfde8973313f20e8288ef9a167fa64ce" + integrity sha1-l/tdlr/eiXMxPyDoKI75oWf6ZM4= + glob-parent@^3.1.0: version "3.1.0" resolved "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz" @@ -5085,6 +5146,11 @@ iconv-lite@^0.6.2: dependencies: safer-buffer ">= 2.1.2 < 3.0.0" +ieee754@^1.1.13: + version "1.2.1" + resolved "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" + integrity sha1-jrehCmP/8l0VpXsAFYbRd9Gw01I= + iferr@^0.1.5: version "0.1.5" resolved "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz" @@ -5184,7 +5250,7 @@ inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.3: resolved "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== -ini@^1.3.2, ini@^1.3.4: +ini@^1.3.2, ini@^1.3.4, ini@~1.3.0: version "1.3.8" resolved "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz" integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== @@ -5721,6 +5787,14 @@ jsprim@^1.2.2: json-schema "0.2.3" verror "1.10.0" +kerberos@^2.2.2: + version "2.2.2" + resolved "https://registry.npmjs.org/kerberos/-/kerberos-2.2.2.tgz#8660fc3f85b4a6e5d065f7a254bf9b5b8ebed772" + integrity sha1-hmD8P4W0puXQZfeiVL+bW46+13I= + dependencies: + node-addon-api "^6.1.0" + prebuild-install "^7.1.2" + keyv@^4.5.4: version "4.5.4" resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.5.4.tgz#a879a99e29452f942439f2a405e3af8b31d4de93" @@ -6204,6 +6278,11 @@ mimic-fn@^1.0.0: resolved "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz" integrity sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ== +mimic-response@^3.1.0: + version "3.1.0" + resolved "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" + integrity sha1-LR1Zr5wbEpgVrMwsRqAipc4fo8k= + min-indent@^1.0.0: version "1.0.1" resolved "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz" @@ -6300,6 +6379,11 @@ minimist@^1.1.3, minimist@^1.2.0, minimist@^1.2.5: resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz" integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== +minimist@^1.2.3: + version "1.2.8" + resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" + integrity sha1-waRk52kzAuCCoHXO4MBXdBrEdyw= + minipass-collect@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/minipass-collect/-/minipass-collect-2.0.1.tgz#1621bc77e12258a12c60d34e2276ec5c20680863" @@ -6397,6 +6481,11 @@ mixin-deep@^1.2.0: for-in "^1.0.2" is-extendable "^1.0.1" +mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: + version "0.5.3" + resolved "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" + integrity sha1-+hDJEVzG2IZb4iG6R+6b7XhgERM= + mkdirp-promise@^5.0.1: version "5.0.1" resolved "https://registry.npmjs.org/mkdirp-promise/-/mkdirp-promise-5.0.1.tgz" @@ -6536,6 +6625,11 @@ nanomatch@^1.2.9: snapdragon "^0.8.1" to-regex "^3.0.1" +napi-build-utils@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz#13c22c0187fcfccce1461844136372a47ddc027e" + integrity sha1-E8IsAYf8/MzhRhhEE2NypH3cAn4= + natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz" @@ -6556,6 +6650,18 @@ nice-try@^1.0.4: resolved "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz" integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== +node-abi@^3.3.0: + version "3.101.0" + resolved "https://registry.npmjs.org/node-abi/-/node-abi-3.101.0.tgz#3c99775cb0a4ddf4f3f0dad2a9ad940d67ef0052" + integrity sha512-bkb/RkuWCE64eWu1PCh3Fu2pGc9mKRs+kOE+FU2bGHRYlQa86/D321DSATV54AsCQMKz3/xSt9sRgraZTpqdhQ== + dependencies: + semver "^7.3.5" + +node-addon-api@^6.1.0: + version "6.1.0" + resolved "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz#ac8470034e58e67d0c6f1204a18ae6995d9c0d76" + integrity sha1-rIRwA05Y5n0MbxIEoYrmmV2cDXY= + node-fetch-npm@^2.0.2: version "2.0.4" resolved "https://registry.npmjs.org/node-fetch-npm/-/node-fetch-npm-2.0.4.tgz" @@ -7338,6 +7444,24 @@ postgres-range@^1.1.1: resolved "https://registry.yarnpkg.com/postgres-range/-/postgres-range-1.1.4.tgz#a59c5f9520909bcec5e63e8cf913a92e4c952863" integrity sha512-i/hbxIE9803Alj/6ytL7UHQxRvZkI9O4Sy+J3HGc4F4oo/2eQAjTSNJ0bfxyse3bH0nuVesCk+3IRLaMtG3H6w== +prebuild-install@^7.1.2: + version "7.1.3" + resolved "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz#d630abad2b147443f20a212917beae68b8092eec" + integrity sha1-1jCrrSsUdEPyCiEpF76uaLgJLuw= + dependencies: + detect-libc "^2.0.0" + expand-template "^2.0.3" + github-from-package "0.0.0" + minimist "^1.2.3" + mkdirp-classic "^0.5.3" + napi-build-utils "^2.0.0" + node-abi "^3.3.0" + pump "^3.0.0" + rc "^1.2.7" + simple-get "^4.0.0" + tar-fs "^2.0.0" + tunnel-agent "^0.6.0" + prelude-ls@^1.2.1: version "1.2.1" resolved "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz" @@ -7484,6 +7608,16 @@ randombytes@^2.1.0: dependencies: safe-buffer "^5.1.0" +rc@^1.2.7: + version "1.2.8" + resolved "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed" + integrity sha1-zZJL9SAKB1uDwYjNa54hG3/A0+0= + dependencies: + deep-extend "^0.6.0" + ini "~1.3.0" + minimist "^1.2.0" + strip-json-comments "~2.0.1" + read-cmd-shim@^1.0.1: version "1.0.5" resolved "https://registry.npmjs.org/read-cmd-shim/-/read-cmd-shim-1.0.5.tgz" @@ -7592,6 +7726,15 @@ read@1, read@~1.0.1: string_decoder "^1.1.1" util-deprecate "^1.0.1" +readable-stream@^3.1.1, readable-stream@^3.4.0: + version "3.6.2" + resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz#56a9b36ea965c00c5a93ef31eb111a0f11056967" + integrity sha1-VqmzbqllwAxak+8x6xEaDxEFaWc= + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + readdir-scoped-modules@^1.0.0: version "1.1.0" resolved "https://registry.npmjs.org/readdir-scoped-modules/-/readdir-scoped-modules-1.1.0.tgz" @@ -8020,6 +8163,20 @@ signal-exit@^4.0.1: resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== +simple-concat@^1.0.0: + version "1.0.1" + resolved "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz#f46976082ba35c2263f1c8ab5edfe26c41c9552f" + integrity sha1-9Gl2CCujXCJj8cirXt/ibEHJVS8= + +simple-get@^4.0.0: + version "4.0.1" + resolved "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz#4a39db549287c979d352112fa03fd99fd6bc3543" + integrity sha1-SjnbVJKHyXnTUhEvoD/Zn9a8NUM= + dependencies: + decompress-response "^6.0.0" + once "^1.3.1" + simple-concat "^1.0.0" + simple-swizzle@^0.2.2: version "0.2.2" resolved "https://registry.yarnpkg.com/simple-swizzle/-/simple-swizzle-0.2.2.tgz#a4da6b635ffcccca33f70d17cb92592de95e557a" @@ -8499,6 +8656,11 @@ strip-json-comments@^3.1.1: resolved "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== +strip-json-comments@~2.0.1: + version "2.0.1" + resolved "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" + integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo= + strong-log-transformer@^2.0.0: version "2.1.0" resolved "https://registry.npmjs.org/strong-log-transformer/-/strong-log-transformer-2.1.0.tgz" @@ -8546,6 +8708,27 @@ tapable@^2.1.1, tapable@^2.2.0: resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.2.tgz#ab4984340d30cb9989a490032f086dbb8b56d872" integrity sha512-Re10+NauLTMCudc7T5WLFLAwDhQ0JWdrMK+9B2M8zR5hRExKmsRDCBA7/aV/pNJFltmBFO5BAMlQFi/vq3nKOg== +tar-fs@^2.0.0: + version "2.1.5" + resolved "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz#33e9c29413dce0c58ada7ff77db4e5a30afffe70" + integrity sha1-M+nClBPc4MWK2n/3fbTlowr//nA= + dependencies: + chownr "^1.1.1" + mkdirp-classic "^0.5.2" + pump "^3.0.0" + tar-stream "^2.1.4" + +tar-stream@^2.1.4: + version "2.2.0" + resolved "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz#acad84c284136b060dc3faa64474aa9aebd77287" + integrity sha1-rK2EwoQTawYNw/qmRHSqmuvXcoc= + dependencies: + bl "^4.0.3" + end-of-stream "^1.4.1" + fs-constants "^1.0.0" + inherits "^2.0.3" + readable-stream "^3.1.1" + tar@^4.4.10, tar@^4.4.12, tar@^4.4.8: version "4.4.19" resolved "https://registry.npmjs.org/tar/-/tar-4.4.19.tgz"