76 lines
2.0 KiB
TypeScript
76 lines
2.0 KiB
TypeScript
import express from 'express';
|
|
import request from 'supertest';
|
|
import jwt from 'jsonwebtoken';
|
|
import nock from 'nock';
|
|
import { authenticate } from '../../../src/middlewares/authenticate';
|
|
import { bearer, mockKeycloakJwks, rogueKeyPem, signValidToken } from '../../setup/authTestHelper';
|
|
|
|
const CAPO_PAYLOAD = {
|
|
sub: 'user-123',
|
|
email: 'capo@example.com',
|
|
name: 'Capo Unità',
|
|
realm_access: { roles: ['capo-unita'] },
|
|
};
|
|
|
|
function buildApp() {
|
|
const app = express();
|
|
app.get('/protetta', authenticate, (req, res) => {
|
|
res.json({ auth: req.auth });
|
|
});
|
|
return app;
|
|
}
|
|
|
|
beforeAll(() => {
|
|
mockKeycloakJwks();
|
|
});
|
|
|
|
afterAll(() => {
|
|
nock.cleanAll();
|
|
});
|
|
|
|
describe('authenticate', () => {
|
|
test('restituisce 401 se manca il token', async () => {
|
|
const app = buildApp();
|
|
|
|
const response = await request(app).get('/protetta');
|
|
|
|
expect(response.status).toBe(401);
|
|
});
|
|
|
|
test('restituisce 401 se il token è scaduto', async () => {
|
|
const app = buildApp();
|
|
const token = signValidToken(CAPO_PAYLOAD, { expiresIn: '-10s' });
|
|
|
|
const response = await request(app).get('/protetta').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_PAYLOAD, rogueKeyPem, {
|
|
algorithm: 'RS256',
|
|
keyid: 'test-kid',
|
|
expiresIn: '5m',
|
|
});
|
|
|
|
const response = await request(app).get('/protetta').set('Authorization', `Bearer ${token}`);
|
|
|
|
expect(response.status).toBe(401);
|
|
});
|
|
|
|
test('restituisce 200 e popola req.auth se il token è valido', async () => {
|
|
const app = buildApp();
|
|
|
|
const response = await request(app).get('/protetta').set('Authorization', bearer(CAPO_PAYLOAD));
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(response.body.auth).toEqual({
|
|
userId: 'user-123',
|
|
email: 'capo@example.com',
|
|
name: 'Capo Unità',
|
|
roles: ['capo-unita'],
|
|
});
|
|
});
|
|
});
|