From bd7fdea2759060210be464e262c59422304bd041 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:52 +0200 Subject: [PATCH] test(web): cover the router, configuration, auth, deployments and server The schema test compares the declared variables against `.env.example`, so the two cannot drift apart. The server tests drive the real handler over a loopback socket rather than a mock, which is what caught the health probe missing from bootstrap mode and the deployments recorded under the wrong guild. Co-Authored-By: Claude Opus 5 (1M context) --- tests/web-auth.test.js | 229 ++++++++++++++++++++++++++++++++ tests/web-configuration.test.js | 184 +++++++++++++++++++++++++ tests/web-deployments.test.js | 224 +++++++++++++++++++++++++++++++ tests/web-router.test.js | 46 +++++++ tests/web-server.test.js | 179 +++++++++++++++++++++++++ 5 files changed, 862 insertions(+) create mode 100644 tests/web-auth.test.js create mode 100644 tests/web-configuration.test.js create mode 100644 tests/web-deployments.test.js create mode 100644 tests/web-router.test.js create mode 100644 tests/web-server.test.js diff --git a/tests/web-auth.test.js b/tests/web-auth.test.js new file mode 100644 index 0000000..272e59e --- /dev/null +++ b/tests/web-auth.test.js @@ -0,0 +1,229 @@ +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { ACCESS_LEVELS } from '../src/config/constants.js'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + createApiToken, + getLiveApiTokenByHash, + listSessions, + revokeApiToken, +} from '../src/database/repositories/web-session-repository.js'; +import { authorize } from '../src/web/auth/guard.js'; +import { resolveAccessLevel } from '../src/web/auth/discord-oauth.js'; +import { + assertSameOrigin, + authenticate, + closeSession, + hashToken, + openSession, +} from '../src/web/auth/session.js'; + +/** Minimal stand-ins for the Node request and response objects. */ +const fakeRequest = (headers = {}, method = 'GET') => ({ + method, + headers: { 'user-agent': 'node-test', ...headers }, + socket: { remoteAddress: '127.0.0.1' }, +}); + +function fakeResponse() { + const headers = {}; + return { + headers, + setHeader: (name, value) => { + headers[name] = value; + }, + getHeader: (name) => headers[name], + }; +} + +const cookieOf = (response) => { + const raw = [].concat(response.getHeader('Set-Cookie') ?? [])[0] ?? ''; + return raw.split(';')[0]; +}; + +describe('access guard', () => { + it('lets a public route through without an actor', () => { + assert.doesNotThrow(() => authorize(null, { public: true })); + }); + + it('refuses an anonymous caller with 401', () => { + assert.throws(() => authorize(null, { access: ACCESS_LEVELS.STAFF }), { status: 401 }); + }); + + it('compares the actor level against the route requirement', () => { + const staff = { accessLevel: ACCESS_LEVELS.STAFF, source: 'discord' }; + assert.doesNotThrow(() => authorize(staff, { access: ACCESS_LEVELS.STAFF })); + assert.throws(() => authorize(staff, { access: ACCESS_LEVELS.OWNER }), { status: 403 }); + }); + + it('defaults to Owner when a route forgets to declare its level', () => { + assert.throws(() => authorize({ accessLevel: ACCESS_LEVELS.DEV, source: 'discord' }, {}), { + status: 403, + }); + }); + + it('confines a bootstrap session to the configuration routes', () => { + const setup = { accessLevel: ACCESS_LEVELS.OWNER, source: 'setup' }; + assert.doesNotThrow(() => authorize(setup, { access: ACCESS_LEVELS.OWNER, setup: true })); + assert.throws(() => authorize(setup, { access: ACCESS_LEVELS.STAFF }), { status: 403 }); + }); +}); + +describe('cross-site protection', () => { + it('never blocks a read', () => { + assert.doesNotThrow(() => assertSameOrigin(fakeRequest({}, 'GET'), { kind: 'session' })); + }); + + it('requires the dashboard header on a write', () => { + assert.throws(() => assertSameOrigin(fakeRequest({}, 'POST'), { kind: 'session' }), { status: 403 }); + assert.doesNotThrow(() => + assertSameOrigin(fakeRequest({ 'x-requested-with': 'fws-dashboard' }, 'POST'), { kind: 'session' }), + ); + }); + + it('rejects a write coming from another origin', () => { + const request = fakeRequest( + { 'x-requested-with': 'fws-dashboard', origin: 'https://evil.example', host: 'bot.example' }, + 'POST', + ); + assert.throws(() => assertSameOrigin(request, { kind: 'session' }), { status: 403 }); + }); + + it('accepts a write from the served host', () => { + const request = fakeRequest( + { 'x-requested-with': 'fws-dashboard', origin: 'https://bot.example', host: 'bot.example' }, + 'POST', + ); + assert.doesNotThrow(() => assertSameOrigin(request, { kind: 'session' })); + }); + + it('exempts machine tokens, which carry no cookie', () => { + assert.doesNotThrow(() => assertSameOrigin(fakeRequest({}, 'POST'), { kind: 'api-token' })); + }); +}); + +describe('dashboard sessions', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM web_sessions; DELETE FROM web_api_tokens;')); + + const login = (level = ACCESS_LEVELS.DEV) => { + const response = fakeResponse(); + const session = openSession(fakeRequest(), response, { + user: { id: '42', username: 'kim', displayName: 'Kim', avatar: null }, + accessLevel: level, + }); + return { session, cookie: cookieOf(response) }; + }; + + it('stores only the hash of the cookie value', () => { + const { session, cookie } = login(); + const token = decodeURIComponent(cookie.split('=')[1]); + + assert.notEqual(session.token_hash, token); + assert.equal(session.token_hash, hashToken(token)); + }); + + it('identifies the caller from its cookie', () => { + const { cookie } = login(ACCESS_LEVELS.STAFF); + const actor = authenticate(fakeRequest({ cookie })); + + assert.equal(actor.kind, 'session'); + assert.equal(actor.userId, '42'); + assert.equal(actor.accessLevel, ACCESS_LEVELS.STAFF); + }); + + it('returns null for an unknown or absent cookie', () => { + assert.equal(authenticate(fakeRequest()), null); + assert.equal(authenticate(fakeRequest({ cookie: 'fws_session=inventé' })), null); + }); + + it('ignores an expired session', () => { + const { cookie } = login(); + getDatabase().exec("UPDATE web_sessions SET expires_at = datetime('now', '-1 hour')"); + assert.equal(authenticate(fakeRequest({ cookie })), null); + }); + + it('closes a session and clears the cookie', () => { + const { cookie } = login(); + const response = fakeResponse(); + closeSession(fakeRequest({ cookie }), response); + + assert.equal(authenticate(fakeRequest({ cookie })), null); + assert.match([].concat(response.getHeader('Set-Cookie'))[0], /Max-Age=0/); + }); + + it('lists the live sessions', () => { + login(); + login(ACCESS_LEVELS.OWNER); + assert.equal(listSessions().length, 2); + }); +}); + +describe('api tokens', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM web_api_tokens;')); + + const issue = () => { + const token = 'fws_test-token-value'; + const id = createApiToken({ + name: 'ci', + tokenHash: hashToken(token), + prefix: token.slice(0, 12), + accessLevel: ACCESS_LEVELS.DEV, + }); + return { id, token }; + }; + + it('authenticates a bearer token', () => { + const { token } = issue(); + const actor = authenticate(fakeRequest({ authorization: `Bearer ${token}` })); + + assert.equal(actor.kind, 'api-token'); + assert.equal(actor.accessLevel, ACCESS_LEVELS.DEV); + }); + + it('records the last usage', () => { + const { token } = issue(); + authenticate(fakeRequest({ authorization: `Bearer ${token}` })); + assert.ok(getLiveApiTokenByHash(hashToken(token)).last_used_at); + }); + + it('refuses a revoked token', () => { + const { id, token } = issue(); + revokeApiToken(id); + assert.equal(authenticate(fakeRequest({ authorization: `Bearer ${token}` })), null); + }); + + it('refuses an unknown token', () => { + assert.equal(authenticate(fakeRequest({ authorization: 'Bearer nope' })), null); + }); +}); + +describe('oauth access level', () => { + const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' }; + + it('gives Owner to the guild owner whatever their roles', () => { + const level = resolveAccessLevel({ member: { roles: [] }, userId: '1', guildOwnerId: '1', roles }); + assert.equal(level, ACCESS_LEVELS.OWNER); + }); + + it('reads the highest matching role', () => { + assert.equal( + resolveAccessLevel({ member: { roles: ['r-staff', 'r-dev'] }, userId: '2', guildOwnerId: '1', roles }), + ACCESS_LEVELS.DEV, + ); + }); + + it('falls back to plain member', () => { + assert.equal( + resolveAccessLevel({ member: { roles: ['autre'] }, userId: '2', guildOwnerId: '1', roles }), + ACCESS_LEVELS.USER, + ); + }); + + it('returns null when the visitor is not in the guild', () => { + assert.equal(resolveAccessLevel({ member: null, userId: '2', guildOwnerId: '1', roles }), null); + }); +}); diff --git a/tests/web-configuration.test.js b/tests/web-configuration.test.js new file mode 100644 index 0000000..38af388 --- /dev/null +++ b/tests/web-configuration.test.js @@ -0,0 +1,184 @@ +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { after, before, describe, it } from 'node:test'; +import { + diffValues, + maskValues, + mergeValues, + parseEnv, + renderEnvFile, + secretStatus, + writeEnvFile, +} from '../src/web/services/env-file.js'; +import { + BY_KEY, + SECTIONS, + VARIABLES, + crossCheck, + requiredKeys, + validateAll, + validateValue, +} from '../src/web/services/env-schema.js'; + +describe('env schema', () => { + it('declares every variable inside a known section', () => { + const sectionIds = new Set(SECTIONS.map((section) => section.id)); + for (const variable of VARIABLES) { + assert.ok(sectionIds.has(variable.section), `${variable.key} points at an unknown section`); + } + }); + + it('documents every variable with a label and a help text', () => { + for (const variable of VARIABLES) { + assert.ok(variable.label?.length > 0, `${variable.key} has no label`); + assert.ok(variable.help?.length > 0, `${variable.key} has no help`); + } + }); + + it('covers the variables the bot refuses to start without', () => { + assert.deepEqual(requiredKeys().sort(), ['DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID', 'DISCORD_TOKEN']); + }); + + it('mirrors the keys used by .env.example', () => { + const example = parseEnv(readFileSync('.env.example', 'utf8')); + for (const key of Object.keys(example)) { + assert.ok(key in BY_KEY, `${key} is in .env.example but missing from the schema`); + } + for (const variable of VARIABLES) { + assert.ok(variable.key in example, `${variable.key} is in the schema but missing from .env.example`); + } + }); + + it('validates Discord identifiers', () => { + assert.equal(validateValue('DISCORD_GUILD_ID', '123456789012345678'), null); + assert.match(validateValue('DISCORD_GUILD_ID', 'abc'), /17 à 20 chiffres/); + }); + + it('validates numbers against their bounds', () => { + assert.equal(validateValue('WEB_PORT', '3080'), null); + assert.match(validateValue('WEB_PORT', '99999'), /Maximum/); + assert.match(validateValue('WEB_PORT', 'abc'), /nombre entier/); + }); + + it('validates booleans, enums and urls', () => { + assert.equal(validateValue('WEB_ENABLED', 'true'), null); + assert.match(validateValue('WEB_ENABLED', 'oui'), /true` ou `false/); + assert.equal(validateValue('LOG_LEVEL', 'debug'), null); + assert.match(validateValue('LOG_LEVEL', 'verbose'), /Valeurs possibles/); + assert.equal(validateValue('GITEA_URL', 'https://gitea.example.org'), null); + assert.match(validateValue('GITEA_URL', 'gitea.example.org'), /URL invalide/); + }); + + it('accepts an empty optional value but not an empty required one', () => { + assert.equal(validateValue('ROLE_OWNER_ID', ''), null); + assert.match(validateValue('DISCORD_TOKEN', ''), /obligatoire/); + }); + + it('reports every invalid key at once', () => { + const errors = validateAll({ DISCORD_TOKEN: 'x', DISCORD_CLIENT_ID: 'nope', DISCORD_GUILD_ID: '' }); + assert.ok(errors.DISCORD_CLIENT_ID); + assert.ok(errors.DISCORD_GUILD_ID); + assert.equal(errors.DISCORD_TOKEN, undefined); + }); + + it('warns about combinations no single field can catch', () => { + const warnings = crossCheck({ WEBHOOK_ENABLED: 'true', GITEA_WEBHOOK_SECRET: '' }); + assert.ok(warnings.some((warning) => warning.includes('rejetés'))); + }); + + it('warns when the dashboard is exposed without HTTPS', () => { + const warnings = crossCheck({ + WEB_ENABLED: 'true', + WEB_HOST: '0.0.0.0', + WEB_PUBLIC_URL: 'http://bot.example.org', + DISCORD_CLIENT_SECRET: 'x', + WEB_SESSION_SECRET: 'y', + }); + assert.ok(warnings.some((warning) => warning.includes('en clair'))); + }); +}); + +describe('env file', () => { + let directory; + let file; + + before(() => { + directory = mkdtempSync(path.join(tmpdir(), 'fws-env-')); + file = path.join(directory, '.env'); + }); + after(() => rmSync(directory, { recursive: true, force: true })); + + it('parses quoted, unquoted and commented lines', () => { + const values = parseEnv('# comment\nA=1\nB="deux mots"\nC=\'trois\'\nexport D=4\ninvalid\n'); + assert.deepEqual(values, { A: '1', B: 'deux mots', C: 'trois', D: '4' }); + }); + + it('renders a file that documents every variable', () => { + const content = renderEnvFile({ DISCORD_TOKEN: 'secret', WEB_PORT: '3080' }); + for (const variable of VARIABLES) { + assert.ok(content.includes(`${variable.key}=`), `${variable.key} is missing from the rendered file`); + assert.ok(content.includes(variable.label), `${variable.label} is missing from the rendered file`); + } + }); + + it('keeps variables it does not know about', () => { + const content = renderEnvFile({}, { CUSTOM_THING: 'valeur' }); + assert.match(content, /CUSTOM_THING=valeur/); + }); + + it('quotes values that need it', () => { + const content = renderEnvFile({ GITEA_OWNER: 'deux mots' }); + assert.match(content, /GITEA_OWNER="deux mots"/); + }); + + it('writes the file with 600 permissions and backs up the previous one', () => { + writeFileSync(file, 'DISCORD_TOKEN=ancien\n'); + const result = writeEnvFile({ DISCORD_TOKEN: 'nouveau' }, { file }); + + assert.ok(result.backup, 'no backup was made'); + assert.match(readFileSync(result.backup, 'utf8'), /ancien/); + assert.match(readFileSync(file, 'utf8'), /DISCORD_TOKEN=nouveau/); + assert.equal(statSync(file).mode & 0o777, 0o600); + }); + + it('keeps the stored secret when the submitted one is empty', () => { + const merged = mergeValues( + { DISCORD_TOKEN: 'garde-moi', GITEA_OWNER: 'FWS' }, + { DISCORD_TOKEN: '', GITEA_OWNER: 'AUTRE' }, + ); + assert.equal(merged.DISCORD_TOKEN, 'garde-moi'); + assert.equal(merged.GITEA_OWNER, 'AUTRE'); + }); + + it('ignores keys that are not part of the schema', () => { + const merged = mergeValues({}, { NOT_A_REAL_KEY: 'x' }); + assert.equal(merged.NOT_A_REAL_KEY, undefined); + }); + + it('never sends a secret back to the browser', () => { + const masked = maskValues({ DISCORD_TOKEN: 'tres-secret', GITEA_OWNER: 'FWS' }); + assert.equal(masked.DISCORD_TOKEN, ''); + assert.equal(masked.GITEA_OWNER, 'FWS'); + + const status = secretStatus({ DISCORD_TOKEN: 'tres-secret' }); + assert.equal(status.DISCORD_TOKEN, true); + assert.equal(status.GITEA_TOKEN, false); + }); + + it('describes a change without revealing the secret', () => { + const diff = diffValues( + { DISCORD_TOKEN: 'avant', WEB_PORT: '3080' }, + { DISCORD_TOKEN: 'apres', WEB_PORT: '4000' }, + ); + const token = diff.find((entry) => entry.key === 'DISCORD_TOKEN'); + + assert.equal(token.before, '••••••'); + assert.equal(token.after, '••••••'); + assert.equal(token.restartRequired, true); + + const port = diff.find((entry) => entry.key === 'WEB_PORT'); + assert.equal(port.after, '4000'); + }); +}); diff --git a/tests/web-deployments.test.js b/tests/web-deployments.test.js new file mode 100644 index 0000000..71a0105 --- /dev/null +++ b/tests/web-deployments.test.js @@ -0,0 +1,224 @@ +import assert from 'node:assert/strict'; +import { createHmac } from 'node:crypto'; +import { createServer } from 'node:http'; +import { after, afterEach, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + countByStatus, + createTarget, + getTarget, + listAutoTargets, + listDeployments, + listTargets, + removeTarget, + updateTarget, +} from '../src/database/repositories/deploy-repository.js'; +import { splitRepository } from '../src/services/gitea/gitea-admin.js'; +import { assertRunnable, describeTarget, runDeployment } from '../src/web/services/deploy-service.js'; + +const GUILD = 'guild-1'; + +const webhookTarget = (overrides = {}) => + createTarget({ + guildId: GUILD, + name: 'production', + repository: 'FWS/FWS-Arch', + environment: 'production', + kind: 'webhook', + config: { url: 'http://127.0.0.1:1/hook', secret: 'partage' }, + ...overrides, + }); + +describe('deploy repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('stores and reads back a target with its parsed config', () => { + const target = webhookTarget(); + assert.equal(target.config.url, 'http://127.0.0.1:1/hook'); + assert.equal(target.enabled, true); + assert.equal(target.auto_deploy, false); + assert.deepEqual(getTarget(target.id), target); + }); + + it('filters targets by repository', () => { + webhookTarget(); + webhookTarget({ name: 'site', repository: 'FWS/site' }); + + assert.equal(listTargets({ guildId: GUILD }).length, 2); + assert.equal(listTargets({ guildId: GUILD, repository: 'FWS/site' }).length, 1); + }); + + it('only returns enabled auto-deploy targets', () => { + webhookTarget({ name: 'manuel' }); + webhookTarget({ name: 'auto', autoDeploy: true }); + webhookTarget({ name: 'auto-en-pause', autoDeploy: true, enabled: false }); + + const auto = listAutoTargets({ guildId: GUILD, repository: 'FWS/FWS-Arch' }); + assert.deepEqual( + auto.map((target) => target.name), + ['auto'], + ); + }); + + it('updates only the known columns', () => { + const target = webhookTarget(); + // The repository speaks in column names; the API layer does the translation. + const updated = updateTarget(target.id, { environment: 'staging', bogus: 'ignoré', auto_deploy: true }); + + assert.equal(updated.environment, 'staging'); + assert.equal(updated.auto_deploy, true); + assert.equal(updated.bogus, undefined); + assert.ok(updated.updated_at); + }); + + it('keeps the history when its target is deleted', async () => { + const target = webhookTarget(); + await runDeployment(null, target, { ref: 'main' }).catch(() => null); + removeTarget(target.id); + + const [deployment] = listDeployments({ guildId: GUILD }); + assert.equal(deployment.target_id, null); + assert.equal(deployment.target_name, 'production'); + }); + + it('describes a target in one line', () => { + assert.match(describeTarget(webhookTarget()), /^POST http/); + assert.equal( + describeTarget({ kind: 'gitea-action', config: { workflow: 'deploy.yml', ref: 'main' } }), + 'workflow deploy.yml sur main', + ); + }); +}); + +describe('deploy guards', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('refuses a disabled target', () => { + assert.throws(() => assertRunnable(webhookTarget({ enabled: false })), { status: 400 }); + }); + + it('refuses a webhook target with no url', () => { + assert.throws(() => assertRunnable(webhookTarget({ config: {} })), { status: 400 }); + }); + + it('refuses a command target while command deploys are off', () => { + const target = webhookTarget({ name: 'shell', kind: 'command', config: { command: 'echo bonjour' } }); + // `WEB_ALLOW_COMMAND_DEPLOYS` is unset in the tests, so this must be blocked. + assert.throws(() => assertRunnable(target), { status: 403 }); + }); + + it('refuses an unknown kind', () => { + assert.throws(() => assertRunnable({ enabled: true, kind: 'magic', config: {} }), { status: 400 }); + }); +}); + +describe('webhook deployments', () => { + let server; + let received; + let reply; + + before(async () => { + initDatabase(':memory:'); + server = createServer((request, response) => { + let body = ''; + request.on('data', (chunk) => (body += chunk)); + request.on('end', () => { + received = { headers: request.headers, body }; + response.writeHead(reply.status, { 'Content-Type': 'text/plain' }).end(reply.body); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + }); + + after(async () => { + await new Promise((resolve) => server.close(resolve)); + closeDatabase(); + }); + + beforeEach(() => { + getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;'); + received = null; + reply = { status: 200, body: 'déployé' }; + }); + afterEach(() => { + received = null; + }); + + const url = () => `http://127.0.0.1:${server.address().port}/hook`; + + it('calls the webhook and records a success', async () => { + const target = webhookTarget({ config: { url: url(), secret: 'partage' } }); + const deployment = await runDeployment(null, target, { releaseTag: 'v1.0.0', triggeredBy: 'u1' }); + + assert.equal(deployment.status, 'success'); + assert.match(deployment.log, /déployé/); + + const [stored] = listDeployments({ guildId: 'guild-1' }); + assert.equal(stored.status, 'success'); + assert.equal(stored.release_tag, 'v1.0.0'); + assert.ok(stored.finished_at); + }); + + it('signs the payload with the shared secret', async () => { + const target = webhookTarget({ config: { url: url(), secret: 'partage' } }); + await runDeployment(null, target, { ref: 'main' }); + + const expected = createHmac('sha256', 'partage').update(received.body).digest('hex'); + assert.equal(received.headers['x-fws-signature'], expected); + }); + + it('sends the deployment context in the body', async () => { + const target = webhookTarget({ config: { url: url() } }); + await runDeployment(null, target, { releaseTag: 'v2.0.0', ref: 'main', triggeredBy: 'u9' }); + + const payload = JSON.parse(received.body); + assert.equal(payload.repository, 'FWS/FWS-Arch'); + assert.equal(payload.environment, 'production'); + assert.equal(payload.releaseTag, 'v2.0.0'); + assert.equal(payload.triggeredBy, 'u9'); + }); + + it('omits the signature when no secret is configured', async () => { + const target = webhookTarget({ config: { url: url() } }); + await runDeployment(null, target, {}); + assert.equal(received.headers['x-fws-signature'], undefined); + }); + + it('records a failure when the endpoint answers with an error', async () => { + reply = { status: 500, body: 'boum' }; + const target = webhookTarget({ config: { url: url() } }); + const deployment = await runDeployment(null, target, {}); + + assert.equal(deployment.status, 'failed'); + assert.match(deployment.error, /500/); + assert.match(deployment.log, /boum/); + }); + + it('counts the deployments by status', async () => { + const ok = webhookTarget({ name: 'ok', config: { url: url() } }); + await runDeployment(null, ok, {}); + reply = { status: 503, body: '' }; + await runDeployment(null, ok, {}); + + const counts = Object.fromEntries(countByStatus('guild-1').map((row) => [row.status, row.count])); + assert.equal(counts.success, 1); + assert.equal(counts.failed, 1); + }); +}); + +describe('repository names', () => { + it('splits a full name', () => { + assert.deepEqual(splitRepository('FWS/FWS-Arch'), { owner: 'FWS', repo: 'FWS-Arch' }); + }); + + it('rejects anything that is not exactly owner/repo', () => { + assert.equal(splitRepository('FWS'), null); + assert.equal(splitRepository('FWS/Arch/extra'), null); + assert.equal(splitRepository(''), null); + assert.equal(splitRepository(undefined), null); + }); +}); diff --git a/tests/web-router.test.js b/tests/web-router.test.js new file mode 100644 index 0000000..3b75ed5 --- /dev/null +++ b/tests/web-router.test.js @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { createRouter } from '../src/web/router.js'; + +const noop = () => null; + +describe('web router', () => { + const router = createRouter(); + router.get('/api/health', noop, { public: true }); + router.get('/api/repositories/:owner/:repo', noop); + router.post('/api/repositories/:owner/:repo/issues', noop); + router.delete('/api/repositories/:owner/:repo/branches', noop); + + it('matches a static route', () => { + const route = router.resolve('GET', '/api/health'); + assert.deepEqual(route.params, {}); + assert.equal(route.options.public, true); + }); + + it('extracts named parameters', () => { + const route = router.resolve('GET', '/api/repositories/FWS/FWS-Arch'); + assert.deepEqual(route.params, { owner: 'FWS', repo: 'FWS-Arch' }); + }); + + it('decodes percent-encoded parameters', () => { + const route = router.resolve('GET', '/api/repositories/FWS/mon%20depot'); + assert.equal(route.params.repo, 'mon depot'); + }); + + it('keeps methods apart on the same path', () => { + assert.doesNotThrow(() => router.resolve('DELETE', '/api/repositories/FWS/Arch/branches')); + assert.throws(() => router.resolve('GET', '/api/repositories/FWS/Arch/branches'), { status: 405 }); + }); + + it('rejects an unknown path with 404', () => { + assert.throws(() => router.resolve('GET', '/api/nope'), { status: 404 }); + }); + + it('does not let a shorter path match a longer pattern', () => { + assert.throws(() => router.resolve('GET', '/api/repositories/FWS'), { status: 404 }); + }); + + it('lists the registered routes', () => { + assert.ok(router.list().includes('POST /api/repositories/:owner/:repo/issues')); + }); +}); diff --git a/tests/web-server.test.js b/tests/web-server.test.js new file mode 100644 index 0000000..c49eb42 --- /dev/null +++ b/tests/web-server.test.js @@ -0,0 +1,179 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { after, before, describe, it } from 'node:test'; +import { closeDatabase, initDatabase } from '../src/database/index.js'; +import { createHandler } from '../src/web/server.js'; +import { generateRuntimeSetupToken } from '../src/web/setup-state.js'; + +/** Drives the real request handler over a loopback socket (M16-T01). */ +function serve(options) { + const server = createServer(createHandler(options)); + const ready = new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + + return { + ready, + close: () => new Promise((resolve) => server.close(resolve)), + url: (path) => `http://127.0.0.1:${server.address().port}${path}`, + fetch: (path, init) => fetch(`http://127.0.0.1:${server.address().port}${path}`, init), + }; +} + +const WRITE_HEADERS = { 'Content-Type': 'application/json', 'X-Requested-With': 'fws-dashboard' }; + +describe('dashboard server', () => { + let app; + + before(async () => { + initDatabase(':memory:'); + app = serve({ client: null, setupOnly: false }); + await app.ready; + }); + after(async () => { + await app.close(); + closeDatabase(); + }); + + it('answers the health probe without a session', async () => { + const response = await app.fetch('/api/health'); + const body = await response.json(); + + assert.equal(response.status, 200); + assert.equal(body.status, 'starting'); + assert.equal(body.setupOnly, false); + }); + + it('describes how to sign in without a session', async () => { + const body = await app.fetch('/api/auth/config').then((response) => response.json()); + assert.equal(typeof body.oauthConfigured, 'boolean'); + assert.equal(body.loginUrl, '/auth/login'); + }); + + it('reports an anonymous visitor as not authenticated', async () => { + const body = await app.fetch('/api/me').then((response) => response.json()); + assert.equal(body.authenticated, false); + }); + + it('refuses a protected route with 401', async () => { + const response = await app.fetch('/api/overview'); + assert.equal(response.status, 401); + assert.match((await response.json()).error, /Authentification/); + }); + + it('returns 404 on an unknown API route', async () => { + assert.equal((await app.fetch('/api/nope')).status, 404); + }); + + it('returns 405 when the path exists under another method', async () => { + const response = await app.fetch('/api/health', { method: 'POST', headers: WRITE_HEADERS, body: '{}' }); + assert.equal(response.status, 405); + }); + + it('blocks a write that does not carry the dashboard header', async () => { + const response = await app.fetch('/api/auth/logout', { method: 'POST' }); + assert.equal(response.status, 403); + assert.match((await response.json()).error, /X-Requested-With/); + }); + + it('serves the single page application shell', async () => { + const response = await app.fetch('/'); + const body = await response.text(); + + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /text\/html/); + assert.match(body, /
{ + const response = await app.fetch('/repos/FWS/FWS-Arch'); + assert.equal(response.status, 200); + assert.match(await response.text(), /
{ + const response = await app.fetch('/core/dom.js'); + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /javascript/); + }); + + it('sends the security headers on every response', async () => { + const response = await app.fetch('/'); + assert.equal(response.headers.get('x-frame-options'), 'DENY'); + assert.equal(response.headers.get('x-content-type-options'), 'nosniff'); + assert.match(response.headers.get('content-security-policy'), /frame-ancestors 'none'/); + }); + + it('never serves a file outside the public directory', async () => { + // The path is normalised server side, so the traversal lands on the shell. + const response = await app.fetch('/..%2f..%2fpackage.json'); + const body = await response.text(); + + assert.equal(response.status, 200); + assert.doesNotMatch(body, /"fws-discordbot"/); + }); + + it('rejects a malformed JSON body', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: 'pas du json', + }); + assert.equal(response.status, 400); + }); +}); + +describe('bootstrap mode', () => { + let app; + let token; + + before(async () => { + initDatabase(':memory:'); + token = generateRuntimeSetupToken(); + app = serve({ client: null, setupOnly: true }); + await app.ready; + }); + after(async () => { + await app.close(); + closeDatabase(); + }); + + it('announces itself as a setup-only server', async () => { + const body = await app.fetch('/api/health').then((response) => response.json()); + assert.equal(body.setupOnly, true); + }); + + it('does not even register the dashboard routes', async () => { + assert.equal((await app.fetch('/api/overview')).status, 404); + assert.equal((await app.fetch('/api/settings')).status, 404); + }); + + it('refuses a wrong bootstrap token', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: JSON.stringify({ token: 'mauvais' }), + }); + assert.equal(response.status, 403); + }); + + it('opens a confined session with the right token', async () => { + const response = await app.fetch('/api/auth/setup', { + method: 'POST', + headers: WRITE_HEADERS, + body: JSON.stringify({ token }), + }); + assert.equal(response.status, 200); + + const cookie = response.headers.getSetCookie()[0].split(';')[0]; + const me = await app.fetch('/api/me', { headers: { cookie } }).then((r) => r.json()); + assert.equal(me.source, 'setup'); + + const configuration = await app.fetch('/api/configuration', { headers: { cookie } }); + assert.equal(configuration.status, 200); + assert.ok((await configuration.json()).sections.length > 0); + }); + + it('serves the wizard front-end', async () => { + const response = await app.fetch('/views/setup.js'); + assert.equal(response.status, 200); + }); +});