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:
SentryAgent.ai Developer
2026-03-28 09:14:41 +00:00
parent 245f8df427
commit d3530285b9
78 changed files with 20590 additions and 1 deletions

View File

@@ -0,0 +1,115 @@
/**
* Unit tests for src/middleware/auth.ts
*/
import crypto from 'crypto';
import { Request, Response, NextFunction } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { signToken } from '../../../src/utils/jwt';
import { ITokenPayload } from '../../../src/types/index';
import { AuthenticationError } from '../../../src/utils/errors';
// Generate test RSA keys
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
});
// Mock environment and Redis before importing auth middleware
jest.mock('../../../src/cache/redis', () => ({
getRedisClient: jest.fn().mockResolvedValue({
get: jest.fn().mockResolvedValue(null), // Not revoked by default
}),
}));
// We need to set env vars before importing the middleware
process.env['JWT_PUBLIC_KEY'] = publicKey;
// Import after setting env
import { authMiddleware } from '../../../src/middleware/auth';
import { getRedisClient } from '../../../src/cache/redis';
const mockGetRedisClient = getRedisClient as jest.Mock;
function makeTestToken(overrides: Partial<ITokenPayload> = {}): string {
const payload: Omit<ITokenPayload, 'iat' | 'exp'> = {
sub: uuidv4(),
client_id: uuidv4(),
scope: 'agents:read',
jti: uuidv4(),
...overrides,
};
return signToken(payload, privateKey);
}
function makeReq(authHeader?: string): Partial<Request> {
return {
headers: authHeader ? { authorization: authHeader } : {},
ip: '127.0.0.1',
};
}
describe('authMiddleware', () => {
let next: jest.MockedFunction<NextFunction>;
beforeEach(() => {
next = jest.fn();
mockGetRedisClient.mockResolvedValue({
get: jest.fn().mockResolvedValue(null),
});
});
it('should call next() and set req.user for a valid token', async () => {
const token = makeTestToken();
const req = makeReq(`Bearer ${token}`) as Request;
const res = {} as Response;
await authMiddleware(req, res, next);
expect(next).toHaveBeenCalledWith();
expect(req.user).toBeDefined();
expect(req.user?.sub).toBeTruthy();
});
it('should call next(AuthenticationError) when Authorization header is missing', async () => {
const req = makeReq() as Request;
const res = {} as Response;
await authMiddleware(req, res, next);
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
});
it('should call next(AuthenticationError) when header does not start with Bearer', async () => {
const req = makeReq('Basic dXNlcjpwYXNz') as Request;
const res = {} as Response;
await authMiddleware(req, res, next);
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
});
it('should call next(AuthenticationError) for an invalid JWT', async () => {
const req = makeReq('Bearer invalid.jwt.token') as Request;
const res = {} as Response;
await authMiddleware(req, res, next);
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
});
it('should call next(AuthenticationError) for a revoked token', async () => {
mockGetRedisClient.mockResolvedValue({
get: jest.fn().mockResolvedValue('1'), // Token is revoked
});
const token = makeTestToken();
const req = makeReq(`Bearer ${token}`) as Request;
const res = {} as Response;
await authMiddleware(req, res, next);
expect(next).toHaveBeenCalledWith(expect.any(AuthenticationError));
});
});

View File

@@ -0,0 +1,182 @@
/**
* Unit tests for src/middleware/errorHandler.ts
*/
import { Request, Response, NextFunction } from 'express';
import { errorHandler } from '../../../src/middleware/errorHandler';
import {
ValidationError,
AgentNotFoundError,
AgentAlreadyExistsError,
AgentAlreadyDecommissionedError,
CredentialNotFoundError,
CredentialAlreadyRevokedError,
CredentialError,
AuthenticationError,
AuthorizationError,
RateLimitError,
FreeTierLimitError,
InsufficientScopeError,
AuditEventNotFoundError,
RetentionWindowError,
} from '../../../src/utils/errors';
function makeRes(): { status: jest.Mock; json: jest.Mock } {
const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
};
return res;
}
const req = {} as Request;
const next = jest.fn() as jest.MockedFunction<NextFunction>;
describe('errorHandler', () => {
beforeEach(() => jest.clearAllMocks());
it('should return 400 for ValidationError', () => {
const res = makeRes();
errorHandler(new ValidationError('bad input'), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ code: 'VALIDATION_ERROR' }));
});
it('should return 404 for AgentNotFoundError', () => {
const res = makeRes();
errorHandler(new AgentNotFoundError(), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(404);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ code: 'AGENT_NOT_FOUND' }));
});
it('should return 409 for AgentAlreadyExistsError', () => {
const res = makeRes();
errorHandler(new AgentAlreadyExistsError('test@test.com'), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(409);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ code: 'AGENT_ALREADY_EXISTS' }));
});
it('should return 409 for AgentAlreadyDecommissionedError', () => {
const res = makeRes();
errorHandler(new AgentAlreadyDecommissionedError('id'), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(409);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'AGENT_ALREADY_DECOMMISSIONED' }),
);
});
it('should return 404 for CredentialNotFoundError', () => {
const res = makeRes();
errorHandler(new CredentialNotFoundError(), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(404);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'CREDENTIAL_NOT_FOUND' }),
);
});
it('should return 409 for CredentialAlreadyRevokedError', () => {
const res = makeRes();
errorHandler(
new CredentialAlreadyRevokedError('cred-id', new Date().toISOString()),
req,
res as unknown as Response,
next,
);
expect(res.status).toHaveBeenCalledWith(409);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'CREDENTIAL_ALREADY_REVOKED' }),
);
});
it('should return 400 for CredentialError', () => {
const res = makeRes();
errorHandler(new CredentialError('error', 'AGENT_NOT_ACTIVE'), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(400);
});
it('should return 401 for AuthenticationError', () => {
const res = makeRes();
errorHandler(new AuthenticationError(), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ code: 'UNAUTHORIZED' }));
});
it('should return 403 for AuthorizationError', () => {
const res = makeRes();
errorHandler(new AuthorizationError(), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ code: 'FORBIDDEN' }));
});
it('should return 429 for RateLimitError', () => {
const res = makeRes();
errorHandler(new RateLimitError(), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(429);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'RATE_LIMIT_EXCEEDED' }),
);
});
it('should return 403 for FreeTierLimitError', () => {
const res = makeRes();
errorHandler(new FreeTierLimitError('Limit reached'), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'FREE_TIER_LIMIT_EXCEEDED' }),
);
});
it('should return 403 for InsufficientScopeError', () => {
const res = makeRes();
errorHandler(new InsufficientScopeError('audit:read'), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'INSUFFICIENT_SCOPE' }),
);
});
it('should return 404 for AuditEventNotFoundError', () => {
const res = makeRes();
errorHandler(new AuditEventNotFoundError(), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(404);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'AUDIT_EVENT_NOT_FOUND' }),
);
});
it('should return 400 for RetentionWindowError', () => {
const res = makeRes();
errorHandler(
new RetentionWindowError(90, '2025-12-28T00:00:00.000Z'),
req,
res as unknown as Response,
next,
);
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'RETENTION_WINDOW_EXCEEDED' }),
);
});
it('should return 500 for unknown errors', () => {
const res = makeRes();
errorHandler(new Error('unexpected'), req, res as unknown as Response, next);
expect(res.status).toHaveBeenCalledWith(500);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ code: 'INTERNAL_SERVER_ERROR' }),
);
});
it('should include details in the response when present', () => {
const res = makeRes();
errorHandler(
new ValidationError('bad', { field: 'email' }),
req,
res as unknown as Response,
next,
);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ details: { field: 'email' } }),
);
});
});

View File

@@ -0,0 +1,93 @@
/**
* Unit tests for src/middleware/rateLimit.ts
*/
import { Request, Response, NextFunction } from 'express';
import { RateLimitError } from '../../../src/utils/errors';
const mockIncr = jest.fn();
const mockExpire = jest.fn();
jest.mock('../../../src/cache/redis', () => ({
getRedisClient: jest.fn().mockResolvedValue({
incr: mockIncr,
expire: mockExpire,
}),
}));
import { rateLimitMiddleware } from '../../../src/middleware/rateLimit';
function buildMocks(clientId?: string): {
req: Partial<Request>;
res: Partial<Response>;
next: NextFunction;
} {
const res: Partial<Response> = {
setHeader: jest.fn(),
};
return {
req: {
user: clientId ? { client_id: clientId, sub: clientId, scope: '', jti: '', iat: 0, exp: 0 } : undefined,
ip: '127.0.0.1',
},
res,
next: jest.fn() as NextFunction,
};
}
describe('rateLimitMiddleware', () => {
beforeEach(() => {
jest.clearAllMocks();
mockExpire.mockResolvedValue(1);
});
it('should set X-RateLimit-* headers and call next() when counter is under the limit', async () => {
mockIncr.mockResolvedValue(1);
const { req, res, next } = buildMocks('agent-123');
await rateLimitMiddleware(req as Request, res as Response, next);
expect(res.setHeader).toHaveBeenCalledWith('X-RateLimit-Limit', 100);
expect(res.setHeader).toHaveBeenCalledWith('X-RateLimit-Remaining', 99);
expect(res.setHeader).toHaveBeenCalledWith('X-RateLimit-Reset', expect.any(Number));
expect(next).toHaveBeenCalledWith();
expect(next).not.toHaveBeenCalledWith(expect.any(Error));
});
it('should call next(RateLimitError) when counter equals 100', async () => {
mockIncr.mockResolvedValue(101);
const { req, res, next } = buildMocks('agent-456');
await rateLimitMiddleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalledWith(expect.any(RateLimitError));
});
it('should use req.ip as key when req.user is not set', async () => {
mockIncr.mockResolvedValue(5);
const { req, res, next } = buildMocks(); // no clientId → no req.user
await rateLimitMiddleware(req as Request, res as Response, next);
expect(mockIncr).toHaveBeenCalledWith(expect.stringContaining('127.0.0.1'));
expect(next).toHaveBeenCalledWith();
});
it('should set expire TTL only on first request (count === 1)', async () => {
mockIncr.mockResolvedValue(1);
const { req, res, next } = buildMocks('agent-789');
await rateLimitMiddleware(req as Request, res as Response, next);
expect(mockExpire).toHaveBeenCalledWith(expect.any(String), 60);
});
it('should not call expire on subsequent requests (count > 1)', async () => {
mockIncr.mockResolvedValue(50);
const { req, res, next } = buildMocks('agent-789');
await rateLimitMiddleware(req as Request, res as Response, next);
expect(mockExpire).not.toHaveBeenCalled();
});
});