Servers and the agent, backend (2.1.0): join, jobs, schedules, port list, stats, alerts
- Agent API /api/agent/v1: join with a one-time token, then poll, stats, report and export upload, all signed with the server's Ed25519 key. - Jobs signed with a separate job key (HUB_JOB_SIGNING_KEY_FILE) when delivered, config sealed to the server; one at a time per server; missed when not picked up in their window. - New install (licence, ports, preflight against the release's env template), Proxy done with public URL checks, scheduled / emergency (2FA, reason) / batch updates with email and banner, uninstall with an encrypted export first (the key is never stored), adopt and linking existing installs, purge after 30 days. - Port list, install defaults, server configuration (encrypted), stats per minute / hour with roll-up, server alerts. contracts 1.3.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* A small in-memory stand-in for the Prisma client, enough for the servers / jobs tests: where
|
||||
* filters (equals, in, notIn, not, lt/lte/gt/gte, OR, AND, nested relation-free), include of the
|
||||
* relations listed in RELATIONS, orderBy, take, create / update / upsert / delete / count and
|
||||
* $transaction. Not a database: no constraints beyond what the code under test checks itself.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
// model → relation → [target model, kind, localKey, foreignKey]
|
||||
const RELATIONS = {
|
||||
job: { server: ['server', 'one', 'serverId', 'id'], deployment: ['deployment', 'one', 'deploymentId', 'id'] },
|
||||
deployment: { server: ['server', 'one', 'serverId', 'id'], customer: ['customer', 'one', 'customerId', 'id'], install: ['install', 'one', 'installId', 'id'], jobs: ['job', 'many', 'id', 'deploymentId'], exports: ['export', 'many', 'id', 'deploymentId'] },
|
||||
server: { alerts: ['serverAlert', 'many', 'id', 'serverId'], deployments: ['deployment', 'many', 'id', 'serverId'], ports: ['port', 'many', 'id', 'serverId'] },
|
||||
licence: { install: ['install', 'oneBack', 'id', 'licenceId'] },
|
||||
install: { deployment: ['deployment', 'oneBack', 'id', 'installId'] },
|
||||
port: { server: ['server', 'one', 'serverId', 'id'] },
|
||||
export: { deployment: ['deployment', 'one', 'deploymentId', 'id'] },
|
||||
};
|
||||
const KEYS = { port: 'port', setting: 'key' };
|
||||
|
||||
const cmp = (a, b) => (a instanceof Date ? a.getTime() : a) - (b instanceof Date ? b.getTime() : b);
|
||||
|
||||
function matches(row, where = {}) {
|
||||
for (const [k, cond] of Object.entries(where || {})) {
|
||||
if (k === 'OR') { if (!cond.some(c => matches(row, c))) return false; continue; }
|
||||
if (k === 'AND') { if (!cond.every(c => matches(row, c))) return false; continue; }
|
||||
const v = row[k];
|
||||
if (cond === null) { if (v != null) return false; continue; }
|
||||
if (cond instanceof Date || typeof cond !== 'object') {
|
||||
if (cond instanceof Date ? !(v instanceof Date && v.getTime() === cond.getTime()) : v !== cond) return false;
|
||||
continue;
|
||||
}
|
||||
if ('in' in cond && !cond.in.includes(v)) return false;
|
||||
if ('notIn' in cond && cond.notIn.includes(v)) return false;
|
||||
if ('not' in cond && (cond.not === null ? v == null : v === cond.not)) return false;
|
||||
if ('lt' in cond && !(v != null && cmp(v, cond.lt) < 0)) return false;
|
||||
if ('lte' in cond && !(v != null && cmp(v, cond.lte) <= 0)) return false;
|
||||
if ('gt' in cond && !(v != null && cmp(v, cond.gt) > 0)) return false;
|
||||
if ('gte' in cond && !(v != null && cmp(v, cond.gte) >= 0)) return false;
|
||||
if ('equals' in cond && v !== cond.equals) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function createFakeDb() {
|
||||
const tables = {};
|
||||
const t = name => (tables[name] ||= []);
|
||||
const keyOf = name => KEYS[name] || 'id';
|
||||
|
||||
function include(name, row, inc) {
|
||||
if (!inc || !row) return row;
|
||||
const out = { ...row };
|
||||
for (const [rel, spec] of Object.entries(inc)) {
|
||||
if (!spec) continue;
|
||||
const [target, kind, local, foreign] = RELATIONS[name]?.[rel] || [];
|
||||
// A plain field in a `select` (rows are returned whole), or an unknown relation.
|
||||
if (!target) { if (spec === true && rel in row) continue; throw new Error(`fakeDb: no relation ${name}.${rel}`); }
|
||||
const opts = spec === true ? {} : spec;
|
||||
if (kind === 'one') {
|
||||
const r = t(target).find(x => x[foreign] === row[local]) || null;
|
||||
out[rel] = r ? include(target, r, opts.include) : null;
|
||||
} else if (kind === 'oneBack') {
|
||||
const r = t(target).find(x => x[foreign] === row[local]) || null;
|
||||
out[rel] = r ? include(target, r, opts.include) : null;
|
||||
} else {
|
||||
let list = t(target).filter(x => x[foreign] === row[local] && matches(x, opts.where));
|
||||
list = sort(list, opts.orderBy);
|
||||
if (opts.take) list = list.slice(0, opts.take);
|
||||
out[rel] = list.map(x => include(target, x, opts.include));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function sort(list, orderBy) {
|
||||
if (!orderBy) return list;
|
||||
const orders = Array.isArray(orderBy) ? orderBy : [orderBy];
|
||||
return [...list].sort((a, b) => {
|
||||
for (const o of orders) {
|
||||
const [k, dir] = Object.entries(o)[0];
|
||||
const c = a[k] == null ? -1 : b[k] == null ? 1 : typeof a[k] === 'string' ? a[k].localeCompare(b[k]) : cmp(a[k], b[k]);
|
||||
if (c) return dir === 'desc' ? -c : c;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
const defaults = {
|
||||
job: { status: 'queued', scheduled: false, emergency: false, createdAt: () => new Date() },
|
||||
deployment: { status: 'installing', product: 'events', createdAt: () => new Date() },
|
||||
server: { mode: 'church', joinedAt: () => new Date() },
|
||||
serverAlert: { createdAt: () => new Date(), resolvedAt: null },
|
||||
export: { bytes: 0, extended: false, deletedAt: null, createdAt: () => new Date() },
|
||||
notice: { createdAt: () => new Date(), updatedAt: () => new Date() },
|
||||
licence: { status: 'active', product: 'events' },
|
||||
};
|
||||
|
||||
function model(name) {
|
||||
const key = keyOf(name);
|
||||
const withDefaults = data => {
|
||||
const row = { ...data };
|
||||
for (const [k, v] of Object.entries(defaults[name] || {})) if (row[k] === undefined) row[k] = typeof v === 'function' ? v() : v;
|
||||
if (key === 'id' && !row.id) row.id = crypto.randomUUID();
|
||||
return row;
|
||||
};
|
||||
return {
|
||||
findUnique: async ({ where, include: inc, select }) => include(name, t(name).find(r => matches(r, where)) || null, inc || select),
|
||||
findFirst: async ({ where, include: inc, orderBy } = {}) => include(name, sort(t(name).filter(r => matches(r, where)), orderBy)[0] || null, inc),
|
||||
findMany: async ({ where, include: inc, orderBy, take, select } = {}) => {
|
||||
let list = sort(t(name).filter(r => matches(r, where)), orderBy);
|
||||
if (take) list = list.slice(0, take);
|
||||
return list.map(r => include(name, r, inc || select));
|
||||
},
|
||||
count: async ({ where } = {}) => t(name).filter(r => matches(r, where)).length,
|
||||
create: async ({ data }) => { const row = withDefaults(data); t(name).push(row); return { ...row }; },
|
||||
update: async ({ where, data }) => {
|
||||
const row = t(name).find(r => matches(r, where));
|
||||
if (!row) throw Object.assign(new Error(`fakeDb: ${name} not found`), { code: 'P2025' });
|
||||
Object.assign(row, Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined)));
|
||||
return { ...row };
|
||||
},
|
||||
updateMany: async ({ where, data }) => {
|
||||
const rows = t(name).filter(r => matches(r, where));
|
||||
for (const r of rows) Object.assign(r, data);
|
||||
return { count: rows.length };
|
||||
},
|
||||
upsert: async ({ where, update, create }) => {
|
||||
const row = t(name).find(r => matches(r, where));
|
||||
if (row) { Object.assign(row, update); return { ...row }; }
|
||||
const created = withDefaults(create);
|
||||
t(name).push(created);
|
||||
return { ...created };
|
||||
},
|
||||
delete: async ({ where }) => { const i = t(name).findIndex(r => matches(r, where)); const [r] = tables[name].splice(i, 1); return r; },
|
||||
deleteMany: async ({ where } = {}) => { const before = t(name).length; tables[name] = t(name).filter(r => !matches(r, where)); return { count: before - tables[name].length }; },
|
||||
groupBy: async () => [],
|
||||
};
|
||||
}
|
||||
|
||||
const db = new Proxy({ tables }, {
|
||||
get(target, prop) {
|
||||
if (prop === 'tables') return tables;
|
||||
if (prop === '$transaction') return async fn => (typeof fn === 'function' ? fn(db) : Promise.all(fn));
|
||||
if (prop === '$executeRaw' || prop === '$executeRawUnsafe') return async () => 0;
|
||||
if (typeof prop !== 'string' || prop.startsWith('_') || prop === 'then') return undefined;
|
||||
return (target[prop] ||= model(prop));
|
||||
},
|
||||
});
|
||||
return db;
|
||||
}
|
||||
|
||||
module.exports = { createFakeDb, matches };
|
||||
@@ -0,0 +1,266 @@
|
||||
// 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 } = 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 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'));
|
||||
expect(mail.text).toContain('/api → http://127.0.0.1:20001');
|
||||
expect(mail.text).toContain('everything else → http://127.0.0.1:20000');
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
||||
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']);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user