Add scouthub-home-be
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
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 createOrganization = jest.fn();
|
||||
const createOrganizationGroup = jest.fn();
|
||||
const addMemberToOrganization = jest.fn();
|
||||
const gruppoScoutCreate = jest.fn();
|
||||
|
||||
jest.mock('../../src/keycloak-admin', () => ({
|
||||
createOrganization: (...args: unknown[]) => createOrganization(...args),
|
||||
createOrganizationGroup: (...args: unknown[]) => createOrganizationGroup(...args),
|
||||
addMemberToOrganization: (...args: unknown[]) => addMemberToOrganization(...args),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/db/prisma', () => ({
|
||||
prisma: {
|
||||
gruppoScout: {
|
||||
create: (...args: unknown[]) => gruppoScoutCreate(...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<string, unknown>;
|
||||
const privateKeyPem = privateKey.export({ type: 'pkcs1', format: 'pem' }) as string;
|
||||
|
||||
function signToken(roles: string[]): string {
|
||||
return jwt.sign(
|
||||
{ sub: 'user-1', realm_access: { roles } },
|
||||
privateKeyPem,
|
||||
{ algorithm: 'RS256', keyid: KID, expiresIn: '5m' },
|
||||
);
|
||||
}
|
||||
|
||||
const adminToken = () => signToken(['admin-centrale']);
|
||||
const nonAdminToken = () => signToken(['capo-gruppo']);
|
||||
|
||||
function conflictError(): Error {
|
||||
return Object.assign(new Error('Conflict'), { isAxiosError: true, response: { status: 409 } });
|
||||
}
|
||||
|
||||
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', () => {
|
||||
test('crea organizzazione, gruppi ruolo, membership e riga locale, rispondendo 201', async () => {
|
||||
createOrganization.mockResolvedValueOnce({ orgId: 'org-1' });
|
||||
createOrganizationGroup.mockResolvedValue({ groupId: 'irrelevant' });
|
||||
addMemberToOrganization.mockResolvedValueOnce(undefined);
|
||||
gruppoScoutCreate.mockResolvedValueOnce({});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/gruppi')
|
||||
.set('Authorization', `Bearer ${adminToken()}`)
|
||||
.send({ nome: 'Gruppo Alfa', regione: 'Lombardia', ruoliDefault: ['Capi', 'Rover'] });
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body).toEqual({ orgId: 'org-1', gruppiCreati: ['Capi', 'Rover'] });
|
||||
|
||||
expect(createOrganization).toHaveBeenCalledWith('Gruppo Alfa');
|
||||
expect(createOrganizationGroup).toHaveBeenCalledTimes(2);
|
||||
expect(createOrganizationGroup).toHaveBeenNthCalledWith(1, 'org-1', 'Capi');
|
||||
expect(createOrganizationGroup).toHaveBeenNthCalledWith(2, 'org-1', 'Rover');
|
||||
expect(addMemberToOrganization).toHaveBeenCalledWith('org-1', 'user-1');
|
||||
expect(gruppoScoutCreate).toHaveBeenCalledWith({
|
||||
data: { orgId: 'org-1', nome: 'Gruppo Alfa', regione: 'Lombardia' },
|
||||
});
|
||||
});
|
||||
|
||||
test('usa i ruoli di default quando ruoliDefault non è specificato', async () => {
|
||||
createOrganization.mockResolvedValueOnce({ orgId: 'org-2' });
|
||||
createOrganizationGroup.mockResolvedValue({ groupId: 'irrelevant' });
|
||||
addMemberToOrganization.mockResolvedValueOnce(undefined);
|
||||
gruppoScoutCreate.mockResolvedValueOnce({});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/gruppi')
|
||||
.set('Authorization', `Bearer ${adminToken()}`)
|
||||
.send({ nome: 'Gruppo Beta' });
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body.gruppiCreati).toEqual(['Capi', 'Aiuto capi', 'Censiti']);
|
||||
expect(createOrganizationGroup).toHaveBeenCalledTimes(3);
|
||||
expect(addMemberToOrganization).toHaveBeenCalledWith('org-2', 'user-1');
|
||||
});
|
||||
|
||||
test('risponde 409 se Keycloak segnala un nome duplicato, senza creare la riga locale', async () => {
|
||||
createOrganization.mockRejectedValueOnce(conflictError());
|
||||
|
||||
const response = await request(app)
|
||||
.post('/gruppi')
|
||||
.set('Authorization', `Bearer ${adminToken()}`)
|
||||
.send({ nome: 'Gruppo Già Esistente' });
|
||||
|
||||
expect(response.status).toBe(409);
|
||||
expect(response.body.message).toMatch(/Gruppo Già Esistente/);
|
||||
expect(createOrganizationGroup).not.toHaveBeenCalled();
|
||||
expect(gruppoScoutCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('se la creazione di un gruppo ruolo fallisce a metà, non salva la riga locale e logga il punto di arresto', async () => {
|
||||
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
|
||||
createOrganization.mockResolvedValueOnce({ orgId: 'org-3' });
|
||||
createOrganizationGroup
|
||||
.mockResolvedValueOnce({ groupId: 'g-capi' })
|
||||
.mockRejectedValueOnce(new Error('Keycloak non raggiungibile'));
|
||||
|
||||
const response = await request(app)
|
||||
.post('/gruppi')
|
||||
.set('Authorization', `Bearer ${adminToken()}`)
|
||||
.send({ nome: 'Gruppo Gamma', ruoliDefault: ['Capi', 'Aiuto capi'] });
|
||||
|
||||
expect(response.status).toBe(502);
|
||||
expect(gruppoScoutCreate).not.toHaveBeenCalled();
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('STEP 2'), expect.anything());
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('org-3'), expect.anything());
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("se l'aggiunta del creatore all'organizzazione fallisce, non salva la riga locale e logga il punto di arresto", async () => {
|
||||
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
|
||||
createOrganization.mockResolvedValueOnce({ orgId: 'org-4' });
|
||||
createOrganizationGroup.mockResolvedValue({ groupId: 'irrelevant' });
|
||||
addMemberToOrganization.mockRejectedValueOnce(new Error('Keycloak non raggiungibile'));
|
||||
|
||||
const response = await request(app)
|
||||
.post('/gruppi')
|
||||
.set('Authorization', `Bearer ${adminToken()}`)
|
||||
.send({ nome: 'Gruppo Delta due' });
|
||||
|
||||
expect(response.status).toBe(502);
|
||||
expect(gruppoScoutCreate).not.toHaveBeenCalled();
|
||||
expect(addMemberToOrganization).toHaveBeenCalledWith('org-4', 'user-1');
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('STEP 3'), expect.anything());
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('org-4'), expect.anything());
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
test('risponde 403 se il ruolo non è admin-centrale', async () => {
|
||||
const response = await request(app)
|
||||
.post('/gruppi')
|
||||
.set('Authorization', `Bearer ${nonAdminToken()}`)
|
||||
.send({ nome: 'Gruppo Delta' });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(createOrganization).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('risponde 401 senza token', async () => {
|
||||
const response = await request(app).post('/gruppi').send({ nome: 'Gruppo Epsilon' });
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(createOrganization).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("risponde 400 se manca il campo 'nome'", async () => {
|
||||
const response = await request(app)
|
||||
.post('/gruppi')
|
||||
.set('Authorization', `Bearer ${adminToken()}`)
|
||||
.send({ regione: 'Piemonte' });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(createOrganization).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
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 invitoCreate = jest.fn();
|
||||
const invitoFindUnique = jest.fn();
|
||||
const invitoUpdate = jest.fn();
|
||||
|
||||
jest.mock('../../src/db/prisma', () => ({
|
||||
prisma: {
|
||||
invito: {
|
||||
create: (...args: unknown[]) => invitoCreate(...args),
|
||||
findUnique: (...args: unknown[]) => invitoFindUnique(...args),
|
||||
update: (...args: unknown[]) => invitoUpdate(...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<string, unknown>;
|
||||
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, email = 'capo@example.com'): string {
|
||||
return signToken({
|
||||
sub: 'user-capo',
|
||||
email,
|
||||
realm_access: { roles: ['capo-gruppo'] },
|
||||
organization: { alfa: { id: orgId, roles: [] } },
|
||||
});
|
||||
}
|
||||
|
||||
function utenteToken(email: string): string {
|
||||
return signToken({ sub: 'user-invitato', email, realm_access: { roles: [] } });
|
||||
}
|
||||
|
||||
const ORA = Date.now();
|
||||
function invitoFixture(overrides: Partial<Record<string, unknown>> = {}) {
|
||||
return {
|
||||
id: 'invito-1',
|
||||
token: 'token-abc',
|
||||
email: 'invitato@example.com',
|
||||
orgId: 'org-1',
|
||||
ruolo: 'Capi',
|
||||
scadenza: new Date(ORA + 60_000),
|
||||
stato: 'pending',
|
||||
gruppoScout: { nome: 'Gruppo Alfa' },
|
||||
...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/inviti', () => {
|
||||
test('crea un invito pending e restituisce 201', async () => {
|
||||
invitoCreate.mockResolvedValueOnce({ id: 'invito-nuovo', scadenza: new Date(ORA + 7 * 24 * 60 * 60 * 1000) });
|
||||
const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/gruppi/org-1/inviti')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-1')}`)
|
||||
.send({ email: 'nuovo@example.com', ruolo: 'Capi' });
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body.invitoId).toBe('invito-nuovo');
|
||||
expect(invitoCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ email: 'nuovo@example.com', orgId: 'org-1', ruolo: 'Capi', stato: 'pending' }),
|
||||
}),
|
||||
);
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('http://localhost:4200/inviti/'));
|
||||
|
||||
consoleLogSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("risponde 403 se il capo gruppo prova ad invitare in un'altra organization", async () => {
|
||||
const response = await request(app)
|
||||
.post('/gruppi/org-1/inviti')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-2')}`)
|
||||
.send({ email: 'nuovo@example.com', ruolo: 'Capi' });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(invitoCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('risponde 403 se manca il ruolo capo-gruppo', async () => {
|
||||
const token = signToken({ sub: 'user-x', email: 'x@example.com', realm_access: { roles: ['censito'] } });
|
||||
|
||||
const response = await request(app)
|
||||
.post('/gruppi/org-1/inviti')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ email: 'nuovo@example.com', ruolo: 'Capi' });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(invitoCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /inviti/:token', () => {
|
||||
test('è pubblico e restituisce valido=true per un invito pending non scaduto', async () => {
|
||||
invitoFindUnique.mockResolvedValueOnce(invitoFixture());
|
||||
|
||||
const response = await request(app).get('/inviti/token-abc');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
email: 'invitato@example.com',
|
||||
nomeGruppo: 'Gruppo Alfa',
|
||||
ruolo: 'Capi',
|
||||
valido: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('restituisce valido=false per un invito scaduto', async () => {
|
||||
invitoFindUnique.mockResolvedValueOnce(invitoFixture({ scadenza: new Date(ORA - 1_000) }));
|
||||
|
||||
const response = await request(app).get('/inviti/token-abc');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.valido).toBe(false);
|
||||
});
|
||||
|
||||
test('restituisce valido=false per un invito già accettato', async () => {
|
||||
invitoFindUnique.mockResolvedValueOnce(invitoFixture({ stato: 'accettato' }));
|
||||
|
||||
const response = await request(app).get('/inviti/token-abc');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.valido).toBe(false);
|
||||
});
|
||||
|
||||
test('risponde 404 se il token non esiste', async () => {
|
||||
invitoFindUnique.mockResolvedValueOnce(null);
|
||||
|
||||
const response = await request(app).get('/inviti/token-inesistente');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /inviti/:token/accetta', () => {
|
||||
test('happy path: assegna su Keycloak, marca l\'invito come accettato e risponde 200', async () => {
|
||||
invitoFindUnique.mockResolvedValueOnce(invitoFixture());
|
||||
addMemberToOrganization.mockResolvedValueOnce(undefined);
|
||||
assignUserToGroup.mockResolvedValueOnce(undefined);
|
||||
assignRealmRoleToUser.mockResolvedValueOnce(undefined);
|
||||
invitoUpdate.mockResolvedValueOnce({});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/inviti/token-abc/accetta')
|
||||
.set('Authorization', `Bearer ${utenteToken('invitato@example.com')}`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ organizationId: 'org-1', ruolo: 'Capi' });
|
||||
|
||||
expect(addMemberToOrganization).toHaveBeenCalledWith('org-1', 'user-invitato');
|
||||
expect(assignUserToGroup).toHaveBeenCalledWith('user-invitato', 'Capi');
|
||||
expect(assignRealmRoleToUser).toHaveBeenCalledWith('user-invitato', 'Capi');
|
||||
expect(invitoUpdate).toHaveBeenCalledWith({ where: { token: 'token-abc' }, data: { stato: 'accettato' } });
|
||||
});
|
||||
|
||||
test('risponde 410 se l\'invito è scaduto', async () => {
|
||||
invitoFindUnique.mockResolvedValueOnce(invitoFixture({ scadenza: new Date(ORA - 1_000) }));
|
||||
|
||||
const response = await request(app)
|
||||
.post('/inviti/token-abc/accetta')
|
||||
.set('Authorization', `Bearer ${utenteToken('invitato@example.com')}`);
|
||||
|
||||
expect(response.status).toBe(410);
|
||||
expect(addMemberToOrganization).not.toHaveBeenCalled();
|
||||
expect(invitoUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('risponde 409 se l\'invito è già stato accettato', async () => {
|
||||
invitoFindUnique.mockResolvedValueOnce(invitoFixture({ stato: 'accettato' }));
|
||||
|
||||
const response = await request(app)
|
||||
.post('/inviti/token-abc/accetta')
|
||||
.set('Authorization', `Bearer ${utenteToken('invitato@example.com')}`);
|
||||
|
||||
expect(response.status).toBe(409);
|
||||
expect(addMemberToOrganization).not.toHaveBeenCalled();
|
||||
expect(invitoUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("risponde 403 se l'email dell'utente autenticato non corrisponde a quella dell'invito", async () => {
|
||||
invitoFindUnique.mockResolvedValueOnce(invitoFixture());
|
||||
|
||||
const response = await request(app)
|
||||
.post('/inviti/token-abc/accetta')
|
||||
.set('Authorization', `Bearer ${utenteToken('qualcun-altro@example.com')}`);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(addMemberToOrganization).not.toHaveBeenCalled();
|
||||
expect(invitoUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('risponde 401 senza autenticazione', async () => {
|
||||
const response = await request(app).post('/inviti/token-abc/accetta');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(addMemberToOrganization).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
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 listOrganizationMembers = jest.fn();
|
||||
const removeMemberFromOrganization = jest.fn();
|
||||
const assignUserToGroup = jest.fn();
|
||||
const removeUserFromGroup = jest.fn();
|
||||
const getUserGroupsInOrganization = jest.fn();
|
||||
const assignRealmRoleToUser = jest.fn();
|
||||
const removeRealmRoleFromUser = jest.fn();
|
||||
const getUserRealmRoles = jest.fn();
|
||||
|
||||
jest.mock('../../src/keycloak-admin', () => ({
|
||||
listOrganizationMembers: (...args: unknown[]) => listOrganizationMembers(...args),
|
||||
removeMemberFromOrganization: (...args: unknown[]) => removeMemberFromOrganization(...args),
|
||||
assignUserToGroup: (...args: unknown[]) => assignUserToGroup(...args),
|
||||
removeUserFromGroup: (...args: unknown[]) => removeUserFromGroup(...args),
|
||||
getUserGroupsInOrganization: (...args: unknown[]) => getUserGroupsInOrganization(...args),
|
||||
assignRealmRoleToUser: (...args: unknown[]) => assignRealmRoleToUser(...args),
|
||||
removeRealmRoleFromUser: (...args: unknown[]) => removeRealmRoleFromUser(...args),
|
||||
getUserRealmRoles: (...args: unknown[]) => getUserRealmRoles(...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<string, unknown>;
|
||||
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 nonCapoToken(orgId: string): string {
|
||||
return signToken({
|
||||
sub: 'user-censito',
|
||||
email: 'censito@example.com',
|
||||
realm_access: { roles: ['censito'] },
|
||||
organization: { alfa: { id: orgId, roles: [] } },
|
||||
});
|
||||
}
|
||||
|
||||
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('GET /gruppi/:orgId/membri', () => {
|
||||
test('restituisce la lista membri con ruolo e gruppo interno', async () => {
|
||||
listOrganizationMembers.mockResolvedValueOnce([
|
||||
{ userId: 'user-1', email: 'uno@example.com' },
|
||||
{ userId: 'user-2', email: 'due@example.com' },
|
||||
]);
|
||||
getUserGroupsInOrganization.mockImplementation(async (_orgId: string, userId: string) =>
|
||||
userId === 'user-1' ? [{ groupId: 'g-capi', nome: 'Capi' }] : [],
|
||||
);
|
||||
getUserRealmRoles.mockImplementation(async (userId: string) => (userId === 'user-1' ? ['Capi'] : []));
|
||||
|
||||
const response = await request(app)
|
||||
.get('/gruppi/org-1/membri')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-1')}`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual([
|
||||
{ userId: 'user-1', email: 'uno@example.com', ruolo: 'Capi', gruppoInterno: 'Capi' },
|
||||
{ userId: 'user-2', email: 'due@example.com', ruolo: null, gruppoInterno: null },
|
||||
]);
|
||||
expect(listOrganizationMembers).toHaveBeenCalledWith('org-1');
|
||||
});
|
||||
|
||||
test("risponde 403 se l'organization non è la propria", async () => {
|
||||
const response = await request(app)
|
||||
.get('/gruppi/org-1/membri')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-2')}`);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(listOrganizationMembers).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('risponde 403 se manca il ruolo capo-gruppo', async () => {
|
||||
const response = await request(app)
|
||||
.get('/gruppi/org-1/membri')
|
||||
.set('Authorization', `Bearer ${nonCapoToken('org-1')}`);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(listOrganizationMembers).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /gruppi/:orgId/membri/:userId/ruolo', () => {
|
||||
test('rimuove gruppo e ruolo correnti e assegna quelli nuovi', async () => {
|
||||
getUserGroupsInOrganization.mockResolvedValueOnce([{ groupId: 'g-capi', nome: 'Capi' }]);
|
||||
getUserRealmRoles.mockResolvedValueOnce(['Capi']);
|
||||
|
||||
const response = await request(app)
|
||||
.put('/gruppi/org-1/membri/user-1/ruolo')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-1')}`)
|
||||
.send({ ruolo: 'Aiuto capi' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ userId: 'user-1', ruolo: 'Aiuto capi' });
|
||||
|
||||
expect(removeUserFromGroup).toHaveBeenCalledWith('user-1', 'g-capi');
|
||||
expect(assignUserToGroup).toHaveBeenCalledWith('user-1', 'Aiuto capi');
|
||||
expect(removeRealmRoleFromUser).toHaveBeenCalledWith('user-1', 'Capi');
|
||||
expect(assignRealmRoleToUser).toHaveBeenCalledWith('user-1', 'Aiuto capi');
|
||||
});
|
||||
|
||||
test("risponde 403 se l'organization non è la propria", async () => {
|
||||
const response = await request(app)
|
||||
.put('/gruppi/org-1/membri/user-1/ruolo')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-2')}`)
|
||||
.send({ ruolo: 'Aiuto capi' });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(assignUserToGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("risponde 400 se manca il campo 'ruolo'", async () => {
|
||||
const response = await request(app)
|
||||
.put('/gruppi/org-1/membri/user-1/ruolo')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-1')}`)
|
||||
.send({});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(assignUserToGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('risponde 502 se una chiamata Keycloak fallisce', async () => {
|
||||
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
getUserGroupsInOrganization.mockResolvedValueOnce([]);
|
||||
getUserRealmRoles.mockResolvedValueOnce([]);
|
||||
assignUserToGroup.mockRejectedValueOnce(new Error('Keycloak non raggiungibile'));
|
||||
|
||||
const response = await request(app)
|
||||
.put('/gruppi/org-1/membri/user-1/ruolo')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-1')}`)
|
||||
.send({ ruolo: 'Aiuto capi' });
|
||||
|
||||
expect(response.status).toBe(502);
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /gruppi/:orgId/membri/:userId', () => {
|
||||
test("rimuove il membro dall'organization e risponde 204", async () => {
|
||||
removeMemberFromOrganization.mockResolvedValueOnce(undefined);
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/gruppi/org-1/membri/user-1')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-1')}`);
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
expect(removeMemberFromOrganization).toHaveBeenCalledWith('org-1', 'user-1');
|
||||
});
|
||||
|
||||
test("risponde 403 se l'organization non è la propria", async () => {
|
||||
const response = await request(app)
|
||||
.delete('/gruppi/org-1/membri/user-1')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-2')}`);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(removeMemberFromOrganization).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('risponde 502 se Keycloak fallisce nel rimuovere il membro', async () => {
|
||||
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
removeMemberFromOrganization.mockRejectedValueOnce(new Error('Keycloak non raggiungibile'));
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/gruppi/org-1/membri/user-1')
|
||||
.set('Authorization', `Bearer ${capoGruppoToken('org-1')}`);
|
||||
|
||||
expect(response.status).toBe(502);
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import nock from 'nock';
|
||||
|
||||
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';
|
||||
|
||||
import { getAccessToken, resetTokenCache } from '../../../src/keycloak-admin/tokenManager';
|
||||
|
||||
const KEYCLOAK_HOST = 'http://keycloak.test';
|
||||
const TOKEN_PATH = '/realms/scouthub/protocol/openid-connect/token';
|
||||
|
||||
function mockTokenEndpoint(accessToken: string, expiresInSeconds: number) {
|
||||
return nock(KEYCLOAK_HOST)
|
||||
.post(TOKEN_PATH)
|
||||
.reply(200, { access_token: accessToken, expires_in: expiresInSeconds, token_type: 'Bearer' });
|
||||
}
|
||||
|
||||
// Il modulo calcola la scadenza con Date.now(): per simulare il passare del
|
||||
// tempo mockiamo solo Date.now (non i timer), così le richieste HTTP mockate
|
||||
// da nock continuano a risolversi normalmente sull'event loop reale.
|
||||
let nowSpy: jest.SpyInstance<number, []> | undefined;
|
||||
|
||||
function advanceTimeBy(ms: number): void {
|
||||
const current = nowSpy ? (nowSpy.getMockImplementation()?.() ?? Date.now()) : Date.now();
|
||||
nowSpy = jest.spyOn(Date, 'now').mockReturnValue(current + ms);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetTokenCache();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
nowSpy?.mockRestore();
|
||||
nowSpy = undefined;
|
||||
nock.cleanAll();
|
||||
});
|
||||
|
||||
describe('keycloak-admin tokenManager', () => {
|
||||
test("ottiene un access token dall'endpoint client_credentials", async () => {
|
||||
const scope = mockTokenEndpoint('token-1', 300);
|
||||
|
||||
const token = await getAccessToken();
|
||||
|
||||
expect(token).toBe('token-1');
|
||||
expect(scope.isDone()).toBe(true);
|
||||
});
|
||||
|
||||
test('riutilizza il token in cache invece di richiederne uno nuovo ad ogni chiamata', async () => {
|
||||
const scope = mockTokenEndpoint('token-1', 300);
|
||||
|
||||
const first = await getAccessToken();
|
||||
const second = await getAccessToken();
|
||||
const third = await getAccessToken();
|
||||
|
||||
expect(first).toBe('token-1');
|
||||
expect(second).toBe('token-1');
|
||||
expect(third).toBe('token-1');
|
||||
// Un solo interceptor registrato (consumato una volta sola): se il codice
|
||||
// avesse richiesto un nuovo token per ogni chiamata, la seconda/terza
|
||||
// sarebbero fallite per mancanza di un match su nock.
|
||||
expect(scope.isDone()).toBe(true);
|
||||
});
|
||||
|
||||
test('rinnova il token quando è vicino alla scadenza (entro il margine di sicurezza)', async () => {
|
||||
mockTokenEndpoint('token-1', 300);
|
||||
await getAccessToken();
|
||||
|
||||
// 295s dopo: mancano 5s alla scadenza reale, sotto al margine di sicurezza di 10s.
|
||||
advanceTimeBy(295_000);
|
||||
|
||||
const renewalScope = mockTokenEndpoint('token-2', 300);
|
||||
const renewed = await getAccessToken();
|
||||
|
||||
expect(renewed).toBe('token-2');
|
||||
expect(renewalScope.isDone()).toBe(true);
|
||||
});
|
||||
|
||||
test('non rinnova il token se la scadenza è ancora lontana', async () => {
|
||||
mockTokenEndpoint('token-1', 300);
|
||||
await getAccessToken();
|
||||
|
||||
advanceTimeBy(60_000); // ben dentro la validità dei 300s
|
||||
|
||||
const token = await getAccessToken();
|
||||
|
||||
expect(token).toBe('token-1');
|
||||
});
|
||||
|
||||
test('richieste concorrenti senza token in cache generano una sola chiamata HTTP', async () => {
|
||||
const scope = mockTokenEndpoint('token-1', 300);
|
||||
|
||||
const [a, b, c] = await Promise.all([getAccessToken(), getAccessToken(), getAccessToken()]);
|
||||
|
||||
expect(a).toBe('token-1');
|
||||
expect(b).toBe('token-1');
|
||||
expect(c).toBe('token-1');
|
||||
expect(scope.isDone()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { generateKeyPairSync } from 'crypto';
|
||||
import express from 'express';
|
||||
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';
|
||||
|
||||
import { authenticate } from '../../../src/middleware/authenticate';
|
||||
import { requireRole } from '../../../src/middleware/requireRole';
|
||||
|
||||
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<string, unknown>;
|
||||
const privateKeyPem = privateKey.export({ type: 'pkcs1', format: 'pem' }) as string;
|
||||
|
||||
// Keypair "estranea": usata per firmare token che non devono validare contro
|
||||
// le chiavi pubblicate nel JWKS mockato (firma non corrispondente).
|
||||
const { privateKey: rogueKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
const rogueKeyPem = rogueKey.export({ type: 'pkcs1', format: 'pem' }) as string;
|
||||
|
||||
function mockJwks(): void {
|
||||
nock(KEYCLOAK_HOST)
|
||||
.persist()
|
||||
.get(CERTS_PATH)
|
||||
.reply(200, { keys: [{ ...jwk, kid: KID, alg: 'RS256', use: 'sig' }] });
|
||||
}
|
||||
|
||||
function signValidToken(payload: object, signOptions: jwt.SignOptions = {}): string {
|
||||
return jwt.sign(payload, privateKeyPem, {
|
||||
algorithm: 'RS256',
|
||||
keyid: KID,
|
||||
expiresIn: '5m',
|
||||
...signOptions,
|
||||
});
|
||||
}
|
||||
|
||||
const CAPO_GRUPPO_PAYLOAD = {
|
||||
sub: 'user-123',
|
||||
email: 'capo@example.com',
|
||||
realm_access: { roles: ['capo-gruppo', 'utente'] },
|
||||
organization: {
|
||||
'gruppo-alfa': { id: 'org-1', roles: ['owner'] },
|
||||
},
|
||||
};
|
||||
|
||||
function buildApp() {
|
||||
const app = express();
|
||||
app.get('/capo', authenticate, requireRole('capo-gruppo'), (req, res) => {
|
||||
res.json({ auth: req.auth });
|
||||
});
|
||||
app.get('/solo-admin', authenticate, requireRole('super-admin'), (req, res) => {
|
||||
res.json({ auth: req.auth });
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
mockJwks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
nock.cleanAll();
|
||||
});
|
||||
|
||||
describe('authenticate + requireRole', () => {
|
||||
test('restituisce 401 se manca il token', async () => {
|
||||
const app = buildApp();
|
||||
|
||||
const response = await request(app).get('/capo');
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
test('restituisce 401 se il token è scaduto', async () => {
|
||||
const app = buildApp();
|
||||
const token = signValidToken(CAPO_GRUPPO_PAYLOAD, { expiresIn: '-10s' });
|
||||
|
||||
const response = await request(app).get('/capo').set('Authorization', `Bearer ${token}`);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
test('restituisce 401 se il token ha una firma non valida', async () => {
|
||||
const app = buildApp();
|
||||
const token = jwt.sign(CAPO_GRUPPO_PAYLOAD, rogueKeyPem, {
|
||||
algorithm: 'RS256',
|
||||
keyid: KID,
|
||||
expiresIn: '5m',
|
||||
});
|
||||
|
||||
const response = await request(app).get('/capo').set('Authorization', `Bearer ${token}`);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
test('restituisce 403 se il token è valido ma manca il ruolo richiesto', async () => {
|
||||
const app = buildApp();
|
||||
const token = signValidToken(CAPO_GRUPPO_PAYLOAD);
|
||||
|
||||
const response = await request(app).get('/solo-admin').set('Authorization', `Bearer ${token}`);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
});
|
||||
|
||||
test('restituisce 200 e popola req.auth se il token è valido con il ruolo corretto', async () => {
|
||||
const app = buildApp();
|
||||
const token = signValidToken(CAPO_GRUPPO_PAYLOAD);
|
||||
|
||||
const response = await request(app).get('/capo').set('Authorization', `Bearer ${token}`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.auth).toEqual({
|
||||
userId: 'user-123',
|
||||
email: 'capo@example.com',
|
||||
organizationId: 'org-1',
|
||||
roles: ['capo-gruppo', 'utente', 'owner'],
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user