forked from mtusi2026/mtusi2026lab7
lab7: app security, Argon2id, mTLS, OpenBao client, least-privilege worker
This commit is contained in:
@@ -9,14 +9,20 @@ import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
||||
import { NodeHttpHandler } from '@smithy/node-http-handler';
|
||||
import { SpanKind } from '@opentelemetry/api';
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
Optional,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import { Readable } from 'node:stream';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js';
|
||||
import { TlsMaterialManager } from '../security/tls-material.js';
|
||||
import { withChildSpan } from '../telemetry/tracing.js';
|
||||
|
||||
export class ObjectStorageUnavailableError extends ServiceUnavailableException {
|
||||
@@ -44,71 +50,69 @@ function isMissingKey(error: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function isS3AuthError(error: unknown): boolean {
|
||||
const candidate = error as {
|
||||
name?: string;
|
||||
Code?: string;
|
||||
$metadata?: { httpStatusCode?: number };
|
||||
};
|
||||
const code = candidate?.Code ?? candidate?.name ?? '';
|
||||
return (
|
||||
code === 'InvalidAccessKeyId' ||
|
||||
code === 'SignatureDoesNotMatch' ||
|
||||
code === 'AccessDenied' ||
|
||||
code === 'ExpiredToken' ||
|
||||
candidate?.$metadata?.httpStatusCode === 403
|
||||
);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ObjectStorage {
|
||||
export class ObjectStorage implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(ObjectStorage.name);
|
||||
private readonly bucket: string;
|
||||
private readonly internal: S3Client;
|
||||
private readonly presign: S3Client;
|
||||
private readonly endpoint: string;
|
||||
private readonly publicEndpoint: string | undefined;
|
||||
private readonly region: string;
|
||||
private readonly connectTimeoutMs: number;
|
||||
private readonly requestTimeoutMs: number;
|
||||
private internal: S3Client;
|
||||
private presign: S3Client | undefined;
|
||||
private agent: http.Agent | https.Agent;
|
||||
private readonly onTlsReload: () => void;
|
||||
|
||||
constructor(config: ConfigService<AppConfig>) {
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
@Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager,
|
||||
@Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore,
|
||||
) {
|
||||
this.bucket = config.getOrThrow('S3_BUCKET');
|
||||
this.endpoint = config.getOrThrow('S3_ENDPOINT');
|
||||
this.publicEndpoint =
|
||||
typeof config.get === 'function'
|
||||
? config.get('S3_PUBLIC_ENDPOINT')
|
||||
: undefined;
|
||||
this.region = config.getOrThrow('S3_REGION');
|
||||
this.connectTimeoutMs = config.getOrThrow('S3_CONNECT_TIMEOUT_MS');
|
||||
this.requestTimeoutMs = config.getOrThrow('S3_REQUEST_TIMEOUT_MS');
|
||||
const common = {
|
||||
region: config.getOrThrow('S3_REGION'),
|
||||
forcePathStyle: true,
|
||||
credentials: {
|
||||
accessKeyId: config.getOrThrow('S3_ACCESS_KEY_ID'),
|
||||
secretAccessKey: config.getOrThrow('S3_SECRET_ACCESS_KEY'),
|
||||
},
|
||||
// Поток нельзя повторить: повтор — решение клиента API.
|
||||
maxAttempts: 1,
|
||||
requestChecksumCalculation: 'WHEN_REQUIRED' as const,
|
||||
responseChecksumValidation: 'WHEN_REQUIRED' as const,
|
||||
// requestTimeout bounds a request until its response arrives and,
|
||||
// with throwOnRequestTimeout, actually fails it (otherwise smithy
|
||||
// only logs a warning); socketTimeout bounds a stalled body read.
|
||||
// A hung S3 therefore costs at most S3_REQUEST_TIMEOUT_MS per call.
|
||||
requestHandler: new NodeHttpHandler({
|
||||
connectionTimeout: config.getOrThrow('S3_CONNECT_TIMEOUT_MS'),
|
||||
requestTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'),
|
||||
throwOnRequestTimeout: true,
|
||||
socketTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'),
|
||||
httpAgent: new http.Agent({ keepAlive: true, maxSockets: 64 }),
|
||||
}),
|
||||
};
|
||||
this.internal = new S3Client({
|
||||
...common,
|
||||
endpoint: config.getOrThrow('S3_ENDPOINT'),
|
||||
});
|
||||
// One CLIENT span per S3 call (S3.PutObject, S3.GetObject, …), only
|
||||
// inside a traced request or job. Object keys contain attachment ids
|
||||
// and are deliberately not recorded.
|
||||
this.internal.middlewareStack.add(
|
||||
(next, handlerContext) => async (args) => {
|
||||
const operation = String(
|
||||
handlerContext.commandName ?? 'Unknown',
|
||||
).replace(/Command$/u, '');
|
||||
return withChildSpan(
|
||||
`S3.${operation}`,
|
||||
SpanKind.CLIENT,
|
||||
{
|
||||
'rpc.system': 'aws-api',
|
||||
'rpc.service': 'S3',
|
||||
'rpc.method': operation,
|
||||
'aws.s3.bucket': this.bucket,
|
||||
},
|
||||
() => next(args),
|
||||
);
|
||||
},
|
||||
{ step: 'initialize', name: 'messengerTelemetry' },
|
||||
);
|
||||
// Сеть не использует: только подпись URL для клиента.
|
||||
this.presign = new S3Client({
|
||||
...common,
|
||||
endpoint: config.getOrThrow('S3_PUBLIC_ENDPOINT'),
|
||||
});
|
||||
|
||||
if (this.tls?.enabled && !this.endpoint.startsWith('https://')) {
|
||||
throw new Error('S3_ENDPOINT must use https:// when TLS_ENABLED=true');
|
||||
}
|
||||
|
||||
const built = this.createClients();
|
||||
this.internal = built.internal;
|
||||
this.presign = built.presign;
|
||||
this.agent = built.agent;
|
||||
|
||||
this.onTlsReload = () => this.rebuildClients();
|
||||
this.tls?.on('reloaded', this.onTlsReload);
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
this.tls?.off('reloaded', this.onTlsReload);
|
||||
this.internal.destroy();
|
||||
this.presign?.destroy();
|
||||
this.agent.destroy();
|
||||
}
|
||||
|
||||
objectKey(attachmentId: string): string {
|
||||
@@ -126,8 +130,6 @@ export class ObjectStorage {
|
||||
extension: 'jpg' | 'webp',
|
||||
attempt = 1,
|
||||
): string {
|
||||
// The attempt suffix makes a stale worker's write harmless: the DB
|
||||
// points at the key of the attempt that won the lease fence.
|
||||
return `attachments/${attachmentId}/v${pipelineVersion}/${variant}-a${attempt}.${extension}`;
|
||||
}
|
||||
|
||||
@@ -147,9 +149,6 @@ export class ObjectStorage {
|
||||
ContentLength: contentLength,
|
||||
ContentType: contentType,
|
||||
}),
|
||||
// The upload deadline (UPLOAD_TIMEOUT_MS, via `signal`) bounds the
|
||||
// PUT: it lasts as long as the client sends, not S3_REQUEST_TIMEOUT_MS.
|
||||
// A worker buffer has no client deadline, so it uses the SDK timeout.
|
||||
signal
|
||||
? { abortSignal: signal, requestTimeout: 0 }
|
||||
: { requestTimeout: this.requestTimeoutMs },
|
||||
@@ -228,6 +227,11 @@ export class ObjectStorage {
|
||||
}
|
||||
|
||||
async presignPut(key: string, options: PresignPutOptions): Promise<string> {
|
||||
if (!this.presign) {
|
||||
throw new Error(
|
||||
'S3_PUBLIC_ENDPOINT is not configured for presigned uploads',
|
||||
);
|
||||
}
|
||||
return getSignedUrl(
|
||||
this.presign,
|
||||
new PutObjectCommand({
|
||||
@@ -249,7 +253,105 @@ export class ObjectStorage {
|
||||
);
|
||||
}
|
||||
|
||||
private createClients(): {
|
||||
internal: S3Client;
|
||||
presign: S3Client | undefined;
|
||||
agent: http.Agent | https.Agent;
|
||||
} {
|
||||
const useHttps = this.endpoint.startsWith('https://');
|
||||
const agent = useHttps
|
||||
? new https.Agent({
|
||||
keepAlive: true,
|
||||
maxSockets: 64,
|
||||
...(this.tls?.ca ? { ca: this.tls.ca } : {}),
|
||||
rejectUnauthorized: true,
|
||||
minVersion: 'TLSv1.2',
|
||||
})
|
||||
: new http.Agent({ keepAlive: true, maxSockets: 64 });
|
||||
|
||||
const credentials = this.secrets
|
||||
? async () => this.secrets!.getS3Credentials()
|
||||
: {
|
||||
accessKeyId: this.config.getOrThrow('S3_ACCESS_KEY_ID')!,
|
||||
secretAccessKey: this.config.getOrThrow('S3_SECRET_ACCESS_KEY')!,
|
||||
};
|
||||
|
||||
const common = {
|
||||
region: this.region,
|
||||
forcePathStyle: true,
|
||||
credentials,
|
||||
maxAttempts: 1,
|
||||
requestChecksumCalculation: 'WHEN_REQUIRED' as const,
|
||||
responseChecksumValidation: 'WHEN_REQUIRED' as const,
|
||||
requestHandler: new NodeHttpHandler({
|
||||
connectionTimeout: this.connectTimeoutMs,
|
||||
requestTimeout: this.requestTimeoutMs,
|
||||
throwOnRequestTimeout: true,
|
||||
socketTimeout: this.requestTimeoutMs,
|
||||
...(useHttps
|
||||
? { httpsAgent: agent as https.Agent }
|
||||
: { httpAgent: agent as http.Agent }),
|
||||
}),
|
||||
};
|
||||
|
||||
const internal = new S3Client({
|
||||
...common,
|
||||
endpoint: this.endpoint,
|
||||
});
|
||||
internal.middlewareStack.add(
|
||||
(next, handlerContext) => async (args) => {
|
||||
const operation = String(
|
||||
handlerContext.commandName ?? 'Unknown',
|
||||
).replace(/Command$/u, '');
|
||||
return withChildSpan(
|
||||
`S3.${operation}`,
|
||||
SpanKind.CLIENT,
|
||||
{
|
||||
'rpc.system': 'aws-api',
|
||||
'rpc.service': 'S3',
|
||||
'rpc.method': operation,
|
||||
'aws.s3.bucket': this.bucket,
|
||||
},
|
||||
() => next(args),
|
||||
);
|
||||
},
|
||||
{ step: 'initialize', name: 'messengerTelemetry' },
|
||||
);
|
||||
|
||||
const presign = this.publicEndpoint
|
||||
? new S3Client({
|
||||
...common,
|
||||
endpoint: this.publicEndpoint,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
return { internal, presign, agent };
|
||||
}
|
||||
|
||||
private rebuildClients(): void {
|
||||
try {
|
||||
const next = this.createClients();
|
||||
const oldInternal = this.internal;
|
||||
const oldPresign = this.presign;
|
||||
const oldAgent = this.agent;
|
||||
this.internal = next.internal;
|
||||
this.presign = next.presign;
|
||||
this.agent = next.agent;
|
||||
oldInternal.destroy();
|
||||
oldPresign?.destroy();
|
||||
oldAgent.destroy();
|
||||
this.logger.log('Rebuilt S3 clients with updated TLS material');
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`S3 client rebuild failed: ${error instanceof Error ? error.name : 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private fail(operation: string, error: unknown): Error {
|
||||
if (isS3AuthError(error)) {
|
||||
void this.secrets?.refreshNow('s3_auth_error');
|
||||
}
|
||||
const name = (error as { name?: string })?.name ?? 'UnknownError';
|
||||
this.logger.warn(`S3 ${operation} failed: ${name}`);
|
||||
return new ObjectStorageUnavailableError();
|
||||
|
||||
Reference in New Issue
Block a user