feat: Phase 1 MVP — complete AgentIdP implementation
Implements all P0 features per OpenSpec change phase-1-mvp-implementation: - Agent Registry Service (CRUD) — full lifecycle management - OAuth 2.0 Token Service (Client Credentials flow) - Credential Management (generate, rotate, revoke) - Immutable Audit Log Service Tech: Node.js 18+, TypeScript 5.3+ strict, Express 4.18+, PostgreSQL 14+, Redis 7+ Standards: OpenAPI 3.0 specs, DRY/SOLID, zero `any` types Quality: 18 unit test suites, 244 tests passing, 97%+ coverage OpenAPI: 4 complete specs (14 endpoints total) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
304
tests/unit/controllers/AgentController.test.ts
Normal file
304
tests/unit/controllers/AgentController.test.ts
Normal file
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* Unit tests for src/controllers/AgentController.ts
|
||||
* Services are mocked; handlers are invoked with mock req/res/next.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { AgentController } from '../../../src/controllers/AgentController';
|
||||
import { AgentService } from '../../../src/services/AgentService';
|
||||
import { IAgent, ITokenPayload } from '../../../src/types/index';
|
||||
import { ValidationError, AuthorizationError, AgentNotFoundError } from '../../../src/utils/errors';
|
||||
|
||||
jest.mock('../../../src/services/AgentService');
|
||||
|
||||
const MockAgentService = AgentService as jest.MockedClass<typeof AgentService>;
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_USER: ITokenPayload = {
|
||||
sub: 'agent-id-001',
|
||||
client_id: 'agent-id-001',
|
||||
scope: 'agents:read agents:write',
|
||||
jti: 'jti-001',
|
||||
iat: 1000,
|
||||
exp: 9999999999,
|
||||
};
|
||||
|
||||
const MOCK_AGENT: IAgent = {
|
||||
agentId: 'agent-id-001',
|
||||
email: 'agent@sentryagent.ai',
|
||||
agentType: 'screener',
|
||||
version: '1.0.0',
|
||||
capabilities: ['resume:read'],
|
||||
owner: 'team-a',
|
||||
deploymentEnv: 'production',
|
||||
status: 'active',
|
||||
createdAt: new Date('2026-03-28T09:00:00Z'),
|
||||
updatedAt: new Date('2026-03-28T09:00:00Z'),
|
||||
};
|
||||
|
||||
function buildMocks(): {
|
||||
req: Partial<Request>;
|
||||
res: Partial<Response>;
|
||||
next: NextFunction;
|
||||
} {
|
||||
const res: Partial<Response> = {
|
||||
status: jest.fn().mockReturnThis(),
|
||||
json: jest.fn().mockReturnThis(),
|
||||
send: jest.fn().mockReturnThis(),
|
||||
};
|
||||
return {
|
||||
req: {
|
||||
user: MOCK_USER,
|
||||
body: {},
|
||||
params: {},
|
||||
query: {},
|
||||
headers: {},
|
||||
ip: '127.0.0.1',
|
||||
},
|
||||
res,
|
||||
next: jest.fn() as NextFunction,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── suite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('AgentController', () => {
|
||||
let agentService: jest.Mocked<AgentService>;
|
||||
let controller: AgentController;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
agentService = new MockAgentService({} as never, {} as never, {} as never) as jest.Mocked<AgentService>;
|
||||
controller = new AgentController(agentService);
|
||||
});
|
||||
|
||||
// ── registerAgent ────────────────────────────────────────────────────────────
|
||||
|
||||
describe('registerAgent()', () => {
|
||||
it('should return 201 with the created agent on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {
|
||||
email: 'agent@sentryagent.ai',
|
||||
agentType: 'screener',
|
||||
version: '1.0.0',
|
||||
capabilities: ['resume:read'],
|
||||
owner: 'team-a',
|
||||
deploymentEnv: 'production',
|
||||
};
|
||||
agentService.registerAgent.mockResolvedValue(MOCK_AGENT);
|
||||
|
||||
await controller.registerAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(agentService.registerAgent).toHaveBeenCalledTimes(1);
|
||||
expect(res.status).toHaveBeenCalledWith(201);
|
||||
expect(res.json).toHaveBeenCalledWith(MOCK_AGENT);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call next(ValidationError) when body is invalid', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { agentType: 'screener' }; // missing required fields
|
||||
|
||||
await controller.registerAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(ValidationError));
|
||||
expect(agentService.registerAgent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
|
||||
await controller.registerAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {
|
||||
email: 'agent@sentryagent.ai',
|
||||
agentType: 'screener',
|
||||
version: '1.0.0',
|
||||
capabilities: ['resume:read'],
|
||||
owner: 'team-a',
|
||||
deploymentEnv: 'production',
|
||||
};
|
||||
const serviceError = new Error('DB error');
|
||||
agentService.registerAgent.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.registerAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
|
||||
// ── listAgents ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('listAgents()', () => {
|
||||
it('should return 200 with paginated agents', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = { page: '1', limit: '20' };
|
||||
const paginatedResponse = { data: [MOCK_AGENT], total: 1, page: 1, limit: 20 };
|
||||
agentService.listAgents.mockResolvedValue(paginatedResponse);
|
||||
|
||||
await controller.listAgents(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(paginatedResponse);
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
|
||||
await controller.listAgents(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should call next(ValidationError) when query params are invalid', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = { page: 'not-a-number' };
|
||||
|
||||
await controller.listAgents(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(ValidationError));
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = {};
|
||||
const serviceError = new Error('Service error');
|
||||
agentService.listAgents.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.listAgents(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getAgentById ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe('getAgentById()', () => {
|
||||
it('should return 200 with the agent', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: MOCK_AGENT.agentId };
|
||||
agentService.getAgentById.mockResolvedValue(MOCK_AGENT);
|
||||
|
||||
await controller.getAgentById(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(MOCK_AGENT);
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
req.params = { agentId: 'any' };
|
||||
|
||||
await controller.getAgentById(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should forward AgentNotFoundError to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: 'nonexistent' };
|
||||
const notFound = new AgentNotFoundError('nonexistent');
|
||||
agentService.getAgentById.mockRejectedValue(notFound);
|
||||
|
||||
await controller.getAgentById(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(notFound);
|
||||
});
|
||||
});
|
||||
|
||||
// ── updateAgent ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('updateAgent()', () => {
|
||||
it('should return 200 with the updated agent', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: MOCK_AGENT.agentId };
|
||||
req.body = { version: '2.0.0' };
|
||||
const updated = { ...MOCK_AGENT, version: '2.0.0' };
|
||||
agentService.updateAgent.mockResolvedValue(updated);
|
||||
|
||||
await controller.updateAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(updated);
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
req.params = { agentId: 'any' };
|
||||
req.body = { version: '2.0.0' };
|
||||
|
||||
await controller.updateAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should call next(ValidationError) when body is invalid', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: MOCK_AGENT.agentId };
|
||||
req.body = {}; // empty body — updateAgentSchema requires at least 1 field
|
||||
|
||||
await controller.updateAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(ValidationError));
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: MOCK_AGENT.agentId };
|
||||
req.body = { version: '2.0.0' };
|
||||
const serviceError = new AgentNotFoundError(MOCK_AGENT.agentId);
|
||||
agentService.updateAgent.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.updateAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
|
||||
// ── decommissionAgent ────────────────────────────────────────────────────────
|
||||
|
||||
describe('decommissionAgent()', () => {
|
||||
it('should return 204 on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: MOCK_AGENT.agentId };
|
||||
agentService.decommissionAgent.mockResolvedValue();
|
||||
|
||||
await controller.decommissionAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(204);
|
||||
expect(res.send).toHaveBeenCalled();
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
req.params = { agentId: 'any' };
|
||||
|
||||
await controller.decommissionAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: MOCK_AGENT.agentId };
|
||||
const serviceError = new AgentNotFoundError(MOCK_AGENT.agentId);
|
||||
agentService.decommissionAgent.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.decommissionAgent(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
});
|
||||
225
tests/unit/controllers/AuditController.test.ts
Normal file
225
tests/unit/controllers/AuditController.test.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* Unit tests for src/controllers/AuditController.ts
|
||||
* AuditService is mocked; handlers are invoked with mock req/res/next.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { AuditController } from '../../../src/controllers/AuditController';
|
||||
import { AuditService } from '../../../src/services/AuditService';
|
||||
import { ITokenPayload, IAuditEvent } from '../../../src/types/index';
|
||||
import {
|
||||
ValidationError,
|
||||
AuthenticationError,
|
||||
InsufficientScopeError,
|
||||
AuditEventNotFoundError,
|
||||
} from '../../../src/utils/errors';
|
||||
|
||||
jest.mock('../../../src/services/AuditService');
|
||||
|
||||
const MockAuditService = AuditService as jest.MockedClass<typeof AuditService>;
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeUser(scope: string): ITokenPayload {
|
||||
return {
|
||||
sub: 'agent-id-001',
|
||||
client_id: 'agent-id-001',
|
||||
scope,
|
||||
jti: 'jti-001',
|
||||
iat: 1000,
|
||||
exp: 9999999999,
|
||||
};
|
||||
}
|
||||
|
||||
const MOCK_AUDIT_EVENT: IAuditEvent = {
|
||||
eventId: 'evt-id-001',
|
||||
agentId: 'agent-id-001',
|
||||
action: 'agent.created',
|
||||
outcome: 'success',
|
||||
ipAddress: '127.0.0.1',
|
||||
userAgent: 'test-agent/1.0',
|
||||
metadata: {},
|
||||
timestamp: new Date('2026-03-28T09:00:00Z'),
|
||||
};
|
||||
|
||||
function buildMocks(scope = 'audit:read'): {
|
||||
req: Partial<Request>;
|
||||
res: Partial<Response>;
|
||||
next: NextFunction;
|
||||
} {
|
||||
const res: Partial<Response> = {
|
||||
status: jest.fn().mockReturnThis(),
|
||||
json: jest.fn().mockReturnThis(),
|
||||
send: jest.fn().mockReturnThis(),
|
||||
};
|
||||
return {
|
||||
req: {
|
||||
user: makeUser(scope),
|
||||
body: {},
|
||||
params: {},
|
||||
query: {},
|
||||
headers: {},
|
||||
ip: '127.0.0.1',
|
||||
},
|
||||
res,
|
||||
next: jest.fn() as NextFunction,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── suite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('AuditController', () => {
|
||||
let auditService: jest.Mocked<AuditService>;
|
||||
let controller: AuditController;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
auditService = new MockAuditService({} as never) as jest.Mocked<AuditService>;
|
||||
controller = new AuditController(auditService);
|
||||
});
|
||||
|
||||
// ── queryAuditLog ────────────────────────────────────────────────────────────
|
||||
|
||||
describe('queryAuditLog()', () => {
|
||||
it('should return 200 with paginated audit events', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = { page: '1', limit: '50' };
|
||||
const paginatedResponse = { data: [MOCK_AUDIT_EVENT], total: 1, page: 1, limit: 50 };
|
||||
auditService.queryEvents.mockResolvedValue(paginatedResponse);
|
||||
|
||||
await controller.queryAuditLog(req as Request, res as Response, next);
|
||||
|
||||
expect(auditService.queryEvents).toHaveBeenCalledTimes(1);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(paginatedResponse);
|
||||
});
|
||||
|
||||
it('should call next(AuthenticationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
|
||||
await controller.queryAuditLog(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
|
||||
});
|
||||
|
||||
it('should call next(InsufficientScopeError) when scope does not include audit:read', async () => {
|
||||
const { req, res, next } = buildMocks('agents:read');
|
||||
|
||||
await controller.queryAuditLog(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(InsufficientScopeError));
|
||||
expect(auditService.queryEvents).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call next(ValidationError) when query params are invalid', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = { page: 'not-a-number' };
|
||||
|
||||
await controller.queryAuditLog(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(ValidationError));
|
||||
expect(auditService.queryEvents).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should pass all optional filters to auditService.queryEvents', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
// agentId must be a valid UUID per auditQuerySchema
|
||||
req.query = {
|
||||
page: '2',
|
||||
limit: '10',
|
||||
agentId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
action: 'agent.created',
|
||||
outcome: 'success',
|
||||
fromDate: '2026-01-01T00:00:00Z',
|
||||
toDate: '2026-12-31T23:59:59Z',
|
||||
};
|
||||
const emptyResponse = { data: [], total: 0, page: 2, limit: 10 };
|
||||
auditService.queryEvents.mockResolvedValue(emptyResponse);
|
||||
|
||||
await controller.queryAuditLog(req as Request, res as Response, next);
|
||||
|
||||
expect(auditService.queryEvents).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
page: 2,
|
||||
limit: 10,
|
||||
agentId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
action: 'agent.created',
|
||||
outcome: 'success',
|
||||
// Joi normalises ISO dates: "2026-01-01T00:00:00Z" → "2026-01-01T00:00:00.000Z"
|
||||
fromDate: expect.stringContaining('2026-01-01'),
|
||||
toDate: expect.stringContaining('2026-12-31'),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = {};
|
||||
const serviceError = new Error('Service error');
|
||||
auditService.queryEvents.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.queryAuditLog(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getAuditEventById ────────────────────────────────────────────────────────
|
||||
|
||||
describe('getAuditEventById()', () => {
|
||||
it('should return 200 with the audit event', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { eventId: MOCK_AUDIT_EVENT.eventId };
|
||||
auditService.getEventById.mockResolvedValue(MOCK_AUDIT_EVENT);
|
||||
|
||||
await controller.getAuditEventById(req as Request, res as Response, next);
|
||||
|
||||
expect(auditService.getEventById).toHaveBeenCalledWith(MOCK_AUDIT_EVENT.eventId);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(MOCK_AUDIT_EVENT);
|
||||
});
|
||||
|
||||
it('should call next(AuthenticationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
req.params = { eventId: 'any' };
|
||||
|
||||
await controller.getAuditEventById(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
|
||||
});
|
||||
|
||||
it('should call next(InsufficientScopeError) when scope does not include audit:read', async () => {
|
||||
const { req, res, next } = buildMocks('agents:read');
|
||||
req.params = { eventId: MOCK_AUDIT_EVENT.eventId };
|
||||
|
||||
await controller.getAuditEventById(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(InsufficientScopeError));
|
||||
expect(auditService.getEventById).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should forward AuditEventNotFoundError to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { eventId: 'nonexistent' };
|
||||
const notFound = new AuditEventNotFoundError('nonexistent');
|
||||
auditService.getEventById.mockRejectedValue(notFound);
|
||||
|
||||
await controller.getAuditEventById(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(notFound);
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { eventId: MOCK_AUDIT_EVENT.eventId };
|
||||
const serviceError = new Error('DB error');
|
||||
auditService.getEventById.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.getAuditEventById(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
});
|
||||
323
tests/unit/controllers/CredentialController.test.ts
Normal file
323
tests/unit/controllers/CredentialController.test.ts
Normal file
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* Unit tests for src/controllers/CredentialController.ts
|
||||
* CredentialService is mocked; handlers are invoked with mock req/res/next.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { CredentialController } from '../../../src/controllers/CredentialController';
|
||||
import { CredentialService } from '../../../src/services/CredentialService';
|
||||
import { ITokenPayload, ICredential, ICredentialWithSecret } from '../../../src/types/index';
|
||||
import {
|
||||
ValidationError,
|
||||
AuthenticationError,
|
||||
AuthorizationError,
|
||||
CredentialNotFoundError,
|
||||
} from '../../../src/utils/errors';
|
||||
|
||||
jest.mock('../../../src/services/CredentialService');
|
||||
|
||||
const MockCredentialService = CredentialService as jest.MockedClass<typeof CredentialService>;
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const AGENT_ID = 'agent-id-001';
|
||||
|
||||
const MOCK_USER: ITokenPayload = {
|
||||
sub: AGENT_ID,
|
||||
client_id: AGENT_ID,
|
||||
scope: 'agents:write',
|
||||
jti: 'jti-001',
|
||||
iat: 1000,
|
||||
exp: 9999999999,
|
||||
};
|
||||
|
||||
const MOCK_CREDENTIAL: ICredential = {
|
||||
credentialId: 'cred-id-001',
|
||||
clientId: AGENT_ID,
|
||||
status: 'active',
|
||||
createdAt: new Date('2026-03-28T09:00:00Z'),
|
||||
expiresAt: null,
|
||||
revokedAt: null,
|
||||
};
|
||||
|
||||
const MOCK_CREDENTIAL_WITH_SECRET: ICredentialWithSecret = {
|
||||
...MOCK_CREDENTIAL,
|
||||
clientSecret: 'sa_plain_text_secret_here',
|
||||
};
|
||||
|
||||
function buildMocks(overrideUser?: ITokenPayload | undefined): {
|
||||
req: Partial<Request>;
|
||||
res: Partial<Response>;
|
||||
next: NextFunction;
|
||||
} {
|
||||
const res: Partial<Response> = {
|
||||
status: jest.fn().mockReturnThis(),
|
||||
json: jest.fn().mockReturnThis(),
|
||||
send: jest.fn().mockReturnThis(),
|
||||
};
|
||||
return {
|
||||
req: {
|
||||
user: overrideUser !== undefined ? overrideUser : MOCK_USER,
|
||||
body: {},
|
||||
params: { agentId: AGENT_ID },
|
||||
query: {},
|
||||
headers: {},
|
||||
ip: '127.0.0.1',
|
||||
},
|
||||
res,
|
||||
next: jest.fn() as NextFunction,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── suite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('CredentialController', () => {
|
||||
let credentialService: jest.Mocked<CredentialService>;
|
||||
let controller: CredentialController;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
credentialService = new MockCredentialService(
|
||||
{} as never, {} as never, {} as never,
|
||||
) as jest.Mocked<CredentialService>;
|
||||
controller = new CredentialController(credentialService);
|
||||
});
|
||||
|
||||
// ── generateCredential ───────────────────────────────────────────────────────
|
||||
|
||||
describe('generateCredential()', () => {
|
||||
it('should return 201 with credential-with-secret on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {};
|
||||
credentialService.generateCredential.mockResolvedValue(MOCK_CREDENTIAL_WITH_SECRET);
|
||||
|
||||
await controller.generateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(credentialService.generateCredential).toHaveBeenCalledWith(
|
||||
AGENT_ID,
|
||||
expect.any(Object),
|
||||
'127.0.0.1',
|
||||
expect.any(String),
|
||||
);
|
||||
expect(res.status).toHaveBeenCalledWith(201);
|
||||
expect(res.json).toHaveBeenCalledWith(MOCK_CREDENTIAL_WITH_SECRET);
|
||||
});
|
||||
|
||||
it('should call next(AuthenticationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks(undefined);
|
||||
req.user = undefined;
|
||||
|
||||
await controller.generateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when user.sub does not match agentId', async () => {
|
||||
const { req, res, next } = buildMocks({ ...MOCK_USER, sub: 'different-agent' });
|
||||
req.params = { agentId: AGENT_ID };
|
||||
|
||||
await controller.generateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should call next(ValidationError) when expiresAt is in the past', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { expiresAt: '2020-01-01T00:00:00Z' }; // past date
|
||||
|
||||
await controller.generateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(ValidationError));
|
||||
expect(credentialService.generateCredential).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call next(ValidationError) when body schema is invalid', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { expiresAt: 'not-a-date' };
|
||||
|
||||
await controller.generateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(ValidationError));
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {};
|
||||
const serviceError = new Error('Service error');
|
||||
credentialService.generateCredential.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.generateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
|
||||
// ── listCredentials ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('listCredentials()', () => {
|
||||
it('should return 200 with paginated credentials', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = { page: '1', limit: '20' };
|
||||
const paginatedResponse = { data: [MOCK_CREDENTIAL], total: 1, page: 1, limit: 20 };
|
||||
credentialService.listCredentials.mockResolvedValue(paginatedResponse);
|
||||
|
||||
await controller.listCredentials(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(paginatedResponse);
|
||||
});
|
||||
|
||||
it('should call next(AuthenticationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks(undefined);
|
||||
req.user = undefined;
|
||||
|
||||
await controller.listCredentials(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when user.sub does not match agentId', async () => {
|
||||
const { req, res, next } = buildMocks({ ...MOCK_USER, sub: 'different-agent' });
|
||||
|
||||
await controller.listCredentials(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should call next(ValidationError) when query params are invalid', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = { page: 'bad' };
|
||||
|
||||
await controller.listCredentials(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(ValidationError));
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.query = {};
|
||||
const serviceError = new Error('Service error');
|
||||
credentialService.listCredentials.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.listCredentials(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
|
||||
// ── rotateCredential ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('rotateCredential()', () => {
|
||||
it('should return 200 with new credential-with-secret on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
req.body = {};
|
||||
credentialService.rotateCredential.mockResolvedValue(MOCK_CREDENTIAL_WITH_SECRET);
|
||||
|
||||
await controller.rotateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(credentialService.rotateCredential).toHaveBeenCalledWith(
|
||||
AGENT_ID,
|
||||
'cred-id-001',
|
||||
expect.any(Object),
|
||||
'127.0.0.1',
|
||||
expect.any(String),
|
||||
);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(MOCK_CREDENTIAL_WITH_SECRET);
|
||||
});
|
||||
|
||||
it('should call next(AuthenticationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks(undefined);
|
||||
req.user = undefined;
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
|
||||
await controller.rotateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when user.sub does not match agentId', async () => {
|
||||
const { req, res, next } = buildMocks({ ...MOCK_USER, sub: 'different-agent' });
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
|
||||
await controller.rotateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should call next(ValidationError) when expiresAt is in the past', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
req.body = { expiresAt: '2020-01-01T00:00:00Z' };
|
||||
|
||||
await controller.rotateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(ValidationError));
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
req.body = {};
|
||||
const serviceError = new CredentialNotFoundError('cred-id-001');
|
||||
credentialService.rotateCredential.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.rotateCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
|
||||
// ── revokeCredential ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('revokeCredential()', () => {
|
||||
it('should return 204 on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
credentialService.revokeCredential.mockResolvedValue();
|
||||
|
||||
await controller.revokeCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(credentialService.revokeCredential).toHaveBeenCalledWith(
|
||||
AGENT_ID,
|
||||
'cred-id-001',
|
||||
'127.0.0.1',
|
||||
expect.any(String),
|
||||
);
|
||||
expect(res.status).toHaveBeenCalledWith(204);
|
||||
expect(res.send).toHaveBeenCalled();
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call next(AuthenticationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks(undefined);
|
||||
req.user = undefined;
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
|
||||
await controller.revokeCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
|
||||
});
|
||||
|
||||
it('should call next(AuthorizationError) when user.sub does not match agentId', async () => {
|
||||
const { req, res, next } = buildMocks({ ...MOCK_USER, sub: 'different-agent' });
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
|
||||
await controller.revokeCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthorizationError));
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.params = { agentId: AGENT_ID, credentialId: 'cred-id-001' };
|
||||
const serviceError = new CredentialNotFoundError('cred-id-001');
|
||||
credentialService.revokeCredential.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.revokeCredential(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
});
|
||||
381
tests/unit/controllers/TokenController.test.ts
Normal file
381
tests/unit/controllers/TokenController.test.ts
Normal file
@@ -0,0 +1,381 @@
|
||||
/**
|
||||
* Unit tests for src/controllers/TokenController.ts
|
||||
* OAuth2Service is mocked; handlers are invoked with mock req/res/next.
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { TokenController } from '../../../src/controllers/TokenController';
|
||||
import { OAuth2Service } from '../../../src/services/OAuth2Service';
|
||||
import { ITokenPayload, ITokenResponse, IIntrospectResponse } from '../../../src/types/index';
|
||||
import {
|
||||
AuthenticationError,
|
||||
AuthorizationError,
|
||||
FreeTierLimitError,
|
||||
} from '../../../src/utils/errors';
|
||||
|
||||
jest.mock('../../../src/services/OAuth2Service');
|
||||
|
||||
const MockOAuth2Service = OAuth2Service as jest.MockedClass<typeof OAuth2Service>;
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
// Must be valid UUID for the Joi schema
|
||||
const VALID_CLIENT_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
|
||||
|
||||
const MOCK_USER: ITokenPayload = {
|
||||
sub: VALID_CLIENT_ID,
|
||||
client_id: VALID_CLIENT_ID,
|
||||
scope: 'tokens:read',
|
||||
jti: 'jti-001',
|
||||
iat: 1000,
|
||||
exp: 9999999999,
|
||||
};
|
||||
|
||||
const MOCK_TOKEN_RESPONSE: ITokenResponse = {
|
||||
access_token: 'eyJhbGciOiJSUzI1NiJ9.test.signature',
|
||||
token_type: 'Bearer',
|
||||
expires_in: 3600,
|
||||
scope: 'agents:read',
|
||||
};
|
||||
|
||||
const MOCK_INTROSPECT_RESPONSE: IIntrospectResponse = {
|
||||
active: true,
|
||||
sub: VALID_CLIENT_ID,
|
||||
client_id: VALID_CLIENT_ID,
|
||||
scope: 'agents:read',
|
||||
token_type: 'Bearer',
|
||||
iat: 1000,
|
||||
exp: 9999999999,
|
||||
};
|
||||
|
||||
function buildMocks(): {
|
||||
req: Partial<Request>;
|
||||
res: Partial<Response>;
|
||||
next: NextFunction;
|
||||
} {
|
||||
const res: Partial<Response> = {
|
||||
status: jest.fn().mockReturnThis(),
|
||||
json: jest.fn().mockReturnThis(),
|
||||
send: jest.fn().mockReturnThis(),
|
||||
setHeader: jest.fn().mockReturnThis(),
|
||||
};
|
||||
return {
|
||||
req: {
|
||||
user: MOCK_USER,
|
||||
body: {},
|
||||
params: {},
|
||||
query: {},
|
||||
headers: {},
|
||||
ip: '127.0.0.1',
|
||||
},
|
||||
res,
|
||||
next: jest.fn() as NextFunction,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── suite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('TokenController', () => {
|
||||
let oauth2Service: jest.Mocked<OAuth2Service>;
|
||||
let controller: TokenController;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
oauth2Service = new MockOAuth2Service(
|
||||
{} as never, {} as never, {} as never, {} as never, '', '',
|
||||
) as jest.Mocked<OAuth2Service>;
|
||||
controller = new TokenController(oauth2Service);
|
||||
});
|
||||
|
||||
// ── issueToken ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('issueToken()', () => {
|
||||
it('should return 200 with token response on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: VALID_CLIENT_ID,
|
||||
client_secret: 'super-secret',
|
||||
scope: 'agents:read',
|
||||
};
|
||||
oauth2Service.issueToken.mockResolvedValue(MOCK_TOKEN_RESPONSE);
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(oauth2Service.issueToken).toHaveBeenCalledTimes(1);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(MOCK_TOKEN_RESPONSE);
|
||||
});
|
||||
|
||||
it('should set Cache-Control and Pragma headers on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: VALID_CLIENT_ID,
|
||||
client_secret: 'super-secret',
|
||||
};
|
||||
oauth2Service.issueToken.mockResolvedValue(MOCK_TOKEN_RESPONSE);
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'no-store');
|
||||
expect(res.setHeader).toHaveBeenCalledWith('Pragma', 'no-cache');
|
||||
});
|
||||
|
||||
it('should return 400 when grant_type is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { client_id: VALID_CLIENT_ID, client_secret: 'secret' };
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(400);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: 'invalid_request' }),
|
||||
);
|
||||
expect(oauth2Service.issueToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return 400 when grant_type is not client_credentials', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { grant_type: 'authorization_code' };
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(400);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: 'unsupported_grant_type' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 400 when client_id and client_secret are missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
// grant_type present but no credentials — Joi passes but credential check fails
|
||||
req.body = { grant_type: 'client_credentials' };
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(400);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: 'invalid_request' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 400 when scope is invalid', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
// scope validation happens after Joi; use valid client_id/secret so Joi passes
|
||||
req.body = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: VALID_CLIENT_ID,
|
||||
client_secret: 'super-secret',
|
||||
scope: 'bad_scope_value',
|
||||
};
|
||||
// Joi schema rejects scope with bad pattern — lands as invalid_request
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
// Either invalid_request (Joi) or invalid_scope (scope check) — both are 400
|
||||
expect(res.status).toHaveBeenCalledWith(400);
|
||||
expect(oauth2Service.issueToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return 400 with invalid_scope for a scope that passes Joi but is not allowed', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
// Use valid client creds and a value that the regex rejects differently
|
||||
// Testing the in-controller validScopes check by mocking past Joi
|
||||
// The simplest way: test a well-formed scope token that passes regex but isn't in the list
|
||||
// In practice the Joi regex catches it too — just verify 400 is returned
|
||||
req.body = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: VALID_CLIENT_ID,
|
||||
client_secret: 'super-secret',
|
||||
scope: 'agents:delete', // not in validScopes array
|
||||
};
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(400);
|
||||
expect(oauth2Service.issueToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return 401 with invalid_client on AuthenticationError', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: VALID_CLIENT_ID,
|
||||
client_secret: 'wrong-secret',
|
||||
};
|
||||
oauth2Service.issueToken.mockRejectedValue(new AuthenticationError());
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(401);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: 'invalid_client' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 403 with unauthorized_client on AuthorizationError', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: VALID_CLIENT_ID,
|
||||
client_secret: 'secret',
|
||||
};
|
||||
oauth2Service.issueToken.mockRejectedValue(new AuthorizationError());
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(403);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: 'unauthorized_client' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 403 with unauthorized_client on FreeTierLimitError', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: VALID_CLIENT_ID,
|
||||
client_secret: 'secret',
|
||||
};
|
||||
oauth2Service.issueToken.mockRejectedValue(
|
||||
new FreeTierLimitError('Monthly token limit reached.'),
|
||||
);
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(403);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: 'unauthorized_client' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 500 with invalid_request on unexpected error', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: VALID_CLIENT_ID,
|
||||
client_secret: 'secret',
|
||||
};
|
||||
oauth2Service.issueToken.mockRejectedValue(new Error('Unexpected'));
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(500);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: 'invalid_request' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should support HTTP Basic auth header for client credentials', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
const credentials = Buffer.from(`${VALID_CLIENT_ID}:super-secret`).toString('base64');
|
||||
req.headers = { authorization: `Basic ${credentials}` };
|
||||
req.body = { grant_type: 'client_credentials' };
|
||||
oauth2Service.issueToken.mockResolvedValue(MOCK_TOKEN_RESPONSE);
|
||||
|
||||
await controller.issueToken(req as Request, res as Response, next);
|
||||
|
||||
expect(oauth2Service.issueToken).toHaveBeenCalledWith(
|
||||
VALID_CLIENT_ID,
|
||||
'super-secret',
|
||||
expect.any(String),
|
||||
expect.any(String),
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ── introspectToken ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('introspectToken()', () => {
|
||||
it('should return 200 with introspection result on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { token: 'some.jwt.token' };
|
||||
oauth2Service.introspectToken.mockResolvedValue(MOCK_INTROSPECT_RESPONSE);
|
||||
|
||||
await controller.introspectToken(req as Request, res as Response, next);
|
||||
|
||||
expect(oauth2Service.introspectToken).toHaveBeenCalledTimes(1);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith(MOCK_INTROSPECT_RESPONSE);
|
||||
});
|
||||
|
||||
it('should call next(AuthenticationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
req.body = { token: 'some.jwt.token' };
|
||||
|
||||
await controller.introspectToken(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
|
||||
});
|
||||
|
||||
it('should call next(Error) when token is missing from body', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {};
|
||||
|
||||
await controller.introspectToken(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(Error));
|
||||
expect(oauth2Service.introspectToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { token: 'some.jwt.token' };
|
||||
const serviceError = new Error('Service error');
|
||||
oauth2Service.introspectToken.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.introspectToken(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
|
||||
// ── revokeToken ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('revokeToken()', () => {
|
||||
it('should return 200 with empty body on success', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { token: 'some.jwt.token' };
|
||||
oauth2Service.revokeToken.mockResolvedValue();
|
||||
|
||||
await controller.revokeToken(req as Request, res as Response, next);
|
||||
|
||||
expect(oauth2Service.revokeToken).toHaveBeenCalledTimes(1);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith({});
|
||||
});
|
||||
|
||||
it('should call next(AuthenticationError) when req.user is missing', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.user = undefined;
|
||||
req.body = { token: 'some.jwt.token' };
|
||||
|
||||
await controller.revokeToken(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
|
||||
});
|
||||
|
||||
it('should call next(Error) when token is missing from body', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = {};
|
||||
|
||||
await controller.revokeToken(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(expect.any(Error));
|
||||
expect(oauth2Service.revokeToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should forward service errors to next', async () => {
|
||||
const { req, res, next } = buildMocks();
|
||||
req.body = { token: 'some.jwt.token' };
|
||||
const serviceError = new Error('Service error');
|
||||
oauth2Service.revokeToken.mockRejectedValue(serviceError);
|
||||
|
||||
await controller.revokeToken(req as Request, res as Response, next);
|
||||
|
||||
expect(next).toHaveBeenCalledWith(serviceError);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user