Files
Catalyst/server/routes.js
josh 15ed329743
All checks were successful
CI / test (pull_request) Successful in 9m32s
fix: db volume ownership and explicit error handling for write failures
Root cause of the 500 on create/update/delete: the non-root app user in
the Docker container lacked write permission to the volume mount point.
Docker volume mounts are owned by root by default; the app user (added
in a previous commit) could read the database but not write to it.

Fixes:

1. Dockerfile — RUN mkdir -p /app/data before chown so the directory
   exists in the image with correct ownership. Docker uses this as a
   seed when initialising a new named volume, ensuring the app user
   owns the mount point from the start.

   NOTE: existing volumes from before the non-root user was introduced
   will still be root-owned. Fix with:
     docker run --rm -v catalyst-data:/data alpine chown -R 1000:1000 /data

2. server/routes.js — replace bare `throw e` in POST/PUT catch blocks
   with console.error (route context + error) + explicit 500 response.
   Add try-catch to DELETE handler which previously had none. Unexpected
   DB errors now log the route they came from and return a clean JSON
   body instead of relying on the generic Express error handler.

3. server/db.js — wrap the boot init() call in try-catch. Fatal startup
   errors (e.g. data directory not writable) now print a clear message
   pointing to the cause before exiting, instead of a raw stack trace.

TDD: tests written first (RED), then fixed (GREEN). Six new tests in
tests/api.test.js verify that unexpected DB errors on POST, PUT, and
DELETE return 500 with { error: 'internal server error' } and call
console.error with the route context string.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 11:11:00 -04:00

125 lines
4.6 KiB
JavaScript

import { Router } from 'express';
import {
getInstances, getInstance, getDistinctStacks,
createInstance, updateInstance, deleteInstance,
} from './db.js';
export const router = Router();
// ── Validation ────────────────────────────────────────────────────────────────
const VALID_STATES = ['deployed', 'testing', 'degraded'];
const VALID_STACKS = ['production', 'development'];
const SERVICE_KEYS = ['atlas', 'argus', 'semaphore', 'patchmon', 'tailscale', 'andromeda'];
function validate(body) {
const errors = [];
if (!body.name || typeof body.name !== 'string' || !body.name.trim())
errors.push('name is required');
if (!Number.isInteger(body.vmid) || body.vmid < 1)
errors.push('vmid must be a positive integer');
if (!VALID_STATES.includes(body.state))
errors.push(`state must be one of: ${VALID_STATES.join(', ')}`);
if (!VALID_STACKS.includes(body.stack))
errors.push(`stack must be one of: ${VALID_STACKS.join(', ')}`);
const ip = (body.tailscale_ip ?? '').trim();
if (ip && !/^(\d{1,3}\.){3}\d{1,3}$/.test(ip))
errors.push('tailscale_ip must be a valid IPv4 address or empty');
return errors;
}
function normalise(body) {
const row = {
name: body.name.trim(),
state: body.state,
stack: body.stack,
vmid: body.vmid,
tailscale_ip: (body.tailscale_ip ?? '').trim(),
hardware_acceleration: body.hardware_acceleration ? 1 : 0,
};
for (const svc of SERVICE_KEYS) row[svc] = body[svc] ? 1 : 0;
return row;
}
// ── Routes ────────────────────────────────────────────────────────────────────
// GET /api/instances/stacks — must be declared before /:vmid
router.get('/instances/stacks', (_req, res) => {
res.json(getDistinctStacks());
});
// GET /api/instances
router.get('/instances', (req, res) => {
const { search, state, stack } = req.query;
res.json(getInstances({ search, state, stack }));
});
// GET /api/instances/:vmid
router.get('/instances/:vmid', (req, res) => {
const vmid = parseInt(req.params.vmid, 10);
if (!vmid) return res.status(400).json({ error: 'invalid vmid' });
const instance = getInstance(vmid);
if (!instance) return res.status(404).json({ error: 'instance not found' });
res.json(instance);
});
// POST /api/instances
router.post('/instances', (req, res) => {
const errors = validate(req.body);
if (errors.length) return res.status(400).json({ errors });
try {
const data = normalise(req.body);
createInstance(data);
const created = getInstance(data.vmid);
res.status(201).json(created);
} catch (e) {
if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'vmid already exists' });
if (e.message.includes('CHECK')) return res.status(400).json({ error: 'invalid field value' });
console.error('POST /api/instances', e);
res.status(500).json({ error: 'internal server error' });
}
});
// PUT /api/instances/:vmid
router.put('/instances/:vmid', (req, res) => {
const vmid = parseInt(req.params.vmid, 10);
if (!vmid) return res.status(400).json({ error: 'invalid vmid' });
if (!getInstance(vmid)) return res.status(404).json({ error: 'instance not found' });
const errors = validate(req.body);
if (errors.length) return res.status(400).json({ errors });
try {
const data = normalise(req.body);
updateInstance(vmid, data);
res.json(getInstance(data.vmid));
} catch (e) {
if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'vmid already exists' });
if (e.message.includes('CHECK')) return res.status(400).json({ error: 'invalid field value' });
console.error('PUT /api/instances/:vmid', e);
res.status(500).json({ error: 'internal server error' });
}
});
// DELETE /api/instances/:vmid
router.delete('/instances/:vmid', (req, res) => {
const vmid = parseInt(req.params.vmid, 10);
if (!vmid) return res.status(400).json({ error: 'invalid vmid' });
const instance = getInstance(vmid);
if (!instance) return res.status(404).json({ error: 'instance not found' });
if (instance.stack !== 'development')
return res.status(422).json({ error: 'only development instances can be deleted' });
try {
deleteInstance(vmid);
res.status(204).end();
} catch (e) {
console.error('DELETE /api/instances/:vmid', e);
res.status(500).json({ error: 'internal server error' });
}
});