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
+257
View File
@@ -0,0 +1,257 @@
import {
DeleteObjectCommand,
GetObjectCommand,
HeadObjectCommand,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { NodeHttpHandler } from '@smithy/node-http-handler';
import { SpanKind } from '@opentelemetry/api';
import {
Injectable,
Logger,
ServiceUnavailableException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import http from 'node:http';
import { Readable } from 'node:stream';
import type { AppConfig } from '../config/app-config.schema.js';
import { withChildSpan } from '../telemetry/tracing.js';
export class ObjectStorageUnavailableError extends ServiceUnavailableException {
constructor() {
super('Object storage unavailable');
}
}
export type PresignPutOptions = {
contentType: string;
contentLength: number;
checksumSha256Base64: string;
expiresInSeconds: number;
};
function isMissingKey(error: unknown): boolean {
const candidate = error as {
name?: string;
$metadata?: { httpStatusCode?: number };
};
return (
candidate?.name === 'NoSuchKey' ||
candidate?.name === 'NotFound' ||
candidate?.$metadata?.httpStatusCode === 404
);
}
@Injectable()
export class ObjectStorage {
private readonly logger = new Logger(ObjectStorage.name);
private readonly bucket: string;
private readonly internal: S3Client;
private readonly presign: S3Client;
private readonly requestTimeoutMs: number;
constructor(config: ConfigService<AppConfig>) {
this.bucket = config.getOrThrow('S3_BUCKET');
this.requestTimeoutMs = config.getOrThrow('S3_REQUEST_TIMEOUT_MS');
const common = {
region: config.getOrThrow('S3_REGION'),
forcePathStyle: true,
credentials: {
accessKeyId: config.getOrThrow('S3_ACCESS_KEY_ID'),
secretAccessKey: config.getOrThrow('S3_SECRET_ACCESS_KEY'),
},
// Поток нельзя повторить: повтор — решение клиента API.
maxAttempts: 1,
requestChecksumCalculation: 'WHEN_REQUIRED' as const,
responseChecksumValidation: 'WHEN_REQUIRED' as const,
// requestTimeout bounds a request until its response arrives and,
// with throwOnRequestTimeout, actually fails it (otherwise smithy
// only logs a warning); socketTimeout bounds a stalled body read.
// A hung S3 therefore costs at most S3_REQUEST_TIMEOUT_MS per call.
requestHandler: new NodeHttpHandler({
connectionTimeout: config.getOrThrow('S3_CONNECT_TIMEOUT_MS'),
requestTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'),
throwOnRequestTimeout: true,
socketTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'),
httpAgent: new http.Agent({ keepAlive: true, maxSockets: 64 }),
}),
};
this.internal = new S3Client({
...common,
endpoint: config.getOrThrow('S3_ENDPOINT'),
});
// One CLIENT span per S3 call (S3.PutObject, S3.GetObject, …), only
// inside a traced request or job. Object keys contain attachment ids
// and are deliberately not recorded.
this.internal.middlewareStack.add(
(next, handlerContext) => async (args) => {
const operation = String(
handlerContext.commandName ?? 'Unknown',
).replace(/Command$/u, '');
return withChildSpan(
`S3.${operation}`,
SpanKind.CLIENT,
{
'rpc.system': 'aws-api',
'rpc.service': 'S3',
'rpc.method': operation,
'aws.s3.bucket': this.bucket,
},
() => next(args),
);
},
{ step: 'initialize', name: 'messengerTelemetry' },
);
// Сеть не использует: только подпись URL для клиента.
this.presign = new S3Client({
...common,
endpoint: config.getOrThrow('S3_PUBLIC_ENDPOINT'),
});
}
objectKey(attachmentId: string): string {
return `attachments/${attachmentId}/original`;
}
stagingKey(attachmentId: string): string {
return `staging/${attachmentId}/original`;
}
variantKey(
attachmentId: string,
pipelineVersion: number,
variant: 'thumbnail' | 'crop' | 'optimized',
extension: 'jpg' | 'webp',
attempt = 1,
): string {
// The attempt suffix makes a stale worker's write harmless: the DB
// points at the key of the attempt that won the lease fence.
return `attachments/${attachmentId}/v${pipelineVersion}/${variant}-a${attempt}.${extension}`;
}
async putStream(
key: string,
body: Readable,
contentLength: number,
contentType: string,
signal?: AbortSignal,
): Promise<void> {
try {
await this.internal.send(
new PutObjectCommand({
Bucket: this.bucket,
Key: key,
Body: body,
ContentLength: contentLength,
ContentType: contentType,
}),
// The upload deadline (UPLOAD_TIMEOUT_MS, via `signal`) bounds the
// PUT: it lasts as long as the client sends, not S3_REQUEST_TIMEOUT_MS.
// A worker buffer has no client deadline, so it uses the SDK timeout.
signal
? { abortSignal: signal, requestTimeout: 0 }
: { requestTimeout: this.requestTimeoutMs },
);
} catch (error) {
throw this.fail('put', error);
}
}
async putBuffer(
key: string,
data: Buffer,
contentType: string,
signal?: AbortSignal,
): Promise<void> {
await this.putStream(
key,
Readable.from([data]),
data.length,
contentType,
signal,
);
}
async getStream(
key: string,
signal?: AbortSignal,
): Promise<Readable | null> {
try {
const result = await this.internal.send(
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
{ abortSignal: signal },
);
return result.Body as Readable;
} catch (error) {
if (isMissingKey(error)) return null;
throw this.fail('get', error);
}
}
async head(key: string): Promise<{
size: number;
checksumSha256?: string;
etag?: string;
lastModified?: Date;
} | null> {
try {
const result = await this.internal.send(
new HeadObjectCommand({
Bucket: this.bucket,
Key: key,
ChecksumMode: 'ENABLED',
}),
);
return {
size: Number(result.ContentLength ?? 0),
checksumSha256: result.ChecksumSHA256,
etag: result.ETag,
lastModified: result.LastModified,
};
} catch (error) {
if (isMissingKey(error)) return null;
throw this.fail('head', error);
}
}
async delete(key: string): Promise<void> {
try {
await this.internal.send(
new DeleteObjectCommand({ Bucket: this.bucket, Key: key }),
);
} catch (error) {
if (isMissingKey(error)) return;
throw this.fail('delete', error);
}
}
async presignPut(key: string, options: PresignPutOptions): Promise<string> {
return getSignedUrl(
this.presign,
new PutObjectCommand({
Bucket: this.bucket,
Key: key,
ContentType: options.contentType,
ContentLength: options.contentLength,
ChecksumSHA256: options.checksumSha256Base64,
}),
{
expiresIn: options.expiresInSeconds,
signableHeaders: new Set([
'content-type',
'content-length',
'x-amz-checksum-sha256',
]),
unhoistableHeaders: new Set(['x-amz-checksum-sha256']),
},
);
}
private fail(operation: string, error: unknown): Error {
const name = (error as { name?: string })?.name ?? 'UnknownError';
this.logger.warn(`S3 ${operation} failed: ${name}`);
return new ObjectStorageUnavailableError();
}
}
+5
View File
@@ -0,0 +1,5 @@
import { Module } from '@nestjs/common';
import { ObjectStorage } from './object-storage.js';
@Module({ providers: [ObjectStorage], exports: [ObjectStorage] })
export class StorageModule {}