lab7: базовый коммит из lab6 (bf06167)

Перенесена кодовая база и инфраструктура lab6: NestJS-приложение (API +
worker, RabbitMQ, outbox, S3, OpenTelemetry), Dockerfile, compose.yaml,
infra/{grafana,haproxy,loki,minio,otel/collector.yaml,prometheus,
rabbitmq,tempo}, docs/runbooks, стендовые скрипты, scripts/lab{4,5,6} и
contracts/extensions.openapi.json.

Задание lab7 оставлено своим: README, REPORT, COURSE, CONTRIBUTING,
MAINTAINERS, lab.json, contracts/{openapi,infrastructure,jobs.schema,
attachment-states,examples,observability,trust-matrix,README},
security/THREAT_MODEL.md, tests (включая security.py), compose.example.yaml,
infra/{openbao,otel}/README.md, .github/pull_request_template.md.
Не переносились старые evidence/lab4..lab6 (18 МБ трека lab6) и
неотслеживаемый docs/lab6.html.

Адаптации при переносе:
- docker-проект mtusi-lab6 -> mtusi-lab7, тег образа mtusi-messenger:lab7
  и папка Grafana Messenger lab7 (compose.yaml, scripts/stop-one.sh,
  .env.example, infra/README.md, infra/grafana/provisioning/dashboards),
  чтобы тома и контейнеры не пересекались с lab6;
- Makefile: сохранены BASE_URL=https://localhost:8443 и цель test-security
  из skeleton lab7, добавлены стендовые и проверочные цели lab6;
- .env.example: рабочие переменные приложения и стенда lab6 + блок
  переменных lab7 (PUBLIC_BASE_URL, TLS_*, BAO_*, ARGON2_*) из skeleton.
This commit is contained in:
2026-11-26 15:35:57 +03:00
parent 20afc2c790
commit 3418252554
198 changed files with 33745 additions and 16 deletions
+435
View File
@@ -0,0 +1,435 @@
import {
BadRequestException,
ConflictException,
HttpException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
PayloadTooLargeException,
ServiceUnavailableException,
UnsupportedMediaTypeException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHash, randomUUID } from 'node:crypto';
import { pipeline, Readable, Transform } from 'node:stream';
import type { AppConfig } from '../config/app-config.schema.js';
import { ChatsService } from '../chats/chats.service.js';
import { FaultInjector } from '../jobs/fault-injector.js';
import { JobsRepository } from '../jobs/jobs.repository.js';
import { OutboxRelay } from '../jobs/outbox-relay.service.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { ObjectStorage } from '../storage/object-storage.js';
import type { User } from '../users/user.js';
import {
toAttachment,
type Attachment,
type AttachmentRow,
} from './attachment.js';
import { validateFilename } from './filename.js';
import {
ImageHeader,
ImageInspector,
ImageRejectedError,
} from './image/image-inspector.js';
import { AttachmentsRepository } from './attachments.repository.js';
import { ImageDecoder } from './image/image-decoder.js';
import { UploadSlots } from './upload-slots.js';
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
export function mediaType(header: unknown): string | undefined {
if (typeof header !== 'string') return undefined;
return header.split(';', 1)[0].trim().toLowerCase();
}
export function imageRejection(error: ImageRejectedError): HttpException {
return error.reason === 'too_many_pixels'
? new PayloadTooLargeException(error.message)
: new UnsupportedMediaTypeException(error.message);
}
class UploadInterruptedError extends Error {}
@Injectable()
export class AttachmentsService {
private readonly logger = new Logger(AttachmentsService.name);
private readonly maxUploadBytes: number;
private readonly maxPixels: number;
private readonly uploadTimeoutMs: number;
private readonly pipelineVersion: number;
private readonly maxAttempts: number;
constructor(
config: ConfigService<AppConfig>,
private readonly repository: AttachmentsRepository,
private readonly jobs: JobsRepository,
private readonly relay: OutboxRelay,
private readonly faults: FaultInjector,
private readonly storage: ObjectStorage,
private readonly chats: ChatsService,
private readonly metrics: MetricsService,
private readonly decoder: ImageDecoder,
private readonly slots: UploadSlots,
) {
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
this.uploadTimeoutMs = config.getOrThrow('UPLOAD_TIMEOUT_MS');
this.pipelineVersion = config.getOrThrow('PIPELINE_VERSION');
this.maxAttempts = config.getOrThrow('JOB_MAX_ATTEMPTS');
}
async uploadProxy(
chatId: string,
user: User,
rawFilename: unknown,
contentTypeHeader: unknown,
contentLengthHeader: unknown,
body: Readable | undefined,
): Promise<Attachment> {
const filename = validateFilename(rawFilename);
const declared = mediaType(contentTypeHeader);
if (declared === undefined || !MEDIA_TYPES.has(declared))
throw new UnsupportedMediaTypeException(
'Content-Type must be image/png or image/jpeg',
);
if (
typeof contentLengthHeader !== 'string' ||
!/^\d{1,15}$/u.test(contentLengthHeader)
)
throw new BadRequestException('Content-Length is required');
const contentLength = Number(contentLengthHeader);
if (contentLength === 0 || body === undefined)
throw new UnsupportedMediaTypeException('Image body is empty');
if (contentLength > this.maxUploadBytes)
throw new PayloadTooLargeException('Image is too large');
return this.slots.run(user.id, async () => {
await this.chats.getForUser(chatId, user);
return this.receive(
chatId,
user,
filename,
declared,
contentLength,
body,
);
});
}
private async receive(
chatId: string,
user: User,
filename: string,
declared: string,
contentLength: number,
body: Readable,
): Promise<Attachment> {
const controller = new AbortController();
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
body.destroy(new Error('upload timeout'));
controller.abort();
}, this.uploadTimeoutMs);
const iterator = body[Symbol.asyncIterator]() as AsyncIterator<Buffer>;
const next = async (): Promise<IteratorResult<Buffer>> => {
try {
return await iterator.next();
} catch {
throw new UploadInterruptedError('Upload was interrupted');
}
};
const inspector = new ImageInspector(this.maxPixels);
const head: Buffer[] = [];
let id: string | undefined;
let key = '';
let rejection: unknown;
try {
// Header phase: nothing exists in the database or S3 yet. It is
// bounded by Content-Length (<= MAX_UPLOAD_BYTES): a JPEG may carry
// megabytes of APPn metadata before its frame header.
try {
while (inspector.header === undefined) {
const step = await next();
if (step.done) {
inspector.finish();
throw new ImageRejectedError(
'unsupported_media_type',
'Image header is missing',
);
}
head.push(step.value);
inspector.push(step.value);
}
} catch (error) {
throw this.mapUploadError(error, timedOut);
}
const header = inspector.header as ImageHeader;
if (header.contentType !== declared)
throw new UnsupportedMediaTypeException(
'Image content does not match Content-Type',
);
id = randomUUID();
key = this.storage.stagingKey(id);
await this.repository.insertPending({
id,
chatId,
ownerId: user.id,
filename,
contentType: declared,
uploadMode: 'proxy',
objectKey: this.storage.objectKey(id),
stagingKey: key,
sizeBytes: null,
sha256: null,
ttlMs: this.uploadTimeoutMs,
});
const sha256 = createHash('sha256');
const decoder = this.decoder;
// Copy for the full decode check; bounded by MAX_UPLOAD_BYTES and
// UPLOAD_MAX_IN_FLIGHT, released as soon as the decode starts.
const copy: Buffer[] = [];
let total = 0;
let allSent = false;
const account = (chunk: Buffer, inspect: boolean): boolean => {
total += chunk.length;
if (total > contentLength)
throw new UploadInterruptedError(
'Body exceeds Content-Length',
);
if (inspect) inspector.push(chunk);
sha256.update(chunk);
this.metrics.add('attachments.proxy.bytes_in', chunk.length);
copy.push(chunk);
return total === contentLength;
};
// Validate before the last bytes reach S3: it cannot commit an object
// whose body is incomplete, so an invalid image never becomes an object.
const finalize = async (): Promise<void> => {
inspector.finish();
const data = Buffer.concat(copy, total);
copy.length = 0;
await decoder.verify(data, controller.signal);
// From here S3 may receive the whole body and commit the object
// even if this request fails or times out afterwards.
allSent = true;
};
async function* generate(): AsyncGenerator<Buffer> {
for (const chunk of head) {
if (account(chunk, false)) await finalize();
yield chunk;
}
for (;;) {
const step = await next();
if (step.done) break;
if (account(step.value, true)) await finalize();
yield step.value;
}
if (total < contentLength)
throw new UploadInterruptedError('Upload was interrupted');
}
const readable = Readable.from(
(async function* () {
try {
yield* generate();
} catch (error) {
rejection = error;
throw error;
}
})(),
);
// A failing body must abort the PUT at once: the SDK does not end a
// request whose Content-Length can no longer be satisfied, it would
// hang until the request timeout. The error itself is reported via
// `rejection`; the listener also keeps a late error from crashing us.
readable.on('error', () => controller.abort());
let claimed = false;
let stored = false;
try {
await this.storage.putStream(
key,
readable,
contentLength,
declared,
controller.signal,
);
this.metrics.add(
'attachments.proxy.bytes_to_s3',
contentLength,
);
stored = true;
const row = await this.jobs.acceptUpload(
id,
{
sizeBytes: total,
sha256: sha256.digest('hex'),
width: header.width,
height: header.height,
},
this.pipelineVersion,
this.maxAttempts,
);
if (row === undefined) {
claimed = true;
throw new ServiceUnavailableException();
}
// Durable: staging object + attachment + job + outbox are committed.
// The fault point deliberately sits between COMMIT and publish; the
// relay recovers the outbox row after a crash.
await this.faults.point('api.after_commit_before_publish');
this.relay.kick();
this.metrics.increment('attachments.upload.queued');
return toAttachment(row);
} catch (error) {
readable.destroy();
if (!claimed) {
// After the last byte was handed to S3, a PUT aborted on our
// side may still be committed by S3 after our DELETE: keep the
// row so the sweeper deletes the key again later.
const outcome = await this.compensate(id, key, {
keepRow: allSent && !stored,
});
// acceptUpload failed on our side, but the row is no longer
// pending: the commit may have succeeded with its reply lost.
// If so, the upload is accepted and 202 is the truth.
if (outcome === 'not_pending' && stored) {
const row = await this.repository
.findById(id)
.catch(() => undefined);
if (
row &&
[
'queued',
'processing',
'ready',
'failed',
].includes(row.status)
) {
this.metrics.increment(
'attachments.upload.recovered',
);
return toAttachment(row);
}
}
}
throw this.mapUploadError(rejection ?? error, timedOut);
}
} finally {
clearTimeout(timer);
}
}
private mapUploadError(error: unknown, timedOut: boolean): unknown {
if (error instanceof ImageRejectedError) return imageRejection(error);
if (error instanceof UploadInterruptedError || timedOut)
return new BadRequestException('Upload was interrupted');
return error;
}
/**
* Undoes an upload that did not reach `ready`. The row is claimed first
* (pending -> deleting) and the object is deleted only after a successful
* claim: if PostgreSQL committed `ready` but the reply was lost, the claim
* matches nothing and the object stays. If PostgreSQL is unreachable,
* nothing is deleted; the sweeper finishes the job after expiry + grace
* (a row stuck in `deleting` is re-claimed after a minute).
*/
async compensate(
id: string,
key: string,
options: { keepRow?: boolean } = {},
): Promise<'compensated' | 'not_pending' | 'deferred'> {
try {
if (!(await this.repository.claimForCompensation(id))) {
this.metrics.increment('attachments.compensation_skipped');
return 'not_pending';
}
await this.storage.delete(key);
// A kept `deleting` row is re-claimed by the sweeper after a minute,
// which deletes the key once more and only then the row.
if (!options.keepRow) await this.repository.deleteClaimed(id);
this.metrics.increment('attachments.compensated');
return 'compensated';
} catch (error) {
this.metrics.increment('attachments.compensation_deferred');
this.logger.warn(
`Compensation of attachment ${id} deferred: ${error instanceof Error ? error.message : 'unknown error'}`,
);
return 'deferred';
}
}
async getMetadata(id: string, user: User): Promise<Attachment> {
const row = await this.repository.findVisible(id, user.id);
if (!row) throw new NotFoundException();
const variants =
row.status === 'ready' && row.ready_pipeline_version !== null
? await this.jobs.variantsFor(
row.id,
row.ready_pipeline_version,
)
: [];
return toAttachment(row, variants);
}
async openContent(
id: string,
user: User,
variant: string | undefined,
): Promise<{
row: AttachmentRow;
contentType: string;
sizeBytes: number;
stream: Readable;
}> {
if (
variant !== undefined &&
!['original', 'thumbnail', 'crop', 'optimized'].includes(variant)
)
throw new BadRequestException('variant is invalid');
const row = await this.repository.findVisible(id, user.id);
if (!row) throw new NotFoundException();
if (row.status !== 'ready')
throw new ConflictException('Attachment is not ready');
let key = row.object_key;
let contentType: string = row.content_type;
let sizeBytes = Number(row.size_bytes);
if (variant !== undefined && variant !== 'original') {
if (row.ready_pipeline_version === null)
throw new NotFoundException();
const variants = await this.jobs.variantsFor(
row.id,
row.ready_pipeline_version,
);
const match = variants.find((item) => item.variant === variant);
if (!match) throw new NotFoundException();
key = match.object_key;
contentType = match.content_type;
sizeBytes = Number(match.size_bytes);
}
const source = await this.storage.getStream(key);
if (source === null) {
this.metrics.increment('attachments.object_missing');
this.logger.error(
`Object for ready attachment ${row.id} is missing in storage`,
);
throw new InternalServerErrorException();
}
const metrics = this.metrics;
const counter = new Transform({
transform(chunk: Buffer, _encoding, callback) {
metrics.add('attachments.download.bytes_out', chunk.length);
callback(null, chunk);
},
});
pipeline(source, counter, () => undefined);
return { row, contentType, sizeBytes, stream: counter };
}
}