fix: harden tenant auth and quality gates
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import { Body, Controller, Get, Post, Req, Res, UnauthorizedException } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Post, Req, Res, UnauthorizedException, UsePipes } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentSessionUserId } from './current-session-user.decorator';
|
||||
import { AuthService, LoginDto } from './auth.service';
|
||||
import { AuthService } from './auth.service';
|
||||
import { ChangeOwnPasswordDto, LoginDto, PasswordVerificationDto } from './auth.dto';
|
||||
import { strictValidationPipe } from '../common/strict-validation.pipe';
|
||||
import { DEVELOPMENT_SESSION_COOKIE_NAME, SESSION_COOKIE_NAME, SessionPortal, SessionService } from './session.service';
|
||||
import type { SessionRequest } from './session-validation.middleware';
|
||||
import { UsersService } from '../users/users.service';
|
||||
@@ -26,6 +28,7 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Post('admin/auth/login')
|
||||
@UsePipes(strictValidationPipe)
|
||||
async adminLogin(@Body() body: LoginDto, @Req() request: SessionRequest, @Res({ passthrough: true }) response: CookieResponse) {
|
||||
let result: Awaited<ReturnType<AuthService['login']>>;
|
||||
try {
|
||||
@@ -43,6 +46,7 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Post('client/auth/login')
|
||||
@UsePipes(strictValidationPipe)
|
||||
async clientLogin(@Body() body: LoginDto, @Req() request: SessionRequest, @Res({ passthrough: true }) response: CookieResponse) {
|
||||
let result: Awaited<ReturnType<AuthService['login']>>;
|
||||
try {
|
||||
@@ -95,7 +99,9 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Post(['admin/auth/session/unlock', 'client/auth/session/unlock'])
|
||||
async unlock(@Req() request: SessionRequest, @Body('password') password: string, @Res({ passthrough: true }) response: CookieResponse) {
|
||||
@UsePipes(strictValidationPipe)
|
||||
async unlock(@Req() request: SessionRequest, @Body() body: PasswordVerificationDto, @Res({ passthrough: true }) response: CookieResponse) {
|
||||
const { password } = body;
|
||||
this.assertSession(request);
|
||||
const result = await this.auth.unlock(request.sessionToken!, request.sessionUserId!, password);
|
||||
if (result.status !== 'active' || !('token' in result)) throw new UnauthorizedException({ code: 'SESSION_LOCK_TIMEOUT', message: '锁定时间过长,请重新登录' });
|
||||
@@ -105,7 +111,9 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Post(['admin/auth/reauthenticate', 'client/auth/reauthenticate'])
|
||||
async reauthenticate(@Req() request: SessionRequest, @Body('password') password: string) {
|
||||
@UsePipes(strictValidationPipe)
|
||||
async reauthenticate(@Req() request: SessionRequest, @Body() body: PasswordVerificationDto) {
|
||||
const { password } = body;
|
||||
this.assertSession(request);
|
||||
const result = await this.auth.reauthenticate(request.sessionToken!, request.sessionUserId!, password);
|
||||
if (result.status !== 'active') throw new UnauthorizedException({ code: 'SESSION_LOCKED', message: '会话已锁定' });
|
||||
@@ -122,9 +130,10 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Post(['admin/auth/password', 'client/auth/password'])
|
||||
changeOwnPassword(@CurrentSessionUserId() userId: string | undefined, @Body() body: { currentPassword?: string; password?: string }) {
|
||||
@UsePipes(strictValidationPipe)
|
||||
changeOwnPassword(@CurrentSessionUserId() userId: string | undefined, @Body() body: ChangeOwnPasswordDto) {
|
||||
if (!userId) throw new UnauthorizedException('登录会话无效,请重新登录');
|
||||
return this.users.changeOwnPassword(userId, body.currentPassword ?? '', body.password ?? '');
|
||||
return this.users.changeOwnPassword(userId, body.currentPassword, body.password);
|
||||
}
|
||||
|
||||
private async finishLogin(result: Awaited<ReturnType<AuthService['login']>>, request: SessionRequest, response: CookieResponse) {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { IsString, MaxLength, MinLength } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsString() @MinLength(1) @MaxLength(200) login!: string;
|
||||
@IsString() @MinLength(1) @MaxLength(256) password!: string;
|
||||
@IsString() @MinLength(1) @MaxLength(64) captchaId!: string;
|
||||
@IsString() @MinLength(1) @MaxLength(32) captchaText!: string;
|
||||
}
|
||||
|
||||
export class PasswordVerificationDto {
|
||||
@IsString() @MinLength(1) @MaxLength(256) password!: string;
|
||||
}
|
||||
|
||||
export class ChangeOwnPasswordDto {
|
||||
@IsString() @MinLength(1) @MaxLength(256) currentPassword!: string;
|
||||
@IsString() @MinLength(8) @MaxLength(256) password!: string;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { hashPassword } from '../users/users.service';
|
||||
import { legacyHashPassword } from './password-hasher';
|
||||
|
||||
function createUsersMock(roleCode: string, overrides: Record<string, unknown> = {}) {
|
||||
const user = {
|
||||
@@ -10,7 +10,7 @@ function createUsersMock(roleCode: string, overrides: Record<string, unknown> =
|
||||
email: 'user@example.com',
|
||||
phone: '13800000000',
|
||||
displayName: '用户',
|
||||
passwordHash: hashPassword('secret1'),
|
||||
passwordHash: legacyHashPassword('secret1'),
|
||||
status: 'active',
|
||||
deletedAt: null,
|
||||
lockedUntil: null,
|
||||
@@ -20,24 +20,32 @@ function createUsersMock(roleCode: string, overrides: Record<string, unknown> =
|
||||
};
|
||||
return {
|
||||
findByLogin: jest.fn().mockResolvedValue(user),
|
||||
verifyLoginPassword: jest.fn(async (_id: string, password: string) => password === 'secret1'),
|
||||
recordLoginSuccess: jest.fn(),
|
||||
recordLoginFailure: jest.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
function createSessionsMock() {
|
||||
const captchas = new Map<string, string>();
|
||||
const failures = new Map<string, number>();
|
||||
const record = {
|
||||
userId: 'user-1', portal: 'admin', sessionVersion: 0, createdAt: 1, lastActivityAt: 1,
|
||||
lastAuthenticatedAt: 1, absoluteExpiresAt: Date.now() + 1000,
|
||||
};
|
||||
return {
|
||||
storeCaptcha: jest.fn(async (id: string, answer: string) => { captchas.set(id, answer); }),
|
||||
consumeCaptcha: jest.fn(async (id: string) => { const answer = captchas.get(id) ?? null; captchas.delete(id); return answer; }),
|
||||
isAnonymousLoginLocked: jest.fn(async (login: string) => (failures.get(login) ?? 0) >= 5),
|
||||
recordAnonymousLoginFailure: jest.fn(async (login: string) => { const count = (failures.get(login) ?? 0) + 1; failures.set(login, count); return count; }),
|
||||
clearAnonymousLoginFailures: jest.fn(async (login: string) => { failures.delete(login); }),
|
||||
create: jest.fn().mockResolvedValue({ token: 'opaque-session-token', record }),
|
||||
publicSession: jest.fn().mockReturnValue({ idleTimeoutSeconds: 3600, absoluteExpiresAt: new Date(record.absoluteExpiresAt).toISOString() }),
|
||||
};
|
||||
}
|
||||
|
||||
async function loginWithCaptcha(service: AuthService, portal: 'admin' | 'client', password = 'secret1') {
|
||||
const captcha = service.createCaptcha();
|
||||
const captcha = await service.createCaptcha();
|
||||
const answer = captcha.challenge.split('=')[0].split('+').map((part) => Number(part.trim())).reduce((sum, value) => sum + value, 0);
|
||||
return service.login({
|
||||
login: 'user@example.com',
|
||||
|
||||
@@ -1,37 +1,20 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { hashPassword, UsersService } from '../users/users.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import type { LoginDto } from './auth.dto';
|
||||
import { SessionService } from './session.service';
|
||||
|
||||
export interface LoginDto {
|
||||
login: string;
|
||||
password: string;
|
||||
captchaId: string;
|
||||
captchaText: string;
|
||||
}
|
||||
|
||||
type LoginPortal = 'admin' | 'client';
|
||||
|
||||
type CaptchaRecord = {
|
||||
answer: string;
|
||||
expiresAt: number;
|
||||
};
|
||||
|
||||
const captchaStore = new Map<string, CaptchaRecord>();
|
||||
const anonymousFailures = new Map<string, { count: number; lockedUntil?: number }>();
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(private readonly users: UsersService, private readonly sessions: SessionService) {}
|
||||
|
||||
createCaptcha() {
|
||||
async createCaptcha() {
|
||||
const left = Math.floor(10 + Math.random() * 40);
|
||||
const right = Math.floor(1 + Math.random() * 9);
|
||||
const captchaId = randomUUID();
|
||||
captchaStore.set(captchaId, {
|
||||
answer: String(left + right),
|
||||
expiresAt: Date.now() + 5 * 60 * 1000,
|
||||
});
|
||||
await this.sessions.storeCaptcha(captchaId, String(left + right), 5 * 60);
|
||||
return {
|
||||
captchaId,
|
||||
challenge: `${left} + ${right} = ?`,
|
||||
@@ -44,12 +27,12 @@ export class AuthService {
|
||||
if (!login || !data.password) {
|
||||
throw new BadRequestException('login and password are required');
|
||||
}
|
||||
this.verifyCaptcha(data.captchaId, data.captchaText);
|
||||
this.assertAnonymousNotLocked(login);
|
||||
await this.verifyCaptcha(data.captchaId, data.captchaText);
|
||||
await this.assertAnonymousNotLocked(login);
|
||||
|
||||
const user = await this.users.findByLogin(login);
|
||||
if (!user) {
|
||||
this.recordAnonymousFailure(login);
|
||||
await this.sessions.recordAnonymousLoginFailure(login);
|
||||
throw new UnauthorizedException('Invalid login or password');
|
||||
}
|
||||
if (user.lockedUntil && user.lockedUntil.getTime() > Date.now()) {
|
||||
@@ -59,7 +42,7 @@ export class AuthService {
|
||||
await this.users.recordLoginFailure(user.id);
|
||||
throw new UnauthorizedException('User is disabled or deleted');
|
||||
}
|
||||
if (user.passwordHash !== hashPassword(data.password)) {
|
||||
if (!await this.users.verifyLoginPassword(user.id, data.password, user.passwordHash)) {
|
||||
await this.users.recordLoginFailure(user.id);
|
||||
throw new UnauthorizedException('Invalid login or password');
|
||||
}
|
||||
@@ -75,7 +58,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
await this.users.recordLoginSuccess(user.id);
|
||||
anonymousFailures.delete(login);
|
||||
await this.sessions.clearAnonymousLoginFailures(login);
|
||||
|
||||
const { token, record } = await this.sessions.create(user.id, portal, user.sessionVersion ?? 0);
|
||||
return {
|
||||
@@ -105,30 +88,19 @@ export class AuthService {
|
||||
return this.sessions.markReauthenticated(token);
|
||||
}
|
||||
|
||||
private verifyCaptcha(captchaId?: string, captchaText?: string) {
|
||||
const record = captchaId ? captchaStore.get(captchaId) : undefined;
|
||||
captchaStore.delete(captchaId ?? '');
|
||||
if (!record || record.expiresAt < Date.now()) {
|
||||
private async verifyCaptcha(captchaId?: string, captchaText?: string) {
|
||||
const answer = captchaId ? await this.sessions.consumeCaptcha(captchaId) : null;
|
||||
if (!answer) {
|
||||
throw new BadRequestException('Captcha expired, refresh and try again');
|
||||
}
|
||||
if (record.answer !== captchaText?.trim()) {
|
||||
if (answer !== captchaText?.trim()) {
|
||||
throw new BadRequestException('Captcha is incorrect');
|
||||
}
|
||||
}
|
||||
|
||||
private assertAnonymousNotLocked(login: string) {
|
||||
const current = anonymousFailures.get(login);
|
||||
if (current?.lockedUntil && current.lockedUntil > Date.now()) {
|
||||
private async assertAnonymousNotLocked(login: string) {
|
||||
if (await this.sessions.isAnonymousLoginLocked(login)) {
|
||||
throw new UnauthorizedException('User is locked for 24 hours after repeated failures');
|
||||
}
|
||||
}
|
||||
|
||||
private recordAnonymousFailure(login: string) {
|
||||
const current = anonymousFailures.get(login) ?? { count: 0 };
|
||||
const count = current.count + 1;
|
||||
anonymousFailures.set(login, {
|
||||
count,
|
||||
lockedUntil: count >= 5 ? Date.now() + 24 * 60 * 60 * 1000 : current.lockedUntil,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ForbiddenException, createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { SessionRequest } from './session-validation.middleware';
|
||||
|
||||
/**
|
||||
* Returns the tenant bound to the authenticated client session.
|
||||
* Request headers, query parameters and request bodies must never determine this value.
|
||||
*/
|
||||
export const CurrentTenantId = createParamDecorator((_: unknown, context: ExecutionContext) => {
|
||||
const request = context.switchToHttp().getRequest<SessionRequest>();
|
||||
if (request.authSession?.portal !== 'client' || !request.sessionTenantId) {
|
||||
throw new ForbiddenException({ code: 'CLIENT_TENANT_REQUIRED', message: '缺少可信企业上下文' });
|
||||
}
|
||||
return request.sessionTenantId;
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { hashPassword, isLegacySha256, legacyHashPassword, passwordNeedsRehash, verifyPassword } from './password-hasher';
|
||||
|
||||
describe('password hasher', () => {
|
||||
it('stores new passwords using versioned salted scrypt hashes', async () => {
|
||||
const first = await hashPassword('correct horse battery staple');
|
||||
const second = await hashPassword('correct horse battery staple');
|
||||
|
||||
expect(first).toMatch(/^\$scrypt\$v=1\$/);
|
||||
expect(second).not.toBe(first);
|
||||
await expect(verifyPassword('correct horse battery staple', first)).resolves.toBe(true);
|
||||
await expect(verifyPassword('wrong password', first)).resolves.toBe(false);
|
||||
expect(passwordNeedsRehash(first)).toBe(false);
|
||||
});
|
||||
|
||||
it('recognizes and verifies legacy SHA-256 hashes for transparent migration', async () => {
|
||||
const legacy = legacyHashPassword('legacy-password');
|
||||
|
||||
expect(isLegacySha256(legacy)).toBe(true);
|
||||
expect(passwordNeedsRehash(legacy)).toBe(true);
|
||||
await expect(verifyPassword('legacy-password', legacy)).resolves.toBe(true);
|
||||
await expect(verifyPassword('wrong-password', legacy)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects malformed or excessive scrypt parameters', async () => {
|
||||
await expect(verifyPassword('password', '$scrypt$v=1$N=1048576,r=8,p=1$YWJjZGVmZ2hpamtsbW5vcA$YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU')).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { createHash, randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'node:crypto';
|
||||
const VERSION = 1;
|
||||
const KEY_LENGTH = 32;
|
||||
const DEFAULT_N = 32768;
|
||||
const DEFAULT_R = 8;
|
||||
const DEFAULT_P = 1;
|
||||
const MAX_MEMORY = 64 * 1024 * 1024;
|
||||
const LEGACY_SHA256 = /^[a-f0-9]{64}$/i;
|
||||
|
||||
export async function hashPassword(password: string) {
|
||||
const salt = randomBytes(16);
|
||||
const derived = await deriveScrypt(password, salt, KEY_LENGTH, {
|
||||
N: DEFAULT_N,
|
||||
r: DEFAULT_R,
|
||||
p: DEFAULT_P,
|
||||
maxmem: MAX_MEMORY,
|
||||
});
|
||||
return `$scrypt$v=${VERSION}$N=${DEFAULT_N},r=${DEFAULT_R},p=${DEFAULT_P}$${salt.toString('base64url')}$${derived.toString('base64url')}`;
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, encoded: string) {
|
||||
if (isLegacySha256(encoded)) {
|
||||
const candidate = Buffer.from(legacyHashPassword(password), 'hex');
|
||||
const expected = Buffer.from(encoded, 'hex');
|
||||
return candidate.length === expected.length && timingSafeEqual(candidate, expected);
|
||||
}
|
||||
|
||||
const parsed = parseScryptHash(encoded);
|
||||
if (!parsed) return false;
|
||||
const derived = await deriveScrypt(password, parsed.salt, parsed.hash.length, {
|
||||
N: parsed.N,
|
||||
r: parsed.r,
|
||||
p: parsed.p,
|
||||
maxmem: MAX_MEMORY,
|
||||
});
|
||||
return derived.length === parsed.hash.length && timingSafeEqual(derived, parsed.hash);
|
||||
}
|
||||
|
||||
export function passwordNeedsRehash(encoded: string) {
|
||||
if (isLegacySha256(encoded)) return true;
|
||||
const parsed = parseScryptHash(encoded);
|
||||
return !parsed || parsed.version !== VERSION || parsed.N !== DEFAULT_N || parsed.r !== DEFAULT_R || parsed.p !== DEFAULT_P;
|
||||
}
|
||||
|
||||
export function isLegacySha256(encoded: string) {
|
||||
return LEGACY_SHA256.test(encoded);
|
||||
}
|
||||
|
||||
export function legacyHashPassword(password: string) {
|
||||
return createHash('sha256').update(password).digest('hex');
|
||||
}
|
||||
|
||||
function parseScryptHash(encoded: string) {
|
||||
const match = /^\$scrypt\$v=(\d+)\$N=(\d+),r=(\d+),p=(\d+)\$([A-Za-z0-9_-]+)\$([A-Za-z0-9_-]+)$/.exec(encoded);
|
||||
if (!match) return undefined;
|
||||
const [, version, N, r, p, salt, hash] = match;
|
||||
const params = { version: Number(version), N: Number(N), r: Number(r), p: Number(p) };
|
||||
if (!Number.isInteger(params.N) || params.N < 2 || params.N > DEFAULT_N
|
||||
|| !Number.isInteger(params.r) || params.r < 1 || params.r > DEFAULT_R
|
||||
|| !Number.isInteger(params.p) || params.p < 1 || params.p > DEFAULT_P) return undefined;
|
||||
try {
|
||||
const decodedSalt = Buffer.from(salt, 'base64url');
|
||||
const decodedHash = Buffer.from(hash, 'base64url');
|
||||
if (decodedSalt.length < 16 || decodedHash.length !== KEY_LENGTH) return undefined;
|
||||
return { ...params, salt: decodedSalt, hash: decodedHash };
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function deriveScrypt(password: string, salt: Buffer, keyLength: number, options: { N: number; r: number; p: number; maxmem: number }) {
|
||||
return new Promise<Buffer>((resolve, reject) => {
|
||||
scryptCallback(password, salt, keyLength, options, (error, derivedKey) => {
|
||||
if (error) reject(error);
|
||||
else resolve(derivedKey);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
import { ForbiddenException, UnauthorizedException } from '@nestjs/common';
|
||||
import { SessionValidationMiddleware, type SessionRequest } from './session-validation.middleware';
|
||||
|
||||
const record = {
|
||||
@@ -6,10 +6,10 @@ const record = {
|
||||
lastActivityAt: 1, lastAuthenticatedAt: 1, absoluteExpiresAt: Date.now() + 1000,
|
||||
};
|
||||
|
||||
function request(path = '/api/admin/users', cookie = 'cmpp_admin_session=opaque-token'): SessionRequest {
|
||||
function request(path = '/api/admin/users', cookie = 'cmpp_admin_session=opaque-token', tenantId?: string): SessionRequest {
|
||||
return {
|
||||
originalUrl: path,
|
||||
header: jest.fn((name: string) => name === 'cookie' ? cookie : undefined),
|
||||
header: jest.fn((name: string) => name === 'cookie' ? cookie : name === 'x-tenant-id' ? tenantId : undefined),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ describe('SessionValidationMiddleware', () => {
|
||||
const cookieName = jest.fn((portal: 'admin' | 'client') => `cmpp_${portal}_session`);
|
||||
|
||||
it('accepts an active Redis session and exposes its user and record', async () => {
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', status: 'active', deletedAt: null, sessionVersion: 3 }) } };
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: null, status: 'active', deletedAt: null, sessionVersion: 3 }) } };
|
||||
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record }), remove: jest.fn() };
|
||||
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
|
||||
const currentRequest = request();
|
||||
@@ -32,7 +32,7 @@ describe('SessionValidationMiddleware', () => {
|
||||
});
|
||||
|
||||
it('rejects a session after the user session version changes', async () => {
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', status: 'active', deletedAt: null, sessionVersion: 4 }) } };
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: null, status: 'active', deletedAt: null, sessionVersion: 4 }) } };
|
||||
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record }), remove: jest.fn() };
|
||||
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
|
||||
|
||||
@@ -41,7 +41,7 @@ describe('SessionValidationMiddleware', () => {
|
||||
});
|
||||
|
||||
it('only lets a locked session reach unlock and logout endpoints', async () => {
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', status: 'active', deletedAt: null, sessionVersion: 3 }) } };
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: null, status: 'active', deletedAt: null, sessionVersion: 3 }) } };
|
||||
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'locked', record }), remove: jest.fn() };
|
||||
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('SessionValidationMiddleware', () => {
|
||||
|
||||
it('selects only the cookie belonging to the requested portal', async () => {
|
||||
const clientRecord = { ...record, portal: 'client' as const };
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', status: 'active', deletedAt: null, sessionVersion: 3 }) } };
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: 'tenant-a', status: 'active', deletedAt: null, sessionVersion: 3 }) } };
|
||||
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record: clientRecord }), remove: jest.fn() };
|
||||
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
|
||||
const currentRequest = request('/api/client/users', 'cmpp_admin_session=admin-token; cmpp_client_session=client-token');
|
||||
@@ -62,6 +62,33 @@ describe('SessionValidationMiddleware', () => {
|
||||
|
||||
expect(sessions.validate).toHaveBeenCalledWith('client-token', false);
|
||||
expect(currentRequest.sessionToken).toBe('client-token');
|
||||
expect(currentRequest.sessionTenantId).toBe('tenant-a');
|
||||
});
|
||||
|
||||
it('rejects a client session whose user is not bound to a tenant', async () => {
|
||||
const clientRecord = { ...record, portal: 'client' as const };
|
||||
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: null, status: 'active', deletedAt: null, sessionVersion: 3 }) } };
|
||||
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record: clientRecord }), remove: jest.fn() };
|
||||
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
|
||||
|
||||
await expect(middleware.use(request('/api/client/users', 'cmpp_client_session=client-token'), {}, jest.fn()))
|
||||
.rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
|
||||
it('rejects and audits a client tenant header that disagrees with the authenticated user', async () => {
|
||||
const clientRecord = { ...record, portal: 'client' as const };
|
||||
const prisma = {
|
||||
user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: 'tenant-a', status: 'active', deletedAt: null, sessionVersion: 3 }) },
|
||||
operationLog: { create: jest.fn().mockResolvedValue({ id: 'log-1' }) },
|
||||
};
|
||||
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record: clientRecord }), remove: jest.fn() };
|
||||
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
|
||||
|
||||
await expect(middleware.use(request('/api/client/users', 'cmpp_client_session=client-token', 'tenant-b'), {}, jest.fn()))
|
||||
.rejects.toMatchObject({ response: expect.objectContaining({ code: 'CLIENT_TENANT_MISMATCH' }) });
|
||||
expect(prisma.operationLog.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ tenantId: 'tenant-a', userId: 'user-1', action: 'security.client_tenant_mismatch' }),
|
||||
});
|
||||
});
|
||||
|
||||
it('does not accept an admin cookie for a client route', async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
|
||||
import { ForbiddenException, Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuthSessionRecord, SessionPortal, SessionService } from './session.service';
|
||||
|
||||
@@ -8,6 +8,7 @@ export type SessionRequest = {
|
||||
url?: string;
|
||||
sessionUserId?: string;
|
||||
sessionToken?: string;
|
||||
sessionTenantId?: string;
|
||||
authSession?: AuthSessionRecord;
|
||||
};
|
||||
|
||||
@@ -38,7 +39,7 @@ export class SessionValidationMiddleware implements NestMiddleware {
|
||||
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: result.record.userId },
|
||||
select: { id: true, status: true, deletedAt: true, sessionVersion: true },
|
||||
select: { id: true, tenantId: true, status: true, deletedAt: true, sessionVersion: true },
|
||||
});
|
||||
if (!user || user.status !== 'active' || user.deletedAt || user.sessionVersion !== result.record.sessionVersion) {
|
||||
await this.sessions.remove(token);
|
||||
@@ -51,6 +52,25 @@ export class SessionValidationMiddleware implements NestMiddleware {
|
||||
request.sessionUserId = user.id;
|
||||
request.sessionToken = token;
|
||||
request.authSession = result.record;
|
||||
if (portal === 'client') {
|
||||
if (!user.tenantId) {
|
||||
throw new ForbiddenException({ code: 'CLIENT_TENANT_REQUIRED', message: '当前客户端账号未关联企业' });
|
||||
}
|
||||
const suppliedTenantId = request.header('x-tenant-id')?.trim();
|
||||
if (suppliedTenantId && suppliedTenantId !== user.tenantId) {
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: user.tenantId,
|
||||
userId: user.id,
|
||||
action: 'security.client_tenant_mismatch',
|
||||
resource: 'auth_session',
|
||||
detail: { suppliedTenantId },
|
||||
},
|
||||
});
|
||||
throw new ForbiddenException({ code: 'CLIENT_TENANT_MISMATCH', message: '请求企业与登录企业不一致' });
|
||||
}
|
||||
request.sessionTenantId = user.tenantId;
|
||||
}
|
||||
const isSessionRecoveryRoute = /\/auth\/(?:session(?:\/unlock)?|logout)(?:\?|$)/.test(path);
|
||||
if (result.status === 'locked' && !isSessionRecoveryRoute) {
|
||||
if (result.newlyLocked) {
|
||||
|
||||
@@ -21,6 +21,9 @@ export type SessionValidationResult =
|
||||
| { status: 'expired'; code: 'SESSION_INVALID' | 'SESSION_ABSOLUTE_TIMEOUT' | 'SESSION_LOCK_TIMEOUT' };
|
||||
|
||||
const SESSION_PREFIX = 'cmpp:auth:session:';
|
||||
const CAPTCHA_PREFIX = 'cmpp:auth:captcha:';
|
||||
const ANONYMOUS_FAILURE_PREFIX = 'cmpp:auth:failure:';
|
||||
const ANONYMOUS_LOCK_PREFIX = 'cmpp:auth:lock:';
|
||||
export const SESSION_COOKIE_NAME = '__Host-cmpp_session';
|
||||
export const DEVELOPMENT_SESSION_COOKIE_NAME = 'cmpp_session';
|
||||
export const ADMIN_SESSION_COOKIE_NAME = '__Host-cmpp_admin_session';
|
||||
@@ -123,6 +126,61 @@ export class SessionService implements OnModuleDestroy {
|
||||
return this.client.del(this.key(token));
|
||||
}
|
||||
|
||||
async storeCaptcha(captchaId: string, answer: string, ttlSeconds: number) {
|
||||
try {
|
||||
await this.client.set(`${CAPTCHA_PREFIX}${captchaId}`, answer, 'EX', ttlSeconds);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('验证码服务暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
async consumeCaptcha(captchaId: string) {
|
||||
try {
|
||||
return await this.client.getdel(`${CAPTCHA_PREFIX}${captchaId}`);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('验证码服务暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
async isAnonymousLoginLocked(login: string) {
|
||||
try {
|
||||
return Boolean(await this.client.exists(`${ANONYMOUS_LOCK_PREFIX}${this.loginDigest(login)}`));
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('登录保护服务暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
async recordAnonymousLoginFailure(login: string) {
|
||||
const digest = this.loginDigest(login);
|
||||
const failureKey = `${ANONYMOUS_FAILURE_PREFIX}${digest}`;
|
||||
const lockKey = `${ANONYMOUS_LOCK_PREFIX}${digest}`;
|
||||
try {
|
||||
const count = Number(await this.client.eval(
|
||||
`local count = redis.call('INCR', KEYS[1])
|
||||
if count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
|
||||
if count >= tonumber(ARGV[2]) then redis.call('SET', KEYS[2], '1', 'EX', ARGV[1]) end
|
||||
return count`,
|
||||
2,
|
||||
failureKey,
|
||||
lockKey,
|
||||
24 * 60 * 60,
|
||||
5,
|
||||
));
|
||||
return count;
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('登录保护服务暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
async clearAnonymousLoginFailures(login: string) {
|
||||
const digest = this.loginDigest(login);
|
||||
try {
|
||||
await this.client.del(`${ANONYMOUS_FAILURE_PREFIX}${digest}`, `${ANONYMOUS_LOCK_PREFIX}${digest}`);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('登录保护服务暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
isRecentlyAuthenticated(record: AuthSessionRecord) {
|
||||
return Date.now() - record.lastAuthenticatedAt < this.recentAuthenticationMs;
|
||||
}
|
||||
@@ -195,6 +253,10 @@ export class SessionService implements OnModuleDestroy {
|
||||
return `${SESSION_PREFIX}${createHash('sha256').update(token).digest('hex')}`;
|
||||
}
|
||||
|
||||
private loginDigest(login: string) {
|
||||
return createHash('sha256').update(login.trim().toLocaleLowerCase('en-US')).digest('hex');
|
||||
}
|
||||
|
||||
private get client() {
|
||||
if (!this.redis) {
|
||||
this.redis = new IORedis(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379', {
|
||||
|
||||
Reference in New Issue
Block a user