forked from mtusi2026/mtusi2026lab7
lab7: app security, Argon2id, mTLS, OpenBao client, least-privilege worker
This commit is contained in:
+277
-53
@@ -1,9 +1,11 @@
|
||||
import {
|
||||
connect as amqpConnect,
|
||||
credentials as amqpCredentials,
|
||||
type Channel,
|
||||
type ChannelModel,
|
||||
type ConfirmChannel,
|
||||
type ConsumeMessage,
|
||||
type Options,
|
||||
} from 'amqplib';
|
||||
import {
|
||||
context,
|
||||
@@ -12,15 +14,22 @@ import {
|
||||
type Span,
|
||||
} from '@opentelemetry/api';
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
Optional,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { URL } from 'node:url';
|
||||
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 } from '../telemetry/instruments.js';
|
||||
import { markSpanError, tracer } from '../telemetry/tracing.js';
|
||||
import {
|
||||
assertTopology,
|
||||
JOB_EXCHANGE,
|
||||
@@ -28,8 +37,6 @@ import {
|
||||
JOB_ROUTING_KEY,
|
||||
} from './broker.topology.js';
|
||||
import type { JobMessage } from './job-message.js';
|
||||
import { instruments } from '../telemetry/instruments.js';
|
||||
import { markSpanError, tracer } from '../telemetry/tracing.js';
|
||||
|
||||
export class BrokerUnavailableError extends ServiceUnavailableException {
|
||||
constructor() {
|
||||
@@ -37,6 +44,9 @@ export class BrokerUnavailableError extends ServiceUnavailableException {
|
||||
}
|
||||
}
|
||||
|
||||
export type BrokerRole = 'producer' | 'consumer' | 'both';
|
||||
export type BrokerAuthMechanism = 'external' | 'plain';
|
||||
|
||||
export type ConsumeHandler = (
|
||||
message: ConsumeMessage,
|
||||
channel: Channel,
|
||||
@@ -44,12 +54,64 @@ export type ConsumeHandler = (
|
||||
|
||||
const MAX_RECONNECT_DELAY_MS = 10_000;
|
||||
|
||||
function isAmqpAuthError(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
return (
|
||||
error.message.includes('ACCESS_REFUSED') ||
|
||||
error.message.includes('403')
|
||||
);
|
||||
}
|
||||
|
||||
function parseBrokerUrl(urlString: string | undefined): {
|
||||
protocol?: string;
|
||||
hostname?: string;
|
||||
port?: number;
|
||||
vhost?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
} {
|
||||
if (!urlString) return {};
|
||||
try {
|
||||
const parsed = new URL(urlString);
|
||||
const rawPath = parsed.pathname.replace(/^\/+/u, '');
|
||||
const vhost = rawPath ? decodeURIComponent(rawPath) : undefined;
|
||||
return {
|
||||
protocol: parsed.protocol.replace(/:$/u, ''),
|
||||
hostname: parsed.hostname || undefined,
|
||||
port: parsed.port ? Number(parsed.port) : undefined,
|
||||
vhost,
|
||||
username: parsed.username
|
||||
? decodeURIComponent(parsed.username)
|
||||
: undefined,
|
||||
password: parsed.password
|
||||
? decodeURIComponent(parsed.password)
|
||||
: undefined,
|
||||
};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export type AmqpConnectFn = (
|
||||
url: string | Options.Connect,
|
||||
socketOptions?: unknown,
|
||||
) => Promise<ChannelModel>;
|
||||
|
||||
@Injectable()
|
||||
export class BrokerClient implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(BrokerClient.name);
|
||||
private readonly url: string;
|
||||
private readonly rawUrl: string | undefined;
|
||||
private readonly host: string;
|
||||
private readonly port: number;
|
||||
private readonly vhost: string;
|
||||
private readonly urlUser: string | undefined;
|
||||
private readonly urlPass: string | undefined;
|
||||
private readonly role: BrokerRole;
|
||||
private readonly authMechanism: BrokerAuthMechanism;
|
||||
private readonly passiveTopology: boolean;
|
||||
private readonly deliveryLimit: number;
|
||||
private readonly publishTimeoutMs: number;
|
||||
private readonly connectFn: AmqpConnectFn;
|
||||
private connection: ChannelModel | undefined;
|
||||
private confirmChannel: ConfirmChannel | undefined;
|
||||
private consumeChannel: Channel | undefined;
|
||||
@@ -63,28 +125,53 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
private reconnectDelayMs = 1000;
|
||||
private subscribeDelayMs = 1000;
|
||||
private closing = false;
|
||||
// Unroutable messages are returned before their confirm; the map lets the
|
||||
// return listener reject the exact publish that produced it.
|
||||
private readonly returned = new Map<string, () => void>();
|
||||
private readonly onRotate: () => void;
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
@Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager,
|
||||
@Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore,
|
||||
connectOverride?: AmqpConnectFn,
|
||||
) {
|
||||
this.url = config.getOrThrow('BROKER_URL');
|
||||
const getOpt = <K extends keyof AppConfig>(key: K): AppConfig[K] | undefined =>
|
||||
typeof config.get === 'function' ? config.get(key) : undefined;
|
||||
this.rawUrl = getOpt('BROKER_URL');
|
||||
const parsed = parseBrokerUrl(this.rawUrl);
|
||||
const tlsEnabled =
|
||||
this.tls?.enabled ??
|
||||
(Boolean(getOpt('TLS_ENABLED')) || parsed.protocol === 'amqps');
|
||||
|
||||
this.host = getOpt('BROKER_HOST') ?? parsed.hostname ?? 'broker';
|
||||
this.port =
|
||||
getOpt('BROKER_PORT') ?? parsed.port ?? (tlsEnabled ? 5671 : 5672);
|
||||
this.vhost = getOpt('BROKER_VHOST') ?? parsed.vhost ?? 'messenger';
|
||||
this.urlUser = parsed.username;
|
||||
this.urlPass = parsed.password;
|
||||
this.role = getOpt('BROKER_ROLE') ?? 'both';
|
||||
this.authMechanism =
|
||||
getOpt('BROKER_AUTH_MECHANISM') ??
|
||||
(tlsEnabled ? 'external' : 'plain');
|
||||
this.passiveTopology = getOpt('BROKER_PASSIVE_TOPOLOGY') ?? tlsEnabled;
|
||||
this.deliveryLimit = config.getOrThrow('BROKER_DELIVERY_LIMIT');
|
||||
this.publishTimeoutMs = config.getOrThrow(
|
||||
'BROKER_PUBLISH_TIMEOUT_MS',
|
||||
);
|
||||
this.publishTimeoutMs = config.getOrThrow('BROKER_PUBLISH_TIMEOUT_MS');
|
||||
this.connectFn =
|
||||
connectOverride ??
|
||||
((target, sockOpts) =>
|
||||
amqpConnect(target, sockOpts as Record<string, unknown>));
|
||||
|
||||
this.onRotate = () => {
|
||||
void this.forceReconnect('rotation');
|
||||
};
|
||||
this.tls?.on('reloaded', this.onRotate);
|
||||
this.secrets?.on('rotated:broker', this.onRotate);
|
||||
}
|
||||
|
||||
/**
|
||||
* PRODUCER span around publish + broker confirm. Its context goes into the
|
||||
* AMQP headers (W3C traceparent/tracestate), so the worker's CONSUMER span
|
||||
* becomes its child; the body keeps the context of the transaction that
|
||||
* wrote the outbox row.
|
||||
*/
|
||||
async publish(message: JobMessage | Buffer): Promise<void> {
|
||||
if (this.role === 'consumer') {
|
||||
throw new BrokerUnavailableError();
|
||||
}
|
||||
const attributes = {
|
||||
'messaging.system': 'rabbitmq',
|
||||
'messaging.operation.type': 'send',
|
||||
@@ -131,7 +218,7 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
traceHeaders: Record<string, string>,
|
||||
): Promise<void> {
|
||||
const channel = await this.withTimeout(
|
||||
this.ensureConnected(),
|
||||
this.ensureConfirmChannel(),
|
||||
this.publishTimeoutMs,
|
||||
);
|
||||
const content = Buffer.isBuffer(message)
|
||||
@@ -190,9 +277,12 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
consume(prefetch: number, handler: ConsumeHandler): void {
|
||||
if (this.role === 'producer') {
|
||||
throw new Error('BrokerClient configured as producer cannot consume');
|
||||
}
|
||||
this.prefetch = prefetch;
|
||||
this.handler = handler;
|
||||
this.ensureConnected()
|
||||
this.ensureConnection()
|
||||
.then(() => this.subscribe())
|
||||
.catch(() => this.scheduleSubscribe());
|
||||
}
|
||||
@@ -201,18 +291,42 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
return this.consumerTag !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries queue depth using a short-lived plain channel on the active
|
||||
* connection — NEVER requires `confirmChannel` or `write`/`configure`
|
||||
* permissions, so `BROKER_ROLE=consumer` (worker LeaseReaper) works cleanly
|
||||
* and a denied `checkQueue` cannot terminate `consumeChannel` or `confirmChannel`.
|
||||
*/
|
||||
async queueDepth(
|
||||
queue: string,
|
||||
): Promise<{ messages: number; consumers: number }> {
|
||||
const channel = await this.withTimeout(
|
||||
this.ensureConnected(),
|
||||
const connection = await this.withTimeout(
|
||||
this.ensureConnection(),
|
||||
this.publishTimeoutMs,
|
||||
);
|
||||
const result = await channel.checkQueue(queue);
|
||||
return {
|
||||
messages: result.messageCount,
|
||||
consumers: result.consumerCount,
|
||||
};
|
||||
const channel = await this.withTimeout(
|
||||
connection.createChannel(),
|
||||
this.publishTimeoutMs,
|
||||
);
|
||||
channel.on('error', () => {
|
||||
// Channel-level errors (e.g. 403/404) are handled by the rejected checkQueue promise.
|
||||
});
|
||||
try {
|
||||
const result = await this.withTimeout(
|
||||
channel.checkQueue(queue),
|
||||
this.publishTimeoutMs,
|
||||
);
|
||||
return {
|
||||
messages: result.messageCount,
|
||||
consumers: result.consumerCount,
|
||||
};
|
||||
} finally {
|
||||
try {
|
||||
await channel.close();
|
||||
} catch {
|
||||
// Already closed by broker on channel exception.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async stopConsuming(): Promise<void> {
|
||||
@@ -227,7 +341,7 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
try {
|
||||
await channel.cancel(tag);
|
||||
} catch {
|
||||
// The channel is already closing; there is nothing to cancel.
|
||||
// The channel is already closing.
|
||||
}
|
||||
}
|
||||
if (channel) {
|
||||
@@ -241,6 +355,8 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
this.closing = true;
|
||||
this.tls?.off('reloaded', this.onRotate);
|
||||
this.secrets?.off('rotated:broker', this.onRotate);
|
||||
clearTimeout(this.reconnectTimer);
|
||||
clearTimeout(this.subscribeTimer);
|
||||
this.reconnectTimer = undefined;
|
||||
@@ -255,14 +371,26 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
try {
|
||||
await connection.close();
|
||||
} catch {
|
||||
// Shutdown is best effort; channels are already unusable.
|
||||
// Shutdown is best effort.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async ensureConnected(): Promise<ConfirmChannel> {
|
||||
private async forceReconnect(reason: string): Promise<void> {
|
||||
if (this.closing) return;
|
||||
const connection = this.connection;
|
||||
if (!connection) return;
|
||||
this.logger.log(`Closing AMQP connection for reconnect (${reason})`);
|
||||
try {
|
||||
await connection.close();
|
||||
} catch {
|
||||
this.handleClose();
|
||||
}
|
||||
}
|
||||
|
||||
private async ensureConnection(): Promise<ChannelModel> {
|
||||
if (this.closing) throw new BrokerUnavailableError();
|
||||
if (this.confirmChannel) return this.confirmChannel;
|
||||
if (this.connection) return this.connection;
|
||||
if (!this.connecting) {
|
||||
this.connecting = this.connect()
|
||||
.then(() => undefined)
|
||||
@@ -271,14 +399,91 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
});
|
||||
}
|
||||
await this.connecting;
|
||||
if (!this.connection) throw new BrokerUnavailableError();
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
private async ensureConfirmChannel(): Promise<ConfirmChannel> {
|
||||
await this.ensureConnection();
|
||||
if (!this.confirmChannel) throw new BrokerUnavailableError();
|
||||
return this.confirmChannel;
|
||||
}
|
||||
|
||||
private buildConnectArgs(): {
|
||||
target: string | Options.Connect;
|
||||
socketOptions?: Record<string, unknown>;
|
||||
} {
|
||||
const tlsEnabled = this.tls?.enabled ?? false;
|
||||
if (tlsEnabled) {
|
||||
if (!this.tls?.ca || !this.tls.clientCert || !this.tls.clientKey) {
|
||||
throw new Error(
|
||||
'Broker AMQPS mTLS requires CA, client certificate, and client key',
|
||||
);
|
||||
}
|
||||
const socketOptions = {
|
||||
ca: this.tls.ca,
|
||||
cert: this.tls.clientCert,
|
||||
key: this.tls.clientKey,
|
||||
servername: this.host,
|
||||
rejectUnauthorized: true,
|
||||
minVersion: 'TLSv1.2',
|
||||
};
|
||||
if (this.authMechanism === 'external') {
|
||||
return {
|
||||
target: {
|
||||
protocol: 'amqps',
|
||||
hostname: this.host,
|
||||
port: this.port,
|
||||
vhost: this.vhost,
|
||||
credentials: amqpCredentials.external(),
|
||||
},
|
||||
socketOptions,
|
||||
};
|
||||
}
|
||||
const creds = this.secrets?.getBrokerCredentials();
|
||||
return {
|
||||
target: {
|
||||
protocol: 'amqps',
|
||||
hostname: this.host,
|
||||
port: this.port,
|
||||
vhost: this.vhost,
|
||||
username: creds?.user ?? this.urlUser,
|
||||
password: creds?.password ?? this.urlPass,
|
||||
},
|
||||
socketOptions,
|
||||
};
|
||||
}
|
||||
|
||||
if (this.rawUrl) return { target: this.rawUrl };
|
||||
const creds = this.secrets?.getBrokerCredentials();
|
||||
return {
|
||||
target: {
|
||||
protocol: 'amqp',
|
||||
hostname: this.host,
|
||||
port: this.port,
|
||||
vhost: this.vhost,
|
||||
username: creds?.user ?? this.urlUser,
|
||||
password: creds?.password ?? this.urlPass,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async connect(): Promise<void> {
|
||||
const connection = await amqpConnect(this.url);
|
||||
const { target, socketOptions } = this.buildConnectArgs();
|
||||
let connection: ChannelModel;
|
||||
try {
|
||||
connection = await this.connectFn(target, socketOptions);
|
||||
} catch (error) {
|
||||
if (isAmqpAuthError(error)) {
|
||||
void this.secrets?.refreshNow('broker_auth_error');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
connection.on('error', (error: Error) => {
|
||||
this.metrics.increment('broker.error');
|
||||
if (isAmqpAuthError(error)) {
|
||||
void this.secrets?.refreshNow('broker_auth_error');
|
||||
}
|
||||
this.logger.warn(`Broker connection error: ${error.message}`);
|
||||
});
|
||||
connection.on('close', () => {
|
||||
@@ -286,22 +491,32 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.handleClose();
|
||||
});
|
||||
try {
|
||||
const confirm = await connection.createConfirmChannel();
|
||||
confirm.on('return', (message) => {
|
||||
const correlationId = message.properties?.correlationId;
|
||||
if (!correlationId) return;
|
||||
const reject = this.returned.get(correlationId);
|
||||
if (!reject) return;
|
||||
this.returned.delete(correlationId);
|
||||
this.logger.warn('Broker returned an unroutable job message');
|
||||
reject();
|
||||
});
|
||||
await assertTopology(confirm, this.deliveryLimit);
|
||||
confirm.on('error', (error: Error) => {
|
||||
this.metrics.increment('broker.confirm_error');
|
||||
this.logger.warn(`Broker confirm channel error: ${error.message}`);
|
||||
});
|
||||
confirm.on('close', () => this.handleConfirmClose(confirm));
|
||||
let confirm: ConfirmChannel | undefined;
|
||||
if (this.role !== 'consumer') {
|
||||
confirm = await connection.createConfirmChannel();
|
||||
confirm.on('return', (message) => {
|
||||
const correlationId = message.properties?.correlationId;
|
||||
if (!correlationId) return;
|
||||
const reject = this.returned.get(correlationId);
|
||||
if (!reject) return;
|
||||
this.returned.delete(correlationId);
|
||||
this.logger.warn('Broker returned an unroutable job message');
|
||||
reject();
|
||||
});
|
||||
if (this.passiveTopology) {
|
||||
await confirm.checkExchange(JOB_EXCHANGE);
|
||||
} else {
|
||||
await assertTopology(confirm, this.deliveryLimit);
|
||||
}
|
||||
confirm.on('error', (error: Error) => {
|
||||
this.metrics.increment('broker.confirm_error');
|
||||
this.logger.warn(
|
||||
`Broker confirm channel error: ${error.message}`,
|
||||
);
|
||||
});
|
||||
confirm.on('close', () => this.handleConfirmClose(confirm!));
|
||||
}
|
||||
|
||||
this.connection = connection;
|
||||
this.confirmChannel = confirm;
|
||||
this.reconnectDelayMs = 1000;
|
||||
@@ -309,6 +524,9 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.reconnectTimer = undefined;
|
||||
this.metrics.increment('broker.connected');
|
||||
} catch (error) {
|
||||
if (isAmqpAuthError(error)) {
|
||||
void this.secrets?.refreshNow('broker_auth_error');
|
||||
}
|
||||
if (this.connection === connection) {
|
||||
this.connection = undefined;
|
||||
this.confirmChannel = undefined;
|
||||
@@ -360,6 +578,9 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
try {
|
||||
channel.on('error', (error: Error) => {
|
||||
this.metrics.increment('broker.consumer_error');
|
||||
if (isAmqpAuthError(error)) {
|
||||
void this.secrets?.refreshNow('broker_auth_error');
|
||||
}
|
||||
this.logger.warn(
|
||||
`Broker consumer channel error: ${error.message}`,
|
||||
);
|
||||
@@ -367,7 +588,11 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
});
|
||||
channel.on('close', () => this.handleConsumerClose(channel));
|
||||
await channel.prefetch(this.prefetch);
|
||||
await assertTopology(channel, this.deliveryLimit);
|
||||
if (this.passiveTopology) {
|
||||
await channel.checkQueue(JOB_QUEUE);
|
||||
} else {
|
||||
await assertTopology(channel, this.deliveryLimit);
|
||||
}
|
||||
if (this.handler !== handler) {
|
||||
await channel.close();
|
||||
return;
|
||||
@@ -376,8 +601,6 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
JOB_QUEUE,
|
||||
(message) => {
|
||||
if (!message) {
|
||||
// basic.cancel from the broker: the worker must not stay
|
||||
// healthy while deaf.
|
||||
this.handleConsumerClose(channel);
|
||||
void channel.close().catch(() => undefined);
|
||||
return;
|
||||
@@ -387,8 +610,6 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.logger.error(
|
||||
`Job handler crashed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
// Hold the message briefly instead of burning the
|
||||
// quorum delivery limit in a tight nack loop.
|
||||
setTimeout(() => {
|
||||
try {
|
||||
channel.nack(message, false, true);
|
||||
@@ -404,6 +625,9 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.consumerTag = consumer.consumerTag;
|
||||
this.subscribeDelayMs = 1000;
|
||||
} catch (error) {
|
||||
if (isAmqpAuthError(error)) {
|
||||
void this.secrets?.refreshNow('broker_auth_error');
|
||||
}
|
||||
try {
|
||||
await channel.close();
|
||||
} catch {
|
||||
@@ -444,7 +668,7 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.metrics.increment('broker.reconnect_scheduled');
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = undefined;
|
||||
this.ensureConnected()
|
||||
this.ensureConnection()
|
||||
.then(() => this.subscribe())
|
||||
.catch(() => this.scheduleReconnect());
|
||||
}, delay);
|
||||
@@ -460,7 +684,7 @@ export class BrokerClient implements OnModuleDestroy {
|
||||
this.metrics.increment('broker.subscribe_scheduled');
|
||||
this.subscribeTimer = setTimeout(() => {
|
||||
this.subscribeTimer = undefined;
|
||||
this.ensureConnected()
|
||||
this.ensureConnection()
|
||||
.then(() => this.subscribe())
|
||||
.catch(() => this.scheduleSubscribe());
|
||||
}, delay);
|
||||
|
||||
Reference in New Issue
Block a user