lab7: app security, Argon2id, mTLS, OpenBao client, least-privilege worker
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import {
|
||||
BrokerClient,
|
||||
BrokerUnavailableError,
|
||||
type AmqpConnectFn,
|
||||
} from './broker.client.js';
|
||||
import { JOB_EXCHANGE, JOB_QUEUE } from './broker.topology.js';
|
||||
|
||||
function makeConfig(overrides: Record<string, unknown> = {}) {
|
||||
const values: Record<string, unknown> = {
|
||||
BROKER_HOST: 'broker',
|
||||
BROKER_PORT: 5671,
|
||||
BROKER_VHOST: 'messenger',
|
||||
BROKER_ROLE: 'consumer',
|
||||
BROKER_AUTH_MECHANISM: 'external',
|
||||
BROKER_PASSIVE_TOPOLOGY: true,
|
||||
BROKER_DELIVERY_LIMIT: 10,
|
||||
BROKER_PUBLISH_TIMEOUT_MS: 2000,
|
||||
TLS_ENABLED: true,
|
||||
...overrides,
|
||||
};
|
||||
return {
|
||||
get: (k: string) => values[k],
|
||||
getOrThrow: (k: string) => values[k],
|
||||
};
|
||||
}
|
||||
|
||||
function makeFakeTls() {
|
||||
const emitter = new EventEmitter();
|
||||
return Object.assign(emitter, {
|
||||
enabled: true,
|
||||
ca: Buffer.from('CA'),
|
||||
clientCert: Buffer.from('CERT'),
|
||||
clientKey: Buffer.from('KEY'),
|
||||
});
|
||||
}
|
||||
|
||||
describe('BrokerClient least-privilege consumer & producer modes', () => {
|
||||
it('consumer mode uses AMQPS EXTERNAL, ZERO confirmChannel, passive checkQueue, and plain channel for queueDepth', async () => {
|
||||
const checkQueue = vi.fn(async () => ({
|
||||
queue: JOB_QUEUE,
|
||||
messageCount: 4,
|
||||
consumerCount: 1,
|
||||
}));
|
||||
const assertExchange = vi.fn();
|
||||
const assertQueue = vi.fn();
|
||||
const consume = vi.fn(async () => ({ consumerTag: 'ctag-1' }));
|
||||
const prefetch = vi.fn(async () => undefined);
|
||||
const closeChannel = vi.fn(async () => undefined);
|
||||
|
||||
const createConfirmChannel = vi.fn();
|
||||
const createChannel = vi.fn(async () =>
|
||||
Object.assign(new EventEmitter(), {
|
||||
checkQueue,
|
||||
assertExchange,
|
||||
assertQueue,
|
||||
consume,
|
||||
prefetch,
|
||||
close: closeChannel,
|
||||
cancel: vi.fn(async () => undefined),
|
||||
}),
|
||||
);
|
||||
|
||||
const connection = Object.assign(new EventEmitter(), {
|
||||
createConfirmChannel,
|
||||
createChannel,
|
||||
close: vi.fn(async () => undefined),
|
||||
});
|
||||
|
||||
const connectFn = vi.fn<AmqpConnectFn>(async () => connection as never);
|
||||
const client = new BrokerClient(
|
||||
makeConfig({ BROKER_ROLE: 'consumer' }) as never,
|
||||
new MetricsService(),
|
||||
makeFakeTls() as never,
|
||||
undefined,
|
||||
connectFn,
|
||||
);
|
||||
|
||||
try {
|
||||
// queueDepth must work in consumer mode without confirmChannel!
|
||||
const depth = await client.queueDepth(JOB_QUEUE);
|
||||
expect(depth).toEqual({ messages: 4, consumers: 1 });
|
||||
expect(createConfirmChannel).not.toHaveBeenCalled();
|
||||
expect(assertExchange).not.toHaveBeenCalled();
|
||||
expect(assertQueue).not.toHaveBeenCalled();
|
||||
expect(closeChannel).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Verify AMQPS + EXTERNAL + mTLS socket options were passed.
|
||||
const [target, sockOpts] = connectFn.mock.calls[0];
|
||||
expect(target).toMatchObject({
|
||||
protocol: 'amqps',
|
||||
hostname: 'broker',
|
||||
port: 5671,
|
||||
vhost: 'messenger',
|
||||
});
|
||||
expect((target as { credentials?: { mechanism?: string } }).credentials?.mechanism).toBe(
|
||||
'EXTERNAL',
|
||||
);
|
||||
expect(sockOpts).toMatchObject({
|
||||
servername: 'broker',
|
||||
rejectUnauthorized: true,
|
||||
minVersion: 'TLSv1.2',
|
||||
});
|
||||
|
||||
// Consumer cannot publish.
|
||||
await expect(
|
||||
client.publish(Buffer.from('forged')),
|
||||
).rejects.toBeInstanceOf(BrokerUnavailableError);
|
||||
|
||||
// Subscribe uses passive checkQueue only.
|
||||
client.consume(2, async () => undefined);
|
||||
await vi.waitFor(() => expect(client.isConsuming()).toBe(true));
|
||||
expect(createConfirmChannel).not.toHaveBeenCalled();
|
||||
expect(assertQueue).not.toHaveBeenCalled();
|
||||
expect(consume).toHaveBeenCalledWith(
|
||||
JOB_QUEUE,
|
||||
expect.any(Function),
|
||||
{ noAck: false },
|
||||
);
|
||||
} finally {
|
||||
await client.onModuleDestroy();
|
||||
}
|
||||
});
|
||||
|
||||
it('producer mode uses confirmChannel + passive checkExchange and refuses consume()', async () => {
|
||||
const checkExchange = vi.fn(async () => ({}));
|
||||
const assertExchange = vi.fn();
|
||||
const publish = vi.fn(
|
||||
(
|
||||
_ex: string,
|
||||
_rk: string,
|
||||
_buf: Buffer,
|
||||
_opts: unknown,
|
||||
cb: (err: Error | null) => void,
|
||||
) => cb(null),
|
||||
);
|
||||
|
||||
const confirm = Object.assign(new EventEmitter(), {
|
||||
checkExchange,
|
||||
assertExchange,
|
||||
publish,
|
||||
});
|
||||
const connection = Object.assign(new EventEmitter(), {
|
||||
createConfirmChannel: vi.fn(async () => confirm),
|
||||
createChannel: vi.fn(),
|
||||
close: vi.fn(async () => undefined),
|
||||
});
|
||||
|
||||
const client = new BrokerClient(
|
||||
makeConfig({ BROKER_ROLE: 'producer' }) as never,
|
||||
new MetricsService(),
|
||||
makeFakeTls() as never,
|
||||
undefined,
|
||||
vi.fn<AmqpConnectFn>(async () => connection as never),
|
||||
);
|
||||
|
||||
try {
|
||||
await client.publish(Buffer.from('job'));
|
||||
expect(checkExchange).toHaveBeenCalledWith(JOB_EXCHANGE);
|
||||
expect(assertExchange).not.toHaveBeenCalled();
|
||||
expect(() => client.consume(1, async () => undefined)).toThrow(
|
||||
/producer cannot consume/i,
|
||||
);
|
||||
} finally {
|
||||
await client.onModuleDestroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
+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);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Inject, Injectable, Logger, Optional } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
@@ -44,7 +44,7 @@ export class FaultInjector {
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
private readonly redis: RedisClient,
|
||||
@Optional() @Inject(RedisClient) private readonly redis: RedisClient | undefined,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
this.enabled = config.getOrThrow('FAULT_INJECTION_ENABLED') === 1;
|
||||
@@ -55,7 +55,7 @@ export class FaultInjector {
|
||||
target?: FaultTarget,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
if (!this.enabled) return;
|
||||
if (!this.enabled || !this.redis) return;
|
||||
const keys = target
|
||||
? [
|
||||
`fault:${name}:${target.attachmentId}:${target.pipelineVersion}`,
|
||||
|
||||
@@ -1,23 +1,28 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { WorkerConfigModule } from '../config/worker-config.module.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { AppConfigModule } from '../config/app-config.module.js';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import {
|
||||
RuntimeSecretsStore,
|
||||
type SecretRole,
|
||||
} from '../openbao/runtime-secrets.service.js';
|
||||
import { SecurityModule, registerBootstrappedSecurity } from '../security/security.module.js';
|
||||
import { TlsMaterialManager } from '../security/tls-material.js';
|
||||
import { ObjectStorage } from '../storage/object-storage.js';
|
||||
import { StorageModule } from '../storage/storage.module.js';
|
||||
import { DEAD_LETTER_QUEUE, JOB_QUEUE } from './broker.topology.js';
|
||||
import { BrokerClient } from './broker.client.js';
|
||||
import { DEAD_LETTER_QUEUE, JOB_QUEUE } from './broker.topology.js';
|
||||
import { JobsModule } from './jobs.module.js';
|
||||
import { JobsRepository } from './jobs.repository.js';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
AppConfigModule,
|
||||
WorkerConfigModule,
|
||||
SecurityModule,
|
||||
DatabaseModule,
|
||||
RedisModule,
|
||||
MetricsModule,
|
||||
StorageModule,
|
||||
JobsModule,
|
||||
@@ -58,9 +63,28 @@ async function s3State(
|
||||
: { exists: false, etag: null, last_modified: null };
|
||||
}
|
||||
|
||||
function detectCliRole(raw: Record<string, unknown>): SecretRole {
|
||||
const certRole = String(raw.BAO_CERT_ROLE ?? raw.BAO_AUTH_ROLE ?? '');
|
||||
const brokerRole = String(raw.BROKER_ROLE ?? '');
|
||||
if (certRole.includes('worker') || brokerRole === 'consumer') return 'worker';
|
||||
return 'api';
|
||||
}
|
||||
|
||||
async function main(): Promise<number> {
|
||||
const args = process.argv.slice(2);
|
||||
const command = args[0];
|
||||
const rawEnv = process.env as Record<string, unknown>;
|
||||
const role = detectCliRole(rawEnv);
|
||||
const tlsMaterial = TlsMaterialManager.initFromEnv('cli', rawEnv);
|
||||
const secretsStore = await RuntimeSecretsStore.bootstrap(
|
||||
role,
|
||||
tlsMaterial,
|
||||
rawEnv,
|
||||
undefined,
|
||||
{ background: false },
|
||||
);
|
||||
registerBootstrappedSecurity(tlsMaterial, secretsStore);
|
||||
|
||||
const app = await NestFactory.createApplicationContext(JobsCliModule, {
|
||||
logger: false,
|
||||
});
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import { BrokerClient } from './broker.client.js';
|
||||
import { FaultInjector } from './fault-injector.js';
|
||||
import { JobsRepository } from './jobs.repository.js';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, RedisModule, MetricsModule],
|
||||
imports: [DatabaseModule, MetricsModule],
|
||||
providers: [BrokerClient, JobsRepository, FaultInjector],
|
||||
exports: [BrokerClient, JobsRepository, FaultInjector],
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user