fix(auth): fence temporary Stage credentials by account generation
This commit is contained in:
1 parent
e036c5d436
commit
80a2e188cf
6 files changed
+48
-5
No files matched your search
@@ -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;
|
||||||
@@ -17,6 +17,7 @@ model User {
|
|||||||
password String? @db.VarChar(255)
|
password String? @db.VarChar(255)
|
||||||
role String @default("User_PetOwner") @db.VarChar(30)
|
role String @default("User_PetOwner") @db.VarChar(30)
|
||||||
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
|
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)
|
stageTestSession String? @map("stage_test_session") @db.VarChar(64)
|
||||||
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
|
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)
|
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ export class CouponInput {
|
|||||||
|
|
||||||
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
||||||
import type { UserAdminActor } 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";
|
import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -274,7 +275,7 @@ export class AdminService {
|
|||||||
|
|
||||||
return this.prisma.user.create({
|
return this.prisma.user.create({
|
||||||
data: {
|
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(),
|
firstName: dto.firstName.trim(),
|
||||||
lastName: dto.lastName.trim(),
|
lastName: dto.lastName.trim(),
|
||||||
mobile,
|
mobile,
|
||||||
|
|||||||
@@ -202,7 +202,7 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
assertPrincipalActive(user);
|
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 tokens = await this.generateTokens(payload);
|
||||||
|
|
||||||
const { password: _p, ...safeUser } = user;
|
const { password: _p, ...safeUser } = user;
|
||||||
@@ -260,7 +260,7 @@ export class AuthService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
assertPrincipalActive(user);
|
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 tokens = await this.generateTokens(payload);
|
||||||
|
|
||||||
const { password: _p, ...safeUser } = user;
|
const { password: _p, ...safeUser } = user;
|
||||||
@@ -304,7 +304,7 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
assertPrincipalActive(user);
|
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 tokens = await this.generateTokens(payload);
|
||||||
|
|
||||||
const { password: _pw, ...safeUser } = user;
|
const { password: _pw, ...safeUser } = user;
|
||||||
@@ -335,6 +335,7 @@ export class AuthService {
|
|||||||
sub: dbAdmin.id,
|
sub: dbAdmin.id,
|
||||||
email: dbAdmin.email,
|
email: dbAdmin.email,
|
||||||
role: dbAdmin.role,
|
role: dbAdmin.role,
|
||||||
|
...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}),
|
||||||
};
|
};
|
||||||
const tokens = await this.generateTokens(payload);
|
const tokens = await this.generateTokens(payload);
|
||||||
const { password: _p, ...safeUser } = dbAdmin;
|
const { password: _p, ...safeUser } = dbAdmin;
|
||||||
@@ -449,11 +450,13 @@ export class AuthService {
|
|||||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||||
if (user) {
|
if (user) {
|
||||||
assertPrincipalActive(user);
|
assertPrincipalActive(user);
|
||||||
|
if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
|
||||||
userPayload = {
|
userPayload = {
|
||||||
sub: user.id,
|
sub: user.id,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
phoneNumber: user.mobile,
|
phoneNumber: user.mobile,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
|
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||||
};
|
};
|
||||||
const { password: _p, ...restUser } = user;
|
const { password: _p, ...restUser } = user;
|
||||||
safeUser = restUser;
|
safeUser = restUser;
|
||||||
@@ -493,12 +496,15 @@ export class AuthService {
|
|||||||
email?: string;
|
email?: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
mobile?: string;
|
mobile?: string;
|
||||||
|
stageTestSession?: string | null;
|
||||||
|
stageTestGeneration?: string | null;
|
||||||
}) {
|
}) {
|
||||||
const payload = {
|
const payload = {
|
||||||
sub: user.id,
|
sub: user.id,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
phoneNumber: user.mobile,
|
phoneNumber: user.mobile,
|
||||||
|
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||||
};
|
};
|
||||||
const tokens = await this.generateTokens(payload);
|
const tokens = await this.generateTokens(payload);
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export interface JwtPayload {
|
|||||||
email?: string;
|
email?: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
phoneNumber?: string;
|
phoneNumber?: string;
|
||||||
|
stageTestSession?: string;
|
||||||
|
stageTestGeneration?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -62,6 +64,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
|||||||
}
|
}
|
||||||
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
|
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
|
||||||
if (user.stageTestSession) {
|
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 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));
|
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');
|
if (!allowed) throw new UnauthorizedException('Stage test scope denied');
|
||||||
|
|||||||
@@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user