Files
sencho/backend/src/__tests__/agents-routes.test.ts
T
Anso f6a7898798 refactor(backend): add route tests then extract settings, scheduled-tasks, agents (phase 4b) (#737)
Round B of Phase 4. Writes integration tests for three under-covered
route groups BEFORE extracting them, then does the extraction once the
new tests pass against the monolith. index.ts drops from ~4,206 to
~3,678 lines.

New test coverage (42 new assertions):
- settings-routes.test.ts (14) — auth, admin gating, private-key stripping,
  allowlist, single-key write, bulk PATCH validation + partial update
- scheduled-tasks-routes.test.ts (18) — list/create/get/toggle/delete/runs,
  action+target_type matrix, cron validation, tier gating on non-admin
- agents-routes.test.ts (10) — GET/POST, admin gating, channel type +
  HTTPS URL validation, boolean enabled check, upsert semantics

Each suite was verified against the inline monolith first, then the
route extraction was performed byte-for-byte and all suites re-run to
ensure no regression.

New route files:
- routes/settings.ts — GET/POST/PATCH with PRIVATE_SETTINGS_KEYS strip,
  ALLOWED_SETTING_KEYS allowlist, and SettingsPatchSchema zod bulk schema
- routes/scheduledTasks.ts — 9 endpoints (list, create, get, update,
  delete, toggle, run-now, runs history, runs CSV export). File-local
  helpers parseTaskId, validateActionTarget, validateOptionalFields
  collapse duplication across create+update handlers. Uses shared
  escapeCsvField from utils/csv.ts.
- routes/agents.ts — notification-channel GET/POST. Owns
  NOTIFICATION_CHANNEL_TYPES and validateHttpsUrl locally because the
  notification-routes block still inlines identical copies; the helpers
  will converge once those routes extract in a later slice.
2026-04-23 21:22:39 -04:00

129 lines
4.8 KiB
TypeScript

/**
* Integration tests for /api/agents (notification-channel configuration).
* Locks down auth, admin gating, and validation before extraction.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
import request from 'supertest';
import bcrypt from 'bcrypt';
import { setupTestDb, cleanupTestDb, loginAsTestAdmin } from './helpers/setupTestDb';
let tmpDir: string;
let app: import('express').Express;
let DatabaseService: typeof import('../services/DatabaseService').DatabaseService;
let adminCookie: string;
let viewerCookie: string;
beforeAll(async () => {
tmpDir = await setupTestDb();
({ DatabaseService } = await import('../services/DatabaseService'));
const { LicenseService } = await import('../services/LicenseService');
vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('paid');
vi.spyOn(LicenseService.getInstance(), 'getVariant').mockReturnValue('admiral');
vi.spyOn(LicenseService.getInstance(), 'getSeatLimits').mockReturnValue({ maxAdmins: null, maxViewers: null });
({ app } = await import('../index'));
adminCookie = await loginAsTestAdmin(app);
const viewerHash = await bcrypt.hash('viewerpass', 1);
DatabaseService.getInstance().addUser({ username: 'agents-viewer', password_hash: viewerHash, role: 'viewer' });
const viewerRes = await request(app).post('/api/auth/login').send({ username: 'agents-viewer', password: 'viewerpass' });
const cookies = viewerRes.headers['set-cookie'] as string | string[];
viewerCookie = Array.isArray(cookies) ? cookies[0] : cookies;
});
afterAll(() => cleanupTestDb(tmpDir));
beforeEach(() => {
const db = DatabaseService.getInstance().getDb();
db.prepare('DELETE FROM agents').run();
});
describe('GET /api/agents', () => {
it('rejects unauthenticated requests with 401', async () => {
const res = await request(app).get('/api/agents');
expect(res.status).toBe(401);
});
it('returns empty array when no agents configured', async () => {
const res = await request(app).get('/api/agents').set('Cookie', adminCookie);
expect(res.status).toBe(200);
expect(res.body).toEqual([]);
});
it('lists configured agents for authenticated users', async () => {
const db = DatabaseService.getInstance();
db.upsertAgent(1, { type: 'discord', url: 'https://discord.com/api/webhooks/abc/def', enabled: true });
const res = await request(app).get('/api/agents').set('Cookie', adminCookie);
expect(res.status).toBe(200);
expect(res.body.length).toBe(1);
expect(res.body[0].type).toBe('discord');
});
});
describe('POST /api/agents', () => {
const validPayload = {
type: 'discord',
url: 'https://discord.com/api/webhooks/1/token',
enabled: true,
};
it('rejects unauthenticated requests with 401', async () => {
const res = await request(app).post('/api/agents').send(validPayload);
expect(res.status).toBe(401);
});
it('rejects non-admin users with 403', async () => {
const res = await request(app).post('/api/agents').set('Cookie', viewerCookie).send(validPayload);
expect(res.status).toBe(403);
});
it('rejects unsupported channel types with 400', async () => {
const res = await request(app).post('/api/agents').set('Cookie', adminCookie).send({
...validPayload, type: 'carrier-pigeon',
});
expect(res.status).toBe(400);
});
it('rejects non-HTTPS urls with 400', async () => {
const res = await request(app).post('/api/agents').set('Cookie', adminCookie).send({
...validPayload, url: 'http://example.com/hook',
});
expect(res.status).toBe(400);
expect(res.body.error).toMatch(/url/);
});
it('rejects non-boolean enabled with 400', async () => {
const res = await request(app).post('/api/agents').set('Cookie', adminCookie).send({
...validPayload, enabled: 'yes',
});
expect(res.status).toBe(400);
});
it('upserts a valid agent', async () => {
const res = await request(app).post('/api/agents').set('Cookie', adminCookie).send(validPayload);
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
const agents = DatabaseService.getInstance().getAgents(1);
expect(agents.length).toBe(1);
expect(agents[0].type).toBe('discord');
expect(Boolean(agents[0].enabled)).toBe(true);
});
it('replaces an existing agent of the same type (upsert)', async () => {
const db = DatabaseService.getInstance();
db.upsertAgent(1, { type: 'slack', url: 'https://hooks.slack.com/old', enabled: false });
const res = await request(app).post('/api/agents').set('Cookie', adminCookie).send({
type: 'slack', url: 'https://hooks.slack.com/new', enabled: true,
});
expect(res.status).toBe(200);
const agents = db.getAgents(1);
expect(agents.length).toBe(1);
expect(agents[0].url).toBe('https://hooks.slack.com/new');
expect(Boolean(agents[0].enabled)).toBe(true);
});
});