fix(stage): isolate credentialless author bootstrap and recovery rehearsal
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 3m55s

This commit is contained in:
Canina Automation committed 2026-10-28 19:52:55 +00:00
1 parent 6ed0e73311
commit 46da1c5339
30 files changed
+1295 -62

No files matched your search

+1 -1
View File
@@ -233,7 +233,7 @@ export class AuthController {
async refresh(
@Req()
req: {
user: { id: string; email?: string; role?: string; mobile?: string };
user: { id: string; email?: string; role?: string; mobile?: string | null };
},
@Res({ passthrough: true }) res?: Response,
) {
+20 -8
View File
@@ -69,6 +69,8 @@ export class AuthService {
async sendOtp(sendOtpDto: SendOtpDto) {
const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber);
const user = await this.prisma.user.findUnique({ where: { mobile: phoneNumber } });
if (user) assertPrincipalActive(user);
// 1. Check 60-second cooldown per phone number
const cooldownKey = `otp:cooldown:${phoneNumber}`;
@@ -220,6 +222,7 @@ export class AuthService {
const firstName = registerDto.firstName.trim();
const lastName = registerDto.lastName.trim();
const mobile = normalizeMobile(registerDto.mobile);
if (!mobile) throw new BadRequestException("شماره موبایل الزامی است");
const email = registerDto.email
? registerDto.email.trim().toLowerCase()
: null;
@@ -319,15 +322,15 @@ export class AuthService {
}
async adminLogin(body: AdminLoginInput) {
// First check database for user with role 'Admin' or 'SUPER_ADMIN'
// Resolve email before checking roles so public authors cannot enter the env fallback.
const dbAdmin = await this.prisma.user.findFirst({
where: {
email: body.email,
role: { in: ["Admin", "SUPER_ADMIN", "ADMIN"] },
},
where: { email: body.email },
});
if (dbAdmin && dbAdmin.password && body.password) {
// Reject before credential/fallback evaluation, including accidentally assigned admin roles.
if (dbAdmin) assertPrincipalActive(dbAdmin);
if (dbAdmin && ["Admin", "SUPER_ADMIN", "ADMIN"].includes(dbAdmin.role) && dbAdmin.password && body.password) {
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
if (isMatch) {
assertPrincipalActive(dbAdmin);
@@ -493,12 +496,21 @@ export class AuthService {
async refresh(user: {
id: string;
email?: string;
email?: string | null;
role?: string;
mobile?: string;
mobile?: string | null;
isPublicAuthor?: boolean;
stageTestSession?: string | null;
stageTestGeneration?: string | null;
}) {
// Re-resolve rather than trusting a stale or partially projected request principal.
const current = await this.prisma.user.findUnique({ where: { id: user.id } });
if (!current) throw new UnauthorizedException("کاربر یافت نشد");
assertPrincipalActive(current);
assertPrincipalActive(user);
if (current.stageTestSession && (!current.stageTestGeneration || user.stageTestGeneration !== current.stageTestGeneration || user.stageTestSession !== current.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
const { password: _password, ...safeUser } = current;
user = safeUser;
const payload = {
sub: user.id,
email: user.email,
+3
View File
@@ -6,6 +6,7 @@ import {
forwardRef,
} from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { assertPrincipalActive } from "./stage-test-principal";
import { ApiKeysService } from "../admin/api-keys.service";
@Injectable()
@@ -28,6 +29,7 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
if (apiKeyHeader && this.apiKeysService) {
try {
const apiKeyUser = await this.apiKeysService.validateKey(apiKeyHeader);
assertPrincipalActive(apiKeyUser as { isPublicAuthor?: boolean });
request.user = apiKeyUser;
return true;
} catch (err: unknown) {
@@ -52,6 +54,7 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
)
);
}
assertPrincipalActive(user as { isPublicAuthor?: boolean });
return user;
}
}
+1 -1
View File
@@ -62,7 +62,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
if (!user) {
throw new UnauthorizedException("کاربر یافت نشد");
}
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal unavailable"); }
if (user.stageTestSession) {
if (!user.stageTestGeneration || payload.stageTestGeneration !== user.stageTestGeneration || payload.stageTestSession !== user.stageTestSession) throw new UnauthorizedException("Stage session revoked");
const path = req.originalUrl?.split('?')[0] || '';
+125
View File
@@ -0,0 +1,125 @@
import { UnauthorizedException, ForbiddenException } from '@nestjs/common';
import { validate } from 'class-validator';
import * as bcrypt from 'bcryptjs';
import { readFileSync } from 'fs';
import { join } from 'path';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { JwtAuthGuard } from './jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
import { assertPrincipalActive } from './stage-test-principal';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
describe('Public authors are attribution only, never principals', () => {
const password = 'test-password';
const author = { id: 'author-id', mobile: '09123456789', email: 'author@example.invalid', password: bcrypt.hashSync(password, 4), role: 'SUPER_ADMIN', isPublicAuthor: true };
let prisma: any, jwt: any, redis: any, sms: any, service: AuthService;
const env = { ...process.env };
beforeEach(() => {
process.env.JWT_SECRET = 'isolated-public-author-test-secret';
process.env.JWT_REFRESH_SECRET = 'isolated-public-author-refresh-secret';
prisma = { user: { findUnique: jest.fn().mockResolvedValue(author), findFirst: jest.fn().mockResolvedValue(author), create: jest.fn() } };
jwt = { sign: jest.fn().mockReturnValue('token'), verify: jest.fn().mockReturnValue({ sub: author.id, jti: 'old-token' }) };
redis = { get: jest.fn(async (key: string) => key.startsWith('otp_attempts:') ? null : key === `otp:${author.mobile}` ? '12345' : key.startsWith('refresh_token:') ? '1' : null), set: jest.fn(), del: jest.fn(), incr: jest.fn().mockResolvedValue(1) };
sms = { sendOtp: jest.fn().mockResolvedValue(true) };
service = new AuthService(prisma, jwt, redis, sms);
});
afterEach(() => { process.env = { ...env }; });
it('shared principal assertion rejects the marker independent of role/mobile', () => {
expect(() => assertPrincipalActive(author)).toThrow(UnauthorizedException);
const withoutMobile = { ...author, mobile: null };
expect(() => assertPrincipalActive(withoutMobile)).toThrow(UnauthorizedException);
});
it.each(['User_PetOwner', 'Admin', 'ADMIN', 'SUPER_ADMIN'])('blocks password login even with role %s', async role => {
prisma.user.findUnique.mockResolvedValue({ ...author, role });
await expect(service.login({ mobile: author.mobile, password })).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it('does not send or store an OTP for a public author', async () => {
await expect(service.sendOtp({ phoneNumber: author.mobile })).rejects.toThrow(UnauthorizedException);
expect(sms.sendOtp).not.toHaveBeenCalled();
expect(redis.set).not.toHaveBeenCalled();
});
it('blocks a previously issued valid OTP without creating an alternate account', async () => {
await expect(service.verifyOtp({ phoneNumber: author.mobile, code: '12345' })).rejects.toThrow(UnauthorizedException);
expect(prisma.user.create).not.toHaveBeenCalled();
expect(jwt.sign).not.toHaveBeenCalled();
});
it.each(['Admin', 'ADMIN', 'SUPER_ADMIN'])('blocks email/admin login including nonproduction fallback for %s', async role => {
process.env.NODE_ENV = 'test';
process.env.ADMIN_EMAIL = author.email;
process.env.ADMIN_PASSWORD = password;
prisma.user.findFirst.mockResolvedValue({ ...author, role, password: null });
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it('blocks email/admin login with a valid stored password', async () => {
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it('email lookup cannot hide a public author behind a non-admin role and enter fallback', async () => {
process.env.ADMIN_EMAIL = author.email;
process.env.ADMIN_PASSWORD = password;
prisma.user.findFirst.mockResolvedValue({ ...author, role: 'User_PetOwner' });
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
expect(prisma.user.findFirst).toHaveBeenCalledWith({ where: { email: author.email } });
expect(jwt.sign).not.toHaveBeenCalled();
});
it('blocks refresh-token rotation for an existing author account', async () => {
await expect(service.refreshToken('previous-token')).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it('blocks legacy refresh even when supplied principal omits the marker', async () => {
await expect(service.refresh({ id: author.id, role: 'SUPER_ADMIN' })).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it.each(['Bearer old-token', 'cookie'])('rejects existing JWT via %s using database marker, not token claims', async transport => {
const strategy = new JwtStrategy({ findById: jest.fn().mockResolvedValue(author) } as any, redis);
const headers = transport === 'cookie' ? { cookie: 'accessToken=old-token' } : { authorization: transport };
await expect(strategy.validate({ headers } as any, { sub: author.id, role: 'SUPER_ADMIN' })).rejects.toThrow(UnauthorizedException);
});
it('JWT guard rejects an accidentally supplied author principal', () => {
expect(() => new JwtAuthGuard().handleRequest(null, author)).toThrow(UnauthorizedException);
});
it('API-key guard rejects an accidentally marked principal', async () => {
const guard = new JwtAuthGuard({ validateKey: jest.fn().mockResolvedValue({ ...author, isApiKey: true, scopes: ['admin'] }) } as any);
const request = { headers: { 'x-api-key': 'test-key' } };
await expect(guard.canActivate({ switchToHttp: () => ({ getRequest: () => request }) } as any)).rejects.toThrow(UnauthorizedException);
});
it.each([{ roles: ['Admin'] }, { roles: [] }])('role guard rejects author even for roles %j', ({ roles }) => {
const guard = new RolesGuard({ getAllAndOverride: () => roles } as any);
const ctx = { getHandler: () => null, getClass: () => null, switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
expect(() => guard.canActivate(ctx)).toThrow(ForbiddenException);
});
it('human admin guard rejects author with admin role', () => {
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
expect(() => new HumanAdminGuard().canActivate(ctx)).toThrow(ForbiddenException);
});
it.each([undefined, null, '', ' '])('registration still requires mobile %j before any database write', async mobile => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.user.create.mockResolvedValue({ ...author, mobile, isPublicAuthor: false });
await expect(service.register({ firstName: 'Real', lastName: 'User', mobile } as any)).rejects.toThrow();
expect(prisma.user.create).not.toHaveBeenCalled();
});
it.each([RegisterDto, LoginDto])('real-user DTO retains required mobile validation', async Dto => {
const dto = Object.assign(new Dto(), { firstName: 'Real', lastName: 'User', password });
expect((await validate(dto)).some(error => error.property === 'mobile')).toBe(true);
});
it('real users can still login, verify OTP and refresh', async () => {
const real = { ...author, isPublicAuthor: false };
prisma.user.findUnique.mockResolvedValue(real);
await expect(service.login({ mobile: real.mobile, password })).resolves.toMatchObject({ success: true });
await expect(service.verifyOtp({ phoneNumber: real.mobile, code: '12345' })).resolves.toMatchObject({ success: true });
await expect(service.refreshToken('previous-token')).resolves.toMatchObject({ success: true });
await expect(service.refresh({ id: real.id })).resolves.toMatchObject({ success: true });
});
it('Prisma author storage permits absent mobile and defaults marker false', () => {
const schema = readFileSync(join(__dirname, '../../prisma/schema.prisma'), 'utf8');
const user = schema.match(/model User \{([\s\S]*?)\n\}/)![1];
expect(user).toMatch(/mobile\s+String\?\s+@unique/);
expect(user).toMatch(/isPublicAuthor\s+Boolean\s+@default\(false\)\s+@map\("is_public_author"\)/);
});
});
+4 -1
View File
@@ -1,3 +1,5 @@
import { UnauthorizedException } from "@nestjs/common";
// Internal seed authority only. No controller, JWT actor, or owner impersonation.
export const STAGE_TEST_ID = 'e876e7a0-738f-4e59-b6db-e270512ababc';
export const STAGE_TEST_EMAIL = 'stage-editorial-reviewer@ci.canina.invalid';
@@ -8,6 +10,7 @@ export function authorizeStageSession(env: NodeJS.ProcessEnv, artifactSha: strin
if (!Number.isInteger(ttl) || ttl < 60 || ttl > 3600) throw new Error('Bounded TTL required');
return {ttl, session:env.STAGE_TEST_SESSION!, sha:artifactSha};
}
export function assertPrincipalActive(user: { authExpiresAt?: Date | null }, now = Date.now()) {
export function assertPrincipalActive(user: { authExpiresAt?: Date | null; isPublicAuthor?: boolean }, now = Date.now()) {
if (user.isPublicAuthor) throw new UnauthorizedException("Public authors cannot authenticate");
if (user.authExpiresAt && user.authExpiresAt.getTime() <= now) throw new Error('Principal expired');
}
@@ -23,7 +23,7 @@ describe('Stage credentials remain fenced to their creation session', () => {
});
it('includes session fencing in newly issued credentials',async()=>{
const jwt=new JwtService({secret:process.env.JWT_SECRET});
const auth=new AuthService({} as any,jwt,redis,undefined as any);
const auth=new AuthService({user:{findUnique:async()=>current}} as any,jwt,redis,undefined as any);
const result=await auth.refresh(current);
expect(jwt.verify(result.data.accessToken).stageTestGeneration).toBe('fresh-generation');
expect(jwt.verify(result.data.accessToken).stageTestSession).toBe('new-session');