Files
events-hub/backend/tests/servers.test.js
T
joshuaandClaude Opus 5.5 16f69afa6f Hub 2.26.0: the Church App, demo scenarios and devotionals
The App installs from New install on app.<address>, with Accounts 1.9.0
first, and is in every product list and filter (installs, Updates).
Every product has demo data; a demo client loads a whole demo scenario
in one seed-scenario job (agent 1.7.0), and installs show whether they
are out of step with it. The Website's and App's .env from the Hub.

Devotionals: written or imported from CSV up to 3 months ahead in the
free translations (KJV, BSB), and GET /api/v2/devotionals for App
licences. An alert when an App's active-member band is above its tier.

Contracts 1.23.0 vendored. Migration 20261130120000_app_scenarios_devotionals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:24:28 +02:00

1496 lines
113 KiB
JavaScript

// Servers and the agent (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md): joining, signed agent
// requests, jobs (signed, config sealed to the server, one at a time, missed when late), reports
// and what follows (installs, updates, batches, uninstall + export), the port list and alerts.
jest.mock('../src/config/db', () => require('./fakeDb').createFakeDb());
const mockMails = [];
jest.mock('../src/utils/mail', () => ({ sendMail: jest.fn(async m => { mockMails.push(m); }), smtpConfigured: async () => true }));
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-test-encryption-key';
process.env.FRONTEND_URL = 'https://hub.test';
const { agent, hub } = require('@crosscode/contracts');
const signing = require('@crosscode/contracts/signing');
const db = require('../src/config/db');
const servers = require('../src/utils/servers');
const jobs = require('../src/utils/jobs');
const { encrypt } = require('../src/utils/crypto');
const { generateSecret, codeAt, STEP } = require('../src/utils/totp');
const hubKey = signing.generateEd25519();
process.env.HUB_JOB_SIGNING_KEY = hubKey.privateKeyPem;
global.fetch = jest.fn(async () => { throw new Error('no network in tests'); });
const NOW = new Date('2026-11-20T08:00:00.000Z');
const H = 60 * 60 * 1000;
const keys = { ed: signing.generateEd25519(), x: signing.generateX25519() };
const totpSecret = generateSecret();
const admin = { id: 'admin-1', name: 'Joshua', totpEnabled: true, totpSecret: encrypt(totpSecret) };
const totpNow = () => codeAt(totpSecret, Math.floor(Date.now() / 1000 / STEP));
async function joinServer(mode = 'church', name = 'church-1') {
const t = await servers.createJoinToken({ name, mode }, NOW);
const reply = await servers.join({ agentApiVersion: 1, token: t.token, mode, hostname: name, agentVersion: '1.0.0', publicKeys: { ed25519: keys.ed.publicKey, x25519: keys.x.publicKey } }, NOW);
const server = await db.server.findUnique({ where: { id: reply.serverId } });
return { reply, server, token: t.token };
}
async function seed() {
for (const k of Object.keys(db.tables)) db.tables[k].length = 0;
mockMails.length = 0;
servers.resetJobKeyForTests();
await db.setting.create({ data: { key: 'alert_email', value: 'joshua@crosscode.test' } });
await db.customer.create({ data: { id: 'cust-1', name: 'Hope Church', billingCycle: 'none' } });
await db.release.create({ data: { id: 'r1', product: 'events', version: '2.3.0', notes: '- New things', releasedAt: NOW } });
await db.release.create({ data: { id: 'r2', product: 'events', version: '2.4.0', notes: '- Newer things', releasedAt: NOW } });
}
const signedReport = (job, status, extra = {}) => ({
schema: 'crosscode.agent-report/1', jobId: job.id, serverId: job.serverId, type: job.type, status,
startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), steps: [{ name: 'step', startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), outcome: status === 'succeeded' ? 'ok' : 'failed' }],
result: {}, log: ['==> done'], ...extra,
});
beforeEach(seed);
describe('joining', () => {
test('a one-time token joins a server once and returns the pinned job key', async () => {
const { reply, token } = await joinServer();
expect(agent.joinResponseSchema.safeParse(reply).success).toBe(true);
expect(reply.hubJobKey).toBe(hubKey.publicKey);
await expect(servers.join({ agentApiVersion: 1, token, mode: 'church', hostname: 'x', agentVersion: '1.0.0', publicKeys: { ed25519: keys.ed.publicKey, x25519: keys.x.publicKey } }, NOW)).rejects.toMatchObject({ code: 'BAD_TOKEN' });
});
test('an expired token or the wrong mode is refused', async () => {
const t = await servers.createJoinToken({ name: 'late', mode: 'church' }, NOW);
const body = { agentApiVersion: 1, token: t.token, mode: 'church', hostname: 'x', agentVersion: '1.0.0', publicKeys: { ed25519: keys.ed.publicKey, x25519: keys.x.publicKey } };
await expect(servers.join(body, new Date(NOW.getTime() + 2 * H))).rejects.toMatchObject({ code: 'BAD_TOKEN' });
await expect(servers.join({ ...body, mode: 'central' }, NOW)).rejects.toMatchObject({ code: 'WRONG_MODE' });
});
test('the install command carries the token and --central', () => {
expect(servers.joinCommand('tok', 'central', 'https://hub.test')).toMatch(/install\.sh \| sudo bash -s -- --hub https:\/\/hub\.test --token tok --central$/);
});
});
describe('signed agent requests', () => {
const call = async (server, headers, raw) => {
const req = { headers, rawBody: raw };
let status = 200;
let body = null;
const res = { status(s) { status = s; return this; }, json(b) { body = b; return this; } };
let passed = false;
await servers.requireAgent(req, res, () => { passed = true; });
return { passed, status, body, req };
};
test('the server\'s key over the exact body passes; anything else is refused', async () => {
const { server } = await joinServer();
const raw = JSON.stringify({ agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null });
const h = signing.signAgentRequest({ serverId: server.id, privateKeyPem: keys.ed.privateKeyPem, rawBody: raw });
expect((await call(server, h, raw)).passed).toBe(true);
expect(await call(server, h, `${raw} `)).toMatchObject({ passed: false, status: 401 });
const other = signing.signAgentRequest({ serverId: server.id, privateKeyPem: signing.generateEd25519().privateKeyPem, rawBody: raw });
expect(await call(server, other, raw)).toMatchObject({ passed: false, status: 401 });
expect(await call(server, { ...h, [agent.AGENT_HEADERS.server]: 'srv_unknown000' }, raw)).toMatchObject({ passed: false, status: 404 });
});
});
describe('jobs', () => {
test('a new install: licence, two ports, an install job the agent can verify and open', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback', DB_ADMIN_URL: 'postgresql://admin:pw@10.0.0.5/postgres' });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za', adminName: 'Jane', adminEmail: 'jane@hope.test' }, admin, NOW);
expect(deployment).toMatchObject({ shortName: 'hope', webPort: 20000, apiPort: 20001, status: 'installing' });
const polled = await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW);
expect(polled.jobs).toHaveLength(1);
const job = polled.jobs[0];
expect(signing.verifyJob(job, hubKey.publicKey)).toBe(true);
expect(agent.agentJobSchema.safeParse(job).success).toBe(true);
expect(job.args).toMatchObject({ church: 'hope', versions: { events: 'events@2.4.0' }, ports: { events: { web: 20000, api: 20001 } } });
const config = signing.openConfig(job.config, keys.x.privateKeyPem);
expect(config.server).toMatchObject({ TRUST_PROXY: 'loopback', DB_ADMIN_URL: 'postgresql://admin:pw@10.0.0.5/postgres' });
expect(config.install.events).toMatchObject({ HUB_ADMIN_EMAIL: 'jane@hope.test' });
expect(config.install.events.HUB_LICENCE_KEY).toMatch(/^CEH-/);
expect(JSON.stringify(job)).not.toContain('pw@');
// One at a time: nothing else while it runs.
expect((await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs).toEqual([]);
});
test('a new install is refused while a server setting is one the apps can\'t start with (TRUST_PROXY=TRUE)', async () => {
const { server } = await joinServer();
// Saved before Hub 2.3.3, which refuses it on save.
await servers.setServerConfig(server.id, { TRUST_PROXY: 'TRUE' });
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW))
.rejects.toMatchObject({ code: 'CONFIG_INVALID', message: expect.stringContaining('loopback') });
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW)).resolves.toBeTruthy();
});
test('a new install is refused while required server settings are missing, or the agent is offline', async () => {
const { server } = await joinServer();
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'CONFIG_MISSING', message: expect.stringContaining('TRUST_PROXY') });
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, new Date(NOW.getTime() + H))).rejects.toMatchObject({ code: 'AGENT_OFFLINE' });
});
test('a successful install waits for the proxy, asks the central server to check the ports, and sends the FastPanel email', async () => {
const { server } = await joinServer();
const central = (await joinServer('central', 'central')).server;
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs;
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: { versions: { events: 'events@2.4.0' }, key: 'nope' } }), NOW);
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toMatchObject({ status: 'waiting_for_proxy', version: '2.4.0' });
expect(await db.job.findFirst({ where: { serverId: central.id, type: 'check-ports' } })).toMatchObject({ args: { ports: [20000, 20001] } });
const mail = mockMails.find(m => m.subject.includes('Installed: hope'));
// 2.10.0: the backend location is ^~, so FastPanel's static-file rule can't take /api/…/logo.png.
expect(mail.text).toContain('location ^~ /api/ {');
expect(mail.text).toContain('proxy_pass http://127.0.0.1:20001;');
expect(mail.text).toContain('as a proxy to http://127.0.0.1:20000 (the frontend)');
expect(mail.html).toContain('location ^~ /api/ {');
expect(mail.html).toContain('href="https://hub.test/servers/installs/');
expect(await jobs.fastPanelText(await db.deployment.findUnique({ where: { id: deployment.id } }))).toContain(' location ^~ /api/ {');
});
test('Proxy done refuses a site whose /api paths with a file extension reach the frontend', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za', adminName: 'Jane', adminEmail: 'jane@hope.test' }, admin, NOW);
const answer = (status, poweredBy, json) => ({ status, headers: new Headers(poweredBy ? { 'x-powered-by': poweredBy } : {}), json: async () => json });
const site = frontendTakesFiles => async url => {
if (url.endsWith('/api/health')) return answer(200, 'Express', { version: null });
if (url.includes('/api/proxy-check.png')) return answer(404, frontendTakesFiles ? 'Next.js' : 'Express');
return answer(200, 'Next.js');
};
const refused = await jobs.proxyDone(deployment.id, NOW, site(true));
expect(refused.live).toBe(false);
expect(refused.problems.join(' ')).toContain('location ^~ /api/');
const ok = await jobs.proxyDone(deployment.id, NOW, site(false));
expect(ok).toEqual({ live: true, problems: [] });
const ready = mockMails.find(m => m.subject.includes('site is ready'));
expect(ready.html).toContain('href="https://events.hope.co.za/setup"');
expect(ready.text).toContain('Start the setup: https://events.hope.co.za/setup');
});
test('a failed install frees its ports again', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs;
await jobs.receiveReport(server, signedReport(job, 'failed'), NOW);
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toMatchObject({ status: 'failed' });
expect(await db.port.count({ where: { port: { in: [20000, 20001] } } })).toBe(0);
});
test('a job not picked up in its window is missed: nothing runs late', async () => {
const { server } = await joinServer();
const job = await jobs.makeJob(db, { serverId: server.id, type: 'status', args: {}, notBefore: NOW });
await jobs.tick(new Date(NOW.getTime() + 16 * 60 * 1000));
expect(await db.job.findUnique({ where: { id: job.id } })).toMatchObject({ status: 'missed' });
expect((await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, new Date(NOW.getTime() + 16 * 60 * 1000))).jobs).toEqual([]);
expect(mockMails.some(m => m.subject.includes('Missed job'))).toBe(true);
});
test('a job isn\'t handed out before its time', async () => {
const { server } = await joinServer();
await jobs.makeJob(db, { serverId: server.id, type: 'status', args: {}, notBefore: new Date(NOW.getTime() + H) });
expect((await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs).toEqual([]);
});
});
describe('scheduled updates (§8)', () => {
async function liveDeployments(n) {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const out = [];
for (let i = 0; i < n; i++) {
const install = await db.install.create({ data: { id: `inst-${i}`, customerId: 'cust-1', product: 'events', name: `Church ${i}`, url: `https://events.c${i}.co.za`, secret: 'x', version: '2.3.0', adminContact: { name: `Admin ${i}`, email: `admin${i}@c.test` } } });
out.push(await db.deployment.create({ data: { id: `dep-${i}`, serverId: server.id, customerId: 'cust-1', installId: install.id, product: 'events', shortName: `c${i}`, domain: `events.c${i}.co.za`, webPort: 20000 + 2 * i, apiPort: 20001 + 2 * i, status: 'live' } }));
}
return { server, deployments: out };
}
test('at least 4 hours ahead; emergency needs 15 minutes, a reason and 2FA', async () => {
const { deployments } = await liveDeployments(1);
const ids = [deployments[0].id];
await expect(jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', at: new Date(NOW.getTime() + 3 * H) }, admin, NOW)).rejects.toMatchObject({ code: 'TOO_SOON' });
await expect(jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', at: new Date(NOW.getTime() + 20 * 60 * 1000), emergency: true, totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ status: 400, message: expect.stringContaining('reason') });
await expect(jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', at: new Date(NOW.getTime() + 20 * 60 * 1000), emergency: true, reason: 'Security fix', totp: '000000' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_TOTP' });
const ok = await jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', at: new Date(NOW.getTime() + 20 * 60 * 1000), emergency: true, reason: 'Security fix', totp: totpNow() }, admin, NOW);
expect(ok.jobs[0]).toMatchObject({ emergency: true, reason: 'Security fix', args: { versions: ['events@2.4.0'] } });
});
test('the church gets an email with what\'s new and a banner straight away', async () => {
const { deployments } = await liveDeployments(1);
const at = new Date(NOW.getTime() + 5 * H);
const { jobs: [job] } = await jobs.scheduleUpdate({ deploymentIds: [deployments[0].id], version: '2.4.0', at }, admin, NOW);
expect(mockMails.find(m => m.to === 'admin0@c.test')?.text).toContain('Newer things');
const notice = await db.notice.findUnique({ where: { id: job.noticeId } });
expect(notice).toMatchObject({ allInstalls: false, installIds: ['inst-0'], showBanner: true });
});
test('a batch runs one at a time and stops at the first failure; the rest are told it\'s postponed', async () => {
const { server, deployments } = await liveDeployments(3);
const at = new Date(NOW.getTime() + 5 * H);
const { jobs: made, batchId } = await jobs.scheduleUpdate({ deploymentIds: deployments.map(d => d.id), version: '2.4.0', at }, admin, NOW);
expect(batchId).toMatch(/^batch_/);
expect(made.map(j => j.status)).toEqual(['queued', 'scheduled', 'scheduled']);
const poll = when => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, when);
const first = (await poll(at)).jobs[0];
await jobs.receiveReport(server, signedReport(first, 'succeeded'), at);
expect((await db.job.findUnique({ where: { id: made[1].id } })).status).toBe('queued');
const second = (await poll(at)).jobs[0];
expect(second.id).toBe(made[1].id);
mockMails.length = 0;
await jobs.receiveReport(server, signedReport(second, 'rolled-back'), at);
expect((await db.job.findUnique({ where: { id: made[1].id } })).status).toBe('rolled_back');
expect((await db.job.findUnique({ where: { id: made[2].id } })).status).toBe('cancelled');
expect(mockMails.find(m => m.to === 'admin1@c.test')?.subject).toContain('didn\'t go through');
expect(mockMails.find(m => m.to === 'admin2@c.test')?.subject).toContain('postponed');
expect(mockMails.some(m => m.subject.includes('Batch stopped'))).toBe(true);
});
test('uninstall: 2FA and the short name; the export goes first and its key is never stored', async () => {
const { server, deployments } = await liveDeployments(1);
const d = deployments[0];
await expect(jobs.scheduleUninstall({ deploymentId: d.id, totp: totpNow(), confirm: 'wrong' }, admin, NOW)).rejects.toMatchObject({ code: 'CONFIRM' });
const at = new Date(NOW.getTime() + 5 * H);
const { exportJob, uninstallJob } = await jobs.scheduleUninstall({ deploymentId: d.id, totp: totpNow(), confirm: 'c0', at }, admin, NOW);
expect(uninstallJob.status).toBe('scheduled');
const job = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, at)).jobs[0];
expect(job.id).toBe(exportJob.id);
await jobs.receiveExport(server, job.args.exportId, Buffer.from('encrypted bytes'));
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: { key: 'SECRET-KEY-abc', encryptedBytes: 15 } }), at);
const stored = await db.job.findUnique({ where: { id: job.id } });
expect(JSON.stringify(stored)).not.toContain('SECRET-KEY-abc');
expect(mockMails.find(m => m.to === 'admin0@c.test' && m.subject.includes('data'))?.text).toContain(`/download/${job.args.exportId}#SECRET-KEY-abc`);
expect((await db.job.findUnique({ where: { id: uninstallJob.id } })).status).toBe('queued');
const un = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, at)).jobs[0];
expect(un.args).toEqual({ church: 'c0' });
await jobs.receiveReport(server, signedReport(un, 'succeeded'), at);
expect(await db.deployment.findUnique({ where: { id: d.id } })).toMatchObject({ status: 'removed' });
expect((await db.install.findUnique({ where: { id: 'inst-0' } })).releasedAt).toEqual(at);
expect(await db.job.findFirst({ where: { type: 'purge', deploymentId: d.id } })).toBeTruthy();
});
test('uninstall: when the export fails the uninstall is cancelled and the install is live again, not stuck uninstalling', async () => {
const { server, deployments } = await liveDeployments(1);
const d = deployments[0];
const at = new Date(NOW.getTime() + 5 * H);
const { uninstallJob } = await jobs.scheduleUninstall({ deploymentId: d.id, totp: totpNow(), confirm: 'c0', at }, admin, NOW);
const job = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, at)).jobs[0];
await jobs.receiveReport(server, signedReport(job, 'failed'), at);
expect(await db.job.findUnique({ where: { id: uninstallJob.id } })).toMatchObject({ status: 'cancelled' });
expect(await db.deployment.findUnique({ where: { id: d.id } })).toMatchObject({ status: 'live' });
});
test('a failed install isn\'t uninstalled: its record is removed instead, and the short name is free', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
await expect(jobs.removeFailedInstall(deployment.id)).rejects.toMatchObject({ code: 'NOT_FAILED' });
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs;
await jobs.receiveReport(server, signedReport(job, 'failed'), NOW);
await expect(jobs.scheduleUninstall({ deploymentId: deployment.id, totp: totpNow(), confirm: 'hope' }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_INSTALLED' });
expect(await jobs.neverInstalled(await db.deployment.findUnique({ where: { id: deployment.id } }))).toBe(true);
await jobs.removeFailedInstall(deployment.id);
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toBeNull();
});
test('a failed install stuck "uninstalling" from before 2.3.2 can have its record removed; a live one can\'t', async () => {
const { server, deployments } = await liveDeployments(1);
await expect(jobs.removeFailedInstall(deployments[0].id)).rejects.toMatchObject({ code: 'NOT_FAILED' });
const stuck = await db.deployment.create({ data: { id: 'dep-stuck', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'stuck', domain: 'events.stuck.co.za', webPort: 20010, apiPort: 20011, status: 'uninstalling' } });
await db.job.create({ data: { id: 'job-inst', serverId: server.id, type: 'install', deploymentId: stuck.id, status: 'failed', args: {}, notBefore: NOW, expiresAt: NOW, createdAt: NOW } });
await db.job.create({ data: { id: 'job-un', serverId: server.id, type: 'uninstall', deploymentId: stuck.id, status: 'cancelled', args: {}, notBefore: NOW, expiresAt: NOW, createdAt: new Date(NOW.getTime() + H) } });
await jobs.removeFailedInstall(stuck.id);
expect(await db.deployment.findUnique({ where: { id: stuck.id } })).toBeNull();
});
});
describe('updates never mix products, and say what happens to Accounts (2.6.0)', () => {
const at = () => new Date(NOW.getTime() + 5 * H);
async function church(shortName, { accounts = null } = {}) {
let server = await db.server.findFirst({ where: { name: 'church-1' } });
if (!server) {
server = (await joinServer()).server;
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
}
const n = (await db.deployment.count()) * 2;
const ev = await db.deployment.create({ data: { id: `ev-${shortName}`, serverId: server.id, customerId: 'cust-1', product: 'events', shortName, domain: `events.${shortName}.co.za`, webPort: 21000 + n, apiPort: 21001 + n, status: 'live', version: '2.4.0' } });
let acc = null;
if (accounts) acc = await db.deployment.create({ data: { id: `acc-${shortName}`, serverId: server.id, customerId: 'cust-1', product: 'accounts', shortName, domain: `accounts.${shortName}.co.za`, webPort: 21100 + n, apiPort: 21101 + n, status: 'live', version: accounts } });
return { server, ev, acc };
}
beforeEach(async () => {
await db.release.create({ data: { id: 'r30', product: 'events', version: '3.0.0', notes: '- Accounts', requires: [{ product: 'accounts', version: '1.1.0' }], releasedAt: NOW } });
await db.release.create({ data: { id: 'ra10', product: 'accounts', version: '1.0.0', releasedAt: NOW } });
await db.release.create({ data: { id: 'ra11', product: 'accounts', version: '1.1.0', releasedAt: NOW } });
});
test('Events and Accounts installs in one update are refused, and so is the wrong product\'s release', async () => {
const { ev, acc } = await church('mix', { accounts: '1.1.0' });
await expect(jobs.scheduleUpdate({ deploymentIds: [ev.id, acc.id], at: at() }, admin, NOW)).rejects.toMatchObject({ message: expect.stringContaining('one product') });
await expect(jobs.scheduleUpdate({ deploymentIds: [ev.id], product: 'accounts', at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'WRONG_PRODUCT' });
await expect(jobs.scheduleUpdate({ deploymentIds: [ev.id], version: 'accounts@1.1.0', at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'WRONG_PRODUCT' });
await expect(jobs.scheduleUpdate({ deploymentIds: [acc.id], version: '3.0.0', at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'NO_RELEASE' });
});
test('an Events update keeps Accounts on the version it runs when nothing needs more', async () => {
const { ev } = await church('keep', { accounts: '1.0.0' });
const { jobs: [job], warnings } = await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '2.4.0', at: at() }, admin, NOW);
expect(job.args).toEqual({ church: 'keep', products: ['events'], versions: ['accounts@1.0.0', 'events@2.4.0'] });
expect(warnings.join(' ')).not.toContain('Accounts is updated');
});
test('Events 3.0 updates an older Accounts in the same deploy, and says so', async () => {
const { ev } = await church('older', { accounts: '1.0.0' });
const { jobs: [job], warnings } = await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '3.0.0', at: at() }, admin, NOW);
expect(job.args.versions).toEqual(['accounts@1.1.0', 'events@3.0.0']);
expect(warnings.join(' ')).toContain('Accounts is updated from 1.0.0 to 1.1.0');
});
test('a church without Accounts gets it installed first, then the update, in one batch', async () => {
const { ev } = await church('none');
const { jobs: made, batchId, warnings } = await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '3.0.0', at: at() }, admin, NOW);
expect(batchId).toMatch(/^batch_/);
expect(made.map(j => [j.type, j.status])).toEqual([['add-product', 'queued'], ['deploy', 'scheduled']]);
expect(made[0].args).toMatchObject({ church: 'none', product: 'accounts', version: 'accounts@1.1.0', domain: 'accounts.none.co.za' });
expect(made[1].args.versions).toEqual(['events@3.0.0']);
expect(warnings.join(' ')).toContain('installed first at accounts.none.co.za');
expect(await db.deployment.findFirst({ where: { shortName: 'none', product: 'accounts' } })).toMatchObject({ status: 'installing' });
});
});
describe('ports and alerts', () => {
test('ports are unique, and a released one is reused only after 30 days', async () => {
const { server } = await joinServer();
await db.port.create({ data: { port: 20000, role: 'taken' } });
await db.port.create({ data: { port: 20001, role: 'web', releasedAt: new Date(NOW.getTime() - 10 * 24 * H) } });
await db.port.create({ data: { port: 20002, role: 'api', releasedAt: new Date(NOW.getTime() - 40 * 24 * H) } });
expect(await servers.allocatePorts(db, server.id, NOW)).toEqual({ web: 20002, api: 20003 });
});
test('server problems: silent agent, full disk, frpc down, the central bind address', () => {
const base = { mode: 'church', lastSeenAt: NOW, lastStats: { disks: [{ mount: '/', totalBytes: 100, usedBytes: 90 }], frpcRunning: false } };
expect(servers.serverProblems(base, [], [], NOW).map(p => p.type)).toEqual(['disk:/', 'frpc_down']);
expect(servers.serverProblems({ ...base, lastSeenAt: new Date(NOW.getTime() - 6 * 60 * 1000) }, [], [], NOW)[0].type).toBe('agent_silent');
const central = { mode: 'central', lastSeenAt: NOW, lastStats: { disks: [], central: { proxyBindAddr: null, frpsRunning: true } } };
expect(servers.serverProblems(central, [], [], NOW).map(p => p.type)).toEqual(['proxy_bind_addr']);
const ram = Array.from({ length: 5 }, () => ({ ramUsedPercent: 95 }));
expect(servers.serverProblems({ ...base, lastStats: { disks: [] } }, ram, [], NOW).map(p => p.type)).toEqual(['ram_high']);
});
test("an agent running a job is busy, not down, until the job's time limit has passed", async () => {
const quiet = { mode: 'church', lastSeenAt: new Date(NOW.getTime() - 20 * 60 * 1000), lastStats: { disks: [] } };
const install = { type: 'install', status: 'delivered', deliveredAt: new Date(NOW.getTime() - 20 * 60 * 1000) };
expect(servers.serverProblems(quiet, [], [], NOW, install).map(p => p.type)).toEqual([]);
// 30 minutes for an install, plus 10: after that it's silence again.
const late = new Date(NOW.getTime() + 21 * 60 * 1000);
expect(servers.serverProblems(quiet, [], [], late, install)[0].type).toBe('agent_silent');
// A finished job doesn't count.
expect(servers.serverProblems(quiet, [], [], NOW, { ...install, status: 'succeeded' })[0].type).toBe('agent_silent');
expect(jobs.agentOnline(quiet, NOW, install)).toBe(true);
expect(jobs.agentOnline(quiet, NOW, null)).toBe(false);
// The alerts job: no alert and no email while it's busy.
const { server } = await joinServer();
await db.server.update({ where: { id: server.id }, data: { lastSeenAt: new Date(NOW.getTime() - 20 * 60 * 1000), lastStats: { disks: [] } } });
await db.job.create({ data: { id: 'job_busy', serverId: server.id, type: 'install', args: {}, status: 'delivered', deliveredAt: new Date(NOW.getTime() - 20 * 60 * 1000), notBefore: NOW, expiresAt: NOW } });
const mailsBefore = mockMails.length;
await servers.runServerAlerts(NOW);
expect(await db.serverAlert.count({ where: { serverId: server.id, type: 'agent_silent' } })).toBe(0);
expect(mockMails.length).toBe(mailsBefore);
});
});
describe('reusing a short name (found in the VM test)', () => {
test('after a failed install the same short name can be used again', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const first = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs;
await jobs.receiveReport(server, signedReport(job, 'failed'), NOW);
const again = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(again.deployment.id).not.toBe(first.deployment.id);
expect(await db.deployment.findUnique({ where: { id: first.deployment.id } })).toBeNull();
expect(again.deployment).toMatchObject({ webPort: 20000, apiPort: 20001 });
});
test('a live install keeps its name', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.other.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'SHORT_NAME_TAKEN' });
});
});
describe('Accounts from the Hub (2.3.0)', () => {
const poll = (server) => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.1.0', mode: 'church', runningJobId: null }, NOW);
beforeEach(async () => {
await db.release.create({ data: { id: 'ra1', product: 'accounts', version: '1.0.0', notes: '- First release', releasedAt: NOW } });
});
test("a church's first product can be Accounts: an install job with its CCA- licence", async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const { deployment } = await jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'accounts.grace.co.za', adminEmail: 'jane@grace.test' }, admin, NOW);
expect(deployment).toMatchObject({ product: 'accounts', status: 'installing' });
const [job] = (await poll(server)).jobs;
expect(job).toMatchObject({ type: 'install', args: { products: ['accounts'], versions: { accounts: 'accounts@1.0.0' }, domains: { accounts: 'accounts.grace.co.za' } } });
expect(agent.agentJobSchema.safeParse(job).success).toBe(true);
const config = signing.openConfig(job.config, keys.x.privateKeyPem);
expect(config.install.accounts.HUB_LICENCE_KEY).toMatch(/^CCA-/);
});
test("next to the church's Events: an add-product job; finishing it waits for the proxy as an install does", async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const events = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
await db.deployment.update({ where: { id: events.deployment.id }, data: { status: 'live' } });
await db.job.updateMany({ where: { deploymentId: events.deployment.id }, data: { status: 'succeeded' } });
const { deployment } = await jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'accounts.hope.co.za' }, admin, NOW);
const [job] = (await poll(server)).jobs;
expect(job).toMatchObject({ type: 'add-product', args: { church: 'hope', product: 'accounts', version: 'accounts@1.0.0', domain: 'accounts.hope.co.za', ports: { web: 20002, api: 20003 } } });
expect(agent.agentJobSchema.safeParse(job).success).toBe(true);
expect(signing.openConfig(job.config, keys.x.privateKeyPem).install.accounts).toBeTruthy();
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: { versions: { accounts: 'accounts@1.0.0' } } }), NOW);
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toMatchObject({ status: 'waiting_for_proxy', version: '1.0.0' });
});
test("refused: another server, a product with no release yet, or while the first is installing", async () => {
const { server } = await joinServer();
const other = (await joinServer('church', 'church-2')).server;
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await servers.setServerConfig(other.id, { TRUST_PROXY: 'loopback' });
await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
await expect(jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'accounts.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'BUSY' });
await expect(jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: other.id, shortName: 'hope', domain: 'accounts.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'OTHER_SERVER' });
// 2.26.0: the App can be installed, once it has a release.
await expect(jobs.newInstall({ product: 'app', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'app.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'NO_RELEASE' });
});
});
describe('Cross Events 3.0 brings its Accounts (2.5.0)', () => {
const poll = (server) => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.1.0', mode: 'church', runningJobId: null }, NOW);
beforeEach(async () => {
await db.release.create({ data: { id: 'r3', product: 'events', version: '3.0.0', notes: '- Sign-in through Accounts', requires: [{ product: 'accounts', version: '1.1.0' }], releasedAt: NOW } });
await db.release.create({ data: { id: 'ra1', product: 'accounts', version: '1.0.0', notes: '- First release', releasedAt: NOW } });
await db.release.create({ data: { id: 'ra2', product: 'accounts', version: '1.1.0', notes: '- For Events 3.0', releasedAt: NOW } });
});
test('a new church gets Accounts installed first, then Events next to it once that succeeded', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'events.grace.co.za' }, admin, NOW);
expect(out.alsoInstalling).toEqual({ product: 'accounts', domain: 'accounts.grace.co.za', version: '1.1.0' });
const accounts = await db.deployment.findFirst({ where: { shortName: 'grace', product: 'accounts' } });
expect(accounts).toMatchObject({ status: 'installing', domain: 'accounts.grace.co.za' });
// Only Accounts runs now.
const [first] = (await poll(server)).jobs;
expect(first).toMatchObject({ type: 'install', args: { products: ['accounts'], versions: { accounts: 'accounts@1.1.0' } } });
expect(signing.openConfig(first.config, keys.x.privateKeyPem).install.accounts.HUB_LICENCE_KEY).toMatch(/^CCA-/);
expect((await poll(server)).jobs).toEqual([]);
await jobs.receiveReport(server, signedReport(first, 'succeeded', { result: { versions: { accounts: 'accounts@1.1.0' } } }), NOW);
// Then Events, added next to it.
const [second] = (await poll(server)).jobs;
expect(second).toMatchObject({ type: 'add-product', args: { church: 'grace', product: 'events', version: 'events@3.0.0', domain: 'events.grace.co.za' } });
expect(agent.agentJobSchema.safeParse(second).success).toBe(true);
});
test('when Accounts fails, Events never runs and its ports are freed', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'events.grace.co.za', accountsDomain: 'login.grace.co.za' }, admin, NOW);
expect(out.alsoInstalling.domain).toBe('login.grace.co.za');
const [first] = (await poll(server)).jobs;
await jobs.receiveReport(server, signedReport(first, 'failed'), NOW);
expect(await db.deployment.findUnique({ where: { id: out.deployment.id } })).toMatchObject({ status: 'failed' });
expect(await db.port.findMany({ where: { port: { in: [out.deployment.webPort, out.deployment.apiPort] } } })).toEqual([]);
expect((await poll(server)).jobs).toEqual([]);
});
test("a church whose Accounts is older than Events 3.0 needs is refused; a new enough one isn't installed again", async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const a = await jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'accounts.hope.co.za', version: '1.0.0' }, admin, NOW);
await db.deployment.update({ where: { id: a.deployment.id }, data: { status: 'live', version: '1.0.0' } });
await db.job.updateMany({ where: { deploymentId: a.deployment.id }, data: { status: 'succeeded' } });
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'REQUIREMENT_NOT_MET' });
await db.deployment.update({ where: { id: a.deployment.id }, data: { version: '1.1.0' } });
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(out.alsoInstalling).toBeUndefined();
const [job] = (await poll(server)).jobs;
expect(job).toMatchObject({ type: 'add-product', args: { product: 'events', version: 'events@3.0.0' } });
});
test("the church's Accounts version is what its heartbeat says, not the install record's (Hub 2.23.1)", async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const a = await jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'accounts.hope.co.za', version: '1.0.0' }, admin, NOW);
await db.job.updateMany({ where: { deploymentId: a.deployment.id }, data: { status: 'succeeded' } });
// Updated on the server to 1.1.0 by a job for another product: the record still says 1.0.0.
const install = await db.install.create({ data: { id: 'inst-acc', product: 'accounts', version: '1.1.0' } });
await db.deployment.update({ where: { id: a.deployment.id }, data: { status: 'live', version: '1.0.0', installId: install.id } });
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(out.alsoInstalling).toBeUndefined();
const [job] = (await poll(server)).jobs;
expect(job).toMatchObject({ type: 'add-product', args: { product: 'events', version: 'events@3.0.0' } });
});
test('Events 2.x installs as before, without Accounts', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'old', domain: 'events.old.co.za', version: '2.4.0' }, admin, NOW);
expect(out.alsoInstalling).toBeUndefined();
expect(await db.deployment.findFirst({ where: { shortName: 'old', product: 'accounts' } })).toBeNull();
});
});
describe('the Church Website from the Hub (2.21.0)', () => {
const poll = (server) => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.1.0', mode: 'church', runningJobId: null }, NOW);
beforeEach(async () => {
await db.release.create({ data: { id: 'rw1', product: 'website', version: '1.0.0', notes: '- First release', requires: [{ product: 'accounts', version: '1.7.0' }], releasedAt: NOW } });
await db.release.create({ data: { id: 'ra7', product: 'accounts', version: '1.7.0', notes: '- Brand style', releasedAt: NOW } });
});
test('a new church: Accounts first at accounts.<its domain>, then the Website on www., with a CCW- licence on the Website plan', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const out = await jobs.newInstall({ product: 'website', customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'www.grace.co.za' }, admin, NOW);
expect(out.alsoInstalling).toEqual({ product: 'accounts', domain: 'accounts.grace.co.za', version: '1.7.0' });
const [first] = (await poll(server)).jobs;
expect(first).toMatchObject({ type: 'install', args: { products: ['accounts'] } });
await jobs.receiveReport(server, signedReport(first, 'succeeded', { result: { versions: { accounts: 'accounts@1.7.0' } } }), NOW);
const [second] = (await poll(server)).jobs;
expect(second).toMatchObject({ type: 'add-product', args: { church: 'grace', product: 'website', version: 'website@1.0.0', domain: 'www.grace.co.za' } });
expect(agent.agentJobSchema.safeParse(second).success).toBe(true);
const key = signing.openConfig(second.config, keys.x.privateKeyPem).install.website.HUB_LICENCE_KEY;
expect(key).toMatch(/^CCW-/);
expect(await db.licence.findFirst({ where: { key } })).toMatchObject({ product: 'website', plan: 'Website' });
});
test('on a Cross Code address, Accounts goes in front of it', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const out = await jobs.newInstall({ product: 'website', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'hope.crosscode.co.za' }, admin, NOW);
expect(out.alsoInstalling.domain).toBe('accounts.hope.crosscode.co.za');
});
test("the FastPanel steps send the bare domain to www. with a 301; a Cross Code address has no such step", async () => {
const own = await jobs.fastPanelText({ id: 'd1', product: 'website', shortName: 'grace', domain: 'www.grace.co.za', webPort: 20010, apiPort: 20011, customer: { name: 'Grace' } });
expect(own).toContain('Add grace.co.za as an alias');
expect(own).toContain('return 301 https://www.grace.co.za$request_uri;');
expect(own).toContain('DNS: www.grace.co.za and grace.co.za');
expect(own).toContain('location ^~ /api/ {');
const crosscode = await jobs.fastPanelText({ id: 'd2', product: 'website', shortName: 'hope', domain: 'hope.crosscode.co.za', webPort: 20012, apiPort: 20013, customer: { name: 'Hope' } });
expect(crosscode).not.toContain('301');
const events = await jobs.fastPanelText({ id: 'd3', product: 'events', shortName: 'hope', domain: 'www.hope.co.za', webPort: 20014, apiPort: 20015, customer: { name: 'Hope' } });
expect(events).not.toContain('301');
});
});
describe("a Website licence carries its storage limit (2.21.0)", () => {
const GB = 1024 ** 3;
const licenceToken = require('../src/utils/licenceToken');
const base = { id: '0b6f2c1e-8a3d-4f5b-9c7e-1d2e3f4a5b6c', customerId: '1c7a3d2f-9b4e-4a6c-8d8f-2e3f4a5b6c7d', plan: 'Website', status: 'active', expiresAt: null, graceDays: 14 };
test('5 GB plus the steps bought, valid for contracts 1.17.0; other products have none', () => {
const p = licenceToken.buildPayload({ ...base, product: 'website', extraStorageSteps: 2 }, { id: '2d8b4e3a-0c5f-4b7d-9e9a-3f4a5b6c7d8e' }, 'Grace', NOW);
expect(p.limits.storageBytes).toBe(15 * GB);
expect(hub.licencePayloadSchema.safeParse(p).success).toBe(true);
expect(licenceToken.buildPayload({ ...base, product: 'website' }, { id: '2d8b4e3a-0c5f-4b7d-9e9a-3f4a5b6c7d8e' }, 'Grace', NOW).limits.storageBytes).toBe(5 * GB);
expect(licenceToken.buildPayload({ ...base, product: 'events', plan: 'Seed', extraStorageSteps: 3 }, { id: '2d8b4e3a-0c5f-4b7d-9e9a-3f4a5b6c7d8e' }, 'Grace', NOW).limits).not.toHaveProperty('storageBytes');
});
});
describe('settings for servers (found in the VM test)', () => {
test('install defaults, the port range and the central IP are saved', async () => {
const { setSettings } = require('../src/utils/settings');
await setSettings({ install_defaults: '{"HUB_URL":"https://hub.test","SENTRY_DSN":"x"}', port_range_start: '21000', port_range_end: '21100', central_server_ip: '203.0.113.10' });
expect(await servers.installDefaults()).toEqual({ HUB_URL: 'https://hub.test', SENTRY_DSN: 'x' });
expect(await servers.portRange()).toEqual({ from: 21000, to: 21100 });
});
});
describe('banners reach a site the Hub installed (found in the VM test)', () => {
test('an update to a deployment registered through its licence gets a banner', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.release.create({ data: { product: 'events', version: '2.4.0', notes: 'New', releasedAt: NOW } });
// A Hub install: the deployment knows its licence, not yet its install.
await db.licence.create({ data: { id: 'lic-9', customerId: 'cust-1', product: 'events', key: 'CEH-TEST' } });
await db.install.create({ data: { id: 'inst-9', customerId: 'cust-1', licenceId: 'lic-9', product: 'events', name: 'Hope', url: 'https://events.hope.test', secret: 'x', version: '2.3.0' } });
const d = await db.deployment.create({ data: { id: 'dep-9', serverId: server.id, customerId: 'cust-1', licenceId: 'lic-9', product: 'events', shortName: 'hope', domain: 'events.hope.test', webPort: 20000, apiPort: 20001, status: 'live', version: '2.3.0' } });
const r = await jobs.scheduleUpdate({ deploymentIds: [d.id], version: '2.4.0', at: new Date(NOW.getTime() + 5 * H) }, admin, NOW);
const job = await db.job.findUnique({ where: { id: r.jobs[0].id } });
expect(job.noticeId).toBeTruthy();
const notice = await db.notice.findUnique({ where: { id: job.noticeId } });
expect(notice).toMatchObject({ showBanner: true, installIds: ['inst-9'] });
expect((await db.deployment.findUnique({ where: { id: d.id } })).installId).toBe('inst-9');
});
});
describe('adopting an existing install', () => {
async function linked(domain) {
const { server } = await joinServer();
await db.release.create({ data: { product: 'events', version: '2.3.0', releasedAt: NOW } });
await db.install.create({ data: { id: `inst-${domain}`, customerId: 'cust-1', product: 'events', name: 'Demo', url: `https://${domain}`, secret: 'x', version: '2.1.1' } });
return jobs.linkDeployment({ serverId: server.id, installId: `inst-${domain}`, shortName: 'cross-events-demo', webPort: 3100, apiPort: 5100 }, admin);
}
const at = new Date(NOW.getTime() + 5 * H);
test('a link takes a name, not a folder', async () => {
const { server } = await joinServer();
await db.install.create({ data: { id: 'inst-p', customerId: 'cust-1', product: 'events', name: 'P', url: 'https://events.p.test', secret: 'x', version: '2.1.1' } });
await expect(jobs.linkDeployment({ serverId: server.id, installId: 'inst-p', shortName: '/var/www/cross-events-demo', webPort: 3100, apiPort: 5100 }, admin))
.rejects.toMatchObject({ status: 400, message: expect.stringContaining('not a folder') });
});
test('the old folder and the church address go to crosscode adopt', async () => {
const d = await linked('events-demo.crosscode.co.za');
const job = await jobs.scheduleAdopt({ deploymentId: d.id, eventsDir: '/var/www/cross-events-demo', address: 'crosscode.co.za', at }, admin, NOW);
expect(job.args).toMatchObject({ church: 'cross-events-demo', eventsDir: '/var/www/cross-events-demo', address: 'crosscode.co.za' });
expect(agent.jobArgsSchemas.adopt.safeParse(job.args).success).toBe(true);
});
test('a domain without "events." needs the address; events.<address> works it out', async () => {
const d = await linked('events-demo.crosscode.co.za');
await expect(jobs.scheduleAdopt({ deploymentId: d.id, eventsDir: '/var/www/cross-events-demo', at }, admin, NOW)).rejects.toMatchObject({ status: 400, code: 'ADDRESS_NEEDED' });
await db.deployment.update({ where: { id: d.id }, data: { domain: 'events.hope.co.za' } });
const job = await jobs.scheduleAdopt({ deploymentId: d.id, eventsDir: '/var/www/hope-events', at }, admin, NOW);
expect(job.args.address).toBe('hope.co.za');
});
});
describe('demo sites (2.4.0)', () => {
async function liveDemo({ agentVersion = '1.2.0', isDemo = true, adminEmail = 'Jane@Hope.test' } = {}) {
const { server } = await joinServer();
await db.server.update({ where: { id: server.id }, data: { agentVersion } });
const d = await db.deployment.create({ data: { id: 'dep-demo', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'demo2', domain: 'events.demo2.test', webPort: 20000, apiPort: 20001, status: 'live', isDemo, adminEmail } });
return { server, d };
}
test('marking a site as demo asks for its short name; unmarking doesn\'t', async () => {
const { d } = await liveDemo({ isDemo: false });
await expect(jobs.setDemo(d.id, { isDemo: true, confirm: 'nope' })).rejects.toMatchObject({ code: 'CONFIRM' });
expect(await jobs.setDemo(d.id, { isDemo: true, confirm: 'demo2' })).toMatchObject({ isDemo: true });
expect(await jobs.setDemo(d.id, { isDemo: false })).toMatchObject({ isDemo: false });
});
test('a seed-demo job for a demo site: the profile, and its admin kept', async () => {
const { server, d } = await liveDemo();
const job = await jobs.seedDemo({ deploymentId: d.id, profile: 'ministry', confirm: 'demo2' }, admin, NOW);
expect(job).toMatchObject({ type: 'seed-demo', deploymentId: d.id, args: { church: 'demo2', profile: 'ministry', adminEmail: 'jane@hope.test' } });
const polled = await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.2.0', mode: 'church', runningJobId: null }, NOW);
expect(agent.agentJobSchema.safeParse(polled.jobs[0]).success).toBe(true);
expect(polled.jobs[0].config).toBeNull();
});
test('refused: not a demo site, wrong short name, unknown profile, an agent before 1.2.0', async () => {
let { d } = await liveDemo({ isDemo: false });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_DEMO' });
await db.deployment.update({ where: { id: d.id }, data: { isDemo: true } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo' }, admin, NOW)).rejects.toMatchObject({ code: 'CONFIRM' });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'everything', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
await seed();
({ d } = await liveDemo({ agentVersion: '1.1.1' }));
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.2.0') });
expect(await db.job.findMany({})).toEqual([]);
});
test('2.25.0: a Website demo site gets a Website profile, on an agent of 1.6.0 or later', async () => {
const { server, d } = await liveDemo({ agentVersion: '1.6.0' });
await db.deployment.update({ where: { id: d.id }, data: { product: 'website' } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST', message: expect.stringContaining('heritage-parish') });
const job = await jobs.seedDemo({ deploymentId: d.id, profile: 'community-town', confirm: 'demo2' }, admin, NOW);
expect(job.args).toEqual({ church: 'demo2', product: 'website', profile: 'community-town' });
const polled = await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.6.0', mode: 'church', runningJobId: null }, NOW);
expect(agent.agentJobSchema.safeParse(polled.jobs[0]).success).toBe(true);
await db.server.update({ where: { id: server.id }, data: { agentVersion: '1.5.0' } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'bold-plant', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.6.0') });
});
test('2.26.0: Accounts and the App have demo data too: a scenario profile, agent 1.7.0, Accounts 1.9.0 / App 1.0.0', async () => {
const { server, d } = await liveDemo({ agentVersion: '1.6.0', isDemo: false });
await db.deployment.update({ where: { id: d.id }, data: { product: 'accounts', version: '1.8.0' } });
expect(await jobs.setDemo(d.id, { isDemo: true, confirm: 'demo2' })).toMatchObject({ isDemo: true });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'community-family', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.7.0') });
await db.server.update({ where: { id: server.id }, data: { agentVersion: '1.7.0' } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'community-family', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'RELEASE_TOO_OLD', message: expect.stringContaining('1.9.0') });
await db.deployment.update({ where: { id: d.id }, data: { version: '1.9.0' } });
expect((await jobs.seedDemo({ deploymentId: d.id, profile: 'community-family', confirm: 'demo2' }, admin, NOW)).args).toEqual({ church: 'demo2', product: 'accounts', profile: 'community-family' });
await db.job.deleteMany({});
await db.deployment.update({ where: { id: d.id }, data: { product: 'app', version: '1.0.0' } });
const job = await jobs.seedDemo({ deploymentId: d.id, profile: 'bold-youth', confirm: 'demo2' }, admin, NOW);
expect(job.args).toEqual({ church: 'demo2', product: 'app', profile: 'bold-youth' });
expect(agent.jobArgsSchemas['seed-demo'].safeParse(job.args).success).toBe(true);
});
test("2.26.0: Events' scenario churches need Events 3.8.0; its first four profiles don't", async () => {
const { d } = await liveDemo();
await db.deployment.update({ where: { id: d.id }, data: { version: '3.7.2' } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'clean-campus', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'RELEASE_TOO_OLD', message: expect.stringContaining('3.8.0') });
expect((await jobs.seedDemo({ deploymentId: d.id, profile: 'multicampus', confirm: 'demo2' }, admin, NOW)).args.profile).toBe('multicampus');
});
test('2.25.0: a demo client: all its installs demo sites (Accounts too), billing off, new installs demo too', async () => {
const { server } = await joinServer();
await db.customer.update({ where: { id: 'cust-1' }, data: { billingCycle: 'monthly', nextInvoiceDate: new Date('2026-12-01') } });
for (const [id, product, port] of [['dep-ev', 'events', 20000], ['dep-acc', 'accounts', 20002]]) {
await db.deployment.create({ data: { id, serverId: server.id, customerId: 'cust-1', product, shortName: 'hope', domain: `${product}.hope.test`, webPort: port, apiPort: port + 1, status: 'live', isDemo: false, removedAt: null } });
}
await db.invoice.create({ data: { id: 'inv-1', customerId: 'cust-1', status: 'approved' } });
await expect(jobs.setCustomerDemo('cust-1', { isDemo: true, confirm: 'Hope' })).rejects.toMatchObject({ code: 'CONFIRM' });
const out = await jobs.setCustomerDemo('cust-1', { isDemo: true, confirm: 'Hope Church' }, NOW);
expect(out).toMatchObject({ sites: 2, warnings: [expect.stringContaining('1 invoice')] });
expect(await db.customer.findUnique({ where: { id: 'cust-1' } })).toMatchObject({ isDemo: true, billingCycle: 'none', nextInvoiceDate: null, demoSince: NOW });
expect((await db.deployment.findMany({ where: { customerId: 'cust-1' } })).map(x => x.isDemo)).toEqual([true, true]);
await expect(jobs.setDemo('dep-acc', { isDemo: false })).rejects.toMatchObject({ code: 'DEMO_CLIENT' });
expect(await jobs.customerIsDemo(db, 'cust-1')).toBe(true);
await jobs.setCustomerDemo('cust-1', { isDemo: false });
expect(await db.customer.findUnique({ where: { id: 'cust-1' } })).toMatchObject({ isDemo: false, billingCycle: 'none', demoSince: null });
expect((await db.deployment.findMany({ where: { customerId: 'cust-1' } })).map(x => x.isDemo)).toEqual([false, false]);
});
test('2.25.0: a demo client\'s new install starts as a demo site', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback', DB_ADMIN_URL: 'postgresql://admin:pw@10.0.0.5/postgres' });
await db.customer.update({ where: { id: 'cust-1' }, data: { isDemo: true } });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(deployment.isDemo).toBe(true);
});
});
describe('sites added on a server are found and tied to their registration (2.6.0)', () => {
const statusResult = (domain = 'accounts.found.co.za') => ({ churches: [{ church: 'found', address: 'found.co.za', products: [
{ product: 'events', ref: 'events@2.4.1', domain: 'events.found.co.za', ports: '21201 21200' },
{ product: 'accounts', ref: 'accounts@1.1.0', domain, ports: '21203 21202' },
] }] });
test('a status report adds the Accounts the Hub didn\'t know, tied to its registered site, with its ports', async () => {
const { server } = await joinServer();
await db.deployment.create({ data: { id: 'ev-found', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'found', domain: 'events.found.co.za', webPort: 21200, apiPort: 21201, status: 'live' } });
const licence = await db.licence.create({ data: { id: 'lic-acc', customerId: 'cust-1', product: 'accounts', key: 'CCA-TEST', status: 'active' } });
await db.install.create({ data: { id: 'inst-acc', customerId: 'cust-1', licenceId: licence.id, product: 'accounts', name: 'Found Accounts', url: 'https://accounts.found.co.za', secret: 'x', version: '1.1.0' } });
const job = await jobs.runNow({ serverId: server.id, type: 'status', args: {} }, admin, NOW);
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: statusResult() }), NOW);
const acc = await db.deployment.findFirst({ where: { shortName: 'found', product: 'accounts' } });
expect(acc).toMatchObject({ serverId: server.id, customerId: 'cust-1', installId: 'inst-acc', licenceId: 'lic-acc', domain: 'accounts.found.co.za', webPort: 21202, apiPort: 21203, version: '1.1.0', status: 'live' });
expect((await db.port.findMany({ where: { deploymentId: acc.id } })).map(p => p.port).sort()).toEqual([21202, 21203]);
expect((await db.job.findUnique({ where: { id: job.id } })).message).toContain('Added: found (Accounts');
// A second report changes nothing.
const again = await jobs.runNow({ serverId: server.id, type: 'status', args: {} }, admin, NOW);
await jobs.receiveReport(server, signedReport(again, 'succeeded', { result: statusResult() }), NOW);
expect(await db.deployment.count({ where: { shortName: 'found', product: 'accounts' } })).toBe(1);
});
test('a registered site with no install record asks its customer\'s server what\'s on it, once a day', async () => {
const { server } = await joinServer();
await db.deployment.create({ data: { id: 'ev-ask', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'ask', domain: 'events.ask.co.za', webPort: 21300, apiPort: 21301, status: 'live' } });
const install = await db.install.create({ data: { id: 'inst-ask', customerId: 'cust-1', product: 'accounts', name: 'Ask Accounts', url: 'https://accounts.ask.co.za', secret: 'x', version: '1.1.0', releasedAt: null } });
const job = await jobs.lookForUnlinked(install, NOW);
expect(job).toMatchObject({ type: 'status', serverId: server.id, status: 'queued' });
expect(await jobs.lookForUnlinked(install, new Date(NOW.getTime() + 3600e3))).toBeNull();
});
test('a site the Hub installed, tied already, asks nothing', async () => {
const { server } = await joinServer();
const install = await db.install.create({ data: { id: 'inst-own', customerId: 'cust-1', product: 'events', name: 'Own', url: 'https://events.own.co.za', secret: 'x', releasedAt: null } });
await db.deployment.create({ data: { id: 'ev-own', serverId: server.id, customerId: 'cust-1', installId: install.id, product: 'events', shortName: 'own', domain: 'events.own.co.za', webPort: 21400, apiPort: 21401, status: 'live' } });
expect(await jobs.lookForUnlinked(install, NOW)).toBeNull();
});
});
describe('the jobs list: every status, product, search and pages (2.6.0)', () => {
const { pageOf, paged } = require('../src/utils/paging');
const list = async (q) => paged(db.job, { where: await jobs.listWhere(q), orderBy: [{ notBefore: 'desc' }], include: { deployment: true } }, pageOf(q));
test('succeeded and cancelled can be listed, by product and church, a page at a time', async () => {
const { server } = await joinServer();
await db.deployment.create({ data: { id: 'd-ev', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'hope', domain: 'events.hope.co.za', webPort: 22000, apiPort: 22001, status: 'live' } });
await db.deployment.create({ data: { id: 'd-acc', serverId: server.id, customerId: 'cust-1', product: 'accounts', shortName: 'hope', domain: 'accounts.hope.co.za', webPort: 22002, apiPort: 22003, status: 'live' } });
for (let i = 0; i < 7; i++) {
await db.job.create({ data: { id: `job_test${i}0000`, serverId: server.id, type: 'deploy', deploymentId: i % 2 ? 'd-acc' : 'd-ev', status: i < 5 ? 'succeeded' : 'cancelled', args: {}, notBefore: new Date(NOW.getTime() + i * 60e3), expiresAt: NOW } });
}
const ok = await list({ status: 'succeeded', pageSize: '2' });
expect([ok.total, ok.pages, ok.rows.length]).toEqual([5, 3, 2]);
expect((await list({ status: 'succeeded', pageSize: '2', page: '3' })).rows.map(j => j.id)).toEqual(['job_test00000']);
expect((await list({ status: 'cancelled' })).total).toBe(2);
expect((await list({ product: 'accounts' })).rows.every(j => j.deployment.product === 'accounts')).toBe(true);
expect((await list({ q: 'ACCOUNTS.hope' })).total).toBe(3);
await expect(jobs.listWhere({ status: 'nonsense' })).rejects.toThrow('Unknown job status.');
expect(pageOf({ pageSize: '100000' }).pageSize).toBe(200);
});
});
describe('the jobs list only asks for statuses the database knows (2.6.1)', () => {
test('JOB_STATUSES is exactly the JobStatus enum, and an old page\'s "timed_out" is dropped', async () => {
const schema = require('fs').readFileSync(require('path').join(__dirname, '..', 'prisma', 'schema.prisma'), 'utf8');
const block = /enum JobStatus \{([\s\S]*?)\}/.exec(schema)[1];
const values = block.split(/\r?\n/).map(l => l.replace(/\/\/.*$/, '').trim()).filter(Boolean);
expect([...jobs.JOB_STATUSES].sort()).toEqual([...values].sort());
expect(await jobs.listWhere({ status: 'failed,timed_out' })).toEqual({ AND: [{ status: { in: ['failed'] } }] });
expect(await jobs.listWhere({ status: 'failed,expired' })).toEqual({ AND: [{ status: { in: ['failed', 'expired'] } }] });
});
});
describe('emergency updates as soon as possible, and events on now (2.7.0)', () => {
async function liveChurch(shortName, live = null, heardMinutesAgo = 5) {
let server = await db.server.findFirst({ where: { name: 'church-1' } });
if (!server) {
server = (await joinServer()).server;
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
}
const n = (await db.deployment.count()) * 2;
const install = await db.install.create({ data: { id: `inst-${shortName}`, customerId: 'cust-1', product: 'events', name: shortName, url: `https://events.${shortName}.co.za`, secret: 'x', version: '2.3.0', lastHeartbeatAt: new Date(NOW.getTime() - heardMinutesAgo * 60e3), stats: live ? { live } : {}, adminContact: { name: 'Admin', email: `admin@${shortName}.test` } } });
return db.deployment.create({ data: { id: `dep-${shortName}`, serverId: server.id, customerId: 'cust-1', installId: install.id, product: 'events', shortName, domain: `events.${shortName}.co.za`, webPort: 23000 + n, apiPort: 23001 + n, status: 'live' } });
}
const urgent = (ids, extra = {}) => jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', emergency: true, reason: 'Broken release', totp: totpNow(), ...extra }, admin, NOW);
test('as soon as possible: queued now for the agent\'s next poll, with the church told it\'s happening now', async () => {
const d = await liveChurch('quick');
const { jobs: [job] } = await urgent([d.id], { asap: true });
expect(job).toMatchObject({ status: 'queued', emergency: true });
expect(new Date(job.notBefore).getTime()).toBe(NOW.getTime());
expect(mockMails.find(m => m.to === 'admin@quick.test')?.subject).toBe('Urgent: Cross Events is being updated now');
const notice = await db.notice.findUnique({ where: { id: job.noticeId } });
expect(notice.message).toContain('is being updated now');
});
test('still an emergency only, with a reason and two-factor; at a time it\'s still 15 minutes', async () => {
const d = await liveChurch('rules');
await expect(jobs.scheduleUpdate({ deploymentIds: [d.id], version: '2.4.0', asap: true }, admin, NOW)).rejects.toMatchObject({ message: expect.stringContaining('Only an emergency') });
await expect(urgent([d.id], { asap: true, reason: '' })).rejects.toMatchObject({ message: expect.stringContaining('reason') });
await expect(urgent([d.id], { asap: true, totp: '000000' })).rejects.toMatchObject({ code: 'BAD_TOTP' });
await expect(urgent([d.id], { at: new Date(NOW.getTime() + 5 * 60e3) })).rejects.toMatchObject({ code: 'TOO_SOON' });
});
test('a church with an event on now is named, and the update waits for a second yes', async () => {
const busy = await liveChurch('busy', { eventsNow: 1, checkInsLastHour: 37 });
const calm = await liveChurch('calm', { eventsNow: 0, checkInsLastHour: 0 });
await expect(urgent([busy.id, calm.id], { asap: true })).rejects.toMatchObject({ code: 'LIVE_EVENT', message: expect.stringContaining('busy (1 event(s) on now, 37 check-in(s) in the last hour)') });
expect(await db.job.count()).toBe(0);
const out = await urgent([busy.id, calm.id], { asap: true, confirmLive: true });
expect(out.jobs).toHaveLength(2);
expect(out.warnings.join(' ')).toContain('Updated while an event was on: busy');
});
test('an old heartbeat, or one without live stats, doesn\'t hold an update back', async () => {
const stale = await liveChurch('stale', { eventsNow: 3, checkInsLastHour: 0 }, 90);
const older = await liveChurch('older');
expect((await urgent([stale.id, older.id], { asap: true })).jobs).toHaveLength(2);
});
});
describe('one update at a time per install (2.7.1)', () => {
test('a second update for an install with one planned is refused, and none is made', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.install.create({ data: { id: 'inst-twice', customerId: 'cust-1', product: 'events', name: 'Twice', url: 'https://events.twice.co.za', secret: 'x', version: '2.3.0' } });
const d = await db.deployment.create({ data: { id: 'dep-twice', serverId: server.id, customerId: 'cust-1', installId: 'inst-twice', product: 'events', shortName: 'twice', domain: 'events.twice.co.za', webPort: 24000, apiPort: 24001, status: 'live' } });
const at = new Date(NOW.getTime() + 5 * 3600e3);
await jobs.scheduleUpdate({ deploymentIds: [d.id], version: '2.4.0', at }, admin, NOW);
await expect(jobs.scheduleUpdate({ deploymentIds: [d.id], version: '2.4.0', at }, admin, NOW)).rejects.toMatchObject({ code: 'ALREADY_PLANNED' });
expect(await db.job.count({ where: { deploymentId: d.id, type: 'deploy' } })).toBe(1);
});
});
describe("an install's .env from the Hub (2.8.0)", () => {
const poll = (server, v = '1.3.0') => jobs.poll(server, { agentApiVersion: 1, agentVersion: v, mode: 'church', runningJobId: null }, NOW);
async function live({ agentVersion = '1.3.0', product = 'events' } = {}) {
const { server } = await joinServer();
await db.server.update({ where: { id: server.id }, data: { agentVersion } });
const d = await db.deployment.create({ data: { id: 'dep-env', serverId: server.id, customerId: 'cust-1', product, shortName: 'hope', domain: `${product}.hope.test`, webPort: 20000, apiPort: 20001, status: 'live' } });
return { server, d };
}
const envResult = (url) => ({ env: {
product: 'events', readAt: NOW.toISOString(),
files: [{ file: 'backend/.env', exists: true, variables: [
{ name: 'FRONTEND_URL', value: url, secret: false, set: true, layer: 'install', description: null, editable: true },
{ name: 'JWT_SECRET', value: null, secret: true, set: true, layer: 'generated', description: null, editable: false },
] }],
} });
test('read: an env-read job the agent can verify, and its result shown on the page', async () => {
const { server, d } = await live();
const job = await jobs.readEnv(d.id, admin, NOW);
expect(job).toMatchObject({ type: 'env-read', args: { church: 'hope', product: 'events' } });
// Asking twice while it waits doesn't make a second job.
expect((await jobs.readEnv(d.id, admin, NOW)).id).toBe(job.id);
expect((await jobs.envState(d.id)).pending).toHaveLength(1);
const [signed] = (await poll(server)).jobs;
expect(agent.agentJobSchema.safeParse(signed).success).toBe(true);
expect(signed.config).toBeNull();
await jobs.receiveReport(server, signedReport(signed, 'succeeded', { result: envResult('https://events.hope.test') }), NOW);
const state = await jobs.envState(d.id);
expect(state.pending).toEqual([]);
expect(state.env.files[0].variables.map(v => [v.name, v.value])).toEqual([['FRONTEND_URL', 'https://events.hope.test'], ['JWT_SECRET', null]]);
});
test('set: plain values and a restart; afterwards the .env is read again', async () => {
const { server, d } = await live();
const job = await jobs.setEnv(d.id, { file: 'backend/.env', set: { FRONTEND_URL: 'https://new.hope.test' }, unset: [], restart: true }, admin, NOW);
expect(job.args).toEqual({ church: 'hope', product: 'events', file: 'backend/.env', set: { FRONTEND_URL: 'https://new.hope.test' }, unset: [], restart: true });
await expect(jobs.setEnv(d.id, { set: { APP_TIMEZONE: 'UTC' } }, admin, NOW)).rejects.toMatchObject({ code: 'ALREADY_PLANNED' });
const [signed] = (await poll(server)).jobs;
expect(agent.agentJobSchema.safeParse(signed).success).toBe(true);
await jobs.receiveReport(server, signedReport(signed, 'succeeded'), NOW);
expect(await db.job.findFirst({ where: { deploymentId: d.id, type: 'env-read', status: 'queued' } })).toBeTruthy();
expect((await jobs.envState(d.id)).lastSet).toMatchObject({ status: 'succeeded' });
});
test("refused: secrets, values the app can't start with, nothing to change, an old agent", async () => {
let { d } = await live();
await expect(jobs.setEnv(d.id, { set: { JWT_SECRET: 'x' } }, admin, NOW)).rejects.toMatchObject({ status: 400, message: expect.stringContaining('secret') });
await expect(jobs.setEnv(d.id, { set: { TRUST_PROXY: 'TRUE' } }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_VALUE' });
await expect(jobs.setEnv(d.id, { set: {} }, admin, NOW)).rejects.toMatchObject({ status: 400 });
await expect(jobs.setEnv(d.id, { file: '../.env', set: { A: '1' } }, admin, NOW)).rejects.toMatchObject({ status: 400 });
await seed();
({ d } = await live({ agentVersion: '1.2.0' }));
await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.3.0') });
await seed();
// 2.26.0: the Website's and App's .env too, on an agent whose script knows them.
({ d } = await live({ product: 'website' }));
await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.6.0') });
await seed();
({ d } = await live({ product: 'app', agentVersion: '1.6.0' }));
await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.7.0') });
expect(await db.job.findMany({})).toEqual([]);
});
test('2.26.0: the Website and the App have .env settings too', async () => {
for (const [product, agentVersion] of [['website', '1.6.0'], ['app', '1.7.0']]) {
await seed();
const { d } = await live({ product, agentVersion });
expect(await jobs.readEnv(d.id, admin, NOW)).toMatchObject({ type: 'env-read', args: { church: 'hope', product } });
expect((await jobs.envState(d.id)).supported).toBe(true);
}
});
});
describe('ports checked on both servers before an install (2.11.0)', () => {
const probeReport = (job, free, reasons = {}) => signedReport(job, 'succeeded', { result: { configPath: '/etc/frp/x.toml', ports: job.args.ports.map(p => ({ port: p, free: free(p), reason: free(p) ? null : reasons[p] || 'in use' })) } });
async function setup() {
const { server } = await joinServer('church', 'church-1');
const { server: central } = await joinServer('central', 'central-1');
for (const s of [server, central]) await db.server.update({ where: { id: s.id }, data: { agentVersion: '1.4.0', lastSeenAt: NOW } });
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
return { server: await db.server.findUnique({ where: { id: server.id } }), central: await db.server.findUnique({ where: { id: central.id } }) };
}
const probesOf = async () => db.job.findMany({ where: { type: 'probe-ports' } });
test('the install waits for both checks, then runs on the first pair free on both', async () => {
const { server, central } = await setup();
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(out.checkingPorts).toBe(true);
const install = (await db.job.findMany({ where: { type: 'install' } }))[0];
expect(install.status).toBe('scheduled');
const probes = await probesOf();
expect(probes.map(p => p.serverId).sort()).toEqual([server.id, central.id].sort());
expect(probes[0].args.ports).toHaveLength(2 + jobs.PROBE_SPARE);
// Reserved: no other install gets them meanwhile.
expect(await db.port.count({ where: { role: 'candidate' } })).toBe(jobs.PROBE_SPARE);
// The church server can't use 20000; the central server can't use 20003.
const cp = probes.find(p => p.serverId === central.id);
const sp = probes.find(p => p.serverId === server.id);
await jobs.receiveReport(central, probeReport(cp, p => p !== 20003, { 20003: 'In use: something listens on 0.0.0.0.' }), NOW);
expect((await db.job.findUnique({ where: { id: install.id } })).status).toBe('scheduled');
await jobs.receiveReport(server, probeReport(sp, p => p !== 20000), NOW);
const after = await db.job.findUnique({ where: { id: install.id } });
expect(after.status).toBe('queued');
expect(after.args.ports).toEqual({ events: { web: 20001, api: 20002 } });
expect(await db.deployment.findUnique({ where: { id: out.deployment.id } })).toMatchObject({ webPort: 20001, apiPort: 20002 });
expect((await db.port.findUnique({ where: { port: 20000 } })).role).toBe('taken');
expect((await db.port.findUnique({ where: { port: 20003 } })).note).toMatch(/central-1/);
expect(await db.port.count({ where: { role: 'candidate' } })).toBe(0);
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.4.0', mode: 'church', runningJobId: null }, NOW)).jobs;
expect(job.type).toBe('install');
expect(agent.agentJobSchema.safeParse(job).success).toBe(true);
});
test('too few free: another round with new ports; a check that fails stops the install', async () => {
const { server, central } = await setup();
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
for (const p of await probesOf()) await jobs.receiveReport(p.serverId === server.id ? server : central, probeReport(p, () => false), NOW);
const round2 = (await probesOf()).filter(p => p.reason === 'ports round 2');
expect(round2).toHaveLength(2);
expect(round2[0].args.ports.every(p => p >= 20010)).toBe(true);
await jobs.receiveReport(central, signedReport(round2.find(p => p.serverId === central.id), 'failed', { message: 'boom' }), NOW);
await jobs.receiveReport(server, probeReport(round2.find(p => p.serverId === server.id), () => true), NOW);
expect((await db.deployment.findUnique({ where: { id: out.deployment.id } })).status).toBe('failed');
expect((await db.job.findMany({ where: { type: 'install' } }))[0].status).toBe('cancelled');
expect(await db.port.count({ where: { role: { in: ['candidate', 'web', 'api'] } } })).toBe(0);
expect(mockMails.some(m => /Install not started/.test(m.subject))).toBe(true);
});
test('Accounts first: both installs get ports from the same check, and run one after the other', async () => {
const { server, central } = await setup();
await db.release.create({ data: { id: 'r3', product: 'events', version: '3.0.0', notes: '- 3', releasedAt: NOW, requires: [{ product: 'accounts', version: '1.0.0' }] } });
await db.release.create({ data: { id: 'a1', product: 'accounts', version: '1.0.0', notes: '- 1', releasedAt: NOW } });
await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'events.grace.co.za' }, admin, NOW);
for (const p of await probesOf()) await jobs.receiveReport(p.serverId === server.id ? server : central, probeReport(p, () => true), NOW);
const installs = await db.job.findMany({ where: { type: { in: ['install', 'add-product'] } }, orderBy: { batchOrder: 'asc' } });
expect(installs.map(j => j.status)).toEqual(['queued', 'scheduled']);
expect(installs[0].args.ports.accounts).toEqual({ web: 20000, api: 20001 });
expect(installs[1].args.ports).toEqual({ web: 20002, api: 20003 });
});
test('older agents: the install runs as before, with a warning', async () => {
const { server } = await setup();
await db.server.update({ where: { id: server.id }, data: { agentVersion: '1.3.1' } });
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(out.checkingPorts).toBe(false);
expect(out.warnings.join(' ')).toMatch(/agent 1.4.0 or later/);
expect((await db.job.findMany({ where: { type: 'install' } }))[0].status).toBe('queued');
});
test('the central agent offline: refused', async () => {
const { server, central } = await setup();
await db.server.update({ where: { id: central.id }, data: { lastSeenAt: new Date(NOW.getTime() - H) } });
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'CENTRAL_OFFLINE' });
});
});
describe("frp's config from the Hub (2.11.0)", () => {
async function central(version = '1.4.0') {
const { server } = await joinServer('central', 'central-1');
return db.server.update({ where: { id: server.id }, data: { agentVersion: version } });
}
const readResult = { service: 'frps', path: '/usr/local/frp/frps.toml', source: 'hub', found: true, format: 'toml', content: 'bindPort = 7000\nauth.token = "***hidden***"\n', hidden: ['auth.token'], proxyBindAddr: '127.0.0.1', allowPorts: '20000-29999', serviceRunning: true, readAt: NOW.toISOString() };
test('set the path, read, then change it with two-factor', async () => {
const s = await central();
await expect(jobs.readFrp(s.id, { path: '/etc/shadow' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
const read = await jobs.readFrp(s.id, { path: '/usr/local/frp/frps.toml' }, admin, NOW);
expect(read.args).toEqual({ path: '/usr/local/frp/frps.toml' });
expect((await db.server.findUnique({ where: { id: s.id } })).frpConfigPath).toBe('/usr/local/frp/frps.toml');
await expect(jobs.writeFrp(s.id, { content: 'x', totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ code: 'READ_FIRST' });
await jobs.receiveReport(s, signedReport(read, 'succeeded', { result: readResult }), NOW);
expect((await db.server.findUnique({ where: { id: s.id } })).frpConfig).toMatchObject({ path: '/usr/local/frp/frps.toml', found: true });
await expect(jobs.writeFrp(s.id, { content: 'bindPort = 7001\n', totp: '000000' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_TOTP' });
const write = await jobs.writeFrp(s.id, { content: 'bindPort = 7001\n', restart: true, totp: totpNow() }, admin, NOW);
expect(write.args).toEqual({ path: '/usr/local/frp/frps.toml', content: 'bindPort = 7001\n', restart: true });
await expect(jobs.writeFrp(s.id, { content: 'bindPort = 7002\n', totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ code: 'BUSY' });
await jobs.receiveReport(s, signedReport(write, 'rolled-back', { result: readResult, message: 'frps did not start' }), NOW);
expect(mockMails.some(m => /frp config change rolled back/.test(m.subject))).toBe(true);
});
test('older agents are refused', async () => {
const s = await central('1.3.1');
await expect(jobs.readFrp(s.id, {}, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD' });
});
test('alerts name the file, and a config not found', () => {
const base = { mode: 'central', name: 'central-1', lastSeenAt: NOW };
const wrongBind = servers.serverProblems({ ...base, lastStats: { disks: [], frpConfigPath: '/usr/local/frp/frps.toml', central: { proxyBindAddr: null, frpsRunning: true } } }, [], [], NOW);
expect(wrongBind.map(p => p.type)).toEqual(['proxy_bind_addr']);
expect(wrongBind[0].message).toMatch(/\/usr\/local\/frp\/frps.toml/);
const missing = servers.serverProblems({ ...base, lastStats: { disks: [], frpConfigPath: null, central: { proxyBindAddr: null, frpsRunning: true } } }, [], [], NOW);
expect(missing.map(p => p.type)).toEqual(['frp_config_missing']);
});
});
describe('uninstalling one product of a church, and stale installs (2.12.0)', () => {
const at = new Date(NOW.getTime() + 5 * H);
const pollAs = (server, agentVersion, when = at) => jobs.poll(server, { agentApiVersion: 1, agentVersion, mode: 'church', runningJobId: null }, when);
async function church({ agentVersion = '1.5.0' } = {}) {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.server.update({ where: { id: server.id }, data: { agentVersion } });
const evInst = await db.install.create({ data: { id: 'inst-ev', customerId: 'cust-1', product: 'events', name: 'Hope', url: 'https://events.hope.co.za', secret: 'x', lastHeartbeatAt: NOW } });
const accInst = await db.install.create({ data: { id: 'inst-acc', customerId: 'cust-1', product: 'accounts', name: 'Hope', url: 'https://accounts.hope.co.za', secret: 'x', lastHeartbeatAt: NOW } });
const ev = await db.deployment.create({ data: { id: 'dep-ev', serverId: server.id, customerId: 'cust-1', installId: evInst.id, product: 'events', shortName: 'hope', domain: 'events.hope.co.za', webPort: 20000, apiPort: 20001, status: 'live', liveAt: NOW, createdAt: NOW } });
const acc = await db.deployment.create({ data: { id: 'dep-acc', serverId: server.id, customerId: 'cust-1', installId: accInst.id, product: 'accounts', shortName: 'hope', domain: 'accounts.hope.co.za', webPort: 20002, apiPort: 20003, status: 'live', liveAt: NOW, createdAt: NOW } });
for (const port of [20000, 20001, 20002, 20003]) await db.port.create({ data: { port, serverId: server.id, role: port % 2 ? 'api' : 'web' } });
return { server, ev, acc };
}
async function runBatch(server, agentVersion) {
const exp = (await pollAs(server, agentVersion)).jobs[0];
await jobs.receiveReport(server, signedReport(exp, 'succeeded'), at);
const un = (await pollAs(server, agentVersion)).jobs[0];
await jobs.receiveReport(server, signedReport(un, 'succeeded'), at);
return { exp, un };
}
test('agent 1.5.0: only Events goes, Accounts stays live; then Accounts on its own', async () => {
const { server, ev, acc } = await church();
await jobs.scheduleUninstall({ deploymentId: ev.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW);
const { exp, un } = await runBatch(server, '1.5.0');
expect(exp.args.products).toEqual(['events']);
expect(un.args).toEqual({ church: 'hope', products: ['events'] });
expect(await db.deployment.findUnique({ where: { id: ev.id } })).toMatchObject({ status: 'removed' });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'live' });
expect((await db.job.findFirst({ where: { type: 'purge', deploymentId: ev.id } })).args).toEqual({ church: 'hope', products: ['events'] });
await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW);
const second = await runBatch(server, '1.5.0');
expect(second.un.args).toEqual({ church: 'hope', products: ['accounts'] });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
});
test('Accounts goes last: refused while Events stays, and not planned before Events\' uninstall', async () => {
const { ev, acc } = await church();
await expect(jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW)).rejects.toMatchObject({ code: 'ACCOUNTS_IN_USE' });
await jobs.scheduleUninstall({ deploymentId: ev.id, totp: totpNow(), confirm: 'hope', at: new Date(at.getTime() + H) }, admin, NOW);
await expect(jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at, join: false }, admin, NOW)).rejects.toMatchObject({ code: 'ACCOUNTS_FIRST' });
await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at: new Date(at.getTime() + 2 * H), join: false }, admin, NOW);
});
test('an older agent would remove the whole church: refused while it has other products', async () => {
const { ev } = await church({ agentVersion: '1.4.0' });
await expect(jobs.scheduleUninstall({ deploymentId: ev.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD' });
const plan = await jobs.uninstallPlan(await db.deployment.findUnique({ where: { id: ev.id }, include: { server: true } }));
expect(plan).toMatchObject({ onlyThisProduct: false, others: [{ product: 'accounts' }] });
});
test('a whole-church uninstall (no products) removes every product of it here, and cancels what was planned for them', async () => {
const { server, ev, acc } = await church({ agentVersion: '1.4.0' });
// As from Hub 2.11.0: an uninstall without products, and Accounts' own batch planned after it.
const un = await jobs.makeJob(db, { serverId: server.id, type: 'uninstall', deploymentId: ev.id, args: { church: 'hope' }, notBefore: at });
const later = await jobs.makeJob(db, { serverId: server.id, type: 'export', deploymentId: acc.id, status: 'scheduled', args: { church: 'hope', exportId: 'exp_abcdefgh' }, notBefore: new Date(at.getTime() + H) });
const job = (await pollAs(server, '1.4.0')).jobs[0];
expect(job.id).toBe(un.id);
await jobs.receiveReport(server, signedReport(job, 'succeeded'), at);
expect(await db.deployment.findUnique({ where: { id: ev.id } })).toMatchObject({ status: 'removed' });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
expect((await db.install.findUnique({ where: { id: 'inst-acc' } })).releasedAt).toEqual(at);
expect(await db.job.findUnique({ where: { id: later.id } })).toMatchObject({ status: 'cancelled' });
expect((await db.job.findFirst({ where: { type: 'purge', deploymentId: ev.id } })).args).toEqual({ church: 'hope' });
});
test('an install without a heartbeat for 24 hours can be removed from the Hub; a fresh one can\'t', async () => {
const { server, acc } = await church();
const later = new Date(NOW.getTime() + 23 * H);
await expect(jobs.forgetStale(acc.id, { confirm: 'hope' }, later)).rejects.toMatchObject({ code: 'NOT_STALE' });
const dayLater = new Date(NOW.getTime() + 25 * H);
await expect(jobs.forgetStale(acc.id, { confirm: 'nope' }, dayLater)).rejects.toMatchObject({ code: 'CONFIRM' });
const planned = await jobs.makeJob(db, { serverId: server.id, type: 'env-read', deploymentId: acc.id, args: { church: 'hope', product: 'accounts' }, status: 'scheduled', notBefore: dayLater });
await jobs.forgetStale(acc.id, { confirm: 'hope' }, dayLater);
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
expect((await db.install.findUnique({ where: { id: 'inst-acc' } })).releasedAt).toEqual(dayLater);
expect(await db.job.findUnique({ where: { id: planned.id } })).toMatchObject({ status: 'cancelled' });
expect((await db.port.findMany({ where: { port: { in: [20002, 20003] } } })).every(p => p.releasedAt)).toBe(true);
});
});
describe('a second product while another is being uninstalled (2.12.0)', () => {
const at = new Date(NOW.getTime() + 5 * H);
const poll = (server, when = at) => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.5.0', mode: 'church', runningJobId: null }, when);
async function church() {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const ev = await db.deployment.create({ data: { id: 'dep-ev', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'hope', domain: 'events.hope.co.za', webPort: 20000, apiPort: 20001, status: 'live', liveAt: NOW, createdAt: NOW } });
const acc = await db.deployment.create({ data: { id: 'dep-acc', serverId: server.id, customerId: 'cust-1', product: 'accounts', shortName: 'hope', domain: 'accounts.hope.co.za', webPort: 20002, apiPort: 20003, status: 'live', liveAt: NOW, createdAt: NOW } });
await db.server.update({ where: { id: server.id }, data: { agentVersion: '1.5.0' } });
await jobs.scheduleUninstall({ deploymentId: ev.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW);
return { server, ev, acc };
}
test('the Hub asks: join that run, or a time of its own', async () => {
const { acc } = await church();
await expect(jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW)).rejects.toMatchObject({ code: 'CHOOSE' });
const plan = await jobs.uninstallPlan(await db.deployment.findUnique({ where: { id: acc.id }, include: { server: true } }));
expect(plan).toMatchObject({ lastProduct: true, pending: [{ products: ['events'], joinable: true }] });
});
test('joined: one export and one uninstall for both, which removes the whole church', async () => {
const { server, ev, acc } = await church();
const out = await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', join: true }, admin, NOW);
expect(out.joined).toBe(true);
expect(out.uninstallJob.notBefore).toEqual(at);
expect(await db.job.count({ where: { type: 'uninstall' } })).toBe(1);
const exp = (await poll(server)).jobs[0];
expect(exp.args.products).toEqual(['accounts', 'events']);
await jobs.receiveReport(server, signedReport(exp, 'succeeded'), at);
const un = (await poll(server)).jobs[0];
expect(un.args).toEqual({ church: 'hope', products: ['accounts', 'events'] });
await jobs.receiveReport(server, signedReport(un, 'succeeded', { result: { products: ['accounts', 'events'], remaining: [] } }), at);
expect(await db.deployment.findUnique({ where: { id: ev.id } })).toMatchObject({ status: 'removed' });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
});
test('joined, and the export fails: both are live again', async () => {
const { server, ev, acc } = await church();
await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', join: true }, admin, NOW);
const exp = (await poll(server)).jobs[0];
await jobs.receiveReport(server, signedReport(exp, 'failed'), at);
expect(await db.deployment.findUnique({ where: { id: ev.id } })).toMatchObject({ status: 'live' });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'live' });
});
test('a run less than 4 hours away can\'t be joined (the church needs notice)', async () => {
const { acc } = await church();
await expect(jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', join: true }, admin, new Date(at.getTime() - 2 * H))).rejects.toMatchObject({ code: 'TOO_SOON' });
});
test('its own, later time: the last product left takes the whole church with it', async () => {
const { server, ev, acc } = await church();
const later = new Date(at.getTime() + H);
await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at: later, join: false }, admin, NOW);
expect(await db.job.count({ where: { type: 'uninstall' } })).toBe(2);
// 10:00: Events only; the church keeps Accounts.
const exp1 = (await poll(server)).jobs[0];
await jobs.receiveReport(server, signedReport(exp1, 'succeeded'), at);
const un1 = (await poll(server)).jobs[0];
expect(un1.args.products).toEqual(['events']);
await jobs.receiveReport(server, signedReport(un1, 'succeeded', { result: { products: ['events'], remaining: ['accounts'] } }), at);
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'uninstalling' });
// 11:00: Accounts, the last one: the script removes the church (remaining is empty).
const exp2 = (await poll(server, later)).jobs[0];
await jobs.receiveReport(server, signedReport(exp2, 'succeeded'), later);
const un2 = (await poll(server, later)).jobs[0];
expect(un2.args.products).toEqual(['accounts']);
await jobs.receiveReport(server, signedReport(un2, 'succeeded', { result: { products: ['accounts'], remaining: [] } }), later);
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
expect(mockMails.some(m => m.subject.includes('Uninstalled: hope') && m.text.includes('folder and app user'))).toBe(true);
});
});
describe('frps allow_ports and port labels (Hub 2.20.0)', () => {
const frpcIni = [
'[common]', 'server_port = 7000', 'token = ••••••', '',
'[events-frontend]', 'type = tcp', 'local_port = 3000', 'remote_port = 3000', '',
'[games-night]', 'type = tcp', 'local_port = 3201', 'remote_port = 3201', '',
'# >>> crosscode:hope:events', '[hope-events-web]', 'type = tcp', 'local_port = 20000', 'remote_port = 20000', '# <<< crosscode:hope:events', '',
].join('\n');
const read = content => ({ service: 'frpc', path: '/etc/frp/frpc.ini', source: 'systemd', found: true, format: 'ini', content, hidden: ['token'], proxyBindAddr: null, allowPorts: null, serviceRunning: true, readAt: NOW.toISOString() });
test("a church server's hand-written tunnels are listed as taken, and taken off when they go", async () => {
const { server } = await joinServer();
await db.port.create({ data: { port: 20000, serverId: server.id, role: 'web', deploymentId: 'dep-1' } });
await db.port.create({ data: { port: 3201, role: 'taken', note: 'mine' } });
await jobs.listFrpcTunnels(server.id, read(frpcIni), NOW);
const rows = Object.fromEntries((await db.port.findMany({})).map(r => [r.port, r]));
expect(rows[3000]).toMatchObject({ role: 'taken', serverId: server.id, note: 'frpc tunnel "events-frontend" on church-1' });
expect(rows[3201].note).toBe('mine'); // marked by hand: left as it is
expect(rows[20000]).toMatchObject({ role: 'web', deploymentId: 'dep-1' }); // an install's
await jobs.listFrpcTunnels(server.id, read(frpcIni.replace('remote_port = 3000', 'remote_port = 3005')), NOW);
const after = (await db.port.findMany({})).map(r => r.port).sort((a, b) => a - b);
expect(after).toEqual([3005, 3201, 20000]);
// A central server's frps config lists nothing.
const central = (await joinServer('central', 'central-1')).server;
await jobs.listFrpcTunnels(central.id, read('[common]\n[x]\nremote_port = 4444\n'), NOW);
expect(await db.port.findUnique({ where: { port: 4444 } })).toBeNull();
});
test('the central server is warned when allow_ports leaves out the range or a listed port', async () => {
const central = (await joinServer('central', 'central-1')).server;
await db.port.create({ data: { port: 3000, role: 'taken', note: 'frpc tunnel "events-frontend" on church-1' } });
await db.port.create({ data: { port: 5000, role: 'taken', releasedAt: NOW } });
const check = await servers.allowPortsCheck('3000,20000-20007');
expect(check).toMatchObject({ needed: '3000,20000-29999', missing: '20008-29999', suggested: '3000,20000-29999' });
expect((await servers.allowPortsCheck('3000,20000-29999')).missing).toBe('');
expect((await servers.allowPortsCheck(null)).missing).toBe('');
await db.server.update({ where: { id: central.id }, data: { lastSeenAt: NOW, lastStats: { disks: [], frpConfigPath: '/etc/frp/frps.ini', central: { proxyBindAddr: '127.0.0.1', allowPorts: '20000-29999', frpsRunning: true } } } });
await servers.runServerAlerts(NOW);
const alert = await db.serverAlert.findFirst({ where: { serverId: central.id, type: 'allow_ports' } });
expect(alert.message).toContain("doesn't allow 3000");
expect(alert.message).toContain('Set it to 3000,20000-29999');
await db.server.update({ where: { id: central.id }, data: { lastStats: { disks: [], frpConfigPath: '/etc/frp/frps.ini', central: { proxyBindAddr: '127.0.0.1', allowPorts: '3000,20000-29999', frpsRunning: true } } } });
await servers.runServerAlerts(NOW);
expect((await db.serverAlert.findFirst({ where: { serverId: central.id, type: 'allow_ports' } })).resolvedAt).toEqual(NOW);
});
});
describe('a whole church to latest in one go (2.24.0)', () => {
const at = () => new Date(NOW.getTime() + 5 * H);
async function church() {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.release.create({ data: { id: 'r30', product: 'events', version: '3.0.0', notes: '- Accounts', requires: [{ product: 'accounts', version: '1.1.0' }], releasedAt: NOW } });
await db.release.create({ data: { id: 'ra10', product: 'accounts', version: '1.0.0', releasedAt: NOW } });
await db.release.create({ data: { id: 'ra11', product: 'accounts', version: '1.1.0', releasedAt: NOW } });
await db.release.create({ data: { id: 'rw10', product: 'website', version: '1.0.0', releasedAt: NOW } });
const dep = (id, product, version, port) => db.deployment.create({ data: { id, serverId: server.id, customerId: 'cust-1', product, shortName: 'hope', domain: `${product}.hope.co.za`, webPort: port, apiPort: port + 1, status: 'live', version } });
const ev = await dep('ev-hope', 'events', '2.4.0', 22000);
const acc = await dep('acc-hope', 'accounts', '1.0.0', 22010);
const web = await dep('web-hope', 'website', '1.0.0', 22020);
return { server, ev, acc, web };
}
test('the plan lists every product in update order, Accounts first, and says which are behind', async () => {
await church();
const plan = await jobs.churchUpdatePlan('cust-1');
expect(plan.map(p => [p.product, p.current, p.latest, p.ready])).toEqual([
['accounts', '1.0.0', '1.1.0', true], ['events', '2.4.0', '3.0.0', true], ['website', '1.0.0', '1.0.0', false],
]);
expect(plan[2].why).toBe('On the latest release.');
});
test('one batch: Accounts first, then Events, which keeps the new Accounts; up to date products are left alone', async () => {
const { server } = await church();
const out = await jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW);
expect(out.batchId).toMatch(/^batch_/);
expect(out.jobs.map(j => [j.deploymentId, j.status, j.batchOrder, j.batchId])).toEqual([
['acc-hope', 'queued', 0, out.batchId], ['ev-hope', 'scheduled', 1, out.batchId],
]);
expect(out.jobs[0].args.versions).toEqual(['accounts@1.1.0']);
// Not accounts@1.0.0: that would undo the update just before it.
expect(out.jobs[1].args.versions).toEqual(['accounts@1.1.0', 'events@3.0.0']);
expect(out.updates).toEqual([
{ product: 'accounts', domain: 'accounts.hope.co.za', from: '1.0.0', to: '1.1.0' },
{ product: 'events', domain: 'events.hope.co.za', from: '2.4.0', to: '3.0.0' },
]);
// The batch runs on: Accounts succeeds, so Events is queued.
const poll = when => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, when);
const first = (await poll(at())).jobs[0];
expect(first.id).toBe(out.jobs[0].id);
await jobs.receiveReport(server, signedReport(first, 'succeeded'), at());
expect((await db.job.findUnique({ where: { id: out.jobs[1].id } })).status).toBe('queued');
// Everything is planned now: a second click is refused.
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_READY' });
});
test('planned whole or not at all, and refused when there is nothing to update', async () => {
const { ev } = await church();
await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '2.4.0', at: at() }, admin, NOW).catch(() => null);
const { jobs: [planned] } = await jobs.scheduleUpdate({ deploymentIds: ['acc-hope'], version: '1.1.0', at: at() }, admin, NOW);
const before = await db.job.count();
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_READY', message: expect.stringContaining('Accounts (accounts.hope.co.za): An update is planned') });
expect(await db.job.count()).toBe(before);
expect(planned.status).toBe('queued');
await db.deployment.update({ where: { id: 'ev-hope' }, data: { version: '3.0.0' } });
await db.deployment.update({ where: { id: 'acc-hope' }, data: { version: '1.1.0' } });
await db.job.update({ where: { id: planned.id }, data: { status: 'cancelled' } });
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'UP_TO_DATE' });
});
test('an emergency runs as soon as possible, with a reason and one two-factor code', async () => {
await church();
await expect(jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, reason: 'Security fix', totp: '000000' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_TOTP' });
await expect(jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ message: expect.stringContaining('reason') });
const out = await jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, reason: 'Security fix', totp: totpNow() }, admin, NOW);
expect(out.jobs.map(j => [j.emergency, j.reason, j.status])).toEqual([[true, 'Security fix', 'queued'], [true, 'Security fix', 'scheduled']]);
expect(out.jobs[0].notBefore).toEqual(NOW);
});
});
describe('the Church App from the Hub (2.26.0)', () => {
const poll = (server) => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.7.0', mode: 'church', runningJobId: null }, NOW);
beforeEach(async () => {
await db.release.create({ data: { id: 'rp1', product: 'app', version: '1.0.0', notes: '- First release', releasedAt: NOW } });
await db.release.create({ data: { id: 'ra9', product: 'accounts', version: '1.9.0', notes: '- messaging.get', releasedAt: NOW } });
});
test('a new church: Accounts 1.9.0 first (even with no "requires" in its notes), then the App, with a CCP- licence on Mustard Seed', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const out = await jobs.newInstall({ product: 'app', customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'app.grace.co.za' }, admin, NOW);
expect(out.alsoInstalling).toEqual({ product: 'accounts', domain: 'accounts.grace.co.za', version: '1.9.0' });
const [first] = (await poll(server)).jobs;
expect(first).toMatchObject({ type: 'install', args: { products: ['accounts'] } });
await jobs.receiveReport(server, signedReport(first, 'succeeded', { result: { versions: { accounts: 'accounts@1.9.0' } } }), NOW);
const [second] = (await poll(server)).jobs;
expect(second).toMatchObject({ type: 'add-product', args: { church: 'grace', product: 'app', version: 'app@1.0.0', domain: 'app.grace.co.za' } });
expect(agent.agentJobSchema.safeParse(second).success).toBe(true);
const key = signing.openConfig(second.config, keys.x.privateKeyPem).install.app.HUB_LICENCE_KEY;
expect(key).toMatch(/^CCP-/);
expect(await db.licence.findFirst({ where: { key } })).toMatchObject({ product: 'app', plan: 'Mustard Seed' });
});
test('a church whose Accounts is older than 1.9.0 is asked to update it first', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.deployment.create({ data: { id: 'acc-old', serverId: server.id, customerId: 'cust-1', product: 'accounts', shortName: 'hope', domain: 'accounts.hope.co.za', webPort: 20000, apiPort: 20001, status: 'live', version: '1.8.0' } });
await expect(jobs.newInstall({ product: 'app', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'app.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'REQUIREMENT_NOT_MET', message: expect.stringContaining('1.9.0') });
});
test('the FastPanel steps for app.<address>', async () => {
const text = await jobs.fastPanelText({ id: 'd1', product: 'app', shortName: 'grace', domain: 'app.grace.co.za', webPort: 20010, apiPort: 20011, customer: { name: 'Grace' } });
expect(text).toContain('Grace, Church App');
expect(text).toContain('location ^~ /api/ {');
expect(text).not.toContain('301');
});
});
describe('demo scenarios (2.26.0)', () => {
const VERSIONS = { accounts: '1.9.0', events: '3.8.0', website: '1.8.0', app: '1.0.0' };
async function demoClient({ products = ['accounts', 'events', 'website', 'app'], agentVersion = '1.7.0', versions = {} } = {}) {
const { server } = await joinServer();
await db.server.update({ where: { id: server.id }, data: { agentVersion, lastSeenAt: NOW } });
await db.customer.update({ where: { id: 'cust-1' }, data: { isDemo: true } });
let port = 20000;
for (const product of products) {
await db.deployment.create({ data: { id: `dep-${product}`, serverId: server.id, customerId: 'cust-1', product, shortName: 'demo2', domain: `${product}.demo2.test`, webPort: port++, apiPort: port++, status: 'live', isDemo: true, version: versions[product] || VERSIONS[product], adminEmail: product === 'events' ? 'Jane@Hope.test' : null } });
}
return { server };
}
test('the plan lists what it replaces, Accounts first; loading it is one seed-scenario job the agent can verify', async () => {
const { server } = await demoClient({ products: ['website', 'accounts', 'events'] });
const plan = await jobs.scenarioPlan('cust-1', 'bold-youth', NOW);
expect(plan).toMatchObject({ shortName: 'demo2', problems: [], notCovered: [] });
expect(plan.installs.map(i => [i.product, i.profile])).toEqual([['accounts', 'bold-youth'], ['events', 'bold-youth'], ['website', 'bold-youth']]);
await expect(jobs.loadScenario('cust-1', { scenario: 'bold-youth', confirm: 'nope' }, admin, NOW)).rejects.toMatchObject({ code: 'CONFIRM' });
const { job } = await jobs.loadScenario('cust-1', { scenario: 'bold-youth', confirm: 'demo2' }, admin, NOW);
expect(job).toMatchObject({ type: 'seed-scenario', deploymentId: 'dep-accounts', args: { church: 'demo2', scenario: 'bold-youth', adminEmail: 'jane@hope.test' } });
const polled = await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.7.0', mode: 'church', runningJobId: null }, NOW);
expect(agent.agentJobSchema.safeParse(polled.jobs[0]).success).toBe(true);
// A second one waits for the first.
expect((await jobs.scenarioPlan('cust-1', 'bold-youth', NOW)).problems).toEqual([expect.stringContaining('already loading')]);
await jobs.receiveReport(server, signedReport(polled.jobs[0], 'succeeded', { result: { loaded: 'accounts events website', skipped: 'app' } }), NOW);
expect(await db.customer.findUnique({ where: { id: 'cust-1' } })).toMatchObject({ demoScenario: 'bold-youth', demoScenarioAt: NOW, demoScenarioJobId: null });
expect((await db.deployment.findMany({})).map(d => d.demoScenario)).toEqual(['bold-youth', 'bold-youth', 'bold-youth']);
expect(mockMails.at(-1).subject).toBe('Cross Code Hub: Demo scenario loaded: demo2');
expect((await jobs.scenarioPlan('cust-1', null, NOW)).installs.every(i => !i.outOfStep)).toBe(true);
});
test("a failure stops the rest: the products it didn't load are out of step", async () => {
const { server } = await demoClient();
const { job } = await jobs.loadScenario('cust-1', { scenario: 'clean-campus', confirm: 'demo2' }, admin, NOW);
await jobs.receiveReport(server, signedReport(job, 'failed', { result: { loaded: 'accounts', skipped: '' } }), NOW);
expect(await db.customer.findUnique({ where: { id: 'cust-1' } })).toMatchObject({ demoScenario: 'clean-campus', demoScenarioJobId: null });
const plan = await jobs.scenarioPlan('cust-1', null, NOW);
expect(plan.installs.map(i => [i.product, i.outOfStep])).toEqual([['accounts', false], ['events', true], ['website', true], ['app', true]]);
expect(mockMails.at(-1).subject).toBe('Cross Code Hub: Demo scenario failed: demo2');
});
test('one product loaded on its own is out of step with the scenario', async () => {
const { server } = await demoClient({ products: ['accounts', 'events'] });
const { job } = await jobs.loadScenario('cust-1', { scenario: 'heritage-city', confirm: 'demo2' }, admin, NOW);
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: { loaded: 'accounts events', skipped: 'website app' } }), NOW);
const single = await jobs.seedDemo({ deploymentId: 'dep-events', profile: 'small', confirm: 'demo2' }, admin, NOW);
await jobs.receiveReport(server, signedReport(single, 'succeeded'), NOW);
expect((await jobs.scenarioPlan('cust-1', null, NOW)).installs.find(i => i.product === 'events')).toMatchObject({ outOfStep: true, demoScenario: null });
});
test('refused: not a demo client, an old agent, an install on too old a release, unknown scenario', async () => {
await demoClient({ agentVersion: '1.6.0', versions: { events: '3.7.2' } });
const plan = await jobs.scenarioPlan('cust-1', 'heritage-parish', NOW);
expect(plan.problems).toEqual(expect.arrayContaining([expect.stringContaining('1.7.0'), expect.stringContaining('Cross Events is 3.7.2')]));
expect(plan.installs.find(i => i.product === 'events')).toMatchObject({ tooOld: true, minVersion: '3.8.0' });
await expect(jobs.loadScenario('cust-1', { scenario: 'heritage-parish', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'CANT_LOAD_SCENARIO' });
await expect(jobs.scenarioPlan('cust-1', 'everything', NOW)).rejects.toMatchObject({ status: 400 });
await db.customer.update({ where: { id: 'cust-1' }, data: { isDemo: false } });
expect((await jobs.scenarioPlan('cust-1', 'heritage-parish', NOW)).problems).toEqual(expect.arrayContaining([expect.stringContaining("isn't a demo client")]));
expect(await db.job.findMany({})).toEqual([]);
});
});