import { generateKeyPairSync } from 'crypto'; import request from 'supertest'; import nock from 'nock'; import jwt from 'jsonwebtoken'; process.env.KEYCLOAK_BASE_URL = 'http://keycloak.test'; process.env.KEYCLOAK_REALM = 'scouthub'; process.env.KEYCLOAK_ORG_SERVICE_CLIENT_ID = 'test-client'; process.env.KEYCLOAK_ORG_SERVICE_CLIENT_SECRET = 'test-secret'; process.env.DATABASE_URL = 'postgresql://user:pass@localhost:5432/scouthub_home_test'; process.env.FRONTEND_BASE_URL = 'http://localhost:4200'; const addMemberToOrganization = jest.fn(); const assignUserToGroup = jest.fn(); const assignRealmRoleToUser = jest.fn(); jest.mock('../../src/keycloak-admin', () => ({ addMemberToOrganization: (...args: unknown[]) => addMemberToOrganization(...args), assignUserToGroup: (...args: unknown[]) => assignUserToGroup(...args), assignRealmRoleToUser: (...args: unknown[]) => assignRealmRoleToUser(...args), })); const richiestaIngressoFindFirst = jest.fn(); const richiestaIngressoCreate = jest.fn(); const richiestaIngressoFindMany = jest.fn(); const richiestaIngressoFindUnique = jest.fn(); const richiestaIngressoUpdate = jest.fn(); jest.mock('../../src/db/prisma', () => ({ prisma: { richiestaIngresso: { findFirst: (...args: unknown[]) => richiestaIngressoFindFirst(...args), create: (...args: unknown[]) => richiestaIngressoCreate(...args), findMany: (...args: unknown[]) => richiestaIngressoFindMany(...args), findUnique: (...args: unknown[]) => richiestaIngressoFindUnique(...args), update: (...args: unknown[]) => richiestaIngressoUpdate(...args), }, }, })); import { app } from '../../src/app'; const KEYCLOAK_HOST = 'http://keycloak.test'; const CERTS_PATH = '/realms/scouthub/protocol/openid-connect/certs'; const KID = 'test-kid'; const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); const jwk = publicKey.export({ format: 'jwk' }) as Record; const privateKeyPem = privateKey.export({ type: 'pkcs1', format: 'pem' }) as string; function signToken(payload: object): string { return jwt.sign(payload, privateKeyPem, { algorithm: 'RS256', keyid: KID, expiresIn: '5m' }); } function capoGruppoToken(orgId: string): string { return signToken({ sub: 'user-capo', email: 'capo@example.com', realm_access: { roles: ['capo-gruppo'] }, organization: { alfa: { id: orgId, roles: [] } }, }); } function adminCentraleToken(): string { return signToken({ sub: 'user-admin', email: 'admin@example.com', realm_access: { roles: ['admin'] }, }); } function utenteToken(userId: string, email: string): string { return signToken({ sub: userId, email, realm_access: { roles: [] } }); } const ORA = new Date(); function richiestaFixture(overrides: Partial> = {}) { return { id: 'richiesta-1', userId: 'user-nuovo', email: 'nuovo@example.com', orgId: 'org-1', stato: 'PENDING', origine: 'PROFILO', createdAt: ORA, updatedAt: ORA, ...overrides, }; } beforeAll(() => { nock(KEYCLOAK_HOST).persist().get(CERTS_PATH).reply(200, { keys: [{ ...jwk, kid: KID, alg: 'RS256', use: 'sig' }], }); }); afterAll(() => { nock.cleanAll(); }); beforeEach(() => { jest.clearAllMocks(); }); describe('POST /gruppi/:orgId/richieste-ingresso', () => { test('crea una richiesta PENDING con origine=PROFILO e risponde 201', async () => { richiestaIngressoFindFirst.mockResolvedValueOnce(null); richiestaIngressoCreate.mockResolvedValueOnce({ id: 'richiesta-1' }); const response = await request(app) .post('/gruppi/org-1/richieste-ingresso') .set('Authorization', `Bearer ${utenteToken('user-nuovo', 'nuovo@example.com')}`) .send({}); expect(response.status).toBe(201); expect(response.body).toEqual({ richiestaId: 'richiesta-1' }); expect(richiestaIngressoCreate).toHaveBeenCalledWith({ data: { userId: 'user-nuovo', email: 'nuovo@example.com', orgId: 'org-1', origine: 'PROFILO', stato: 'PENDING', }, }); }); test("risponde 409 se l'utente ha già una richiesta PENDING per lo stesso gruppo", async () => { richiestaIngressoFindFirst.mockResolvedValueOnce(richiestaFixture()); const response = await request(app) .post('/gruppi/org-1/richieste-ingresso') .set('Authorization', `Bearer ${utenteToken('user-nuovo', 'nuovo@example.com')}`) .send({}); expect(response.status).toBe(409); expect(richiestaIngressoCreate).not.toHaveBeenCalled(); }); test('risponde 401 senza token', async () => { const response = await request(app).post('/gruppi/org-1/richieste-ingresso').send({}); expect(response.status).toBe(401); expect(richiestaIngressoCreate).not.toHaveBeenCalled(); }); }); describe('GET /gruppi/:orgId/richieste-ingresso', () => { test('restituisce le richieste PENDING del gruppo per capo-gruppo della propria org', async () => { richiestaIngressoFindMany.mockResolvedValueOnce([ richiestaFixture({ id: 'richiesta-1' }), richiestaFixture({ id: 'richiesta-2', userId: 'user-due', email: 'due@example.com', origine: 'LINK' }), ]); const response = await request(app) .get('/gruppi/org-1/richieste-ingresso') .set('Authorization', `Bearer ${capoGruppoToken('org-1')}`); expect(response.status).toBe(200); expect(response.body).toEqual([ { id: 'richiesta-1', userId: 'user-nuovo', email: 'nuovo@example.com', origine: 'PROFILO', createdAt: ORA.toISOString() }, { id: 'richiesta-2', userId: 'user-due', email: 'due@example.com', origine: 'LINK', createdAt: ORA.toISOString() }, ]); expect(richiestaIngressoFindMany).toHaveBeenCalledWith({ where: { orgId: 'org-1', stato: 'PENDING' }, orderBy: { createdAt: 'asc' }, }); }); test('admin può leggere le richieste anche di un altro gruppo', async () => { richiestaIngressoFindMany.mockResolvedValueOnce([]); const response = await request(app) .get('/gruppi/org-altrui/richieste-ingresso') .set('Authorization', `Bearer ${adminCentraleToken()}`); expect(response.status).toBe(200); expect(richiestaIngressoFindMany).toHaveBeenCalledWith({ where: { orgId: 'org-altrui', stato: 'PENDING' }, orderBy: { createdAt: 'asc' }, }); }); test("risponde 403 se il capo gruppo prova a leggere le richieste di un'altra organizzazione", async () => { const response = await request(app) .get('/gruppi/org-1/richieste-ingresso') .set('Authorization', `Bearer ${capoGruppoToken('org-2')}`); expect(response.status).toBe(403); expect(richiestaIngressoFindMany).not.toHaveBeenCalled(); }); }); describe('PUT /gruppi/:orgId/richieste-ingresso/:id', () => { test('approva la richiesta: assegna gruppo/ruolo su Keycloak e aggiorna stato=APPROVATA', async () => { richiestaIngressoFindUnique.mockResolvedValueOnce(richiestaFixture()); addMemberToOrganization.mockResolvedValueOnce(undefined); assignUserToGroup.mockResolvedValueOnce(undefined); assignRealmRoleToUser.mockResolvedValueOnce(undefined); richiestaIngressoUpdate.mockResolvedValueOnce(richiestaFixture({ stato: 'APPROVATA' })); const response = await request(app) .put('/gruppi/org-1/richieste-ingresso/richiesta-1') .set('Authorization', `Bearer ${capoGruppoToken('org-1')}`) .send({ esito: 'approvata', ruolo: 'Capi' }); expect(response.status).toBe(200); expect(response.body).toEqual({ id: 'richiesta-1', stato: 'APPROVATA' }); expect(addMemberToOrganization).toHaveBeenCalledWith('org-1', 'user-nuovo'); expect(assignUserToGroup).toHaveBeenCalledWith('user-nuovo', 'Capi'); expect(assignRealmRoleToUser).toHaveBeenCalledWith('user-nuovo', 'Capi'); expect(richiestaIngressoUpdate).toHaveBeenCalledWith({ where: { id: 'richiesta-1' }, data: { stato: 'APPROVATA' }, }); }); test('risponde 502 e NON marca la richiesta come approvata se Keycloak fallisce', async () => { const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined); richiestaIngressoFindUnique.mockResolvedValueOnce(richiestaFixture()); addMemberToOrganization.mockResolvedValueOnce(undefined); assignUserToGroup.mockRejectedValueOnce(new Error('Keycloak non raggiungibile')); const response = await request(app) .put('/gruppi/org-1/richieste-ingresso/richiesta-1') .set('Authorization', `Bearer ${capoGruppoToken('org-1')}`) .send({ esito: 'approvata', ruolo: 'Capi' }); expect(response.status).toBe(502); expect(richiestaIngressoUpdate).not.toHaveBeenCalled(); expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('richiesta-1'), expect.anything()); expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining("PENDING"), expect.anything()); consoleErrorSpy.mockRestore(); }); test('rifiuta la richiesta senza toccare Keycloak e aggiorna stato=RIFIUTATA', async () => { richiestaIngressoFindUnique.mockResolvedValueOnce(richiestaFixture()); richiestaIngressoUpdate.mockResolvedValueOnce(richiestaFixture({ stato: 'RIFIUTATA' })); const response = await request(app) .put('/gruppi/org-1/richieste-ingresso/richiesta-1') .set('Authorization', `Bearer ${capoGruppoToken('org-1')}`) .send({ esito: 'rifiutata' }); expect(response.status).toBe(200); expect(response.body).toEqual({ id: 'richiesta-1', stato: 'RIFIUTATA' }); expect(addMemberToOrganization).not.toHaveBeenCalled(); expect(assignUserToGroup).not.toHaveBeenCalled(); expect(richiestaIngressoUpdate).toHaveBeenCalledWith({ where: { id: 'richiesta-1' }, data: { stato: 'RIFIUTATA' }, }); }); test("risponde 400 se esito='approvata' senza il campo ruolo", async () => { const response = await request(app) .put('/gruppi/org-1/richieste-ingresso/richiesta-1') .set('Authorization', `Bearer ${capoGruppoToken('org-1')}`) .send({ esito: 'approvata' }); expect(response.status).toBe(400); expect(richiestaIngressoFindUnique).not.toHaveBeenCalled(); }); test('risponde 409 se la richiesta non è più PENDING', async () => { richiestaIngressoFindUnique.mockResolvedValueOnce(richiestaFixture({ stato: 'APPROVATA' })); const response = await request(app) .put('/gruppi/org-1/richieste-ingresso/richiesta-1') .set('Authorization', `Bearer ${capoGruppoToken('org-1')}`) .send({ esito: 'rifiutata' }); expect(response.status).toBe(409); expect(richiestaIngressoUpdate).not.toHaveBeenCalled(); }); test('risponde 404 se la richiesta non esiste', async () => { richiestaIngressoFindUnique.mockResolvedValueOnce(null); const response = await request(app) .put('/gruppi/org-1/richieste-ingresso/richiesta-inesistente') .set('Authorization', `Bearer ${capoGruppoToken('org-1')}`) .send({ esito: 'rifiutata' }); expect(response.status).toBe(404); }); test("risponde 403 se il capo gruppo prova ad approvare una richiesta di un'altra organizzazione", async () => { const response = await request(app) .put('/gruppi/org-2/richieste-ingresso/richiesta-1') .set('Authorization', `Bearer ${capoGruppoToken('org-1')}`) .send({ esito: 'rifiutata' }); expect(response.status).toBe(403); expect(richiestaIngressoFindUnique).not.toHaveBeenCalled(); }); });