Перенесена кодовая база и инфраструктура 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.
294 lines
8.9 KiB
TypeScript
294 lines
8.9 KiB
TypeScript
import {
|
|
ConflictException,
|
|
HttpException,
|
|
Injectable,
|
|
NotFoundException,
|
|
PayloadTooLargeException,
|
|
UnsupportedMediaTypeException,
|
|
} from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { randomUUID } from 'node:crypto';
|
|
import type { AppConfig } from '../config/app-config.schema.js';
|
|
import { ChatsService } from '../chats/chats.service.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,
|
|
ObjectStorageUnavailableError,
|
|
} from '../storage/object-storage.js';
|
|
import type { User } from '../users/user.js';
|
|
import {
|
|
toAttachment,
|
|
type Attachment,
|
|
type AttachmentRow,
|
|
} from './attachment.js';
|
|
import { AttachmentsRepository } from './attachments.repository.js';
|
|
import { imageRejection } from './attachments.service.js';
|
|
import type { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js';
|
|
import { validateFilename } from './filename.js';
|
|
import { ImageDecoder } from './image/image-decoder.js';
|
|
import { UploadSlots } from './upload-slots.js';
|
|
import {
|
|
ImageInspector,
|
|
ImageRejectedError,
|
|
type ImageHeader,
|
|
} from './image/image-inspector.js';
|
|
|
|
export type DirectUpload = {
|
|
attachment_id: string;
|
|
method: 'PUT';
|
|
url: string;
|
|
headers: Record<string, string>;
|
|
expires_at: string;
|
|
};
|
|
|
|
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
|
|
|
|
@Injectable()
|
|
export class DirectUploadsService {
|
|
private readonly maxUploadBytes: number;
|
|
private readonly maxPixels: number;
|
|
private readonly uploadTimeoutMs: number;
|
|
private readonly ttlSeconds: number;
|
|
private readonly maxPending: 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 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.ttlSeconds = config.getOrThrow('DIRECT_UPLOAD_URL_TTL_SECONDS');
|
|
this.maxPending = config.getOrThrow(
|
|
'DIRECT_UPLOAD_MAX_PENDING_PER_USER',
|
|
);
|
|
this.pipelineVersion = config.getOrThrow('PIPELINE_VERSION');
|
|
this.maxAttempts = config.getOrThrow('JOB_MAX_ATTEMPTS');
|
|
}
|
|
|
|
async init(
|
|
chatId: string,
|
|
user: User,
|
|
dto: CreateDirectUploadDto,
|
|
): Promise<DirectUpload> {
|
|
const filename = validateFilename(dto.filename);
|
|
if (!MEDIA_TYPES.has(dto.content_type))
|
|
throw new UnsupportedMediaTypeException(
|
|
'content_type must be image/png or image/jpeg',
|
|
);
|
|
if (dto.size_bytes > this.maxUploadBytes)
|
|
throw new PayloadTooLargeException('Image is too large');
|
|
await this.chats.getForUser(chatId, user);
|
|
const id = randomUUID();
|
|
const stagingKey = this.storage.stagingKey(id);
|
|
const inserted = await this.repository.insertPendingLimited(
|
|
{
|
|
id,
|
|
chatId,
|
|
ownerId: user.id,
|
|
filename,
|
|
contentType: dto.content_type,
|
|
uploadMode: 'direct',
|
|
objectKey: this.storage.objectKey(id),
|
|
stagingKey,
|
|
sizeBytes: dto.size_bytes,
|
|
sha256: dto.sha256,
|
|
ttlMs: this.ttlSeconds * 1000,
|
|
},
|
|
this.maxPending,
|
|
);
|
|
if (!inserted)
|
|
throw new HttpException(
|
|
{
|
|
message: 'Too many unfinished direct uploads',
|
|
retryAfter: this.ttlSeconds,
|
|
},
|
|
429,
|
|
);
|
|
const checksum = Buffer.from(dto.sha256, 'hex').toString('base64');
|
|
let url: string;
|
|
try {
|
|
url = await this.storage.presignPut(stagingKey, {
|
|
contentType: dto.content_type,
|
|
contentLength: dto.size_bytes,
|
|
checksumSha256Base64: checksum,
|
|
expiresInSeconds: this.ttlSeconds,
|
|
});
|
|
} catch (error) {
|
|
await this.repository.deletePending(id);
|
|
throw error;
|
|
}
|
|
this.metrics.increment('attachments.direct.initiated');
|
|
return {
|
|
attachment_id: id,
|
|
method: 'PUT',
|
|
url,
|
|
headers: {
|
|
'Content-Type': dto.content_type,
|
|
'x-amz-checksum-sha256': checksum,
|
|
},
|
|
expires_at: new Date(
|
|
Date.now() + this.ttlSeconds * 1000,
|
|
).toISOString(),
|
|
};
|
|
}
|
|
|
|
async complete(attachmentId: string, user: User): Promise<Attachment> {
|
|
const row = await this.repository.findForComplete(
|
|
attachmentId,
|
|
user.id,
|
|
);
|
|
if (!row) throw new NotFoundException();
|
|
if (row.status !== 'pending') return this.describe(row);
|
|
return this.slots.run(user.id, () => this.verifyAndAccept(row));
|
|
}
|
|
|
|
private async describe(row: AttachmentRow): Promise<Attachment> {
|
|
const variants =
|
|
row.status === 'ready' && row.ready_pipeline_version !== null
|
|
? await this.jobs.variantsFor(
|
|
row.id,
|
|
row.ready_pipeline_version,
|
|
)
|
|
: [];
|
|
return toAttachment(row, variants);
|
|
}
|
|
|
|
private async verifyAndAccept(row: AttachmentRow): Promise<Attachment> {
|
|
const size = Number(row.size_bytes);
|
|
const stagingKey = row.staging_key;
|
|
if (stagingKey === null)
|
|
throw new ConflictException('Upload has not been received');
|
|
const expectedChecksum = Buffer.from(
|
|
row.sha256 as string,
|
|
'hex',
|
|
).toString('base64');
|
|
const head = await this.storage.head(stagingKey);
|
|
if (head === null)
|
|
throw new ConflictException('Upload has not been received');
|
|
if (head.size !== size || head.checksumSha256 !== expectedChecksum) {
|
|
await this.reject(row, stagingKey);
|
|
throw new ConflictException(
|
|
'Uploaded object does not match the declaration',
|
|
);
|
|
}
|
|
|
|
let header: ImageHeader;
|
|
try {
|
|
header = await this.verifyObject(stagingKey, size);
|
|
} catch (error) {
|
|
if (error instanceof ImageRejectedError) {
|
|
await this.reject(row, stagingKey);
|
|
throw imageRejection(error);
|
|
}
|
|
throw error;
|
|
}
|
|
if (header.contentType !== row.content_type) {
|
|
await this.reject(row, stagingKey);
|
|
throw new UnsupportedMediaTypeException(
|
|
'Image content does not match content_type',
|
|
);
|
|
}
|
|
const accepted = await this.jobs.acceptUpload(
|
|
row.id,
|
|
{
|
|
sizeBytes: size,
|
|
sha256: row.sha256 as string,
|
|
width: header.width,
|
|
height: header.height,
|
|
},
|
|
this.pipelineVersion,
|
|
this.maxAttempts,
|
|
);
|
|
if (!accepted) {
|
|
// A parallel complete of the same upload won: answer like a repeat.
|
|
const current = await this.repository.findForComplete(
|
|
row.id,
|
|
row.owner_id,
|
|
);
|
|
if (current && current.status !== 'pending')
|
|
return this.describe(current);
|
|
throw new ConflictException('Upload is no longer pending');
|
|
}
|
|
this.relay.kick();
|
|
this.metrics.increment('attachments.direct.completed');
|
|
return toAttachment(accepted);
|
|
}
|
|
|
|
/**
|
|
* Reads the whole object: a correct signed checksum only proves that the
|
|
* bytes are the ones the client declared, not that they form an image. The
|
|
* stream goes through ImageInspector (structure, CRCs, completeness), then
|
|
* the copy is fully decoded. Memory is bounded like a proxy upload.
|
|
*/
|
|
private async verifyObject(
|
|
key: string,
|
|
size: number,
|
|
): Promise<ImageHeader> {
|
|
// Same deadline as a proxy upload: a slow or hung read releases its slot.
|
|
const signal = AbortSignal.timeout(this.uploadTimeoutMs);
|
|
const stream = await this.storage.getStream(key, signal);
|
|
if (stream === null)
|
|
throw new ConflictException('Upload has not been received');
|
|
const inspector = new ImageInspector(this.maxPixels);
|
|
const chunks: Buffer[] = [];
|
|
let read = 0;
|
|
try {
|
|
for await (const chunk of stream as AsyncIterable<Buffer>) {
|
|
read += chunk.length;
|
|
if (read > size)
|
|
throw new ImageRejectedError(
|
|
'unsupported_media_type',
|
|
'Object is larger than declared',
|
|
);
|
|
inspector.push(chunk);
|
|
chunks.push(chunk);
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof ImageRejectedError) throw error;
|
|
// The object stream broke mid-read (S3 outage, timeout): the image
|
|
// was not judged, so this is an outage, not a client error.
|
|
throw new ObjectStorageUnavailableError();
|
|
} finally {
|
|
stream.destroy();
|
|
this.metrics.add('attachments.direct.verify_bytes', read);
|
|
}
|
|
const header = inspector.finish();
|
|
const data = Buffer.concat(chunks, read);
|
|
chunks.length = 0;
|
|
await this.decoder.verify(data, signal);
|
|
return header;
|
|
}
|
|
|
|
/**
|
|
* A rejected claim keeps its row (status `rejected`, original expiry) while
|
|
* the signed URL may still be used: a later re-PUT would otherwise leave an
|
|
* object that no row refers to. The sweeper removes both after expiry + grace.
|
|
*/
|
|
private async reject(
|
|
row: AttachmentRow,
|
|
stagingKey: string,
|
|
): Promise<void> {
|
|
// Row first: a row that is not pending any more (accepted after a parallel
|
|
// complete, or claimed by the sweeper) keeps its object.
|
|
if (!(await this.repository.rejectPending(row.id))) return;
|
|
try {
|
|
await this.storage.delete(stagingKey);
|
|
} catch {
|
|
// The sweeper deletes the object again after expiry.
|
|
}
|
|
this.metrics.increment('attachments.direct.rejected');
|
|
}
|
|
}
|