Nox real mode requires rights on each telescope and dome it drives
ci / server (mysql) (pull_request) Successful in 16s
ci / server (sqlite) (pull_request) Successful in 16s
ci / lint (pull_request) Successful in 26s
ci / nox (pull_request) Successful in 28s
ci / client (pull_request) Successful in 47s
ci / sidecar (pull_request) Successful in 37s
ci / image (pull_request) Successful in 1m19s
ci / sourcemaps (pull_request) Skipped
ci / deploy (pull_request) Skipped

Finding fmw149sl04. Real mode checked only sign-in and confirmed: true, then resolved any telescope or dome by name, so a signed-in account could drive another site's hardware.

The driver now takes the calling user and checks every op: canControlTelescope for a telescope, canEditSite for a dome. The route refuses with 403 before the first op when a string literal names a resource the caller has no rights on. Names repeat across sites, so a name resolves among the caller's rows, and two matches is an error.

canControl moved from routes/control.js to perms.js as canControlTelescope. It now passes an admin with no booking live, as the control.js header said it did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1
2026-11-03 18:01:41 -05:00
co-authored by Claude Opus 5.5
parent d375166a25
commit fce190c03a
10 changed files with 464 additions and 119 deletions
+1
View File
@@ -22,6 +22,7 @@ All notable changes to Caelum are documented here. Format follows [Keep a Change
- **Clearer offline errors for research tools.** Upstream fetch failures (SIMBAD, JPL, NASA, AAVSO, and now the Lab's Anthropic call) surface "No outbound network from this server - this tool needs internet" instead of a raw "fetch failed"/"aborted", and the two mismatched timeouts (6s/15s) are unified to 12s.
### Fixed
- **Nox real mode checks rights on the hardware it drives.** A signed-in account could run a program against any site's telescope or dome by name. `/api/nox/run` and `/run-stream` now refuse with 403 before the first op, and the driver re-checks on every op. Telescopes follow the `/api/control` rule and domes the `/api/hardware` rule. `/api/control` now also lets an admin in when no booking is live, as its header comment already said.
- **Slews refuse to point near the Sun.** Every path that moves a mount (`/api/control`, `/api/hardware`, `/api/astra`, Nox real mode on each driver, what the dispatcher hands a bridge, and the target on what `/api/jobs` hands a daemon) now refuses a target inside 46 degrees of the Sun unless the telescope declares `solar_filter` on `PUT /api/hardware/telescopes/:id/driver`. Nox real mode also sent RA in degrees to drivers that take hours, so it pointed somewhere else; it now converts.
- **Vet endpoint 500 on MySQL.** `UPDATE sites SET successful_observations = MAX(0, …)` is a syntax error on MySQL (2-arg `MAX` is aggregate-only) - every `PUT /api/observations/:id/vet` failed in production while passing SQLite dev tests. Replaced with a portable `CASE` expression, verified against MySQL 8.4.
- **Simulator hardware control.** A freshly-seeded (idle) simulator now slews without a manual connect (the Nox real-mode path had no connect step), and disconnecting a simulator actually returns it to idle instead of leaving it stuck "connected". New HTTP-level `control.js` integration tests for the connect → status → slew → position → disconnect flow.
+4 -1
View File
@@ -560,7 +560,10 @@ async function runProgram() {
}),
signal: runAbort.signal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
if (!res.ok) {
const failure = await res.json().catch(() => null);
throw new Error(failure?.error || `HTTP ${res.status}`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = '';
+26 -5
View File
@@ -7,7 +7,8 @@ run endpoints, `/examples`, `/docs-search` and `/docs` are open, so the "try Nox
without signing up" console works for anonymous visitors. Running in `"real"`
mode is the exception: it reaches live telescope drivers, so it requires both an
`Authorization: Bearer <token>` header and an explicit `confirmed: true` in the
request body.
request body, and the caller must hold rights on every telescope and dome the
program uses.
## `POST /api/nox/check`
@@ -80,6 +81,12 @@ whatever ops ran before the failure.
**Response 403** when `mode` is `"real"` and the body omits `confirmed: true`.
The body includes a `hint` describing the dry-run-then-confirm flow.
**Response 403** when `mode` is `"real"` and the caller has no rights on a
telescope or dome the program uses. [Modes](#modes) gives the rule. A resource
named by a string literal is checked before the first op runs. A name computed
at run time is checked at its first op, so ops on other resources may already
have run.
**Response 401** when `mode` is `"real"`, `confirmed` is set, and the bearer
token is missing or invalid. A suspended account gets 403 from the auth layer.
@@ -91,9 +98,9 @@ long-running or the client wants to render the op log live.
**Body** identical to `/run`, and gated the same way.
**Response** `text/event-stream`. Errors raised before the stream opens (bad
`source`, unknown `mode`, unconfirmed real mode) come back as JSON with the
status codes listed under `/run`. Once the stream opens the status is 200, and a
failure arrives as an `error` event.
`source`, unknown `mode`, unconfirmed real mode, no rights on a named resource)
come back as JSON with the status codes listed under `/run`. Once the stream
opens the status is 200, and a failure arrives as an `error` event.
**Events**
@@ -212,6 +219,20 @@ client can slew a telescope by accident: the request must be authenticated, and
it must carry `confirmed: true`. The intended flow is to run the program in mock
mode, show the operator the op log, and resend with the flag set.
A third gate decides whose hardware the program may touch. It runs again on every
op, so a booking that starts mid-run stops the program at its next op.
- A telescope follows the `/api/control` rule. While a confirmed booking is live
at the site, only an admin, the holder of a booking on that telescope, or that
booking's collaborators pass. Otherwise an admin, the site owner, or a site
member with role `owner` or `operator` passes.
- A dome follows the `/api/hardware` dome rule: an admin, the site owner, or a
site member with role `owner` or `operator`.
Names and codes can repeat across sites, so a name resolves among the rows the
caller has rights on. A name matching two of those rows is a 400 and moves
nothing.
## Policy options
When the program contains a `policy "..." { ... }` block, the runtime evaluates
@@ -230,7 +251,7 @@ values run as a daemon. A `halt` inside a rule aborts the loop.
| ---- | ----- |
| 400 | Missing source, source not a string, unknown mode, type error, runtime error, or a docs path that escapes the docs root |
| 401 | Real mode without a valid bearer token |
| 403 | Real mode without `confirmed: true` |
| 403 | Real mode without `confirmed: true`, or with no rights on a telescope or dome the program uses |
| 404 | Docs path not found |
| 500 | Bug in the runtime or the docs index; check server logs |
| 503 | Docs directory absent on this host |
+48
View File
@@ -62,6 +62,54 @@ export async function canEditTelescopeSite(telescopeId, user) {
return row ? canEditSite(row.site_id, user) : false;
}
// The telescope row if this user may drive the mount right now, else null.
// While a confirmed booking is live anywhere at the site, only an admin, the
// booking holder on this telescope, or that booking's collaborators qualify.
// Otherwise: admin, site owner, or a member with role owner/operator.
export async function canControlTelescope(telescopeId, user) {
const telescope = await db.get(`
SELECT t.*, e.site_id, s.owner_id FROM telescopes t
JOIN enclosures e ON t.enclosure_id = e.id
JOIN sites s ON e.site_id = s.id
WHERE t.id = ?
`, [telescopeId]);
if (!telescope) return null;
if (user.role === 'admin') return telescope;
const anyActiveSession = await db.all(`
SELECT b.user_id FROM bookings b
JOIN telescopes t ON b.telescope_id = t.id
JOIN enclosures e ON t.enclosure_id = e.id
WHERE e.site_id = ? AND b.status = 'confirmed'
AND b.start_time <= CURRENT_TIMESTAMP
AND b.end_time >= CURRENT_TIMESTAMP
`, [telescope.site_id]);
if (anyActiveSession.length) {
const ownBooking = await db.get(`
SELECT id FROM bookings WHERE telescope_id = ? AND user_id = ? AND status = 'confirmed'
AND start_time <= CURRENT_TIMESTAMP AND end_time >= CURRENT_TIMESTAMP
`, [telescopeId, user.id]);
if (ownBooking) return telescope;
const collab = await db.get(`
SELECT 1 FROM session_collaborators sc JOIN bookings b ON sc.booking_id = b.id
WHERE b.telescope_id = ? AND sc.user_id = ? AND b.status = 'confirmed'
AND b.start_time <= CURRENT_TIMESTAMP AND b.end_time >= CURRENT_TIMESTAMP
LIMIT 1
`, [telescopeId, user.id]);
if (collab) return telescope;
return null;
}
if (telescope.owner_id === user.id) return telescope;
const member = await db.get(
"SELECT role FROM site_members WHERE site_id = ? AND user_id = ? AND role IN ('owner', 'operator')",
[telescope.site_id, user.id]
);
if (member) return telescope;
return null;
}
// --- Archive frame access -----------------------------------------------
// canViewFrame: public/network frames are visible to any authenticated user;
// private frames only to the uploader, a member of the frame's site, or admin.
+6 -49
View File
@@ -1,7 +1,7 @@
// Direct mount control over the Stellarium protocol: connect, slew, read back
// position. Mounted at /api/control. Every route needs authentication, and
// canControl() below then requires admin, site ownership, or membership at the
// telescope's site.
// canControlTelescope() then requires admin, site ownership, or membership at
// the telescope's site.
//
// POST /api/control/:telescopeId/connect -> dial the driver
// POST /api/control/:telescopeId/disconnect -> hang up, force status idle
@@ -17,56 +17,13 @@ import { v4 as uuid } from 'uuid';
import db from '../config/database.js';
import { log } from '../services/log.js';
import { authenticate } from '../middleware/auth.js';
import { canControlTelescope } from '../middleware/perms.js';
import { connectTelescope, disconnectTelescope, slewTo, getPosition, isConnected } from '../services/telescope-control.js';
const router = Router();
async function canControl(userId, telescopeId, userRole) {
const telescope = await db.get(`
SELECT t.*, e.site_id, s.owner_id FROM telescopes t
JOIN enclosures e ON t.enclosure_id = e.id
JOIN sites s ON e.site_id = s.id
WHERE t.id = ?
`, [telescopeId]);
if (!telescope) return null;
const anyActiveSession = await db.all(`
SELECT b.user_id FROM bookings b
JOIN telescopes t ON b.telescope_id = t.id
JOIN enclosures e ON t.enclosure_id = e.id
WHERE e.site_id = ? AND b.status = 'confirmed'
AND b.start_time <= CURRENT_TIMESTAMP
AND b.end_time >= CURRENT_TIMESTAMP
`, [telescope.site_id]);
if (anyActiveSession.length) {
if (userRole === 'admin') return telescope;
const ownBooking = await db.get(`
SELECT id FROM bookings WHERE telescope_id = ? AND user_id = ? AND status = 'confirmed'
AND start_time <= CURRENT_TIMESTAMP AND end_time >= CURRENT_TIMESTAMP
`, [telescopeId, userId]);
if (ownBooking) return telescope;
const collab = await db.get(`
SELECT 1 FROM session_collaborators sc JOIN bookings b ON sc.booking_id = b.id
WHERE b.telescope_id = ? AND sc.user_id = ? AND b.status = 'confirmed'
AND b.start_time <= CURRENT_TIMESTAMP AND b.end_time >= CURRENT_TIMESTAMP
LIMIT 1
`, [telescopeId, userId]);
if (collab) return telescope;
return null;
}
if (telescope.owner_id === userId) return telescope;
const member = await db.get(
"SELECT role FROM site_members WHERE site_id = ? AND user_id = ? AND role IN ('owner', 'operator')",
[telescope.site_id, userId]
);
if (member) return telescope;
return null;
}
router.post('/:telescopeId/connect', authenticate, async (req, res) => {
const telescope = await canControl(req.user.id, req.params.telescopeId, req.user.role);
const telescope = await canControlTelescope(req.params.telescopeId, req.user);
if (!telescope) return res.status(403).json({ error: 'Not authorized to control this telescope' });
const { host, port } = req.body;
@@ -89,14 +46,14 @@ router.post('/:telescopeId/connect', authenticate, async (req, res) => {
});
router.post('/:telescopeId/disconnect', authenticate, async (req, res) => {
const telescope = await canControl(req.user.id, req.params.telescopeId, req.user.role);
const telescope = await canControlTelescope(req.params.telescopeId, req.user);
if (!telescope) return res.status(403).json({ error: 'Not authorized' });
res.json(await disconnectTelescope(req.params.telescopeId));
});
router.post('/:telescopeId/slew', authenticate, async (req, res) => {
const telescope = await canControl(req.user.id, req.params.telescopeId, req.user.role);
const telescope = await canControlTelescope(req.params.telescopeId, req.user);
if (!telescope) return res.status(403).json({ error: 'Not authorized' });
const { ra, dec } = req.body;
+33 -8
View File
@@ -9,15 +9,16 @@
// GET /api/nox/docs/<path> -> text/markdown
//
// `mode` is "mock" (default) or "real". Real mode is gated by
// requireRealModeSafety below. Reference docs: nox/docs/reference/http-api.md.
// requireRealModeSafety and requireRealModeRights below. Reference docs:
// nox/docs/reference/http-api.md.
import { Router } from 'express';
import fs from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { run, checkSource } from '@caelum/nox-runtime';
import { createRealDriver } from '../services/nox-driver.js';
import { run, checkSource, compile } from '@caelum/nox-runtime';
import { createRealDriver, authorizeResource, NoxAccessError } from '../services/nox-driver.js';
import { searchDocs } from '../services/nox-docs-index.js';
import { authenticate } from '../middleware/auth.js';
import { log } from '../services/log.js';
@@ -45,6 +46,30 @@ async function requireRealModeSafety(req, res, next) {
return authenticate(req, res, next);
}
// Runs after requireRealModeSafety. Refuses a real run before its first op when
// any resource it names belongs to someone else, so a program cannot move one
// telescope and then fail on the next. A name computed at run time has no
// literal to read here; the driver checks every op, so that case still refuses.
async function requireRealModeRights(req, res, next) {
if (req.body?.mode !== 'real') return next();
let uses;
try {
uses = compile(req.body.source).body.flatMap(n => (n.type === 'Session' ? n.members : [n]));
} catch {
return next(); // the run handler reports the bad source as a 400
}
for (const use of uses) {
if (use.type !== 'Use' || use.value?.type !== 'String') continue;
try {
await authorizeResource(use.kind, use.value.value, req.user);
} catch (e) {
if (e instanceof NoxAccessError) return res.status(403).json({ error: e.message });
// Not found or ambiguous: the driver raises the same error at the op.
}
}
return next();
}
// Summarize an op log into { [kind]: { [op]: count } } so the client can show
// "12 slews, 5 exposures" instead of just "17 operations".
function summarizeOpLog(log) {
@@ -95,17 +120,17 @@ router.post('/check', (req, res) => {
}
});
router.post('/run', requireRealModeSafety, async (req, res) => {
router.post('/run', requireRealModeSafety, requireRealModeRights, async (req, res) => {
const { source, mode = 'mock', policy } = req.body || {};
if (typeof source !== 'string') return res.status(400).json({ error: 'source required' });
const log = [];
try {
let driver = null;
if (mode === 'real') driver = createRealDriver({ log });
if (mode === 'real') driver = createRealDriver({ log, user: req.user });
const result = await run(source, { strict: true, driver, policy });
res.json({ log: result.log, summary: summarizeOpLog(result.log) });
} catch (e) {
res.status(400).json({ error: e.message, log });
res.status(e instanceof NoxAccessError ? 403 : 400).json({ error: e.message, log });
}
});
@@ -114,7 +139,7 @@ router.post('/run', requireRealModeSafety, async (req, res) => {
// stays a POST (the source can be kilobytes, and a query string caps out), so
// the browser reads the response with fetch + ReadableStream rather than
// EventSource. SSE wire format: `event: <name>\ndata: <json>\n\n` per event.
router.post('/run-stream', requireRealModeSafety, async (req, res) => {
router.post('/run-stream', requireRealModeSafety, requireRealModeRights, async (req, res) => {
const { source, mode = 'mock', policy } = req.body || {};
if (typeof source !== 'string') return res.status(400).json({ error: 'source required' });
@@ -135,7 +160,7 @@ router.post('/run-stream', requireRealModeSafety, async (req, res) => {
try {
let driver = null;
if (mode === 'real') driver = createRealDriver({ log: [], onOp });
if (mode === 'real') driver = createRealDriver({ log: [], onOp, user: req.user });
await run(source, { strict: true, driver, onOp, policy });
send('done', { count });
} catch (e) {
+77 -45
View File
@@ -9,10 +9,14 @@
// 'alpaca' → translates the op into ASCOM Alpaca REST calls.
//
// Anything not listed above logs to the op trace but doesn't reach hardware.
//
// Every op re-checks the caller's rights on its resource before it is logged
// or sent: canControlTelescope for a telescope, canEditSite for a dome.
import db from '../config/database.js';
import { slewTo } from './telescope-control.js';
import { domeAction } from './external-drivers.js';
import { canControlTelescope, canEditSite } from '../middleware/perms.js';
import {
alpacaSlew, alpacaPark, alpacaHome, alpacaWaitUntilSettled,
} from './alpaca-telescope.js';
@@ -30,7 +34,53 @@ const _missingResourceWarned = new Set();
function isAlpaca(row) { return row && row.driver_type === 'alpaca'; }
export function createRealDriver({ log, onOp = null }) {
// A caller reached a resource they hold no rights on. The route answers 403.
export class NoxAccessError extends Error {}
// Names and codes are unique per enclosure or site, so one name can match rows
// at several sites. Choosing among the caller's rows keeps someone else's
// telescope of the same name from being driven, or from refusing this program.
async function pickAllowed(rows, allowed, label, name) {
const mine = [];
for (const r of rows) if (await allowed(r)) mine.push(r);
if (!mine.length) throw new NoxAccessError(`not authorized to control ${label}: ${name}`);
if (mine.length > 1) throw new Error(`${label} name is ambiguous: ${name} matches ${mine.length} of yours`);
return mine[0];
}
async function resolveTelescope(name, user) {
const rows = await db.all(
// Pull every column the dispatchers need (driver_type/host/port/device).
'SELECT id, name, status, driver_type, driver_host, driver_port, driver_device_number, solar_filter FROM telescopes WHERE name = ? OR code = ?',
[name, name]
);
if (!rows.length) {
if (!_missingResourceWarned.has('T:' + name)) {
logger.warn(`[nox] telescope not found: ${name}`);
_missingResourceWarned.add('T:' + name);
}
throw new Error(`telescope not found: ${name}`);
}
return pickAllowed(rows, r => canControlTelescope(r.id, user), 'telescope', name);
}
// Same rule as POST /api/hardware/enclosures/:id/dome/:action.
async function resolveEnclosure(name, user) {
const rows = await db.all('SELECT * FROM enclosures WHERE name = ? OR code = ?', [name, name]);
if (!rows.length) throw new Error(`enclosure not found: ${name}`);
return pickAllowed(rows, r => canEditSite(r.site_id, user), 'enclosure', name);
}
// Throws NoxAccessError when `user` may not drive this resource. Lets the route
// refuse a whole program before its first op moves anything.
export async function authorizeResource(kind, name, user) {
if (kind === 'telescope') await resolveTelescope(name, user);
else if (kind === 'dome') await resolveEnclosure(name, user);
}
export function createRealDriver({ log, onOp = null, user }) {
if (!user) throw new Error('real driver needs the calling user');
function record(kind, op, args = {}) {
const entry = { kind, op, args, t: Date.now() };
log.push(entry);
@@ -39,28 +89,17 @@ export function createRealDriver({ log, onOp = null }) {
return {
telescope(name) {
const rowP = db.get(
// Pull every column the dispatchers need (driver_type/host/port/device).
'SELECT id, name, status, driver_type, driver_host, driver_port, driver_device_number, solar_filter FROM telescopes WHERE name = ? OR code = ?',
[name, name]
);
async function row() {
const r = await rowP;
if (!r) {
if (!_missingResourceWarned.has('T:' + name)) {
logger.warn(`[nox] telescope not found: ${name}`);
_missingResourceWarned.add('T:' + name);
}
throw new Error(`telescope not found: ${name}`);
}
// Resolved per op, so rights lost mid-run (a booking starts or ends, a
// member is removed) stop the program at its next op.
async function begin(op, args, part = '') {
const r = await resolveTelescope(name, user);
record('T:' + name + part, op, args);
return r;
}
return {
async slew(target) {
record('T:' + name, 'slew', { target });
const r = await row();
const r = await begin('slew', { target });
// A Nox Coord holds RA in degrees. Both drivers take hours, and both
// run the Sun check, so a degree value here would aim the mount and
// the check at a position the program never asked for.
@@ -69,20 +108,17 @@ export function createRealDriver({ log, onOp = null }) {
else await slewTo(r.id, raHours, target.dec);
},
async park() {
record('T:' + name, 'park');
const r = await row();
const r = await begin('park');
if (isAlpaca(r)) await alpacaPark(r);
else await db.run("UPDATE telescopes SET status = 'idle' WHERE id = ?", [r.id]);
},
async home() {
record('T:' + name, 'home');
const r = await row();
const r = await begin('home');
if (isAlpaca(r)) await alpacaHome(r);
else await db.run("UPDATE telescopes SET current_ra = 0, current_dec = 0 WHERE id = ?", [r.id]);
},
async wait_until_settled() {
record('T:' + name, 'wait_until_settled');
const r = await row();
const r = await begin('wait_until_settled');
if (isAlpaca(r)) { await alpacaWaitUntilSettled(r); return; }
// Simulator/stellarium path: poll the DB status until not 'slewing'.
for (let i = 0; i < 60; i++) {
@@ -92,8 +128,7 @@ export function createRealDriver({ log, onOp = null }) {
}
},
async cooldown(target, timeout) {
record('T:' + name, 'cooldown', { target, timeout });
const r = await row();
const r = await begin('cooldown', { target, timeout });
if (isAlpaca(r)) {
// target arrives as a Quantity{value, dim:'Temperature'} from Nox.
const degC = target && typeof target.value === 'number' ? target.value : target;
@@ -101,13 +136,11 @@ export function createRealDriver({ log, onOp = null }) {
}
},
async warm_up() {
record('T:' + name, 'warm_up');
const r = await row();
const r = await begin('warm_up');
if (isAlpaca(r)) await alpacaCooldown(r, 20, { timeoutMs: 300_000 });
},
async expose(exp, filter) {
record('T:' + name, 'expose', { exp, filter });
const r = await row();
const r = await begin('expose', { exp, filter });
if (isAlpaca(r)) {
// exp arrives as Quantity{value, dim:'Duration'} (already in seconds).
const seconds = exp && typeof exp.value === 'number' ? exp.value : Number(exp);
@@ -115,37 +148,36 @@ export function createRealDriver({ log, onOp = null }) {
}
return { _tag: 'Image', filter };
},
async focus(method) { record('T:' + name, 'focus', { method }); },
async focus_if_needed(args) { record('T:' + name, 'focus_if_needed', args); },
async dither(amount, pattern) { record('T:' + name, 'dither', { amount, pattern }); },
async auto_flat_exposure(filter){ record('T:' + name, 'auto_flat_exposure', { filter }); return 5; },
async focus(method) { await begin('focus', { method }); },
async focus_if_needed(args) { await begin('focus_if_needed', args); },
async dither(amount, pattern) { await begin('dither', { amount, pattern }); },
async auto_flat_exposure(filter){ await begin('auto_flat_exposure', { filter }); return 5; },
is_idle: true,
filter_wheel: {
async select(filter) { record('T:' + name + ':fw', 'select', { filter }); },
async select(filter) { await begin('select', { filter }, ':fw'); },
},
focuser: {
async move_to(pos) { record('T:' + name + ':focuser', 'move_to', { pos }); },
async move_to(pos) { await begin('move_to', { pos }, ':focuser'); },
},
camera: {
async shutter(state) { record('T:' + name + ':camera', 'shutter', { state }); },
async shutter(state) { await begin('shutter', { state }, ':camera'); },
},
};
},
dome(name) {
const encP = db.get('SELECT * FROM enclosures WHERE name = ? OR code = ?', [name, name]);
async function enc() {
const r = await encP;
if (!r) throw new Error(`enclosure not found: ${name}`);
async function begin(op, args, part = '') {
const r = await resolveEnclosure(name, user);
record('D:' + name + part, op, args);
return r;
}
return {
async open() { record('D:' + name, 'open'); await domeAction(await enc(), 'open'); },
async close() { record('D:' + name, 'close'); await domeAction(await enc(), 'close'); },
async open() { await domeAction(await begin('open'), 'open'); },
async close() { await domeAction(await begin('close'), 'close'); },
is_closed() { return true; }, // TODO: read shutter_status when available
flat_panel: {
async on(brightness) { record('D:' + name + ':panel', 'on', { brightness }); },
async off() { record('D:' + name + ':panel', 'off'); },
async on(brightness) { await begin('on', { brightness }, ':panel'); },
async off() { await begin('off', undefined, ':panel'); },
},
};
},
+256
View File
@@ -0,0 +1,256 @@
// Nox real mode acts only on hardware the caller has rights on. Runs the routes
// against a real SQLite DB with simulator telescopes: a program that ran sets
// current_ra to 0 through T.home(), and one that was refused leaves it at 5.
import { test, before, after, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import express from 'express';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
let server, base, db, tmpDb, generateToken, canControlTelescope;
const USERS = ['owner', 'operator', 'observer', 'stranger', 'admin', 'booker'];
const token = {};
async function runReal(source, as, route = 'run') {
const r = await fetch(`${base}/api/nox/${route}`, {
method: 'POST',
headers: { authorization: `Bearer ${token[as]}`, 'content-type': 'application/json' },
body: JSON.stringify({ source, mode: 'real', confirmed: true }),
});
const text = await r.text();
let body; try { body = JSON.parse(text); } catch { body = text; }
return { status: r.status, body, type: r.headers.get('content-type') };
}
const home = name => `use telescope T = "${name}"\nT.home()\n`;
const ra = async id => Number((await db.get('SELECT current_ra FROM telescopes WHERE id = ?', [id])).current_ra);
const shutter = async id => (await db.get('SELECT shutter_status FROM enclosures WHERE id = ?', [id])).shutter_status;
async function addSite(id, owner) {
await db.run(`INSERT INTO sites (id, name, code, owner_id, latitude, longitude) VALUES (?,?,?,?,?,?)`,
[id, id, id, owner, 0, 0]);
}
async function addEnclosure(id, site, name) {
await db.run(`INSERT INTO enclosures (id, site_id, name, code, driver_type, shutter_status) VALUES (?,?,?,?,?,?)`,
[id, site, name, name, 'simulator', 'closed']);
}
async function addTelescope(id, enclosure, name) {
await db.run(`INSERT INTO telescopes (id, enclosure_id, name, code, status, driver_type, current_ra, current_dec) VALUES (?,?,?,?,?,?,?,?)`,
[id, enclosure, name, name, 'idle', 'simulator', 5, 5]);
}
async function bookNow(id, telescope, user) {
await db.run(`INSERT INTO bookings (id, telescope_id, user_id, title, start_time, end_time, status)
VALUES (?, ?, ?, 'night', datetime('now', '-1 hour'), datetime('now', '+1 hour'), 'confirmed')`, [id, telescope, user]);
}
before(async () => {
tmpDb = path.join(os.tmpdir(), `caelum-nox-auth-${Date.now()}.sqlite`);
process.env.DB_KIND = 'sqlite';
process.env.SQLITE_PATH = tmpDb;
const dbMod = await import('../src/config/database.js');
db = dbMod.default;
await dbMod.initDb();
({ generateToken } = await import('../src/middleware/auth.js'));
({ canControlTelescope } = await import('../src/middleware/perms.js'));
const noxRouter = (await import('../src/routes/nox.js')).default;
for (const u of USERS) {
const role = u === 'admin' ? 'admin' : 'observer';
await db.run('INSERT INTO users (id, email, username, password_hash, role) VALUES (?,?,?,?,?)',
[u, `${u}@test`, u, 'x', role]);
token[u] = generateToken({ id: u, email: `${u}@test`, username: u, role });
}
await addSite('site-a', 'owner');
await addSite('site-b', 'stranger');
await db.run('INSERT INTO site_members (site_id, user_id, role) VALUES (?,?,?)', ['site-a', 'operator', 'operator']);
await db.run('INSERT INTO site_members (site_id, user_id, role) VALUES (?,?,?)', ['site-a', 'observer', 'observer']);
await addEnclosure('enc-a', 'site-a', 'DomeA');
await addEnclosure('enc-b', 'site-b', 'DomeB');
await addTelescope('tel-a', 'enc-a', 'ScopeA');
await addTelescope('tel-a2', 'enc-a', 'ScopeA2');
await addTelescope('tel-b', 'enc-b', 'ScopeB');
// One name at two sites: each owner must reach their own row.
await addTelescope('twin-a', 'enc-a', 'Twin');
await addTelescope('twin-b', 'enc-b', 'Twin');
const app = express();
app.use(express.json());
app.use('/api/nox', noxRouter);
await new Promise(resolve => { server = app.listen(0, '127.0.0.1', resolve); });
base = `http://127.0.0.1:${server.address().port}`;
});
after(async () => {
await new Promise(resolve => server.close(resolve));
fs.rmSync(tmpDb, { force: true });
});
beforeEach(async () => {
await db.run('DELETE FROM bookings');
await db.run('UPDATE telescopes SET current_ra = 5, current_dec = 5');
await db.run("UPDATE enclosures SET shutter_status = 'closed'");
});
test('Nox real run: site owner may drive their telescope', async () => {
const r = await runReal(home('ScopeA'), 'owner');
assert.equal(r.status, 200);
assert.equal(await ra('tel-a'), 0);
});
test('Nox real run: site operator may drive it', async () => {
const r = await runReal(home('ScopeA'), 'operator');
assert.equal(r.status, 200);
assert.equal(await ra('tel-a'), 0);
});
test('Nox real run: admin may drive it', async () => {
const r = await runReal(home('ScopeA'), 'admin');
assert.equal(r.status, 200);
assert.equal(await ra('tel-a'), 0);
});
test('Nox real run: a user from another site is refused with 403', async () => {
const r = await runReal(home('ScopeA'), 'stranger');
assert.equal(r.status, 403);
assert.match(r.body.error, /not authorized to control telescope: ScopeA/);
assert.equal(await ra('tel-a'), 5);
});
test('Nox real run: an observer member is refused, matching /api/control', async () => {
const r = await runReal(home('ScopeA'), 'observer');
assert.equal(r.status, 403);
assert.equal(await ra('tel-a'), 5);
});
test('Nox real run-stream: a refusal is a 403 before the stream opens', async () => {
const r = await runReal(home('ScopeA'), 'stranger', 'run-stream');
assert.equal(r.status, 403);
assert.match(r.type, /json/);
assert.equal(await ra('tel-a'), 5);
});
test('Nox real run-stream: the owner gets the stream and the op runs', async () => {
const r = await runReal(home('ScopeA'), 'owner', 'run-stream');
assert.equal(r.status, 200);
assert.match(r.type, /event-stream/);
assert.match(r.body, /event: done/);
assert.equal(await ra('tel-a'), 0);
});
test('Nox real run: one foreign telescope refuses the program before any op', async () => {
const source = `use telescope A = "ScopeA"\nuse telescope B = "ScopeB"\nA.home()\nB.home()\n`;
const r = await runReal(source, 'owner');
assert.equal(r.status, 403);
assert.equal(await ra('tel-a'), 5);
assert.equal(await ra('tel-b'), 5);
});
test('Nox real run: a resource inside a session is checked before any op', async () => {
const source = `use telescope A = "ScopeA"\nA.home()\nsession "s" {\n use telescope B = "ScopeB"\n B.home()\n}\n`;
const r = await runReal(source, 'owner');
assert.equal(r.status, 403);
assert.equal(await ra('tel-a'), 5);
});
test('Nox real run: a name computed at run time is refused by the driver', async () => {
const source = `let n = "ScopeB"\nuse telescope T = n\nT.home()\n`;
const r = await runReal(source, 'owner');
assert.equal(r.status, 403, JSON.stringify(r.body));
assert.deepEqual(r.body.log, []);
assert.equal(await ra('tel-b'), 5);
});
test('Nox real run: an op with no hardware behind it is refused too', async () => {
const source = `let n = "ScopeB"\nuse telescope T = n\nT.camera.shutter("open")\n`;
const r = await runReal(source, 'owner');
assert.equal(r.status, 403, JSON.stringify(r.body));
assert.deepEqual(r.body.log, []);
});
test('Nox real run: a shared name resolves to the caller\'s own telescope', async () => {
const mine = await runReal(home('Twin'), 'owner');
assert.equal(mine.status, 200);
assert.equal(await ra('twin-a'), 0);
assert.equal(await ra('twin-b'), 5);
const theirs = await runReal(home('Twin'), 'stranger');
assert.equal(theirs.status, 200);
assert.equal(await ra('twin-b'), 0);
});
test('Nox real run: a shared name matching two of the caller\'s rows moves neither', async () => {
const r = await runReal(home('Twin'), 'admin');
assert.equal(r.status, 400);
assert.match(r.body.error, /ambiguous/);
assert.equal(await ra('twin-a'), 5);
assert.equal(await ra('twin-b'), 5);
});
test('Nox real run: an unknown telescope is a 400 not found', async () => {
const r = await runReal(home('NoSuchScope'), 'owner');
assert.equal(r.status, 400);
assert.match(r.body.error, /telescope not found/);
});
test('Nox real run: a booking holder with no site role may drive the booked telescope', async () => {
await bookNow('b1', 'tel-a', 'booker');
const r = await runReal(home('ScopeA'), 'booker');
assert.equal(r.status, 200);
assert.equal(await ra('tel-a'), 0);
});
test('Nox real run: the holder of a booking on one telescope is refused on another', async () => {
await bookNow('b1', 'tel-a', 'booker');
const r = await runReal(home('ScopeA2'), 'booker');
assert.equal(r.status, 403);
assert.equal(await ra('tel-a2'), 5);
});
test('Nox real run: the site owner is refused during another user\'s session', async () => {
await bookNow('b1', 'tel-a', 'booker');
const r = await runReal(home('ScopeA'), 'owner');
assert.equal(r.status, 403);
assert.equal(await ra('tel-a'), 5);
});
test('Nox real run: rights lost mid-run stop the program at its next op', async () => {
const { createRealDriver, NoxAccessError } = await import('../src/services/nox-driver.js');
const log = [];
const t = createRealDriver({ log, user: { id: 'owner', role: 'observer' } }).telescope('ScopeA');
await t.home();
await bookNow('b1', 'tel-a', 'booker');
await assert.rejects(() => t.park(), NoxAccessError);
assert.deepEqual(log.map(e => e.op), ['home']);
});
test('Nox real run: the site owner may open their dome', async () => {
const r = await runReal(`use dome D = "DomeA"\nD.open()\n`, 'owner');
assert.equal(r.status, 200);
assert.equal(await shutter('enc-a'), 'open');
});
test('Nox real run: a user from another site may not open the dome', async () => {
const r = await runReal(`use dome D = "DomeA"\nD.open()\n`, 'stranger');
assert.equal(r.status, 403);
assert.match(r.body.error, /not authorized to control enclosure: DomeA/);
assert.equal(await shutter('enc-a'), 'closed');
});
test('createRealDriver: no user is an error', async () => {
const { createRealDriver } = await import('../src/services/nox-driver.js');
assert.throws(() => createRealDriver({ log: [] }), /calling user/);
});
test('canControlTelescope: an admin passes with no booking in progress', async () => {
const row = await canControlTelescope('tel-a', { id: 'admin', role: 'admin' });
assert.equal(row.id, 'tel-a');
});
+7 -5
View File
@@ -14,6 +14,8 @@ let realFetch;
let fetchCalls;
let dbModule, driverModule;
const ADMIN = { id: 'u-1', role: 'admin' };
beforeEach(async () => {
process.env.DB_KIND = 'sqlite';
process.env.SQLITE_PATH = path.join(os.tmpdir(), `caelum-dispatch-${Date.now()}.sqlite`);
@@ -80,7 +82,7 @@ afterEach(async () => {
test('telescope.slew on driver_type=alpaca calls the Alpaca server', async () => {
const log = [];
const driver = driverModule.createRealDriver({ log });
const driver = driverModule.createRealDriver({ log, user: ADMIN });
const t = driver.telescope('AlpacaScope');
await t.slew({ ra: 10.685, dec: 41.269 });
assert.equal(log.length, 1);
@@ -93,7 +95,7 @@ test('telescope.slew on driver_type=alpaca calls the Alpaca server', async () =>
test('telescope.slew on driver_type=simulator does NOT call Alpaca', async () => {
const log = [];
const driver = driverModule.createRealDriver({ log });
const driver = driverModule.createRealDriver({ log, user: ADMIN });
const t = driver.telescope('SimScope');
// Simulator path requires a "connected" status to slew; we seeded that.
await t.slew({ ra: 10.685, dec: 41.269 });
@@ -105,7 +107,7 @@ test('telescope.slew on driver_type=simulator does NOT call Alpaca', async () =>
test('telescope.park routes correctly per driver_type', async () => {
const log = [];
const driver = driverModule.createRealDriver({ log });
const driver = driverModule.createRealDriver({ log, user: ADMIN });
await driver.telescope('AlpacaScope').park();
await driver.telescope('SimScope').park();
assert.equal(log.length, 2);
@@ -116,7 +118,7 @@ test('telescope.park routes correctly per driver_type', async () => {
test('telescope.wait_until_settled polls the Alpaca slewing flag', async () => {
const log = [];
const driver = driverModule.createRealDriver({ log });
const driver = driverModule.createRealDriver({ log, user: ADMIN });
await driver.telescope('AlpacaScope').wait_until_settled();
// The mocked Alpaca returns slewing=false immediately, so we expect at
// least one slewing GET + the final position GETs (RA + Dec).
@@ -127,7 +129,7 @@ test('telescope.wait_until_settled polls the Alpaca slewing flag', async () => {
test('unknown telescope name throws a clean error', async () => {
const log = [];
const driver = driverModule.createRealDriver({ log });
const driver = driverModule.createRealDriver({ log, user: ADMIN });
await assert.rejects(
() => driver.telescope('DoesNotExist').slew({ ra: 0, dec: 0 }),
/telescope not found/
+6 -6
View File
@@ -266,19 +266,19 @@ test('alpacaSlew: a row read without the column counts as no filter', async () =
// ---------- the Nox driver, which holds degrees ----------
test('Nox driver, Alpaca: refused beside the Sun, mount not called', async () => {
const driver = createRealDriver({ log: [] });
const driver = createRealDriver({ log: [], user: { id: 'sun-admin', role: 'admin' } });
await assert.rejects(() => driver.telescope(ALPACA).slew(toNox(beside())), sun.SunAvoidanceError);
assert.equal(mountSlews().length, 0);
});
test('Nox driver, Alpaca: allowed opposite the Sun', async () => {
const driver = createRealDriver({ log: [] });
const driver = createRealDriver({ log: [], user: { id: 'sun-admin', role: 'admin' } });
await driver.telescope(ALPACA).slew(toNox(opposite()));
assert.equal(mountSlews().length, 1);
});
test('Nox driver, Alpaca: declared filter allows it, and RA reaches the mount in hours', async () => {
const driver = createRealDriver({ log: [] });
const driver = createRealDriver({ log: [], user: { id: 'sun-admin', role: 'admin' } });
const b = beside();
await driver.telescope(ALPACA_FILTER).slew(toNox(b));
const [call] = mountSlews();
@@ -288,12 +288,12 @@ test('Nox driver, Alpaca: declared filter allows it, and RA reaches the mount in
});
test('Nox driver, simulator: refused beside the Sun', async () => {
const driver = createRealDriver({ log: [] });
const driver = createRealDriver({ log: [], user: { id: 'sun-admin', role: 'admin' } });
await assert.rejects(() => driver.telescope(SIM).slew(toNox(beside())), sun.SunAvoidanceError);
});
test('Nox driver, simulator: allowed opposite the Sun, stored position in hours', async () => {
const driver = createRealDriver({ log: [] });
const driver = createRealDriver({ log: [], user: { id: 'sun-admin', role: 'admin' } });
const o = opposite();
await driver.telescope(SIM).slew(toNox(o));
const row = await db.get('SELECT current_ra FROM telescopes WHERE id = ?', [SIM]);
@@ -301,7 +301,7 @@ test('Nox driver, simulator: allowed opposite the Sun, stored position in hours'
});
test('Nox driver: a target with no coordinates is refused', async () => {
const driver = createRealDriver({ log: [] });
const driver = createRealDriver({ log: [], user: { id: 'sun-admin', role: 'admin' } });
await assert.rejects(() => driver.telescope(SIM_FILTER).slew({}), sun.SunAvoidanceError);
});