import { SupportChatSettingsService } from './support-chat-settings.service'; import { Test } from '@nestjs/testing'; import { INestApplication, ValidationPipe } from '@nestjs/common'; import { PassportModule, PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; import { JwtService } from '@nestjs/jwt'; import request from 'supertest'; import { SupportChatController } from './support-chat.controller'; import { SupportChatService, UNAVAILABLE } from './support-chat.service'; import { OptionalCustomerJwtGuard } from './support-chat.guard'; import { PrismaService } from '../prisma/prisma.service'; class TestJwt extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'test-secret', algorithms: ['HS256'] }); } validate(payload: any) { return { id: payload.sub }; } } describe('support HTTP boundary', () => { let app: INestApplication; const prisma: any = { supportConversation: { create: jest.fn().mockResolvedValue({ id: '11111111-1111-4111-8111-111111111111', userId: null, messages: [] }), findUnique: jest.fn().mockResolvedValue(null), update: jest.fn().mockResolvedValue({}) }, supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) }, product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockImplementation(({where}) => [{ id: where.userId + '-order', status: 'processing', totalAmount: '19' }]) }, user: { findUnique: jest.fn().mockImplementation(({where}) => ({ walletBalance: where.id === 'alice' ? '11' : '22', mobile: where.id+'-mobile', email: where.id+'@example.test', firstName: 'Test', lastName: 'User' })) } }; const jwt = new JwtService({ secret: 'test-secret' }); beforeAll(async () => { process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters'; const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [{ provide: SupportChatSettingsService, useValue: { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } }, SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile(); app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init(); }); afterAll(() => app.close()); beforeEach(() => { jest.restoreAllMocks(); jest.clearAllMocks(); process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test'; jest.spyOn(global,'fetch').mockImplementation(async (url, opts) => { const message=JSON.parse(opts!.body as string).message; const intent=message==='کیف پول'?'wallet':message==='سفارش من'||message==='سفارش'?'orders':message.includes('شماره تماس')?'profile':'public'; return {ok:true,status:200,json:async()=>String(url).endsWith('/classify')?{intent}:{answer:'راهنمای محصولات کنینا'}} as any; }); }); it.each(['scope','userId','history','context','sessionId','conversationId'])('rejects untrusted %s', async field => { await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سلام', [field]:'alice'}).expect(400); }); it.each(['Bearer broken','Basic abc','', 'Bearer '])('rejects supplied invalid auth %j', async auth => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization',auth).send({message:'سلام'}).expect(401); }); it('fails closed when configured JWT secret is missing', async () => { const saved=process.env.JWT_ACCESS_SECRET; delete process.env.JWT_ACCESS_SECRET; await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'کیف پول'}).expect(401); process.env.JWT_ACCESS_SECRET=saved; }); it('rejects expired JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'}, {expiresIn:-1})).send({message:'سلام'}).expect(401); }); it('rejects cookie JWT rather than downgrading to guest', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Cookie','accessToken=broken').send({message:'سلام'}).expect(401); }); it('guest orders do not touch any private rows', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سفارش من'}).expect(201); expect(r.body.answer).toContain('وارد'); expect(prisma.order.findMany).not.toHaveBeenCalled(); }); it('returns only the authenticated user profile contact data', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'شماره تماس و ایمیل ثبت‌شده من چیست؟'}).expect(201); expect(r.body.answer).toContain('alice-mobile'); expect(r.body.answer).toContain('alice@example.test'); expect(prisma.user.findUnique).toHaveBeenCalledWith(expect.objectContaining({where:{id:'alice'}})); }); it('scopes wallet to validated identity across concurrent callers', async () => { const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول'}).expect(201))); expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled(); }); it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); }); it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); }); it('does not query private data in public scope even with valid JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'سلام'}); expect(prisma.user.findUnique).not.toHaveBeenCalled(); expect(prisma.order.findMany).not.toHaveBeenCalled(); }); it.each([{error:'upstream-secret'}, {answer:'Provider authentication failed Hermes'}, {answer:''}])('filters malformed and default upstream failures', async body => { process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test'; const f=jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); expect(JSON.stringify(r.body)).not.toContain('upstream-secret'); f.mockRestore(); }); it('returns safe unavailable on network errors', async () => { const f=jest.spyOn(global,'fetch').mockRejectedValue(new Error('private-secret')); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); f.mockRestore(); }); });