forked from mtusi2026/mtusi2026lab7
lab7: app security, Argon2id, mTLS, OpenBao client, least-privilege worker
This commit is contained in:
@@ -0,0 +1,344 @@
|
||||
import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
OnModuleInit,
|
||||
Optional,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import argon2 from 'argon2';
|
||||
import {
|
||||
randomBytes,
|
||||
scrypt as cryptoScrypt,
|
||||
timingSafeEqual,
|
||||
} from 'node:crypto';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import { meter } from '../telemetry/instruments.js';
|
||||
|
||||
export type PasswordVerifyResult = {
|
||||
readonly valid: boolean;
|
||||
readonly needsRehash: boolean;
|
||||
};
|
||||
|
||||
export type PasswordVerifyAndUpgradeResult = {
|
||||
readonly valid: boolean;
|
||||
readonly upgradedHash?: string;
|
||||
};
|
||||
|
||||
type Waiter = {
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
timer: NodeJS.Timeout;
|
||||
};
|
||||
|
||||
const SCRYPT_PHC_RE =
|
||||
/^\$scrypt\$ln=(\d+),r=(\d+),p=(\d+)\$([A-Za-z0-9+/=_-]+)\$([A-Za-z0-9+/=_-]+)$/u;
|
||||
|
||||
function scryptAsync(
|
||||
password: string,
|
||||
salt: Buffer,
|
||||
keyLen: number,
|
||||
options: { N: number; r: number; p: number; maxmem: number },
|
||||
): Promise<Buffer> {
|
||||
return new Promise<Buffer>((resolve, reject) => {
|
||||
cryptoScrypt(password, salt, keyLen, options, (error, derivedKey) => {
|
||||
if (error) reject(error);
|
||||
else resolve(derivedKey);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function decodeBase64Flexible(encoded: string): Buffer {
|
||||
const normalized = encoded.replace(/-/gu, '+').replace(/_/gu, '/');
|
||||
const pad = normalized.length % 4;
|
||||
const padded =
|
||||
pad === 0 ? normalized : `${normalized}${'='.repeat(4 - pad)}`;
|
||||
return Buffer.from(padded, 'base64');
|
||||
}
|
||||
|
||||
async function verifyLegacyScrypt(
|
||||
storedHash: string,
|
||||
password: string,
|
||||
): Promise<boolean | undefined> {
|
||||
const match = SCRYPT_PHC_RE.exec(storedHash);
|
||||
if (!match) return undefined;
|
||||
const ln = Number(match[1]);
|
||||
const r = Number(match[2]);
|
||||
const p = Number(match[3]);
|
||||
if (
|
||||
!Number.isInteger(ln) ||
|
||||
ln < 10 ||
|
||||
ln > 18 ||
|
||||
!Number.isInteger(r) ||
|
||||
r < 1 ||
|
||||
r > 16 ||
|
||||
!Number.isInteger(p) ||
|
||||
p < 1 ||
|
||||
p > 4
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const salt = decodeBase64Flexible(match[4]);
|
||||
const expected = decodeBase64Flexible(match[5]);
|
||||
if (salt.length < 8 || expected.length < 16 || expected.length > 64) {
|
||||
return undefined;
|
||||
}
|
||||
const N = 2 ** ln;
|
||||
const maxmem = Math.max(128 * N * r * 2, 32 * 1024 * 1024);
|
||||
const derived = await scryptAsync(password, salt, expected.length, {
|
||||
N,
|
||||
r,
|
||||
p,
|
||||
maxmem,
|
||||
});
|
||||
if (derived.length !== expected.length) return false;
|
||||
return timingSafeEqual(derived, expected);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PasswordHasherService implements OnModuleInit {
|
||||
private readonly memoryCost: number;
|
||||
private readonly timeCost: number;
|
||||
private readonly parallelism: number;
|
||||
private readonly maxConcurrent: number;
|
||||
private readonly maxQueue: number;
|
||||
private readonly queueTimeoutMs: number;
|
||||
private dummyHash: string | undefined;
|
||||
private dummyInitPromise: Promise<string> | undefined;
|
||||
private active = 0;
|
||||
private readonly queue: Waiter[] = [];
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
@Optional() private readonly metrics?: MetricsService,
|
||||
) {
|
||||
this.memoryCost = config.getOrThrow('ARGON2_MEMORY_KIB');
|
||||
this.timeCost = config.getOrThrow('ARGON2_ITERATIONS');
|
||||
this.parallelism = config.getOrThrow('ARGON2_PARALLELISM');
|
||||
this.maxConcurrent = config.getOrThrow('AUTH_HASH_MAX_CONCURRENT');
|
||||
this.maxQueue = config.getOrThrow('AUTH_HASH_MAX_QUEUE');
|
||||
this.queueTimeoutMs = config.getOrThrow('AUTH_HASH_QUEUE_TIMEOUT_MS');
|
||||
}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
this.observeConcurrency();
|
||||
await this.ensureDummyHash();
|
||||
}
|
||||
|
||||
get activeCount(): number {
|
||||
return this.active;
|
||||
}
|
||||
|
||||
get queuedCount(): number {
|
||||
return this.queue.length;
|
||||
}
|
||||
|
||||
async hash(password: string): Promise<string> {
|
||||
return this.withPermit(() => this.computeHash(password));
|
||||
}
|
||||
|
||||
async verify(
|
||||
storedHash: string | undefined,
|
||||
password: string,
|
||||
): Promise<PasswordVerifyResult> {
|
||||
return this.withPermit(() => this.verifyInternal(storedHash, password));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies a password and, if valid and parameters/algorithm are outdated,
|
||||
* computes the upgraded Argon2id hash inside the SAME concurrency permit so
|
||||
* a single login never double-acquires permits or deadlocks under load.
|
||||
*/
|
||||
async verifyAndUpgrade(
|
||||
storedHash: string | undefined,
|
||||
password: string,
|
||||
): Promise<PasswordVerifyAndUpgradeResult> {
|
||||
return this.withPermit(async () => {
|
||||
const result = await this.verifyInternal(storedHash, password);
|
||||
if (!result.valid) return { valid: false };
|
||||
if (!result.needsRehash) return { valid: true };
|
||||
const upgradedHash = await this.computeHash(password);
|
||||
return { valid: true, upgradedHash };
|
||||
});
|
||||
}
|
||||
|
||||
private async verifyInternal(
|
||||
storedHash: string | undefined,
|
||||
password: string,
|
||||
): Promise<PasswordVerifyResult> {
|
||||
const dummy = await this.ensureDummyHash();
|
||||
if (!storedHash) {
|
||||
await argon2.verify(dummy, password).catch(() => false);
|
||||
return { valid: false, needsRehash: false };
|
||||
}
|
||||
|
||||
if (
|
||||
storedHash.startsWith('$argon2id$') ||
|
||||
storedHash.startsWith('$argon2i$') ||
|
||||
storedHash.startsWith('$argon2d$')
|
||||
) {
|
||||
try {
|
||||
const valid = await argon2.verify(storedHash, password);
|
||||
if (!valid) return { valid: false, needsRehash: false };
|
||||
const needsRehash =
|
||||
!storedHash.startsWith('$argon2id$') ||
|
||||
argon2.needsRehash(storedHash, {
|
||||
memoryCost: this.memoryCost,
|
||||
timeCost: this.timeCost,
|
||||
parallelism: this.parallelism,
|
||||
});
|
||||
return { valid: true, needsRehash };
|
||||
} catch {
|
||||
await argon2.verify(dummy, password).catch(() => false);
|
||||
return { valid: false, needsRehash: false };
|
||||
}
|
||||
}
|
||||
|
||||
if (storedHash.startsWith('$scrypt$')) {
|
||||
try {
|
||||
const valid = await verifyLegacyScrypt(storedHash, password);
|
||||
if (valid === undefined) {
|
||||
await argon2.verify(dummy, password).catch(() => false);
|
||||
return { valid: false, needsRehash: false };
|
||||
}
|
||||
return { valid, needsRehash: valid };
|
||||
} catch {
|
||||
await argon2.verify(dummy, password).catch(() => false);
|
||||
return { valid: false, needsRehash: false };
|
||||
}
|
||||
}
|
||||
|
||||
await argon2.verify(dummy, password).catch(() => false);
|
||||
return { valid: false, needsRehash: false };
|
||||
}
|
||||
|
||||
private computeHash(password: string): Promise<string> {
|
||||
return argon2.hash(password, {
|
||||
type: argon2.argon2id,
|
||||
memoryCost: this.memoryCost,
|
||||
timeCost: this.timeCost,
|
||||
parallelism: this.parallelism,
|
||||
hashLength: 32,
|
||||
});
|
||||
}
|
||||
|
||||
private ensureDummyHash(): Promise<string> {
|
||||
if (this.dummyHash) return Promise.resolve(this.dummyHash);
|
||||
if (!this.dummyInitPromise) {
|
||||
this.dummyInitPromise = this.computeHash(
|
||||
randomBytes(32).toString('hex'),
|
||||
)
|
||||
.then((computed) => {
|
||||
this.dummyHash = computed;
|
||||
return computed;
|
||||
})
|
||||
.finally(() => {
|
||||
this.dummyInitPromise = undefined;
|
||||
});
|
||||
}
|
||||
return this.dummyInitPromise;
|
||||
}
|
||||
|
||||
private async withPermit<T>(work: () => Promise<T>): Promise<T> {
|
||||
await this.acquire();
|
||||
const started = performance.now();
|
||||
try {
|
||||
return await work();
|
||||
} finally {
|
||||
const elapsedMs = performance.now() - started;
|
||||
this.metrics?.increment('auth.hash.completed');
|
||||
this.recordDuration(elapsedMs);
|
||||
this.release();
|
||||
}
|
||||
}
|
||||
|
||||
private acquire(): Promise<void> {
|
||||
if (this.active < this.maxConcurrent) {
|
||||
this.active += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (this.queue.length >= this.maxQueue) {
|
||||
this.metrics?.increment('auth.hash.rejected');
|
||||
return Promise.reject(
|
||||
new HttpException(
|
||||
{
|
||||
message: 'Too many authentication requests',
|
||||
retryAfter: 1,
|
||||
},
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
),
|
||||
);
|
||||
}
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const waiter: Waiter = {
|
||||
resolve,
|
||||
reject,
|
||||
timer: setTimeout(() => {
|
||||
const idx = this.queue.indexOf(waiter);
|
||||
if (idx >= 0) this.queue.splice(idx, 1);
|
||||
this.metrics?.increment('auth.hash.rejected');
|
||||
reject(
|
||||
new HttpException(
|
||||
{
|
||||
message: 'Too many authentication requests',
|
||||
retryAfter: 1,
|
||||
},
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
),
|
||||
);
|
||||
}, this.queueTimeoutMs),
|
||||
};
|
||||
waiter.timer.unref();
|
||||
this.queue.push(waiter);
|
||||
});
|
||||
}
|
||||
|
||||
private release(): void {
|
||||
const next = this.queue.shift();
|
||||
if (next) {
|
||||
clearTimeout(next.timer);
|
||||
next.resolve();
|
||||
return;
|
||||
}
|
||||
this.active = Math.max(0, this.active - 1);
|
||||
}
|
||||
|
||||
private durationHistogram:
|
||||
| ReturnType<ReturnType<typeof meter>['createHistogram']>
|
||||
| undefined;
|
||||
|
||||
private recordDuration(ms: number): void {
|
||||
try {
|
||||
this.durationHistogram ??= meter().createHistogram(
|
||||
'auth.hash.duration_ms',
|
||||
{
|
||||
unit: 'ms',
|
||||
description: 'Password hashing/verification duration',
|
||||
},
|
||||
);
|
||||
this.durationHistogram.record(ms);
|
||||
} catch {
|
||||
// Best-effort telemetry recording.
|
||||
}
|
||||
}
|
||||
|
||||
private observeConcurrency(): void {
|
||||
const m = meter();
|
||||
const activeGauge = m.createObservableUpDownCounter('auth.hash.active', {
|
||||
unit: '{operation}',
|
||||
description: 'In-flight password hash/verify operations',
|
||||
});
|
||||
const queuedGauge = m.createObservableUpDownCounter('auth.hash.queued', {
|
||||
unit: '{operation}',
|
||||
description: 'Queued password hash/verify operations',
|
||||
});
|
||||
m.addBatchObservableCallback(
|
||||
(result) => {
|
||||
result.observe(activeGauge, this.active);
|
||||
result.observe(queuedGauge, this.queue.length);
|
||||
},
|
||||
[activeGauge, queuedGauge],
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user