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:
276
tests/unit/repositories/AgentRepository.test.ts
Normal file
276
tests/unit/repositories/AgentRepository.test.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
/**
|
||||
* Unit tests for src/repositories/AgentRepository.ts
|
||||
* Uses a mocked pg.Pool — no real database connection.
|
||||
*/
|
||||
|
||||
import { Pool } from 'pg';
|
||||
import { AgentRepository } from '../../../src/repositories/AgentRepository';
|
||||
import { IAgent, ICreateAgentRequest, IUpdateAgentRequest, IAgentListFilters } from '../../../src/types/index';
|
||||
|
||||
jest.mock('pg', () => ({
|
||||
Pool: jest.fn().mockImplementation(() => ({
|
||||
query: jest.fn(),
|
||||
connect: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const AGENT_ROW = {
|
||||
agent_id: 'a1b2c3d4-0000-0000-0000-000000000001',
|
||||
email: 'agent@sentryagent.ai',
|
||||
agent_type: 'screener',
|
||||
version: '1.0.0',
|
||||
capabilities: ['resume:read'],
|
||||
owner: 'team-a',
|
||||
deployment_env: 'production',
|
||||
status: 'active',
|
||||
created_at: new Date('2026-03-28T09:00:00Z'),
|
||||
updated_at: new Date('2026-03-28T09:00:00Z'),
|
||||
};
|
||||
|
||||
const EXPECTED_AGENT: IAgent = {
|
||||
agentId: AGENT_ROW.agent_id,
|
||||
email: AGENT_ROW.email,
|
||||
agentType: 'screener',
|
||||
version: AGENT_ROW.version,
|
||||
capabilities: AGENT_ROW.capabilities,
|
||||
owner: AGENT_ROW.owner,
|
||||
deploymentEnv: 'production',
|
||||
status: 'active',
|
||||
createdAt: AGENT_ROW.created_at,
|
||||
updatedAt: AGENT_ROW.updated_at,
|
||||
};
|
||||
|
||||
// ─── suite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('AgentRepository', () => {
|
||||
let pool: jest.Mocked<Pool>;
|
||||
let repo: AgentRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
pool = new Pool() as jest.Mocked<Pool>;
|
||||
repo = new AgentRepository(pool);
|
||||
});
|
||||
|
||||
// ── create ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('create()', () => {
|
||||
const createData: ICreateAgentRequest = {
|
||||
email: 'agent@sentryagent.ai',
|
||||
agentType: 'screener',
|
||||
version: '1.0.0',
|
||||
capabilities: ['resume:read'],
|
||||
owner: 'team-a',
|
||||
deploymentEnv: 'production',
|
||||
};
|
||||
|
||||
it('should insert a row and return a mapped IAgent', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [AGENT_ROW], rowCount: 1 });
|
||||
|
||||
const result = await repo.create(createData);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledTimes(1);
|
||||
const [sql, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('INSERT INTO agents');
|
||||
expect(params).toContain(createData.email);
|
||||
expect(params).toContain(createData.agentType);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
email: EXPECTED_AGENT.email,
|
||||
agentType: EXPECTED_AGENT.agentType,
|
||||
status: 'active',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── findById ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('findById()', () => {
|
||||
it('should return a mapped IAgent when the row exists', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [AGENT_ROW], rowCount: 1 });
|
||||
|
||||
const result = await repo.findById(AGENT_ROW.agent_id);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledWith(
|
||||
expect.stringContaining('SELECT'),
|
||||
[AGENT_ROW.agent_id],
|
||||
);
|
||||
expect(result).toMatchObject(EXPECTED_AGENT);
|
||||
});
|
||||
|
||||
it('should return null when no rows are returned', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.findById('nonexistent');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── findByEmail ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('findByEmail()', () => {
|
||||
it('should return a mapped IAgent when the email exists', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [AGENT_ROW], rowCount: 1 });
|
||||
|
||||
const result = await repo.findByEmail(AGENT_ROW.email);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledWith(
|
||||
expect.stringContaining('email'),
|
||||
[AGENT_ROW.email],
|
||||
);
|
||||
expect(result).toMatchObject(EXPECTED_AGENT);
|
||||
});
|
||||
|
||||
it('should return null when no rows are returned', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.findByEmail('notfound@example.com');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── findAll ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('findAll()', () => {
|
||||
it('should return paginated agents with total count (no filters)', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '1' }], rowCount: 1 }) // count query
|
||||
.mockResolvedValueOnce({ rows: [AGENT_ROW], rowCount: 1 }); // data query
|
||||
|
||||
const filters: IAgentListFilters = { page: 1, limit: 20 };
|
||||
const result = await repo.findAll(filters);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledTimes(2);
|
||||
expect(result.total).toBe(1);
|
||||
expect(result.agents).toHaveLength(1);
|
||||
expect(result.agents[0]).toMatchObject(EXPECTED_AGENT);
|
||||
});
|
||||
|
||||
it('should apply owner, agentType, and status filters', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const filters: IAgentListFilters = {
|
||||
page: 1,
|
||||
limit: 10,
|
||||
owner: 'team-a',
|
||||
agentType: 'screener',
|
||||
status: 'active',
|
||||
};
|
||||
const result = await repo.findAll(filters);
|
||||
|
||||
const [countSql] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(countSql).toContain('owner');
|
||||
expect(countSql).toContain('agent_type');
|
||||
expect(countSql).toContain('status');
|
||||
expect(result.total).toBe(0);
|
||||
expect(result.agents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return an empty list when no agents exist', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.findAll({ page: 1, limit: 20 });
|
||||
|
||||
expect(result.total).toBe(0);
|
||||
expect(result.agents).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ── update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('update()', () => {
|
||||
it('should update fields and return mapped IAgent', async () => {
|
||||
const updatedRow = { ...AGENT_ROW, version: '2.0.0' };
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [updatedRow], rowCount: 1 });
|
||||
|
||||
const data: IUpdateAgentRequest = { version: '2.0.0' };
|
||||
const result = await repo.update(AGENT_ROW.agent_id, data);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledTimes(1);
|
||||
const [sql] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('UPDATE agents');
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.version).toBe('2.0.0');
|
||||
});
|
||||
|
||||
it('should return null when the agent is not found after update', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.update('nonexistent', { version: '2.0.0' });
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null when no fields are provided', async () => {
|
||||
const result = await repo.update(AGENT_ROW.agent_id, {});
|
||||
|
||||
expect(pool.query).not.toHaveBeenCalled();
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should update multiple fields at once', async () => {
|
||||
const updatedRow = { ...AGENT_ROW, version: '3.0.0', status: 'suspended', owner: 'team-b' };
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [updatedRow], rowCount: 1 });
|
||||
|
||||
const data: IUpdateAgentRequest = { version: '3.0.0', status: 'suspended', owner: 'team-b' };
|
||||
const result = await repo.update(AGENT_ROW.agent_id, data);
|
||||
|
||||
expect(result?.status).toBe('suspended');
|
||||
expect(result?.owner).toBe('team-b');
|
||||
});
|
||||
});
|
||||
|
||||
// ── decommission ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('decommission()', () => {
|
||||
it('should set status to decommissioned and return the agent', async () => {
|
||||
const decomRow = { ...AGENT_ROW, status: 'decommissioned' };
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [decomRow], rowCount: 1 });
|
||||
|
||||
const result = await repo.decommission(AGENT_ROW.agent_id);
|
||||
|
||||
const [sql, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('decommissioned');
|
||||
expect(params).toContain(AGENT_ROW.agent_id);
|
||||
expect(result?.status).toBe('decommissioned');
|
||||
});
|
||||
|
||||
it('should return null when agent is not found', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.decommission('nonexistent');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── countActive ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('countActive()', () => {
|
||||
it('should return the count of non-decommissioned agents', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [{ count: '42' }], rowCount: 1 });
|
||||
|
||||
const count = await repo.countActive();
|
||||
|
||||
const [sql] = (pool.query as jest.Mock).mock.calls[0] as [string];
|
||||
expect(sql).toContain('decommissioned');
|
||||
expect(count).toBe(42);
|
||||
});
|
||||
|
||||
it('should return 0 when there are no active agents', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 });
|
||||
|
||||
const count = await repo.countActive();
|
||||
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
221
tests/unit/repositories/AuditRepository.test.ts
Normal file
221
tests/unit/repositories/AuditRepository.test.ts
Normal file
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Unit tests for src/repositories/AuditRepository.ts
|
||||
* Uses a mocked pg.Pool — no real database connection.
|
||||
*/
|
||||
|
||||
import { Pool } from 'pg';
|
||||
import { AuditRepository } from '../../../src/repositories/AuditRepository';
|
||||
import { IAuditEvent, ICreateAuditEventInput, IAuditListFilters } from '../../../src/types/index';
|
||||
|
||||
jest.mock('pg', () => ({
|
||||
Pool: jest.fn().mockImplementation(() => ({
|
||||
query: jest.fn(),
|
||||
connect: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const AUDIT_ROW = {
|
||||
event_id: 'evt-0000-0000-0000-000000000001',
|
||||
agent_id: 'agent-0000-0000-0000-000000000001',
|
||||
action: 'agent.created',
|
||||
outcome: 'success',
|
||||
ip_address: '127.0.0.1',
|
||||
user_agent: 'test-agent/1.0',
|
||||
metadata: { agentType: 'screener' },
|
||||
timestamp: new Date('2026-03-28T09:00:00Z'),
|
||||
};
|
||||
|
||||
const EXPECTED_EVENT: IAuditEvent = {
|
||||
eventId: AUDIT_ROW.event_id,
|
||||
agentId: AUDIT_ROW.agent_id,
|
||||
action: 'agent.created',
|
||||
outcome: 'success',
|
||||
ipAddress: AUDIT_ROW.ip_address,
|
||||
userAgent: AUDIT_ROW.user_agent,
|
||||
metadata: AUDIT_ROW.metadata,
|
||||
timestamp: AUDIT_ROW.timestamp,
|
||||
};
|
||||
|
||||
const RETENTION_CUTOFF = new Date('2026-01-01T00:00:00Z');
|
||||
|
||||
// ─── suite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('AuditRepository', () => {
|
||||
let pool: jest.Mocked<Pool>;
|
||||
let repo: AuditRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
pool = new Pool() as jest.Mocked<Pool>;
|
||||
repo = new AuditRepository(pool);
|
||||
});
|
||||
|
||||
// ── create ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('create()', () => {
|
||||
const eventInput: ICreateAuditEventInput = {
|
||||
agentId: AUDIT_ROW.agent_id,
|
||||
action: 'agent.created',
|
||||
outcome: 'success',
|
||||
ipAddress: '127.0.0.1',
|
||||
userAgent: 'test-agent/1.0',
|
||||
metadata: { agentType: 'screener' },
|
||||
};
|
||||
|
||||
it('should insert a row and return a mapped IAuditEvent', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [AUDIT_ROW], rowCount: 1 });
|
||||
|
||||
const result = await repo.create(eventInput);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledTimes(1);
|
||||
const [sql, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('INSERT INTO audit_events');
|
||||
expect(params).toContain(eventInput.agentId);
|
||||
expect(params).toContain(eventInput.action);
|
||||
expect(params).toContain(eventInput.outcome);
|
||||
expect(params).toContain(eventInput.ipAddress);
|
||||
expect(params).toContain(eventInput.userAgent);
|
||||
expect(result).toMatchObject(EXPECTED_EVENT);
|
||||
});
|
||||
|
||||
it('should JSON-stringify the metadata field', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [AUDIT_ROW], rowCount: 1 });
|
||||
|
||||
await repo.create(eventInput);
|
||||
|
||||
const [, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
// metadata param should be a JSON string
|
||||
const metadataParam = params.find((p) => typeof p === 'string' && p.startsWith('{'));
|
||||
expect(metadataParam).toBe(JSON.stringify(eventInput.metadata));
|
||||
});
|
||||
});
|
||||
|
||||
// ── findById ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('findById()', () => {
|
||||
it('should return a mapped IAuditEvent when found', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [AUDIT_ROW], rowCount: 1 });
|
||||
|
||||
const result = await repo.findById(AUDIT_ROW.event_id);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledWith(
|
||||
expect.stringContaining('event_id'),
|
||||
[AUDIT_ROW.event_id],
|
||||
);
|
||||
expect(result).toMatchObject(EXPECTED_EVENT);
|
||||
});
|
||||
|
||||
it('should return null when not found', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.findById('nonexistent');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── findAll ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('findAll()', () => {
|
||||
it('should return paginated events with total count (no optional filters)', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '1' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [AUDIT_ROW], rowCount: 1 });
|
||||
|
||||
const filters: IAuditListFilters = { page: 1, limit: 50 };
|
||||
const result = await repo.findAll(filters, RETENTION_CUTOFF);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledTimes(2);
|
||||
expect(result.total).toBe(1);
|
||||
expect(result.events).toHaveLength(1);
|
||||
expect(result.events[0]).toMatchObject(EXPECTED_EVENT);
|
||||
});
|
||||
|
||||
it('should include retention cutoff in the WHERE clause', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
await repo.findAll({ page: 1, limit: 50 }, RETENTION_CUTOFF);
|
||||
|
||||
const [countSql, countParams] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(countSql).toContain('timestamp');
|
||||
expect(countParams).toContain(RETENTION_CUTOFF);
|
||||
});
|
||||
|
||||
it('should apply agentId filter', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '1' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [AUDIT_ROW], rowCount: 1 });
|
||||
|
||||
const filters: IAuditListFilters = { page: 1, limit: 50, agentId: AUDIT_ROW.agent_id };
|
||||
await repo.findAll(filters, RETENTION_CUTOFF);
|
||||
|
||||
const [countSql] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(countSql).toContain('agent_id');
|
||||
});
|
||||
|
||||
it('should apply action filter', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
await repo.findAll({ page: 1, limit: 50, action: 'token.issued' }, RETENTION_CUTOFF);
|
||||
|
||||
const [countSql] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(countSql).toContain('action');
|
||||
});
|
||||
|
||||
it('should apply outcome filter', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
await repo.findAll({ page: 1, limit: 50, outcome: 'failure' }, RETENTION_CUTOFF);
|
||||
|
||||
const [countSql] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(countSql).toContain('outcome');
|
||||
});
|
||||
|
||||
it('should apply fromDate filter', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
await repo.findAll(
|
||||
{ page: 1, limit: 50, fromDate: '2026-03-01T00:00:00Z' },
|
||||
RETENTION_CUTOFF,
|
||||
);
|
||||
|
||||
const [countSql] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(countSql).toContain('timestamp');
|
||||
});
|
||||
|
||||
it('should apply toDate filter', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
await repo.findAll(
|
||||
{ page: 1, limit: 50, toDate: '2026-03-31T23:59:59Z' },
|
||||
RETENTION_CUTOFF,
|
||||
);
|
||||
|
||||
const [countSql] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(countSql).toContain('timestamp');
|
||||
});
|
||||
|
||||
it('should return empty list when no events exist', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.findAll({ page: 1, limit: 50 }, RETENTION_CUTOFF);
|
||||
|
||||
expect(result.total).toBe(0);
|
||||
expect(result.events).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
256
tests/unit/repositories/CredentialRepository.test.ts
Normal file
256
tests/unit/repositories/CredentialRepository.test.ts
Normal file
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Unit tests for src/repositories/CredentialRepository.ts
|
||||
* Uses a mocked pg.Pool — no real database connection.
|
||||
*/
|
||||
|
||||
import { Pool } from 'pg';
|
||||
import { CredentialRepository } from '../../../src/repositories/CredentialRepository';
|
||||
import { ICredential, ICredentialRow, ICredentialListFilters } from '../../../src/types/index';
|
||||
|
||||
jest.mock('pg', () => ({
|
||||
Pool: jest.fn().mockImplementation(() => ({
|
||||
query: jest.fn(),
|
||||
connect: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const CREDENTIAL_ROW = {
|
||||
credential_id: 'cred-0000-0000-0000-000000000001',
|
||||
client_id: 'agent-0000-0000-0000-000000000001',
|
||||
secret_hash: '$2b$10$hashedSecret',
|
||||
status: 'active',
|
||||
created_at: new Date('2026-03-28T09:00:00Z'),
|
||||
expires_at: null,
|
||||
revoked_at: null,
|
||||
};
|
||||
|
||||
const EXPECTED_CREDENTIAL: ICredential = {
|
||||
credentialId: CREDENTIAL_ROW.credential_id,
|
||||
clientId: CREDENTIAL_ROW.client_id,
|
||||
status: 'active',
|
||||
createdAt: CREDENTIAL_ROW.created_at,
|
||||
expiresAt: null,
|
||||
revokedAt: null,
|
||||
};
|
||||
|
||||
const EXPECTED_CREDENTIAL_ROW: ICredentialRow = {
|
||||
...EXPECTED_CREDENTIAL,
|
||||
secretHash: CREDENTIAL_ROW.secret_hash,
|
||||
};
|
||||
|
||||
// ─── suite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('CredentialRepository', () => {
|
||||
let pool: jest.Mocked<Pool>;
|
||||
let repo: CredentialRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
pool = new Pool() as jest.Mocked<Pool>;
|
||||
repo = new CredentialRepository(pool);
|
||||
});
|
||||
|
||||
// ── create ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('create()', () => {
|
||||
it('should insert a credential row and return ICredential without secret hash', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [CREDENTIAL_ROW], rowCount: 1 });
|
||||
|
||||
const result = await repo.create(
|
||||
CREDENTIAL_ROW.client_id,
|
||||
CREDENTIAL_ROW.secret_hash,
|
||||
null,
|
||||
);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledTimes(1);
|
||||
const [sql, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('INSERT INTO credentials');
|
||||
expect(params).toContain(CREDENTIAL_ROW.client_id);
|
||||
expect(params).toContain(CREDENTIAL_ROW.secret_hash);
|
||||
|
||||
// Secret hash must NOT be on the returned ICredential
|
||||
expect(result).toMatchObject(EXPECTED_CREDENTIAL);
|
||||
expect((result as ICredentialRow).secretHash).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should pass expiresAt when provided', async () => {
|
||||
const expiresAt = new Date('2027-01-01T00:00:00Z');
|
||||
const rowWithExpiry = { ...CREDENTIAL_ROW, expires_at: expiresAt };
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [rowWithExpiry], rowCount: 1 });
|
||||
|
||||
const result = await repo.create(CREDENTIAL_ROW.client_id, CREDENTIAL_ROW.secret_hash, expiresAt);
|
||||
|
||||
const [, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(params).toContain(expiresAt);
|
||||
expect(result.expiresAt).toEqual(expiresAt);
|
||||
});
|
||||
});
|
||||
|
||||
// ── findById ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('findById()', () => {
|
||||
it('should return ICredentialRow (with secretHash) when found', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [CREDENTIAL_ROW], rowCount: 1 });
|
||||
|
||||
const result = await repo.findById(CREDENTIAL_ROW.credential_id);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledWith(
|
||||
expect.stringContaining('credential_id'),
|
||||
[CREDENTIAL_ROW.credential_id],
|
||||
);
|
||||
expect(result).toMatchObject(EXPECTED_CREDENTIAL_ROW);
|
||||
expect(result?.secretHash).toBe(CREDENTIAL_ROW.secret_hash);
|
||||
});
|
||||
|
||||
it('should return null when not found', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.findById('nonexistent');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── findByAgentId ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe('findByAgentId()', () => {
|
||||
it('should return paginated credentials for an agent', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '1' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [CREDENTIAL_ROW], rowCount: 1 });
|
||||
|
||||
const filters: ICredentialListFilters = { page: 1, limit: 20 };
|
||||
const result = await repo.findByAgentId(CREDENTIAL_ROW.client_id, filters);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledTimes(2);
|
||||
expect(result.total).toBe(1);
|
||||
expect(result.credentials).toHaveLength(1);
|
||||
expect(result.credentials[0]).toMatchObject(EXPECTED_CREDENTIAL);
|
||||
});
|
||||
|
||||
it('should apply status filter when provided', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const filters: ICredentialListFilters = { page: 1, limit: 20, status: 'revoked' };
|
||||
const result = await repo.findByAgentId(CREDENTIAL_ROW.client_id, filters);
|
||||
|
||||
const [countSql] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(countSql).toContain('status');
|
||||
expect(result.total).toBe(0);
|
||||
expect(result.credentials).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return empty list when no credentials exist', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '0' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.findByAgentId('agent-no-creds', { page: 1, limit: 20 });
|
||||
|
||||
expect(result.total).toBe(0);
|
||||
expect(result.credentials).toEqual([]);
|
||||
});
|
||||
|
||||
it('should not include secretHash in returned credentials', async () => {
|
||||
(pool.query as jest.Mock)
|
||||
.mockResolvedValueOnce({ rows: [{ count: '1' }], rowCount: 1 })
|
||||
.mockResolvedValueOnce({ rows: [CREDENTIAL_ROW], rowCount: 1 });
|
||||
|
||||
const result = await repo.findByAgentId(CREDENTIAL_ROW.client_id, { page: 1, limit: 20 });
|
||||
|
||||
expect((result.credentials[0] as ICredentialRow).secretHash).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ── updateHash ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('updateHash()', () => {
|
||||
it('should update the secret hash and return ICredential', async () => {
|
||||
const newHash = '$2b$10$newHash';
|
||||
const updatedRow = { ...CREDENTIAL_ROW, secret_hash: newHash };
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [updatedRow], rowCount: 1 });
|
||||
|
||||
const result = await repo.updateHash(CREDENTIAL_ROW.credential_id, newHash, null);
|
||||
|
||||
expect(pool.query).toHaveBeenCalledTimes(1);
|
||||
const [sql, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('secret_hash');
|
||||
expect(params).toContain(newHash);
|
||||
expect(params).toContain(CREDENTIAL_ROW.credential_id);
|
||||
expect(result).toMatchObject(EXPECTED_CREDENTIAL);
|
||||
});
|
||||
|
||||
it('should return null when credential is not found', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.updateHash('nonexistent', '$2b$10$hash', null);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should pass new expiresAt when provided', async () => {
|
||||
const newExpiry = new Date('2028-01-01T00:00:00Z');
|
||||
const updatedRow = { ...CREDENTIAL_ROW, expires_at: newExpiry };
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [updatedRow], rowCount: 1 });
|
||||
|
||||
const result = await repo.updateHash(CREDENTIAL_ROW.credential_id, '$2b$10$hash', newExpiry);
|
||||
|
||||
const [, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(params).toContain(newExpiry);
|
||||
expect(result?.expiresAt).toEqual(newExpiry);
|
||||
});
|
||||
});
|
||||
|
||||
// ── revoke ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('revoke()', () => {
|
||||
it('should set status to revoked and return ICredential', async () => {
|
||||
const revokedAt = new Date('2026-03-28T10:00:00Z');
|
||||
const revokedRow = { ...CREDENTIAL_ROW, status: 'revoked', revoked_at: revokedAt };
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [revokedRow], rowCount: 1 });
|
||||
|
||||
const result = await repo.revoke(CREDENTIAL_ROW.credential_id);
|
||||
|
||||
const [sql, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('revoked');
|
||||
expect(params).toContain(CREDENTIAL_ROW.credential_id);
|
||||
expect(result?.status).toBe('revoked');
|
||||
expect(result?.revokedAt).toEqual(revokedAt);
|
||||
});
|
||||
|
||||
it('should return null when credential is not found', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.revoke('nonexistent');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── revokeAllForAgent ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('revokeAllForAgent()', () => {
|
||||
it('should return the count of revoked credentials', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 3 });
|
||||
|
||||
const count = await repo.revokeAllForAgent(CREDENTIAL_ROW.client_id);
|
||||
|
||||
const [sql, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('revoked');
|
||||
expect(params).toContain(CREDENTIAL_ROW.client_id);
|
||||
expect(count).toBe(3);
|
||||
});
|
||||
|
||||
it('should return 0 when no active credentials exist', async () => {
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: null });
|
||||
|
||||
const count = await repo.revokeAllForAgent('agent-no-creds');
|
||||
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
175
tests/unit/repositories/TokenRepository.test.ts
Normal file
175
tests/unit/repositories/TokenRepository.test.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Unit tests for src/repositories/TokenRepository.ts
|
||||
* Uses mocked pg.Pool and Redis client — no real infrastructure.
|
||||
*/
|
||||
|
||||
import { Pool } from 'pg';
|
||||
import { RedisClientType } from 'redis';
|
||||
import { TokenRepository } from '../../../src/repositories/TokenRepository';
|
||||
|
||||
jest.mock('pg', () => ({
|
||||
Pool: jest.fn().mockImplementation(() => ({
|
||||
query: jest.fn(),
|
||||
connect: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildMockRedis(): jest.Mocked<Pick<RedisClientType, 'get' | 'set' | 'incr' | 'expire'>> {
|
||||
return {
|
||||
get: jest.fn(),
|
||||
set: jest.fn(),
|
||||
incr: jest.fn(),
|
||||
expire: jest.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── suite ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('TokenRepository', () => {
|
||||
let pool: jest.Mocked<Pool>;
|
||||
let redis: ReturnType<typeof buildMockRedis>;
|
||||
let repo: TokenRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
pool = new Pool() as jest.Mocked<Pool>;
|
||||
redis = buildMockRedis();
|
||||
repo = new TokenRepository(pool, redis as unknown as RedisClientType);
|
||||
});
|
||||
|
||||
// ── addToRevocationList ───────────────────────────────────────────────────────
|
||||
|
||||
describe('addToRevocationList()', () => {
|
||||
it('should write to Redis with correct key and TTL, then insert to DB', async () => {
|
||||
redis.set.mockResolvedValue('OK');
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 1 });
|
||||
|
||||
const jti = 'test-jti-001';
|
||||
const expiresAt = new Date(Date.now() + 3600_000); // 1 hour from now
|
||||
await repo.addToRevocationList(jti, expiresAt);
|
||||
|
||||
// Redis set call
|
||||
expect(redis.set).toHaveBeenCalledTimes(1);
|
||||
const [redisKey, value, options] = redis.set.mock.calls[0] as [string, string, { EX: number }];
|
||||
expect(redisKey).toBe(`revoked:${jti}`);
|
||||
expect(value).toBe('1');
|
||||
expect(options.EX).toBeGreaterThan(0);
|
||||
|
||||
// DB insert call
|
||||
expect(pool.query).toHaveBeenCalledTimes(1);
|
||||
const [sql, params] = (pool.query as jest.Mock).mock.calls[0] as [string, unknown[]];
|
||||
expect(sql).toContain('INSERT INTO token_revocations');
|
||||
expect(params).toContain(jti);
|
||||
expect(params).toContain(expiresAt);
|
||||
});
|
||||
|
||||
it('should use a minimum TTL of 1 second for already-expired tokens', async () => {
|
||||
redis.set.mockResolvedValue('OK');
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 1 });
|
||||
|
||||
const jti = 'expired-jti';
|
||||
const expiresAt = new Date(Date.now() - 5000); // already expired
|
||||
await repo.addToRevocationList(jti, expiresAt);
|
||||
|
||||
const [, , options] = redis.set.mock.calls[0] as [string, string, { EX: number }];
|
||||
expect(options.EX).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ── isRevoked ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('isRevoked()', () => {
|
||||
it('should return true immediately when Redis has the key', async () => {
|
||||
redis.get.mockResolvedValue('1');
|
||||
|
||||
const result = await repo.isRevoked('revoked-jti');
|
||||
|
||||
expect(result).toBe(true);
|
||||
// DB should NOT be queried
|
||||
expect(pool.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should fall back to DB and return true when found there', async () => {
|
||||
redis.get.mockResolvedValue(null);
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({
|
||||
rows: [{ jti: 'db-revoked-jti', expires_at: new Date(), revoked_at: new Date() }],
|
||||
rowCount: 1,
|
||||
});
|
||||
|
||||
const result = await repo.isRevoked('db-revoked-jti');
|
||||
|
||||
expect(redis.get).toHaveBeenCalledTimes(1);
|
||||
expect(pool.query).toHaveBeenCalledTimes(1);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when neither Redis nor DB has the key', async () => {
|
||||
redis.get.mockResolvedValue(null);
|
||||
(pool.query as jest.Mock).mockResolvedValueOnce({ rows: [], rowCount: 0 });
|
||||
|
||||
const result = await repo.isRevoked('valid-jti');
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ── incrementMonthlyCount ─────────────────────────────────────────────────────
|
||||
|
||||
describe('incrementMonthlyCount()', () => {
|
||||
it('should increment the Redis key and return the new count', async () => {
|
||||
redis.incr.mockResolvedValue(5);
|
||||
redis.expire.mockResolvedValue(true);
|
||||
|
||||
const count = await repo.incrementMonthlyCount('client-001');
|
||||
|
||||
expect(redis.incr).toHaveBeenCalledTimes(1);
|
||||
const [key] = redis.incr.mock.calls[0] as [string];
|
||||
expect(key).toMatch(/^monthly:tokens:client-001:/);
|
||||
expect(count).toBe(5);
|
||||
});
|
||||
|
||||
it('should set TTL when count becomes 1 (first token of the month)', async () => {
|
||||
redis.incr.mockResolvedValue(1);
|
||||
redis.expire.mockResolvedValue(true);
|
||||
|
||||
await repo.incrementMonthlyCount('client-new');
|
||||
|
||||
expect(redis.expire).toHaveBeenCalledTimes(1);
|
||||
const [, ttl] = redis.expire.mock.calls[0] as [string, number];
|
||||
expect(ttl).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should NOT set TTL when count is greater than 1', async () => {
|
||||
redis.incr.mockResolvedValue(10);
|
||||
|
||||
await repo.incrementMonthlyCount('client-existing');
|
||||
|
||||
expect(redis.expire).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ── getMonthlyCount ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('getMonthlyCount()', () => {
|
||||
it('should return the count from Redis', async () => {
|
||||
redis.get.mockResolvedValue('42');
|
||||
|
||||
const count = await repo.getMonthlyCount('client-001');
|
||||
|
||||
expect(redis.get).toHaveBeenCalledTimes(1);
|
||||
const [key] = redis.get.mock.calls[0] as [string];
|
||||
expect(key).toMatch(/^monthly:tokens:client-001:/);
|
||||
expect(count).toBe(42);
|
||||
});
|
||||
|
||||
it('should return 0 when the Redis key does not exist', async () => {
|
||||
redis.get.mockResolvedValue(null);
|
||||
|
||||
const count = await repo.getMonthlyCount('client-no-tokens');
|
||||
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user