lab7: app security, Argon2id, mTLS, OpenBao client, least-privilege worker

This commit is contained in:
2026-11-26 16:47:23 +03:00
parent 3418252554
commit cda6e27fb8
58 changed files with 6031 additions and 639 deletions
+181 -70
View File
@@ -1,9 +1,18 @@
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
Optional,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SpanKind, type Attributes, type Span } from '@opentelemetry/api';
import { URL } from 'node:url';
import pg from 'pg';
import { MetricsService } from '../metrics/metrics.service.js';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js';
import { TlsMaterialManager } from '../security/tls-material.js';
import { instruments, meter } from '../telemetry/instruments.js';
import { errorType, withChildSpan } from '../telemetry/tracing.js';
@@ -14,13 +23,11 @@ const TRANSACTION_CONTROL =
const SQL_TARGET =
/\b(?:FROM|INTO|UPDATE|JOIN)\s+"?([A-Za-z_][A-Za-z0-9_]*)"?/iu;
/** First SQL keyword (SELECT, INSERT, WITH, …): a bounded attribute. */
function sqlOperation(text: string): string {
const match = /^\s*([A-Za-z]+)/u.exec(text);
return match ? match[1].toUpperCase() : 'OTHER';
}
/** Best-effort table name for span names; never used as a metric label. */
function sqlTarget(text: string): string | undefined {
return SQL_TARGET.exec(text)?.[1]?.toLowerCase();
}
@@ -62,13 +69,37 @@ function statementAttributes(
};
}
/**
* Inside a traced transaction every statement gets its own CLIENT span
* (`UPDATE attachment_jobs`, `INSERT job_outbox`, …) while repository code
* stays unaware of tracing. Transaction control, callback-style calls and
* submittables (cursors, streams) pass through untouched. SQL text and
* parameter values are never recorded.
*/
function isPgAuthError(error: unknown): boolean {
if (typeof error !== 'object' || error === null) return false;
const code = (error as { code?: unknown }).code;
return code === '28P01' || code === '28000';
}
function parseDatabaseUrl(urlString: string | undefined): {
host?: string;
port?: number;
database?: string;
user?: string;
password?: string;
} {
if (!urlString) return {};
try {
const parsed = new URL(urlString);
const dbName = parsed.pathname.replace(/^\/+/u, '');
return {
host: parsed.hostname || undefined,
port: parsed.port ? Number(parsed.port) : undefined,
database: dbName || undefined,
user: parsed.username ? decodeURIComponent(parsed.username) : undefined,
password: parsed.password
? decodeURIComponent(parsed.password)
: undefined,
};
} catch {
return {};
}
}
function tracedClient(client: pg.PoolClient, label: string): pg.PoolClient {
return new Proxy(client, {
get(target, property) {
@@ -95,58 +126,32 @@ function tracedClient(client: pg.PoolClient, label: string): pg.PoolClient {
@Injectable()
export class DatabaseClient implements OnModuleDestroy {
readonly pool: pg.Pool;
private readonly healthPool: pg.Pool;
private activePool: pg.Pool;
private activeHealthPool: pg.Pool;
private readonly logger = new Logger(DatabaseClient.name);
private readonly onRotateDb: () => void;
private readonly onTlsReload: () => void;
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
@Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager,
@Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore,
) {
this.pool = new pg.Pool({
connectionString: this.config.getOrThrow('DATABASE_URL'),
max: this.config.getOrThrow('DATABASE_POOL_MAX'),
connectionTimeoutMillis: this.config.getOrThrow(
'DATABASE_CONNECTION_TIMEOUT_MS',
),
statement_timeout: this.config.getOrThrow(
'DATABASE_STATEMENT_TIMEOUT_MS',
),
// A relay that waits on the broker must not leave the transaction
// idle forever if confirm handling stalls.
options: `-c idle_in_transaction_session_timeout=${this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS')}`,
});
// Idle clients emit 'error' on the pool when the database drops; without a
// listener Node treats it as uncaught and terminates the process.
this.pool.on('error', (error: Error) => {
this.metrics.increment('database.pool_error');
this.logger.warn(`PostgreSQL pool error: ${error.message}`);
});
// Проба готовности не должна стоять в очереди за бизнес-запросами: занятый
// общий пул — это перегрузка, а не потеря зависимости.
this.healthPool = new pg.Pool({
connectionString: this.config.getOrThrow('DATABASE_URL'),
max: 1,
idleTimeoutMillis: 0,
connectionTimeoutMillis:
this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
});
this.healthPool.on('error', (error: Error) => {
this.metrics.increment('database.health_pool_error');
this.logger.warn(
`PostgreSQL health connection error: ${error.message}`,
);
});
this.activePool = this.createMainPool();
this.activeHealthPool = this.createHealthPool();
this.observePool(this.config.getOrThrow('DATABASE_POOL_MAX'));
this.onRotateDb = () => this.rotatePools('secret_rotated');
this.onTlsReload = () => this.rotatePools('tls_reloaded');
this.secrets?.on('rotated:db', this.onRotateDb);
this.tls?.on('reloaded', this.onTlsReload);
}
get pool(): pg.Pool {
return this.activePool;
}
/**
* Same contract as pg.Pool#query — a failed query destroys its connection —
* but the checkout is explicit, so the wait for a pooled connection is
* measured apart from the statement: «the pool is exhausted» and «the
* database is slow» are different incidents with different runbooks.
*/
query<T extends pg.QueryResultRow = pg.QueryResultRow>(
label: string,
text: string,
@@ -167,6 +172,7 @@ export class DatabaseClient implements OnModuleDestroy {
try {
return await client.query<T>({ text, values: [...values] });
} catch (error) {
this.maybeRefreshOnAuthError(error);
failure ??=
error instanceof Error ? error : new Error('Query failed');
throw error;
@@ -180,7 +186,12 @@ export class DatabaseClient implements OnModuleDestroy {
async health(): Promise<void> {
this.metrics.increment('health.database');
await this.healthPool.query('SELECT 1');
try {
await this.activeHealthPool.query('SELECT 1');
} catch (error) {
this.maybeRefreshOnAuthError(error);
throw error;
}
}
withTransaction<T>(
@@ -189,20 +200,12 @@ export class DatabaseClient implements OnModuleDestroy {
return this.transaction('transaction', work);
}
/**
* A labelled transaction: one span for the unit of work with a child span
* per statement and one db.client.operation.duration sample (pool wait
* included) with db.operation.name = TRANSACTION.
*/
transaction<T>(
label: string,
work: (client: pg.PoolClient) => Promise<T>,
): Promise<T> {
return this.observe(label, 'TRANSACTION', undefined, async (span) => {
const client = await this.checkout();
// A server-side idle_in_transaction_session_timeout or a network drop
// can emit 'error' on a checked-out client after pg-pool removed its
// idle listener. Without this listener Node treats it as uncaught.
let fatal: Error | undefined;
const onError = (error: Error): void => {
fatal = error;
@@ -216,6 +219,7 @@ export class DatabaseClient implements OnModuleDestroy {
await client.query('COMMIT');
return result;
} catch (error) {
this.maybeRefreshOnAuthError(error);
try {
await client.query('ROLLBACK');
} catch (rollbackError) {
@@ -224,7 +228,6 @@ export class DatabaseClient implements OnModuleDestroy {
`Rollback failed: ${rollbackError instanceof Error ? rollbackError.message : 'unknown error'}`,
);
}
// Callers must see the operation error, not the rollback error.
throw error;
} finally {
client.removeListener('error', onError);
@@ -234,7 +237,114 @@ export class DatabaseClient implements OnModuleDestroy {
}
async onModuleDestroy(): Promise<void> {
await Promise.all([this.pool.end(), this.healthPool.end()]);
this.secrets?.off('rotated:db', this.onRotateDb);
this.tls?.off('reloaded', this.onTlsReload);
await Promise.all([this.activePool.end(), this.activeHealthPool.end()]);
}
private buildConnectionFields(): pg.PoolConfig {
const getOpt = <K extends keyof AppConfig>(key: K): AppConfig[K] | undefined =>
typeof this.config.get === 'function' ? this.config.get(key) : undefined;
const parsed = parseDatabaseUrl(getOpt('DATABASE_URL'));
const host = getOpt('PG_HOST') ?? parsed.host ?? 'postgres';
const port = getOpt('PG_PORT') ?? parsed.port ?? 5432;
const database = getOpt('PG_DATABASE') ?? parsed.database ?? 'messenger';
const creds = this.secrets?.getDbCredentials();
const user = creds?.user ?? getOpt('PG_USER') ?? parsed.user;
const password =
creds?.password ?? getOpt('PG_PASSWORD') ?? parsed.password;
const tlsEnabled = this.tls?.enabled ?? Boolean(getOpt('TLS_ENABLED'));
const pgMtls = Boolean(getOpt('PG_TLS_MTLS'));
let ssl: pg.PoolConfig['ssl'];
if (tlsEnabled) {
if (!this.tls?.ca) {
throw new Error(
'PostgreSQL TLS requires CA certificate (TLS_CA_FILE)',
);
}
ssl = {
ca: this.tls.ca,
rejectUnauthorized: true,
servername: host,
minVersion: 'TLSv1.2',
...(pgMtls && this.tls.clientCert && this.tls.clientKey
? { cert: this.tls.clientCert, key: this.tls.clientKey }
: {}),
};
}
return {
host,
port,
database,
user,
password,
...(ssl ? { ssl } : {}),
};
}
private createMainPool(): pg.Pool {
const pool = new pg.Pool({
...this.buildConnectionFields(),
max: this.config.getOrThrow('DATABASE_POOL_MAX'),
connectionTimeoutMillis: this.config.getOrThrow(
'DATABASE_CONNECTION_TIMEOUT_MS',
),
statement_timeout: this.config.getOrThrow(
'DATABASE_STATEMENT_TIMEOUT_MS',
),
options: `-c idle_in_transaction_session_timeout=${this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS')}`,
});
pool.on('error', (error: Error) => {
this.metrics.increment('database.pool_error');
this.maybeRefreshOnAuthError(error);
this.logger.warn(`PostgreSQL pool error: ${error.message}`);
});
return pool;
}
private createHealthPool(): pg.Pool {
const pool = new pg.Pool({
...this.buildConnectionFields(),
max: 1,
idleTimeoutMillis: 0,
connectionTimeoutMillis:
this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
});
pool.on('error', (error: Error) => {
this.metrics.increment('database.health_pool_error');
this.maybeRefreshOnAuthError(error);
this.logger.warn(
`PostgreSQL health connection error: ${error.message}`,
);
});
return pool;
}
private rotatePools(reason: string): void {
try {
const nextMain = this.createMainPool();
const nextHealth = this.createHealthPool();
const oldMain = this.activePool;
const oldHealth = this.activeHealthPool;
this.activePool = nextMain;
this.activeHealthPool = nextHealth;
this.logger.log(`Swapped PostgreSQL pools (${reason})`);
void Promise.allSettled([oldMain.end(), oldHealth.end()]);
} catch (error) {
this.logger.warn(
`PostgreSQL pool swap skipped (${reason}): ${error instanceof Error ? error.name : 'unknown error'}`,
);
}
}
private maybeRefreshOnAuthError(error: unknown): void {
if (isPgAuthError(error)) {
void this.secrets?.refreshNow('pg_auth_error');
}
}
private observe<T>(
@@ -271,8 +381,9 @@ export class DatabaseClient implements OnModuleDestroy {
const started = process.hrtime.bigint();
let failure: string | undefined;
try {
return await this.pool.connect();
return await this.activePool.connect();
} catch (error) {
this.maybeRefreshOnAuthError(error);
failure = errorType(error);
throw error;
} finally {
@@ -283,7 +394,6 @@ export class DatabaseClient implements OnModuleDestroy {
}
}
/** Pool saturation: used vs max connections and callers queued for one. */
private observePool(max: number): void {
const m = meter();
const pool = { 'db.client.connection.pool.name': POOL_NAME };
@@ -307,8 +417,9 @@ export class DatabaseClient implements OnModuleDestroy {
);
m.addBatchObservableCallback(
(result) => {
const idle = this.pool.idleCount;
result.observe(count, this.pool.totalCount - idle, {
const current = this.activePool;
const idle = current.idleCount;
result.observe(count, current.totalCount - idle, {
...pool,
'db.client.connection.state': 'used',
});
@@ -317,7 +428,7 @@ export class DatabaseClient implements OnModuleDestroy {
'db.client.connection.state': 'idle',
});
result.observe(limit, max, pool);
result.observe(pending, this.pool.waitingCount, pool);
result.observe(pending, current.waitingCount, pool);
},
[count, limit, pending],
);