forked from mtusi2026/mtusi2026lab7
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:
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import { ObjectStorage } from '../storage/object-storage.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
|
||||
const SWEEP_BATCH = 100;
|
||||
|
||||
/**
|
||||
* Removes unfinished uploads (pending past expiry + grace) and rows whose
|
||||
* deletion was claimed but never finished. A live upload is never touched:
|
||||
* its expiry is a hard request deadline and the grace period is far longer.
|
||||
*/
|
||||
@Injectable()
|
||||
export class AttachmentSweeper implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(AttachmentSweeper.name);
|
||||
private timer: NodeJS.Timeout | undefined;
|
||||
private running = false;
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly repository: AttachmentsRepository,
|
||||
private readonly storage: ObjectStorage,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
const interval = this.config.getOrThrow('ATTACHMENT_SWEEP_INTERVAL_MS');
|
||||
if (interval <= 0) return;
|
||||
this.timer = setInterval(() => {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.sweepOnce()
|
||||
.catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Sweep failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
this.running = false;
|
||||
});
|
||||
}, interval);
|
||||
this.timer.unref();
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = undefined;
|
||||
}
|
||||
|
||||
async sweepOnce(): Promise<{ claimed: number; deleted: number }> {
|
||||
const claimed = await this.repository.claimExpired(
|
||||
this.config.getOrThrow('ATTACHMENT_SWEEP_GRACE_SECONDS'),
|
||||
SWEEP_BATCH,
|
||||
);
|
||||
let deleted = 0;
|
||||
for (const item of claimed) {
|
||||
try {
|
||||
// New uploads live in staging; lab4 rows have no staging key and
|
||||
// their final object is the only copy.
|
||||
await this.storage.delete(item.staging_key ?? item.object_key);
|
||||
await this.repository.deleteClaimed(item.id);
|
||||
deleted += 1;
|
||||
this.metrics.increment('attachments.sweep.deleted');
|
||||
} catch (error) {
|
||||
this.metrics.increment('attachments.sweep.error');
|
||||
this.logger.warn(
|
||||
`Sweep of attachment ${item.id} failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return { claimed: claimed.length, deleted };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
export type AttachmentStatus = 'queued' | 'processing' | 'ready' | 'failed';
|
||||
export type VariantName = 'thumbnail' | 'crop' | 'optimized';
|
||||
|
||||
export const VARIANT_ORDER: VariantName[] = ['thumbnail', 'crop', 'optimized'];
|
||||
|
||||
export type Variant = {
|
||||
name: VariantName;
|
||||
content_type: 'image/jpeg' | 'image/png' | 'image/webp';
|
||||
size_bytes: number;
|
||||
width: number;
|
||||
height: number;
|
||||
sha256: string;
|
||||
};
|
||||
|
||||
export type Attachment = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
owner_id: string;
|
||||
filename: string;
|
||||
content_type: 'image/png' | 'image/jpeg';
|
||||
size_bytes: number;
|
||||
sha256: string;
|
||||
status: AttachmentStatus;
|
||||
variants: Variant[];
|
||||
error_code: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type AttachmentRow = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
owner_id: string;
|
||||
filename: string;
|
||||
content_type: 'image/png' | 'image/jpeg';
|
||||
upload_mode: 'proxy' | 'direct';
|
||||
status:
|
||||
| 'pending'
|
||||
| 'queued'
|
||||
| 'processing'
|
||||
| 'ready'
|
||||
| 'failed'
|
||||
| 'deleting'
|
||||
| 'rejected';
|
||||
object_key: string;
|
||||
staging_key: string | null;
|
||||
size_bytes: string | number | null;
|
||||
sha256: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
error_code: string | null;
|
||||
ready_pipeline_version: number | null;
|
||||
expires_at: Date | null;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
};
|
||||
|
||||
export type VariantRow = {
|
||||
attachment_id: string;
|
||||
pipeline_version: number;
|
||||
variant: VariantName;
|
||||
object_key: string;
|
||||
content_type: 'image/jpeg' | 'image/png' | 'image/webp';
|
||||
size_bytes: string | number;
|
||||
width: number;
|
||||
height: number;
|
||||
sha256: string;
|
||||
job_id: string;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
function toVariant(row: VariantRow): Variant {
|
||||
return {
|
||||
name: row.variant,
|
||||
content_type: row.content_type,
|
||||
size_bytes: Number(row.size_bytes),
|
||||
width: row.width,
|
||||
height: row.height,
|
||||
sha256: row.sha256,
|
||||
};
|
||||
}
|
||||
|
||||
export function toAttachment(
|
||||
row: AttachmentRow,
|
||||
variants: VariantRow[] = [],
|
||||
): Attachment {
|
||||
const ordered =
|
||||
row.status === 'ready'
|
||||
? [...variants].sort(
|
||||
(left, right) =>
|
||||
VARIANT_ORDER.indexOf(left.variant) -
|
||||
VARIANT_ORDER.indexOf(right.variant),
|
||||
)
|
||||
: [];
|
||||
return {
|
||||
id: row.id,
|
||||
chat_id: row.chat_id,
|
||||
owner_id: row.owner_id,
|
||||
filename: row.filename,
|
||||
content_type: row.content_type,
|
||||
size_bytes: Number(row.size_bytes),
|
||||
sha256: row.sha256 as string,
|
||||
status: row.status as AttachmentStatus,
|
||||
variants: ordered.map(toVariant),
|
||||
error_code: row.status === 'failed' ? row.error_code : null,
|
||||
created_at: row.created_at.toISOString(),
|
||||
updated_at: row.updated_at.toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parseAppConfig } from '../config/app-config.schema.js';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import { ObjectStorage } from '../storage/object-storage.js';
|
||||
import { AttachmentSweeper } from './attachment-sweeper.service.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
|
||||
// Manual operator pass over unfinished uploads (the API also sweeps in the
|
||||
// background). Never touches rows before expiry + ATTACHMENT_SWEEP_GRACE_SECONDS.
|
||||
// in the stand: docker compose exec api node dist/attachments/attachments-sweep.cli.js
|
||||
// on the host: npm run attachments:sweep (needs reachable DATABASE_URL and S3)
|
||||
async function main(): Promise<void> {
|
||||
const config = parseAppConfig(process.env as Record<string, unknown>);
|
||||
const configService = {
|
||||
getOrThrow: (key: keyof typeof config) => config[key],
|
||||
} as never;
|
||||
const metrics = new MetricsService();
|
||||
const database = new DatabaseClient(configService, metrics);
|
||||
try {
|
||||
const sweeper = new AttachmentSweeper(
|
||||
configService,
|
||||
new AttachmentsRepository(database),
|
||||
new ObjectStorage(configService),
|
||||
metrics,
|
||||
);
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const { claimed, deleted } = await sweeper.sweepOnce();
|
||||
total += deleted;
|
||||
// A pass that claimed rows but could not delete any would loop forever.
|
||||
if (claimed === 0 || deleted === 0) break;
|
||||
}
|
||||
process.stdout.write(
|
||||
`Swept ${total} attachment(s) older than ${config.ATTACHMENT_SWEEP_GRACE_SECONDS} seconds past expiry\n`,
|
||||
);
|
||||
} finally {
|
||||
await database.onModuleDestroy();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
|
||||
@@ -0,0 +1,109 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
StreamableFile,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type { Readable } from 'node:stream';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator.js';
|
||||
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import { AttachmentsService } from './attachments.service.js';
|
||||
import { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js';
|
||||
import { DirectUploadsService } from './direct-uploads.service.js';
|
||||
import type { UploadRequest } from './upload-request.js';
|
||||
import { contentDisposition } from './filename.js';
|
||||
|
||||
@Controller('api/v1')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
export class AttachmentsController {
|
||||
private readonly maxUploadBytes: number;
|
||||
|
||||
constructor(
|
||||
private readonly attachments: AttachmentsService,
|
||||
private readonly directUploads: DirectUploadsService,
|
||||
config: ConfigService<AppConfig>,
|
||||
) {
|
||||
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
|
||||
}
|
||||
|
||||
@Post('chats/:chatId/attachments')
|
||||
@HttpCode(202)
|
||||
upload(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Query('filename') filename: unknown,
|
||||
@Headers('content-length') contentLength: string | undefined,
|
||||
@Req() request: FastifyRequest & UploadRequest,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
) {
|
||||
// A gigantic body is not worth draining: close the connection after the answer.
|
||||
if (Number(contentLength) > 2 * this.maxUploadBytes)
|
||||
reply.header('Connection', 'close');
|
||||
return this.attachments.uploadProxy(
|
||||
chatId,
|
||||
user,
|
||||
filename,
|
||||
request.uploadContentType,
|
||||
contentLength,
|
||||
request.body as Readable | undefined,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('chats/:chatId/attachments/direct-uploads')
|
||||
@HttpCode(201)
|
||||
initDirectUpload(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Body() body: CreateDirectUploadDto,
|
||||
) {
|
||||
return this.directUploads.init(chatId, user, body);
|
||||
}
|
||||
|
||||
@Post('attachments/:attachmentId/complete')
|
||||
@HttpCode(200)
|
||||
completeDirectUpload(
|
||||
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
|
||||
@CurrentUser() user: User,
|
||||
) {
|
||||
return this.directUploads.complete(attachmentId, user);
|
||||
}
|
||||
|
||||
@Get('attachments/:attachmentId')
|
||||
metadata(
|
||||
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
|
||||
@CurrentUser() user: User,
|
||||
) {
|
||||
return this.attachments.getMetadata(attachmentId, user);
|
||||
}
|
||||
|
||||
@Get('attachments/:attachmentId/content')
|
||||
async content(
|
||||
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
@Query('variant') variant?: string,
|
||||
) {
|
||||
const { row, contentType, sizeBytes, stream } =
|
||||
await this.attachments.openContent(attachmentId, user, variant);
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
reply.header('Cache-Control', 'private, no-store');
|
||||
return new StreamableFile(stream, {
|
||||
type: contentType,
|
||||
length: sizeBytes,
|
||||
disposition: contentDisposition(row.filename),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { ChatsModule } from '../chats/chats.module.js';
|
||||
import { UsersModule } from '../users/users.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { StorageModule } from '../storage/storage.module.js';
|
||||
import { JobsModule } from '../jobs/jobs.module.js';
|
||||
import { OutboxRelay } from '../jobs/outbox-relay.service.js';
|
||||
import { AttachmentSweeper } from './attachment-sweeper.service.js';
|
||||
import { AttachmentsController } from './attachments.controller.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
import { ImageDecoder } from './image/image-decoder.js';
|
||||
import { UploadSlots } from './upload-slots.js';
|
||||
import { DirectUploadsService } from './direct-uploads.service.js';
|
||||
import { AttachmentsService } from './attachments.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
DatabaseModule,
|
||||
ChatsModule,
|
||||
UsersModule,
|
||||
RedisModule,
|
||||
MetricsModule,
|
||||
StorageModule,
|
||||
JobsModule,
|
||||
],
|
||||
controllers: [AttachmentsController],
|
||||
providers: [
|
||||
AttachmentsRepository,
|
||||
AttachmentsService,
|
||||
DirectUploadsService,
|
||||
ImageDecoder,
|
||||
UploadSlots,
|
||||
AttachmentSweeper,
|
||||
// The relay runs only in the API process; the worker never imports
|
||||
// AttachmentsModule.
|
||||
OutboxRelay,
|
||||
],
|
||||
exports: [AttachmentsRepository],
|
||||
})
|
||||
export class AttachmentsModule {}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import type { AttachmentRow } from './attachment.js';
|
||||
|
||||
export type InsertPending = {
|
||||
id: string;
|
||||
chatId: string;
|
||||
ownerId: string;
|
||||
filename: string;
|
||||
contentType: string;
|
||||
uploadMode: 'proxy' | 'direct';
|
||||
objectKey: string;
|
||||
stagingKey: string | null;
|
||||
sizeBytes: number | null;
|
||||
sha256: string | null;
|
||||
ttlMs: number;
|
||||
};
|
||||
|
||||
const VISIBLE_MEMBER = `JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2`;
|
||||
|
||||
const INSERT_PENDING_SQL = `INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, upload_mode, status,
|
||||
object_key, staging_key, size_bytes, sha256, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, $8, $9, $10,
|
||||
now() + make_interval(secs => $11::double precision / 1000.0))`;
|
||||
|
||||
@Injectable()
|
||||
export class AttachmentsRepository {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
private values(input: InsertPending): unknown[] {
|
||||
return [
|
||||
input.id,
|
||||
input.chatId,
|
||||
input.ownerId,
|
||||
input.filename,
|
||||
input.contentType,
|
||||
input.uploadMode,
|
||||
input.objectKey,
|
||||
input.stagingKey,
|
||||
input.sizeBytes,
|
||||
input.sha256,
|
||||
input.ttlMs,
|
||||
];
|
||||
}
|
||||
|
||||
async insertPending(input: InsertPending): Promise<void> {
|
||||
await this.database.query(
|
||||
'attachments.insert_pending',
|
||||
INSERT_PENDING_SQL,
|
||||
this.values(input),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes the per-owner pending check with the insert. Two parallel
|
||||
* `init` calls cannot both pass the limit.
|
||||
*/
|
||||
async insertPendingLimited(
|
||||
input: InsertPending,
|
||||
maxPending: number,
|
||||
): Promise<boolean> {
|
||||
return this.database.withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`,
|
||||
[input.ownerId],
|
||||
);
|
||||
const count = await client.query<{ count: string }>(
|
||||
`SELECT count(*) AS count FROM attachments
|
||||
WHERE owner_id = $1 AND status IN ('pending', 'rejected')
|
||||
AND upload_mode = 'direct' AND expires_at > now()`,
|
||||
[input.ownerId],
|
||||
);
|
||||
if (Number(count.rows[0].count) >= maxPending) return false;
|
||||
await client.query(INSERT_PENDING_SQL, this.values(input));
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
async deletePending(id: string): Promise<void> {
|
||||
await this.database.query(
|
||||
'attachments.delete_pending',
|
||||
`DELETE FROM attachments WHERE id = $1 AND status = 'pending'`,
|
||||
[id],
|
||||
);
|
||||
}
|
||||
|
||||
async rejectPending(id: string): Promise<boolean> {
|
||||
const result = await this.database.query(
|
||||
'attachments.reject_pending',
|
||||
`UPDATE attachments SET status = 'rejected', updated_at = now()
|
||||
WHERE id = $1 AND status = 'pending'`,
|
||||
[id],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a pending row out of play before its object is deleted. The object
|
||||
* is deleted only when this returns true: a row that is already `ready`
|
||||
* (its commit succeeded even if the reply was lost) keeps its object.
|
||||
*/
|
||||
async claimForCompensation(id: string): Promise<boolean> {
|
||||
const result = await this.database.query(
|
||||
'attachments.claim_for_compensation',
|
||||
`UPDATE attachments SET status = 'deleting', updated_at = now()
|
||||
WHERE id = $1 AND status = 'pending'`,
|
||||
[id],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<AttachmentRow | undefined> {
|
||||
const result = await this.database.query<AttachmentRow>(
|
||||
'attachments.find_by_id',
|
||||
'SELECT * FROM attachments WHERE id = $1',
|
||||
[id],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async findVisible(
|
||||
id: string,
|
||||
userId: string,
|
||||
): Promise<AttachmentRow | undefined> {
|
||||
const result = await this.database.query<AttachmentRow>(
|
||||
'attachments.find_visible',
|
||||
`SELECT a.* FROM attachments a ${VISIBLE_MEMBER}
|
||||
WHERE a.id = $1 AND a.status IN ('queued','processing','ready','failed')`,
|
||||
[id, userId],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async findForComplete(
|
||||
id: string,
|
||||
userId: string,
|
||||
): Promise<AttachmentRow | undefined> {
|
||||
const result = await this.database.query<AttachmentRow>(
|
||||
'attachments.find_for_complete',
|
||||
`SELECT a.* FROM attachments a ${VISIBLE_MEMBER}
|
||||
WHERE a.id = $1 AND a.upload_mode = 'direct' AND a.owner_id = $2
|
||||
AND a.status IN ('pending','queued','processing','ready','failed')`,
|
||||
[id, userId],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async countPendingDirect(ownerId: string): Promise<number> {
|
||||
const result = await this.database.query<{ count: string }>(
|
||||
'attachments.count_pending_direct',
|
||||
`SELECT count(*) AS count FROM attachments
|
||||
WHERE owner_id = $1 AND status IN ('pending', 'rejected')
|
||||
AND upload_mode = 'direct' AND expires_at > now()`,
|
||||
[ownerId],
|
||||
);
|
||||
return Number(result.rows[0].count);
|
||||
}
|
||||
|
||||
async linkState(
|
||||
chatId: string,
|
||||
ids: string[],
|
||||
): Promise<'ok' | 'failed' | 'missing'> {
|
||||
const result = await this.database.query<{
|
||||
linkable: string;
|
||||
failed: string;
|
||||
}>(
|
||||
'attachments.link_state',
|
||||
`SELECT count(*) FILTER (WHERE status IN ('queued','processing','ready')) AS linkable,
|
||||
count(*) FILTER (WHERE status = 'failed') AS failed
|
||||
FROM attachments
|
||||
WHERE chat_id = $1 AND id = ANY($2::uuid[])`,
|
||||
[chatId, ids],
|
||||
);
|
||||
const linkable = Number(result.rows[0]?.linkable ?? 0);
|
||||
const failed = Number(result.rows[0]?.failed ?? 0);
|
||||
if (linkable === ids.length) return 'ok';
|
||||
if (linkable + failed === ids.length) return 'failed';
|
||||
return 'missing';
|
||||
}
|
||||
|
||||
async claimExpired(
|
||||
graceSeconds: number,
|
||||
limit: number,
|
||||
): Promise<
|
||||
{ id: string; object_key: string; staging_key: string | null }[]
|
||||
> {
|
||||
const result = await this.database.query<{
|
||||
id: string;
|
||||
object_key: string;
|
||||
staging_key: string | null;
|
||||
}>(
|
||||
'attachments.claim_expired',
|
||||
`UPDATE attachments SET status = 'deleting', updated_at = now()
|
||||
WHERE id IN (
|
||||
SELECT id FROM attachments
|
||||
WHERE (status IN ('pending', 'rejected')
|
||||
AND expires_at < now() - make_interval(secs => $1::double precision))
|
||||
OR (status = 'deleting' AND updated_at < now() - interval '1 minute')
|
||||
ORDER BY expires_at NULLS FIRST
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED)
|
||||
RETURNING id, object_key, staging_key`,
|
||||
[graceSeconds, limit],
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async deleteClaimed(id: string): Promise<void> {
|
||||
await this.database.query(
|
||||
'attachments.delete_claimed',
|
||||
`DELETE FROM attachments WHERE id = $1 AND status = 'deleting'`,
|
||||
[id],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { AttachmentRow } from './attachment.js';
|
||||
import { AttachmentsService } from './attachments.service.js';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const png = readFileSync(join(here, '../../../tests/fixtures/sample.png'));
|
||||
const lostReply = () =>
|
||||
Object.assign(new Error('Connection terminated unexpectedly'), {});
|
||||
|
||||
const settings: Record<string, number> = {
|
||||
MAX_UPLOAD_BYTES: 10_485_760,
|
||||
MAX_IMAGE_PIXELS: 40_000_000,
|
||||
UPLOAD_TIMEOUT_MS: 10_000,
|
||||
PIPELINE_VERSION: 1,
|
||||
JOB_MAX_ATTEMPTS: 5,
|
||||
};
|
||||
|
||||
function setup(
|
||||
repository: Record<string, unknown>,
|
||||
jobs: Record<string, unknown> = {},
|
||||
) {
|
||||
const storage = {
|
||||
objectKey: (id: string) => `attachments/${id}/original`,
|
||||
stagingKey: (id: string) => `staging/${id}/original`,
|
||||
putStream: vi.fn(async (_key: string, body: Readable) => {
|
||||
for await (const _chunk of body) {
|
||||
// drain like S3 does
|
||||
}
|
||||
}),
|
||||
delete: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const service = new AttachmentsService(
|
||||
{ getOrThrow: (key: string) => settings[key] } as never,
|
||||
{
|
||||
insertPending: vi.fn(),
|
||||
deleteClaimed: vi.fn(),
|
||||
...repository,
|
||||
} as never,
|
||||
{ acceptUpload: vi.fn(), ...jobs } as never,
|
||||
{ kick: vi.fn() } as never,
|
||||
{ point: vi.fn() } as never,
|
||||
storage as never,
|
||||
{ getForUser: vi.fn() } as never,
|
||||
{ increment: vi.fn(), add: vi.fn() } as never,
|
||||
{ verify: vi.fn() } as never,
|
||||
{
|
||||
run: (_user: string, work: () => Promise<unknown>) => work(),
|
||||
} as never,
|
||||
);
|
||||
const upload = () =>
|
||||
service.uploadProxy(
|
||||
'chat',
|
||||
{ id: 'user' } as never,
|
||||
'a.png',
|
||||
'image/png',
|
||||
String(png.length),
|
||||
Readable.from([png]),
|
||||
);
|
||||
return { storage, upload };
|
||||
}
|
||||
|
||||
const readyRow = (id: string): AttachmentRow => ({
|
||||
id,
|
||||
chat_id: 'chat',
|
||||
owner_id: 'user',
|
||||
filename: 'a.png',
|
||||
content_type: 'image/png',
|
||||
upload_mode: 'proxy',
|
||||
status: 'ready',
|
||||
object_key: `attachments/${id}/original`,
|
||||
staging_key: `staging/${id}/original`,
|
||||
size_bytes: png.length,
|
||||
sha256: 'a'.repeat(64),
|
||||
width: 320,
|
||||
height: 200,
|
||||
error_code: null,
|
||||
ready_pipeline_version: 1,
|
||||
expires_at: null,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
});
|
||||
|
||||
describe('AttachmentsService compensation', () => {
|
||||
it('keeps the object and answers 202 when the job commit reply was lost', async () => {
|
||||
const { storage, upload } = setup(
|
||||
{
|
||||
claimForCompensation: vi.fn().mockResolvedValue(false),
|
||||
findById: vi.fn((id: string) => Promise.resolve(readyRow(id))),
|
||||
},
|
||||
{ acceptUpload: vi.fn().mockRejectedValue(lostReply()) },
|
||||
);
|
||||
const attachment = await upload();
|
||||
expect(attachment.status).toBe('ready');
|
||||
expect(storage.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('deletes nothing while PostgreSQL is unreachable', async () => {
|
||||
const { storage, upload } = setup(
|
||||
{
|
||||
claimForCompensation: vi.fn().mockRejectedValue(lostReply()),
|
||||
findById: vi.fn().mockRejectedValue(lostReply()),
|
||||
},
|
||||
{ acceptUpload: vi.fn().mockRejectedValue(lostReply()) },
|
||||
);
|
||||
await expect(upload()).rejects.toThrow();
|
||||
expect(storage.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('deletes the object only after claiming the pending row', async () => {
|
||||
const order: string[] = [];
|
||||
const { storage, upload } = setup(
|
||||
{
|
||||
claimForCompensation: vi.fn(async () => {
|
||||
order.push('claim');
|
||||
return true;
|
||||
}),
|
||||
deleteClaimed: vi.fn(async () => {
|
||||
order.push('delete-row');
|
||||
}),
|
||||
},
|
||||
{ acceptUpload: vi.fn().mockRejectedValue(lostReply()) },
|
||||
);
|
||||
storage.delete.mockImplementation(async () => {
|
||||
order.push('delete-object');
|
||||
});
|
||||
await expect(upload()).rejects.toThrow();
|
||||
expect(order).toEqual(['claim', 'delete-object', 'delete-row']);
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { IsInt, IsString, Matches, Min } from 'class-validator';
|
||||
|
||||
export class CreateDirectUploadDto {
|
||||
@IsString()
|
||||
filename!: string;
|
||||
|
||||
@IsString()
|
||||
content_type!: string;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
size_bytes!: number;
|
||||
|
||||
@Matches(/^[a-f0-9]{64}$/u)
|
||||
sha256!: string;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
const FORBIDDEN =
|
||||
// eslint-disable-next-line no-control-regex
|
||||
/[/\\\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;
|
||||
|
||||
/** The name is stored as-is and used for display only, never in paths or keys. */
|
||||
export function validateFilename(value: unknown): string {
|
||||
if (typeof value !== 'string') throw invalid();
|
||||
const length = [...value].length;
|
||||
if (
|
||||
length < 1 ||
|
||||
length > 255 ||
|
||||
/^\s*$/u.test(value) ||
|
||||
value === '.' ||
|
||||
value === '..' ||
|
||||
FORBIDDEN.test(value)
|
||||
)
|
||||
throw invalid();
|
||||
return value;
|
||||
}
|
||||
|
||||
function invalid(): BadRequestException {
|
||||
return new BadRequestException('filename is invalid');
|
||||
}
|
||||
|
||||
export function contentDisposition(filename: string): string {
|
||||
const fallback = filename.replace(/[^\x20-\x7e]|["\\]/gu, '_');
|
||||
const encoded = encodeURIComponent(filename).replace(
|
||||
/['()*]/gu,
|
||||
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
return `inline; filename="${fallback}"; filename*=UTF-8''${encoded}`;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { jpegWithoutScanData } from '../../../test/support/jpeg.js';
|
||||
import {
|
||||
maxPixelsRgba16Png,
|
||||
noisePng,
|
||||
pngWithGarbageIdat,
|
||||
} from '../../../test/support/png.js';
|
||||
import { ImageDecoder } from './image-decoder.js';
|
||||
import { ImageInspector, ImageRejectedError } from './image-inspector.js';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const png = readFileSync(join(here, '../../../../tests/fixtures/sample.png'));
|
||||
const jpeg = readFileSync(join(here, '../../../test/fixtures/sample.jpg'));
|
||||
const progressive = readFileSync(
|
||||
join(here, '../../../test/fixtures/sample-progressive.jpg'),
|
||||
);
|
||||
|
||||
const settings: Record<string, number> = {
|
||||
MAX_IMAGE_PIXELS: 40_000_000,
|
||||
IMAGE_DECODE_MAX_CONCURRENT: 1,
|
||||
};
|
||||
const decoder = new ImageDecoder(
|
||||
{ getOrThrow: (key: string) => settings[key] } as never,
|
||||
{ increment: () => undefined, add: () => undefined } as never,
|
||||
);
|
||||
|
||||
describe('ImageDecoder', () => {
|
||||
it('accepts valid PNG and JPEG files, also concurrently', async () => {
|
||||
await Promise.all(
|
||||
[png, jpeg, progressive, noisePng(1_048_576)].map((data) =>
|
||||
decoder.verify(data),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// These files pass the structural inspector; only a decode catches them.
|
||||
it.each([
|
||||
['PNG with a garbage zlib stream', pngWithGarbageIdat()],
|
||||
['JPEG without scan data', jpegWithoutScanData(jpeg)],
|
||||
[
|
||||
'progressive JPEG without scan data',
|
||||
jpegWithoutScanData(progressive),
|
||||
],
|
||||
])('rejects a %s', async (_name, data) => {
|
||||
const inspector = new ImageInspector(40_000_000);
|
||||
inspector.push(data);
|
||||
expect(inspector.finish().width).toBe(320);
|
||||
await expect(decoder.verify(data)).rejects.toBeInstanceOf(
|
||||
ImageRejectedError,
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts the heaviest valid input: 40 MP RGBA 16-bit', async () => {
|
||||
await decoder.verify(await maxPixelsRgba16Png());
|
||||
}, 30_000);
|
||||
|
||||
it('drops an aborted waiter from the queue without running its decode', async () => {
|
||||
const busy = decoder.verify(noisePng(4_000_000));
|
||||
const controller = new AbortController();
|
||||
const waiting = decoder.verify(png, controller.signal);
|
||||
controller.abort();
|
||||
await expect(waiting).rejects.toMatchObject({ status: 503 });
|
||||
await busy;
|
||||
// The slot was not leaked: the next decode runs.
|
||||
await decoder.verify(png);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import {
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import sharp from 'sharp';
|
||||
import type { AppConfig } from '../../config/app-config.schema.js';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
import { ImageRejectedError } from './image-inspector.js';
|
||||
|
||||
// One libvips worker per decode and no operation cache: decodes are one-off,
|
||||
// and memory must stay predictable under the per-replica limit.
|
||||
sharp.cache(false);
|
||||
sharp.concurrency(1);
|
||||
|
||||
// Failures of the replica itself, not of the image: they must not turn into a
|
||||
// client 415. libvips spills large images to a temp file unless
|
||||
// VIPS_DISC_THRESHOLD (compose.yaml) keeps them in memory; a full /tmp or an
|
||||
// allocation failure ends up here.
|
||||
export const SERVER_FAULT =
|
||||
/no space left|out of memory|unable to allocate|cannot allocate|write failed|unable to open|tmp/iu;
|
||||
|
||||
/**
|
||||
* Full decode check. ImageInspector only proves the container structure
|
||||
* (signature, chunk CRCs, markers, dimensions); a PNG with a garbage zlib stream
|
||||
* or a JPEG without scan data passes it. Decoding every scanline with
|
||||
* failOn=warning rejects those, including truncated or corrupted compressed
|
||||
* data. A downscale to a thumbnail is the sink: it decodes all input but keeps
|
||||
* far less in memory than a full-size pipeline (measured in
|
||||
* evidence/lab4/decode-memory.txt). Decodes are bounded by
|
||||
* IMAGE_DECODE_MAX_CONCURRENT; a waiter whose request was aborted leaves the
|
||||
* queue and releases its buffer.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ImageDecoder {
|
||||
private readonly logger = new Logger(ImageDecoder.name);
|
||||
private readonly maxPixels: number;
|
||||
private readonly maxConcurrent: number;
|
||||
private active = 0;
|
||||
private readonly waiting = new Set<() => void>();
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
|
||||
this.maxConcurrent = config.getOrThrow('IMAGE_DECODE_MAX_CONCURRENT');
|
||||
}
|
||||
|
||||
async verify(data: Buffer, signal?: AbortSignal): Promise<void> {
|
||||
await this.acquire(signal);
|
||||
const started = performance.now();
|
||||
try {
|
||||
await sharp(data, {
|
||||
failOn: 'warning',
|
||||
sequentialRead: true,
|
||||
limitInputPixels: this.maxPixels,
|
||||
})
|
||||
.resize(64, 64, { fit: 'inside' })
|
||||
.toBuffer();
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
if (SERVER_FAULT.test(message)) {
|
||||
this.metrics.increment('attachments.decode.server_error');
|
||||
this.logger.error(
|
||||
`Image decode failed on the server: ${message}`,
|
||||
);
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
this.metrics.increment('attachments.decode.rejected');
|
||||
throw new ImageRejectedError(
|
||||
'unsupported_media_type',
|
||||
'Image data cannot be decoded',
|
||||
);
|
||||
} finally {
|
||||
this.metrics.add(
|
||||
'attachments.decode.ms',
|
||||
performance.now() - started,
|
||||
);
|
||||
this.release();
|
||||
}
|
||||
}
|
||||
|
||||
private acquire(signal?: AbortSignal): Promise<void> {
|
||||
const abandoned = new ServiceUnavailableException(
|
||||
'Image check was abandoned',
|
||||
);
|
||||
if (signal?.aborted) return Promise.reject(abandoned);
|
||||
if (this.active < this.maxConcurrent) {
|
||||
this.active += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
||||
const cancel = () => {
|
||||
this.waiting.delete(grant);
|
||||
reject(abandoned);
|
||||
};
|
||||
const grant = () => {
|
||||
signal?.removeEventListener('abort', cancel);
|
||||
resolve();
|
||||
};
|
||||
this.waiting.add(grant);
|
||||
signal?.addEventListener('abort', cancel, { once: true });
|
||||
return promise;
|
||||
}
|
||||
|
||||
private release(): void {
|
||||
const next = this.waiting.values().next();
|
||||
if (next.done) {
|
||||
this.active -= 1;
|
||||
return;
|
||||
}
|
||||
this.waiting.delete(next.value);
|
||||
next.value();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { noisePng, pixelBombPng } from '../../../test/support/png.js';
|
||||
import { ImageInspector, ImageRejectedError } from './image-inspector.js';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const png = readFileSync(join(here, '../../../../tests/fixtures/sample.png'));
|
||||
const jpeg = readFileSync(join(here, '../../../test/fixtures/sample.jpg'));
|
||||
const progressive = readFileSync(
|
||||
join(here, '../../../test/fixtures/sample-progressive.jpg'),
|
||||
);
|
||||
const MAX = 40_000_000;
|
||||
|
||||
function inspect(data: Buffer, step = data.length, max = MAX) {
|
||||
const inspector = new ImageInspector(max);
|
||||
for (let offset = 0; offset < data.length; offset += step)
|
||||
inspector.push(data.subarray(offset, offset + step));
|
||||
return inspector.finish();
|
||||
}
|
||||
|
||||
function rejection(action: () => unknown): ImageRejectedError {
|
||||
try {
|
||||
action();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ImageRejectedError);
|
||||
return error as ImageRejectedError;
|
||||
}
|
||||
throw new Error('expected rejection');
|
||||
}
|
||||
|
||||
describe('ImageInspector', () => {
|
||||
it.each([
|
||||
['png', png, 'image/png'],
|
||||
['jpeg', jpeg, 'image/jpeg'],
|
||||
['progressive jpeg', progressive, 'image/jpeg'],
|
||||
])('accepts %s and reports its size', (_name, data, contentType) => {
|
||||
const expected = { contentType, width: 320, height: 200 };
|
||||
expect(inspect(data)).toEqual(expected);
|
||||
expect(inspect(data, 1)).toEqual(expected);
|
||||
expect(inspect(data, 7)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('rejects truncated files on finish', () => {
|
||||
for (const data of [png, jpeg, progressive])
|
||||
for (const cut of [10, 40, data.length - 100, data.length - 1]) {
|
||||
const reason = rejection(() =>
|
||||
inspect(data.subarray(0, cut)),
|
||||
).reason;
|
||||
expect(reason).toBe('unsupported_media_type');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a flipped byte inside IDAT by checksum', () => {
|
||||
const damaged = Buffer.from(png);
|
||||
damaged[Math.floor(png.length / 2)] ^= 0xff;
|
||||
expect(rejection(() => inspect(damaged)).reason).toBe(
|
||||
'unsupported_media_type',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a pixel bomb right after IHDR, before any IDAT', () => {
|
||||
const bomb = pixelBombPng();
|
||||
const inspector = new ImageInspector(MAX);
|
||||
// signature + IHDR chunk = 8 + 25 bytes
|
||||
const reason = rejection(() =>
|
||||
inspector.push(bomb.subarray(0, 33)),
|
||||
).reason;
|
||||
expect(reason).toBe('too_many_pixels');
|
||||
expect(inspector.header).toBeUndefined();
|
||||
});
|
||||
|
||||
it('applies the pixel limit to JPEG frame headers', () => {
|
||||
expect(rejection(() => inspect(jpeg, jpeg.length, 63_999)).reason).toBe(
|
||||
'too_many_pixels',
|
||||
);
|
||||
expect(inspect(jpeg, jpeg.length, 64_000).width).toBe(320);
|
||||
});
|
||||
|
||||
it('rejects foreign formats and trailing data after IEND', () => {
|
||||
for (const data of [
|
||||
Buffer.from('GIF89a' + 'x'.repeat(40)),
|
||||
Buffer.from('plain text, not an image'),
|
||||
Buffer.alloc(0),
|
||||
])
|
||||
expect(rejection(() => inspect(data)).reason).toBe(
|
||||
'unsupported_media_type',
|
||||
);
|
||||
expect(
|
||||
rejection(() => inspect(Buffer.concat([png, Buffer.from([0])])))
|
||||
.reason,
|
||||
).toBe('unsupported_media_type');
|
||||
});
|
||||
|
||||
it('accepts padded and noise PNGs of exact sizes', () => {
|
||||
for (const size of [131_072, 1_048_576]) {
|
||||
const data = noisePng(size);
|
||||
expect(data.length).toBe(size);
|
||||
expect(inspect(data).width).toBe(1024);
|
||||
}
|
||||
});
|
||||
|
||||
it('tolerates trailing data after JPEG EOI', () => {
|
||||
expect(
|
||||
inspect(Buffer.concat([jpeg, Buffer.from('MPF trailer')])).height,
|
||||
).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,387 @@
|
||||
import { crc32 } from 'node:zlib';
|
||||
|
||||
export type ImageHeader = {
|
||||
contentType: 'image/png' | 'image/jpeg';
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
export class ImageRejectedError extends Error {
|
||||
constructor(
|
||||
readonly reason: 'unsupported_media_type' | 'too_many_pixels',
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ImageRejectedError';
|
||||
}
|
||||
}
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
||||
]);
|
||||
const PNG_MAX_DIMENSION = 2 ** 31 - 1;
|
||||
const PNG_BIT_DEPTHS: Record<number, readonly number[]> = {
|
||||
0: [1, 2, 4, 8, 16],
|
||||
2: [8, 16],
|
||||
3: [1, 2, 4, 8],
|
||||
4: [8, 16],
|
||||
6: [8, 16],
|
||||
};
|
||||
const SOF_MARKERS = new Set([
|
||||
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce,
|
||||
0xcf,
|
||||
]);
|
||||
|
||||
type State =
|
||||
| 'start'
|
||||
// PNG
|
||||
| 'png_chunk_head'
|
||||
| 'png_ihdr'
|
||||
| 'png_skip'
|
||||
| 'png_crc'
|
||||
| 'png_done'
|
||||
// JPEG
|
||||
| 'jpeg_marker'
|
||||
| 'jpeg_code'
|
||||
| 'jpeg_length'
|
||||
| 'jpeg_sof'
|
||||
| 'jpeg_skip'
|
||||
| 'jpeg_entropy'
|
||||
| 'jpeg_entropy_ff'
|
||||
| 'jpeg_trailer';
|
||||
|
||||
function unsupported(message: string): ImageRejectedError {
|
||||
return new ImageRejectedError('unsupported_media_type', message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming structural validator for PNG and JPEG. It never buffers the body:
|
||||
* only fixed-size fields (chunk headers, IHDR, SOF) are accumulated, and
|
||||
* nothing is decompressed. It is the early gate (type, dimensions, pixel limit
|
||||
* before anything is stored), not proof of a valid image: compressed pixel
|
||||
* data is checked by ImageDecoder.
|
||||
*/
|
||||
export class ImageInspector {
|
||||
private state: State = 'start';
|
||||
private imageHeader: ImageHeader | undefined;
|
||||
|
||||
// Accumulator for fixed-length fields.
|
||||
private field = Buffer.alloc(16);
|
||||
private fieldNeed = 0;
|
||||
private fieldLength = 0;
|
||||
|
||||
// Remaining bytes to skip in png_skip / jpeg_skip.
|
||||
private skip = 0;
|
||||
|
||||
// PNG
|
||||
private chunkType = '';
|
||||
private chunkLength = 0;
|
||||
private crc = 0;
|
||||
private firstChunk = true;
|
||||
private seenIdat = false;
|
||||
|
||||
// JPEG
|
||||
private marker = 0;
|
||||
private scans = 0;
|
||||
private afterSkip: State = 'jpeg_marker';
|
||||
|
||||
constructor(private readonly maxPixels: number) {}
|
||||
|
||||
get header(): ImageHeader | undefined {
|
||||
return this.imageHeader;
|
||||
}
|
||||
|
||||
push(chunk: Buffer): void {
|
||||
let offset = 0;
|
||||
while (offset < chunk.length) offset = this.step(chunk, offset);
|
||||
}
|
||||
|
||||
finish(): ImageHeader {
|
||||
const done = this.state === 'png_done' || this.state === 'jpeg_trailer';
|
||||
if (!done || this.imageHeader === undefined)
|
||||
throw unsupported('Image data is incomplete');
|
||||
return this.imageHeader;
|
||||
}
|
||||
|
||||
private collect(need: number): void {
|
||||
this.fieldNeed = need;
|
||||
this.fieldLength = 0;
|
||||
}
|
||||
|
||||
/** Copies up to fieldNeed bytes; returns new offset and whether complete. */
|
||||
private fill(chunk: Buffer, offset: number): [number, boolean] {
|
||||
const take = Math.min(
|
||||
this.fieldNeed - this.fieldLength,
|
||||
chunk.length - offset,
|
||||
);
|
||||
chunk.copy(this.field, this.fieldLength, offset, offset + take);
|
||||
this.fieldLength += take;
|
||||
return [offset + take, this.fieldLength === this.fieldNeed];
|
||||
}
|
||||
|
||||
private step(chunk: Buffer, offset: number): number {
|
||||
switch (this.state) {
|
||||
case 'start':
|
||||
return this.stepStart(chunk, offset);
|
||||
case 'png_chunk_head':
|
||||
case 'png_ihdr':
|
||||
case 'png_crc':
|
||||
case 'jpeg_length':
|
||||
case 'jpeg_sof': {
|
||||
const [next, complete] = this.fill(chunk, offset);
|
||||
if (complete) this.fieldDone();
|
||||
return next;
|
||||
}
|
||||
case 'png_skip':
|
||||
case 'jpeg_skip': {
|
||||
const take = Math.min(this.skip, chunk.length - offset);
|
||||
if (this.state === 'png_skip')
|
||||
this.crc = crc32(
|
||||
chunk.subarray(offset, offset + take),
|
||||
this.crc,
|
||||
);
|
||||
this.skip -= take;
|
||||
if (this.skip === 0) this.skipDone();
|
||||
return offset + take;
|
||||
}
|
||||
case 'png_done':
|
||||
throw unsupported('Data after the PNG end chunk');
|
||||
case 'jpeg_marker':
|
||||
if (chunk[offset] !== 0xff)
|
||||
throw unsupported('Unexpected byte between JPEG segments');
|
||||
this.state = 'jpeg_code';
|
||||
return offset + 1;
|
||||
case 'jpeg_code':
|
||||
this.onMarkerCode(chunk[offset]);
|
||||
return offset + 1;
|
||||
case 'jpeg_entropy': {
|
||||
const next = chunk.indexOf(0xff, offset);
|
||||
if (next === -1) return chunk.length;
|
||||
this.state = 'jpeg_entropy_ff';
|
||||
return next + 1;
|
||||
}
|
||||
case 'jpeg_entropy_ff': {
|
||||
const byte = chunk[offset];
|
||||
if (byte === 0xff) return offset + 1;
|
||||
if (byte === 0x00 || (byte >= 0xd0 && byte <= 0xd7)) {
|
||||
this.state = 'jpeg_entropy';
|
||||
return offset + 1;
|
||||
}
|
||||
this.onMarkerCode(byte);
|
||||
return offset + 1;
|
||||
}
|
||||
case 'jpeg_trailer':
|
||||
return chunk.length;
|
||||
}
|
||||
}
|
||||
|
||||
private stepStart(chunk: Buffer, offset: number): number {
|
||||
// Accumulate until the type is certain: 3 bytes for JPEG, 8 for PNG.
|
||||
if (this.fieldLength === 0 && this.fieldNeed === 0) this.collect(8);
|
||||
const have = this.fieldLength;
|
||||
const take = Math.min(this.fieldNeed - have, chunk.length - offset);
|
||||
chunk.copy(this.field, have, offset, offset + take);
|
||||
this.fieldLength += take;
|
||||
const first = this.field[0];
|
||||
if (first === 0xff) {
|
||||
if (this.fieldLength >= 3) {
|
||||
if (this.field[1] !== 0xd8 || this.field[2] !== 0xff)
|
||||
throw unsupported('Not a JPEG file');
|
||||
// The third byte opens the next marker.
|
||||
this.state = 'jpeg_code';
|
||||
this.fieldNeed = 0;
|
||||
this.fieldLength = 0;
|
||||
return offset + (3 - have);
|
||||
}
|
||||
return offset + take;
|
||||
}
|
||||
if (first === PNG_SIGNATURE[0]) {
|
||||
for (let index = 0; index < this.fieldLength; index += 1)
|
||||
if (this.field[index] !== PNG_SIGNATURE[index])
|
||||
throw unsupported('Not a PNG file');
|
||||
if (this.fieldLength === 8) {
|
||||
this.state = 'png_chunk_head';
|
||||
this.collect(8);
|
||||
}
|
||||
return offset + take;
|
||||
}
|
||||
throw unsupported('Unsupported image format');
|
||||
}
|
||||
|
||||
private fieldDone(): void {
|
||||
switch (this.state) {
|
||||
case 'png_chunk_head':
|
||||
this.onPngChunkHead();
|
||||
return;
|
||||
case 'png_ihdr':
|
||||
this.crc = crc32(this.field.subarray(0, 13), this.crc);
|
||||
this.parseIhdr();
|
||||
this.state = 'png_crc';
|
||||
this.collect(4);
|
||||
return;
|
||||
case 'png_crc': {
|
||||
const expected = this.field.readUInt32BE(0);
|
||||
if (this.crc >>> 0 !== expected)
|
||||
throw unsupported('PNG chunk checksum mismatch');
|
||||
this.onPngChunkEnd();
|
||||
return;
|
||||
}
|
||||
case 'jpeg_length':
|
||||
this.onJpegLength();
|
||||
return;
|
||||
case 'jpeg_sof':
|
||||
this.onJpegSof();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private skipDone(): void {
|
||||
if (this.state === 'png_skip') {
|
||||
this.state = 'png_crc';
|
||||
this.collect(4);
|
||||
} else {
|
||||
this.state = this.afterSkip;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- PNG ----
|
||||
|
||||
private onPngChunkHead(): void {
|
||||
const length = this.field.readUInt32BE(0);
|
||||
const type = this.field.toString('latin1', 4, 8);
|
||||
if (length > PNG_MAX_DIMENSION)
|
||||
throw unsupported('PNG chunk is too long');
|
||||
if (!/^[A-Za-z]{4}$/u.test(type))
|
||||
throw unsupported('PNG chunk type is invalid');
|
||||
if (this.firstChunk) {
|
||||
if (type !== 'IHDR' || length !== 13)
|
||||
throw unsupported('PNG must start with IHDR');
|
||||
this.firstChunk = false;
|
||||
} else if (type === 'IHDR') {
|
||||
throw unsupported('Duplicate PNG IHDR');
|
||||
}
|
||||
if (type === 'IEND') {
|
||||
if (length !== 0 || !this.seenIdat)
|
||||
throw unsupported('PNG IEND is invalid');
|
||||
}
|
||||
if (type === 'IDAT') this.seenIdat = true;
|
||||
this.chunkType = type;
|
||||
this.chunkLength = length;
|
||||
this.crc = crc32(this.field.subarray(4, 8), 0);
|
||||
if (type === 'IHDR') {
|
||||
this.state = 'png_ihdr';
|
||||
this.collect(13);
|
||||
} else if (length === 0) {
|
||||
this.state = 'png_crc';
|
||||
this.collect(4);
|
||||
} else {
|
||||
this.state = 'png_skip';
|
||||
this.skip = length;
|
||||
}
|
||||
}
|
||||
|
||||
private parseIhdr(): void {
|
||||
const width = this.field.readUInt32BE(0);
|
||||
const height = this.field.readUInt32BE(4);
|
||||
const bitDepth = this.field[8];
|
||||
const colorType = this.field[9];
|
||||
if (width < 1 || width > PNG_MAX_DIMENSION)
|
||||
throw unsupported('PNG width is invalid');
|
||||
if (height < 1 || height > PNG_MAX_DIMENSION)
|
||||
throw unsupported('PNG height is invalid');
|
||||
if (!PNG_BIT_DEPTHS[colorType]?.includes(bitDepth))
|
||||
throw unsupported('PNG color type / bit depth is invalid');
|
||||
if (this.field[10] !== 0 || this.field[11] !== 0)
|
||||
throw unsupported('PNG compression/filter method is invalid');
|
||||
if (this.field[12] > 1)
|
||||
throw unsupported('PNG interlace method is invalid');
|
||||
this.pendingHeader = { contentType: 'image/png', width, height };
|
||||
}
|
||||
|
||||
private pendingHeader: ImageHeader | undefined;
|
||||
|
||||
private onPngChunkEnd(): void {
|
||||
if (this.chunkType === 'IHDR' && this.pendingHeader) {
|
||||
const { width, height } = this.pendingHeader;
|
||||
if (width * height > this.maxPixels)
|
||||
throw new ImageRejectedError(
|
||||
'too_many_pixels',
|
||||
'Image has too many pixels',
|
||||
);
|
||||
this.imageHeader = this.pendingHeader;
|
||||
}
|
||||
if (this.chunkType === 'IEND') {
|
||||
this.state = 'png_done';
|
||||
return;
|
||||
}
|
||||
this.state = 'png_chunk_head';
|
||||
this.collect(8);
|
||||
}
|
||||
|
||||
// ---- JPEG ----
|
||||
|
||||
private onMarkerCode(code: number): void {
|
||||
if (code === 0xff) return; // fill byte
|
||||
this.marker = code;
|
||||
if (code === 0x00 || code === 0xd8)
|
||||
throw unsupported('Unexpected JPEG marker');
|
||||
if (code === 0x01 || (code >= 0xd0 && code <= 0xd7)) {
|
||||
this.state = 'jpeg_marker';
|
||||
return;
|
||||
}
|
||||
if (code === 0xd9) {
|
||||
if (this.imageHeader === undefined || this.scans === 0)
|
||||
throw unsupported('JPEG ended before image data');
|
||||
this.state = 'jpeg_trailer';
|
||||
return;
|
||||
}
|
||||
if (code === 0xda && this.imageHeader === undefined)
|
||||
throw unsupported('JPEG scan before frame header');
|
||||
this.state = 'jpeg_length';
|
||||
this.collect(2);
|
||||
}
|
||||
|
||||
private onJpegLength(): void {
|
||||
const length = this.field.readUInt16BE(0);
|
||||
if (length < 2) throw unsupported('JPEG segment length is invalid');
|
||||
const dataLength = length - 2;
|
||||
if (SOF_MARKERS.has(this.marker)) {
|
||||
if (this.imageHeader !== undefined || this.pendingHeader)
|
||||
throw unsupported('Duplicate JPEG frame header');
|
||||
if (dataLength < 6) throw unsupported('JPEG frame header is short');
|
||||
this.skip = dataLength - 6;
|
||||
this.afterSkip = 'jpeg_marker';
|
||||
this.state = 'jpeg_sof';
|
||||
this.collect(6);
|
||||
return;
|
||||
}
|
||||
if (this.marker === 0xda) {
|
||||
this.scans += 1;
|
||||
this.afterSkip = 'jpeg_entropy';
|
||||
} else {
|
||||
this.afterSkip = 'jpeg_marker';
|
||||
}
|
||||
if (dataLength === 0) this.state = this.afterSkip;
|
||||
else {
|
||||
this.skip = dataLength;
|
||||
this.state = 'jpeg_skip';
|
||||
}
|
||||
}
|
||||
|
||||
private onJpegSof(): void {
|
||||
const height = this.field.readUInt16BE(1);
|
||||
const width = this.field.readUInt16BE(3);
|
||||
if (width === 0 || height === 0 || this.field[5] === 0)
|
||||
throw unsupported('JPEG dimensions are invalid');
|
||||
if (width * height > this.maxPixels)
|
||||
throw new ImageRejectedError(
|
||||
'too_many_pixels',
|
||||
'Image has too many pixels',
|
||||
);
|
||||
this.imageHeader = { contentType: 'image/jpeg', width, height };
|
||||
if (this.skip === 0) this.state = 'jpeg_marker';
|
||||
else this.state = 'jpeg_skip';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Request of the upload route; see the onRequest hook in main.ts. */
|
||||
export type UploadRequest = {
|
||||
method: string;
|
||||
routeOptions?: { url?: string };
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
/** Content-Type as sent by the client (the header itself is rewritten). */
|
||||
uploadContentType?: string | string[];
|
||||
body?: unknown;
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { UploadSlots } from './upload-slots.js';
|
||||
|
||||
const slots = (max: number, perUser: number) =>
|
||||
new UploadSlots({
|
||||
getOrThrow: (key: string) =>
|
||||
key === 'UPLOAD_MAX_IN_FLIGHT' ? max : perUser,
|
||||
} as never);
|
||||
|
||||
function hold() {
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
return { work: () => promise, release: resolve };
|
||||
}
|
||||
|
||||
describe('UploadSlots', () => {
|
||||
it('caps one user without starving others, and frees slots after work', async () => {
|
||||
const limiter = slots(10, 2);
|
||||
const held = [hold(), hold()];
|
||||
const running = held.map((h) => limiter.run('a', h.work));
|
||||
await expect(limiter.run('a', async () => 'x')).rejects.toMatchObject({
|
||||
status: 429,
|
||||
});
|
||||
await expect(limiter.run('b', async () => 'ok')).resolves.toBe('ok');
|
||||
held.forEach((h) => h.release());
|
||||
await Promise.all(running);
|
||||
await expect(limiter.run('a', async () => 'again')).resolves.toBe(
|
||||
'again',
|
||||
);
|
||||
});
|
||||
|
||||
it('applies the replica-wide cap across users', async () => {
|
||||
const limiter = slots(2, 2);
|
||||
const held = [hold(), hold()];
|
||||
const running = [
|
||||
limiter.run('a', held[0].work),
|
||||
limiter.run('b', held[1].work),
|
||||
];
|
||||
await expect(limiter.run('c', async () => 'x')).rejects.toMatchObject({
|
||||
status: 429,
|
||||
});
|
||||
held.forEach((h) => h.release());
|
||||
await Promise.all(running);
|
||||
});
|
||||
|
||||
it('releases a slot when the work fails', async () => {
|
||||
const limiter = slots(1, 1);
|
||||
await expect(
|
||||
limiter.run('a', async () => {
|
||||
throw new Error('boom');
|
||||
}),
|
||||
).rejects.toThrow('boom');
|
||||
await expect(limiter.run('a', async () => 'ok')).resolves.toBe('ok');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { HttpException, Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
|
||||
/**
|
||||
* Per-replica caps on requests that hold an image in memory (proxy upload,
|
||||
* direct complete): each may keep up to MAX_UPLOAD_BYTES for the decode check.
|
||||
* The per-user cap keeps one client (e.g. slow senders holding slots until
|
||||
* UPLOAD_TIMEOUT_MS) from starving everyone else.
|
||||
*/
|
||||
@Injectable()
|
||||
export class UploadSlots {
|
||||
private inFlight = 0;
|
||||
private readonly perUser = new Map<string, number>();
|
||||
private readonly max: number;
|
||||
private readonly maxPerUser: number;
|
||||
|
||||
constructor(config: ConfigService<AppConfig>) {
|
||||
this.max = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT');
|
||||
this.maxPerUser = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT_PER_USER');
|
||||
}
|
||||
|
||||
async run<T>(userId: string, work: () => Promise<T>): Promise<T> {
|
||||
const mine = this.perUser.get(userId) ?? 0;
|
||||
if (this.inFlight >= this.max || mine >= this.maxPerUser)
|
||||
throw new HttpException(
|
||||
{ message: 'Too many concurrent uploads', retryAfter: 1 },
|
||||
429,
|
||||
);
|
||||
this.inFlight += 1;
|
||||
this.perUser.set(userId, mine + 1);
|
||||
try {
|
||||
return await work();
|
||||
} finally {
|
||||
this.inFlight -= 1;
|
||||
const left = (this.perUser.get(userId) ?? 1) - 1;
|
||||
if (left === 0) this.perUser.delete(userId);
|
||||
else this.perUser.set(userId, left);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user