/**
* API Authentication Guard Tests
*/
import { describe, it, expect, afterEach } from 'vitest';
import { validateApiAuth } from '../../src/middleware/api-auth.js';
describe('validateApiAuth', () => {
const originalEnv = process.env['GATEWAY_API_KEY'];
afterEach(() => {
if (originalEnv === undefined) {
delete process.env['GATEWAY_API_KEY'];
} else {
process.env['GATEWAY_API_KEY'] = originalEnv;
}
});
it('allows public paths without auth', () => {
process.env['GATEWAY_API_KEY'] = 'secret-key';
const result1 = validateApiAuth('/.well-known/ucp', {});
expect(result1.authenticated).toBe(true);
const result2 = validateApiAuth('/.well-known/agent.json', {});
expect(result2.authenticated).toBe(true);
});
it('allows all requests when GATEWAY_API_KEY is not set', () => {
delete process.env['GATEWAY_API_KEY'];
const result = validateApiAuth('/ucp/v1/catalog', {});
expect(result.authenticated).toBe(true);
});
it('rejects requests without Authorization header when key is set', () => {
process.env['GATEWAY_API_KEY'] = 'secret-key';
const result = validateApiAuth('/ucp/v1/catalog', {});
expect(result.authenticated).toBe(false);
expect(result.error).toContain('Missing');
});
it('rejects requests with wrong Authorization scheme', () => {
process.env['GATEWAY_API_KEY'] = 'secret-key';
const result = validateApiAuth('/ucp/v1/catalog', {
authorization: 'Basic abc123',
});
expect(result.authenticated).toBe(false);
expect(result.error).toContain('Bearer');
});
it('rejects requests with invalid API key', () => {
process.env['GATEWAY_API_KEY'] = 'secret-key';
const result = validateApiAuth('/ucp/v1/catalog', {
authorization: 'Bearer wrong-key',
});
expect(result.authenticated).toBe(false);
expect(result.error).toContain('Invalid');
});
it('accepts requests with valid API key', () => {
process.env['GATEWAY_API_KEY'] = 'secret-key';
const result = validateApiAuth('/ucp/v1/catalog', {
authorization: 'Bearer secret-key',
});
expect(result.authenticated).toBe(true);
});
it('handles case-insensitive Authorization header', () => {
process.env['GATEWAY_API_KEY'] = 'my-key';
const result = validateApiAuth('/mcp', {
Authorization: 'Bearer my-key',
});
expect(result.authenticated).toBe(true);
});
it('rejects keys of different length safely', () => {
process.env['GATEWAY_API_KEY'] = 'short';
const result = validateApiAuth('/a2a', {
authorization: 'Bearer a-very-long-different-key',
});
expect(result.authenticated).toBe(false);
});
});