From 94fbfe984faeb7462256153594b2af1e4176bc25 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 24 Oct 2026 12:33:56 +0000 Subject: [PATCH] fix(auth): fence temporary Stage credentials by account generation --- .../migration.sql | 2 +- backend/prisma/schema.prisma | 1 + backend/src/admin/admin.service.ts | 3 +- backend/src/auth/auth.service.ts | 12 +++++-- backend/src/auth/jwt.strategy.ts | 3 ++ .../auth/stage-test-session-security.spec.ts | 32 +++++++++++++++++++ 6 files changed, 48 insertions(+), 5 deletions(-) create mode 100644 backend/src/auth/stage-test-session-security.spec.ts diff --git a/backend/prisma/migrations/20261024090000_stage_test_principal/migration.sql b/backend/prisma/migrations/20261024090000_stage_test_principal/migration.sql index e950ee4d..089248e4 100644 --- a/backend/prisma/migrations/20261024090000_stage_test_principal/migration.sql +++ b/backend/prisma/migrations/20261024090000_stage_test_principal/migration.sql @@ -1 +1 @@ -ALTER TABLE "users" ADD COLUMN "auth_expires_at" TIMESTAMPTZ, ADD COLUMN "stage_test_session" VARCHAR(64); +ALTER TABLE "users" ADD COLUMN "auth_expires_at" TIMESTAMPTZ, ADD COLUMN "stage_test_session" VARCHAR(64), ADD COLUMN "stage_test_generation" UUID; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 004262c8..9701df16 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -17,6 +17,7 @@ model User { password String? @db.VarChar(255) role String @default("User_PetOwner") @db.VarChar(30) authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz() + stageTestGeneration String? @map("stage_test_generation") @db.Uuid stageTestSession String? @map("stage_test_session") @db.VarChar(64) walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2) charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2) diff --git a/backend/src/admin/admin.service.ts b/backend/src/admin/admin.service.ts index f30da005..0b5a5004 100644 --- a/backend/src/admin/admin.service.ts +++ b/backend/src/admin/admin.service.ts @@ -63,6 +63,7 @@ export class CouponInput { import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy"; import type { UserAdminActor } from "./user-role-policy"; +import { randomUUID } from "crypto"; import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal"; @Injectable() @@ -274,7 +275,7 @@ export class AdminService { return this.prisma.user.create({ data: { - ...(stage ? { id: STAGE_TEST_ID, stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}), + ...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}), firstName: dto.firstName.trim(), lastName: dto.lastName.trim(), mobile, diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 39bd1e9d..5aff004c 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -202,7 +202,7 @@ export class AuthService { } assertPrincipalActive(user); - const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role }; + const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) }; const tokens = await this.generateTokens(payload); const { password: _p, ...safeUser } = user; @@ -260,7 +260,7 @@ export class AuthService { }); assertPrincipalActive(user); - const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role }; + const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) }; const tokens = await this.generateTokens(payload); const { password: _p, ...safeUser } = user; @@ -304,7 +304,7 @@ export class AuthService { } assertPrincipalActive(user); - const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role }; + const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) }; const tokens = await this.generateTokens(payload); const { password: _pw, ...safeUser } = user; @@ -335,6 +335,7 @@ export class AuthService { sub: dbAdmin.id, email: dbAdmin.email, role: dbAdmin.role, + ...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}), }; const tokens = await this.generateTokens(payload); const { password: _p, ...safeUser } = dbAdmin; @@ -449,11 +450,13 @@ export class AuthService { const user = await this.prisma.user.findUnique({ where: { id: userId } }); if (user) { assertPrincipalActive(user); + if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked"); userPayload = { sub: user.id, email: user.email, phoneNumber: user.mobile, role: user.role, + ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}), }; const { password: _p, ...restUser } = user; safeUser = restUser; @@ -493,12 +496,15 @@ export class AuthService { email?: string; role?: string; mobile?: string; + stageTestSession?: string | null; + stageTestGeneration?: string | null; }) { const payload = { sub: user.id, email: user.email, role: user.role, phoneNumber: user.mobile, + ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}), }; const tokens = await this.generateTokens(payload); return { diff --git a/backend/src/auth/jwt.strategy.ts b/backend/src/auth/jwt.strategy.ts index d42a91ce..4e200049 100644 --- a/backend/src/auth/jwt.strategy.ts +++ b/backend/src/auth/jwt.strategy.ts @@ -13,6 +13,8 @@ export interface JwtPayload { email?: string; role?: string; phoneNumber?: string; + stageTestSession?: string; + stageTestGeneration?: string; } @Injectable() @@ -62,6 +64,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) { } try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); } 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] || ''; const allowed = req.method === 'GET' && /^\/api\/admin\/orchestration\/tasks(?:\/[a-f0-9-]+)?$/.test(path) || req.method === 'POST' && (/^\/api\/admin\/orchestration\/tasks$/.test(path) || /^\/api\/admin\/orchestration\/tasks\/[a-f0-9-]+\/(?:gates\/1\/decide|editorial-failure)$/.test(path)); if (!allowed) throw new UnauthorizedException('Stage test scope denied'); diff --git a/backend/src/auth/stage-test-session-security.spec.ts b/backend/src/auth/stage-test-session-security.spec.ts new file mode 100644 index 00000000..c67f0036 --- /dev/null +++ b/backend/src/auth/stage-test-session-security.spec.ts @@ -0,0 +1,32 @@ +import { JwtService } from '@nestjs/jwt'; +import { JwtStrategy } from './jwt.strategy'; +import { AuthService } from './auth.service'; + +describe('Stage credentials remain fenced to their creation session', () => { + const id='e876e7a0-738f-4e59-b6db-e270512ababc'; + const current={id, role:'SUPER_ADMIN', stageTestSession:'new-session', stageTestGeneration:'fresh-generation', authExpiresAt:new Date(Date.now()+600000)}; + const redis:any={get:jest.fn(async()=> '1'),del:jest.fn(),set:jest.fn()}; + beforeAll(()=> {process.env.JWT_SECRET='disposable-only-test-secret-at-least-32-characters';process.env.JWT_REFRESH_SECRET='disposable-only-refresh-secret-at-least-32-characters';}); + it('rejects an old-session access token after fixed account ID is recreated',async()=>{ + const strategy=new JwtStrategy({findById:async()=>current} as any,{get:async()=>null} as any); + const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{}}; + await expect(strategy.validate(req,{sub:id,stageTestSession:'old-session'} as any)).rejects.toThrow(); + await expect(strategy.validate(req,{sub:id})).rejects.toThrow(); + await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'old-generation'} as any)).rejects.toThrow(); + await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'fresh-generation'} as any)).resolves.toMatchObject({id}); + }); + it('rejects an old-session refresh token even while its Redis entry remains active',async()=>{ + const jwt=new JwtService({secret:process.env.JWT_SECRET}); + const auth=new AuthService({user:{findUnique:async()=>current}} as any,jwt,redis,undefined as any); + const token=jwt.sign({sub:id,jti:'old-refresh',role:'SUPER_ADMIN',stageTestSession:'old-session'},{secret:process.env.JWT_REFRESH_SECRET}); + await expect(auth.refreshToken(token)).rejects.toThrow(); + }); + 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 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'); + expect(jwt.verify(result.data.refreshToken,{secret:process.env.JWT_REFRESH_SECRET}).stageTestSession).toBe('new-session'); + }); +});