import { test } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import type { AddressInfo } from 'node:net'; import { Store } from '../src/store.ts'; import { viewAjuan, visible, laneOf, type BoardConfig, type Viewer } from '../src/boardview.ts'; import { createBoard } from '../src/board.ts'; const cfg: BoardConfig = { host: '127.0.0.1', port: 0, publicUrl: 'http://localhost:4810', gitlabClientId: null, approvers: ['sen'], lanes: [ { name: 'Prod', branches: ['production', 'main'] }, { name: 'Staging', branches: ['development'] }, ], doneHours: 24, }; const sen: Viewer = { username: 'sen', name: 'Sen', approver: true, projects: ['g/api'] }; const dev: Viewer = { username: 'raka', name: 'Raka', approver: false, projects: ['g/api'] }; function seeded() { const store = new Store(path.join(mkdtempSync(path.join(os.tmpdir(), 'labuh-board-')), 'db.sqlite')); const add = (iid: number, fields: object) => { const { ajuan } = store.upsertAjuan({ project: 'g/api', iid, webUrl: `https://gitlab.com/g/api/-/merge_requests/${iid}`, title: `MR ${iid}`, sha: 'h1', author: 'raka', targetBranch: 'production' }); store.update(ajuan.id, fields as any); return store.ajuanById(ajuan.id); }; const verdict = (v: string) => JSON.stringify({ verdict: v, reason: 'alasan', findings: [{ kind: 'bad', text: 'urutan migrasi', evidence: [{ label: 'a.go:3', url: 'https://gitlab.com/g/api/-/blob/h1/a.go#L3' }, { label: 'rubric R9', url: 'file:///x/rubric.md#r9' }] }], postDeploy: [], dropped: [], overrides: [] }); return { store, add, verdict }; } test('statuses map to zones; a moved head shows as being checked again', () => { const { store, add, verdict } = seeded(); const held = add(1, { status: 'no_go', reviewed_sha: 'h1', verdict_json: verdict('no_go') }); const v = viewAjuan(held, store.events(held.id), cfg, sen); assert.equal(v.status, 'fix'); assert.equal(v.zone, 'cek'); assert.equal(v.lane, 'Prod'); assert.equal(v.reason, 'alasan'); assert.deepEqual(v.findings[0].evidence.map((e) => e.url), ['https://gitlab.com/g/api/-/blob/h1/a.go#L3', '/rubric#r9']); assert.equal(v.needsYou, false, 'a held ajuan does not need the approver'); assert.equal(viewAjuan(held, [], cfg, dev).needsYou, true, 'but it needs its author'); const moved = add(2, { status: 'go', reviewed_sha: 'h0', head_sha: 'h1', verdict_json: verdict('go') }); const m = viewAjuan(moved, [], cfg, sen); assert.equal(m.status, 'checking'); assert.deepEqual(m.findings, [], 'an old verdict is not shown as current'); const ready = add(3, { status: 'go', reviewed_sha: 'h1', verdict_json: verdict('go') }); assert.equal(viewAjuan(ready, [], cfg, sen).zone, 'siap'); assert.equal(viewAjuan(ready, [], cfg, sen).needsYou, true); assert.equal(laneOf('feature/x', cfg), 'Lainnya'); }); test('only readable projects, open ajuan and merges from the last day are visible', () => { const { add } = seeded(); const open = add(1, { status: 'reviewing' }); const merged = add(2, { status: 'closed', closed_state: 'merged' }); const closed = add(3, { status: 'closed', closed_state: 'closed' }); assert.equal(visible(open, cfg, sen), true); assert.equal(visible(merged, cfg, sen), true); assert.equal(visible(merged, cfg, sen, Date.now() + 25 * 3600_000), false); assert.equal(visible(closed, cfg, sen), false); assert.equal(visible(open, cfg, { ...sen, projects: ['other/repo'] }), false); }); test('the timeline reads as people talk', () => { const { store, add } = seeded(); const a = add(1, { status: 'no_go' }); const opened = store.nextEvent()!; store.finishEvent(opened.id, 'no_go di h1abcdef'); store.enqueue(a.id, 'mention', {}); store.finishEvent(store.nextEvent()!.id, 'dijawab'); const v = viewAjuan(store.ajuanById(a.id), store.events(a.id), cfg, sen); assert.deepEqual(v.timeline.map((t) => t.text), ['Diajukan raka; Labuh: tahan', 'Ditanya; Labuh jawab di MR']); }); async function serve(store: Store, c: BoardConfig, devUser?: string) { const server = createBoard(store, c, ['g/api'], { devUser }); await new Promise((r) => server.listen(0, '127.0.0.1', r)); const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; return { base, close: () => new Promise((r) => server.close(r)) }; } test('without a session the board shows sign-in and the API refuses', async () => { const { store, add } = seeded(); add(1, { status: 'reviewing' }); const s = await serve(store, cfg); try { const page = await fetch(`${s.base}/`); assert.equal(page.status, 401); assert.match(await page.text(), /Masuk dengan GitLab/); assert.match(page.headers.get('content-security-policy')!, /script-src 'self'/); assert.equal((await fetch(`${s.base}/api/board`)).status, 401); assert.equal((await fetch(`${s.base}/rubric`)).status, 401); const login = await fetch(`${s.base}/auth/login`, { redirect: 'manual' }); assert.equal(login.status, 503, 'no OAuth app configured yet'); const cb = await fetch(`${s.base}/auth/callback?code=x&state=forged`); assert.equal(cb.status, 400, 'an unknown state is refused'); } finally { await s.close(); } }); test('the OAuth redirect uses PKCE and read_api', async () => { const { store } = seeded(); const s = await serve(store, { ...cfg, gitlabClientId: 'client-1' }); try { const r = await fetch(`${s.base}/auth/login`, { redirect: 'manual' }); const to = new URL(r.headers.get('location')!); assert.equal(to.origin + to.pathname, 'https://gitlab.com/oauth/authorize'); assert.equal(to.searchParams.get('scope'), 'read_api'); assert.equal(to.searchParams.get('code_challenge_method'), 'S256'); assert.equal(to.searchParams.get('redirect_uri'), 'http://localhost:4810/auth/callback'); } finally { await s.close(); } }); test('the local dev user works only when bound to 127.0.0.1', async () => { const { store, add, verdict } = seeded(); add(1, { status: 'no_go', reviewed_sha: 'h1', verdict_json: verdict('no_go') }); const local = await serve(store, cfg, 'sen'); try { const r = await fetch(`${local.base}/api/board`); assert.equal(r.status, 200); const body = await r.json(); assert.equal(body.viewer.approver, true); assert.equal(body.ajuan.length, 1); assert.equal(body.ajuan[0].findings[0].evidence[1].url, '/rubric#r9'); const rubric = await fetch(`${local.base}/rubric`); assert.match(await rubric.text(), /id="r9"/); } finally { await local.close(); } const exposed = await serve(store, { ...cfg, host: '0.0.0.0' }, 'sen'); try { assert.equal((await fetch(`${exposed.base}/api/board`)).status, 401); } finally { await exposed.close(); } }); test('decisions and deploys move the boat: Gas waits in Siap gas, sailing and failed sit in Beres', () => { const { store, add, verdict } = seeded(); const base = { status: 'go', reviewed_sha: 'h1', verdict_json: verdict('go') }; const zone = (a: any, act?: any) => viewAjuan(a, [], cfg, sen, act); const gas = add(1, { ...base, decision: 'gas', decision_by: 'sen' }); const v = zone(gas, { taken: false, gasQueuedAt: 1000, graceSeconds: 15, allowed: ['undo'], dry: false }); assert.deepEqual([v.status, v.zone, v.gasAt, v.actions], ['gas', 'siap', 16000, ['undo']]); assert.deepEqual(viewAjuan(gas, [], cfg, dev, { taken: false, gasQueuedAt: 1000, graceSeconds: 15, allowed: ['undo'], dry: false }).actions, [], 'developers get no actions'); assert.deepEqual([zone(add(2, { ...base, decision: 'tunda', decision_by: 'sen', decision_note: 'jam sibuk' })).zone], ['cek']); assert.match(zone(store.ajuan('g/api', 2)!).reason, /Ditunda @sen: “jam sibuk”/); assert.equal(zone(add(3, { ...base, decision: 'tolak', decision_by: 'sen' })).status, 'rejected'); const sailing = zone(add(4, { ...base, status: 'closed', closed_state: 'merged', deploy_state: 'deploying' })); assert.deepEqual([sailing.status, sailing.zone], ['sailing', 'beres']); const failed = zone(add(5, { ...base, status: 'closed', closed_state: 'merged', deploy_state: 'failed' })); assert.deepEqual([failed.status, failed.needsYou], ['failed', true]); // A new commit outranks an old decision on the board. assert.equal(zone(add(6, { ...base, head_sha: 'h2', decision: 'gas' })).status, 'checking'); }); test('only an approver, same origin and JSON, can act; Gas is recorded for the Hub', async () => { const { store, add, verdict } = seeded(); const a = add(1, { status: 'go', reviewed_sha: 'h1', verdict_json: verdict('go') }); const post = (base: string, body: object, headers: Record = { Origin: 'http://localhost:4810', 'Content-Type': 'application/json' }) => fetch(`${base}/api/ajuan/${a.id}/action`, { method: 'POST', headers, body: JSON.stringify(body) }); const asDev = await serve(store, cfg, 'raka'); try { assert.equal((await post(asDev.base, { action: 'gas', sha: 'h1' })).status, 403); } finally { await asDev.close(); } const s = await serve(store, cfg, 'sen'); try { assert.equal((await post(s.base, { action: 'gas', sha: 'h1' }, { Origin: 'https://evil.example', 'Content-Type': 'application/json' })).status, 403); assert.equal((await post(s.base, { action: 'gas', sha: 'h1' }, { Origin: 'http://localhost:4810', 'Content-Type': 'text/plain' })).status, 403); assert.equal((await post(s.base, { action: 'merge-now' })).status, 400); const stale = await post(s.base, { action: 'gas', sha: 'h0' }); assert.equal(stale.status, 409); assert.match((await stale.json()).error, /commit baru/); assert.equal((await post(s.base, { action: 'gas', sha: 'h1' })).status, 200); assert.equal(store.ajuanById(a.id).decision, 'gas'); assert.deepEqual(store.pendingActions(a.id).map((e) => [e.kind, e.payload.by, e.payload.sha]), [['gas', 'sen', 'h1']]); const board = await (await fetch(`${s.base}/api/board`)).json(); assert.deepEqual(board.ajuan[0].actions, ['undo']); assert.ok(board.ajuan[0].gasAt > Date.now()); assert.equal((await post(s.base, { action: 'undo' })).status, 200); assert.equal(store.pendingActions(a.id).length, 0); } finally { await s.close(); } }); test('a session ends when the Hub starts watching a project it never checked', async () => { const { store } = seeded(); const { createHash } = await import('node:crypto'); const s = await serve(store, cfg); try { // Signed in when only g/api was watched: still valid. store.db.prepare("INSERT INTO board_sessions (id, username, name, approver, projects, checked, expires_at) VALUES (?, 'sen', 'Sen', 1, '[\"g/api\"]', '[\"g/api\"]', ?)").run(createHash('sha256').update('old').digest('hex'), Date.now() + 3600_000); assert.equal((await fetch(`${s.base}/api/board`, { headers: { cookie: 'labuh_session=old' } })).status, 200); } finally { await s.close(); } const more = createBoard(store, cfg, ['g/api', 'g/web']); await new Promise((r) => more.listen(0, '127.0.0.1', r)); try { const base = `http://127.0.0.1:${(more.address() as AddressInfo).port}`; assert.equal((await fetch(`${base}/api/board`, { headers: { cookie: 'labuh_session=old' } })).status, 401, 'g/web was never checked for this session'); } finally { await new Promise((r) => more.close(r)); } }); test('the release proposal shows on merged ajuan; only an approver can confirm it, with a valid tag', async () => { const { store, add } = seeded(); const a = add(1, { status: 'closed', closed_state: 'merged', merge_sha: 'm1', deploy_state: 'awaiting_release' }); const r = store.addRelease({ project: 'g/api', branch: 'production', sha: 'm1', from_tag: 'v2.0.9', proposed_tag: 'v2.0.10', changes: { mrs: [{ iid: 1, title: 'MR 1', author: 'raka' }], commits: [] } }); const post = (base: string, body: object, origin = 'http://localhost:4810') => fetch(`${base}/api/release/${r.id}/action`, { method: 'POST', headers: { Origin: origin, 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const asDev = await serve(store, cfg, 'raka'); try { const board = await (await fetch(`${asDev.base}/api/board`)).json(); assert.equal(board.ajuan[0].release.proposedTag, 'v2.0.10'); assert.deepEqual(board.ajuan[0].release.actions, []); assert.equal((await post(asDev.base, { action: 'release', tag: 'v2.0.10' })).status, 403); } finally { await asDev.close(); } const s = await serve(store, cfg, 'sen'); try { assert.equal((await post(s.base, { action: 'release', tag: 'v2.0.10' }, 'https://evil.example')).status, 403); const bad = await post(s.base, { action: 'release', tag: 'v2.0.5' }); assert.equal(bad.status, 400); assert.match((await bad.json()).error, /lebih baru dari v2\.0\.9/); assert.equal((await post(s.base, { action: 'release', tag: 'v2.1.0' })).status, 200); const board = await (await fetch(`${s.base}/api/board`)).json(); assert.deepEqual([board.ajuan[0].release.state, board.ajuan[0].release.tag, board.ajuan[0].release.actions], ['queued', 'v2.1.0', ['undo']]); assert.ok(board.ajuan[0].release.at > Date.now()); assert.equal((await post(s.base, { action: 'undo' })).status, 200); assert.equal(store.releaseById(r.id)!.state, 'proposed'); } finally { await s.close(); } assert.equal(a.deploy_state, 'awaiting_release'); });