diff --git a/api/controllers/log/tail.js b/api/controllers/log/tail.js new file mode 100644 index 0000000..0298ae9 --- /dev/null +++ b/api/controllers/log/tail.js @@ -0,0 +1,62 @@ +const fs = require('fs'); +const path = require('path'); +const {LINES, DEFAULT_LINES} = require('../../lib/log-viewer'); + +/** + * POST /api/v1/log/tail + * + * The last lines of one fog-node log file, for the Log Viewer page + * (GET /logviewer). Body {file, lines, reverse}. Answers {file, lines: [...]}, + * oldest first, or newest first when `reverse`. Needs setting.read. + * + * `file` must be a name that the files rule lists (api/helpers/log/files.js). + * The path is built here from the folder and that name, never from the client. + * After the open, fstat must give the same dev and ino as the listed file: a + * file swapped in between (for example for a symlink) answers 400. A rotation + * between the list and the open gives the same 400 for a moment; the next poll + * of the page reads the new file. O_NOFOLLOW does not exist on Windows, so + * this check is the guard. + */ + +// A number, or a string of digits, whose value is in LINES; else the default. +const parseLines = (value) => { + const n = typeof value === 'number' ? value : (typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : NaN); + return LINES.includes(n) ? n : DEFAULT_LINES; +}; + +module.exports = { + friendlyName: 'Log tail', + description: 'The last lines of a fog-node log file.', + fn: async function () { + const req = this.req; + const res = this.res; + if (!sails.helpers.audit.can(req, 'setting.read')) { + return res.forbidden(); + } + const body = req.body || {}; + const unknown = () => res.status(400).json({error: 'Unknown log file.'}); + const {dir, files} = sails.helpers.log.files(); + const entry = typeof body.file === 'string' ? files.find((f) => f.name === body.file) : undefined; + if (!entry) { return unknown(); } + const lines = parseLines(body.lines); + const reverse = body.reverse === true || body.reverse === 'true'; + + let fd; + try { + fd = fs.openSync(path.join(dir, entry.name), 'r'); + const st = fs.fstatSync(fd, {bigint: true}); + if (!st.isFile() || st.dev !== entry.dev || st.ino !== entry.ino) { + return unknown(); + } + const tail = sails.helpers.log.tail.with({fd, size: Number(st.size), lines}); + return res.json({file: entry.name, lines: reverse ? tail.lines.reverse() : tail.lines}); + } catch (err) { + // The file is gone: an empty answer, as a log that has no lines yet. + if (err.code === 'ENOENT') { return res.json({file: entry.name, lines: []}); } + sails.log.warn(`The Log Viewer cannot read ${entry.name}: ${err.message}`); + return res.status(500).json({error: 'Cannot read the log file.'}); + } finally { + if (fd !== undefined) { fs.closeSync(fd); } + } + } +}; diff --git a/api/controllers/pages/logviewer.js b/api/controllers/pages/logviewer.js new file mode 100644 index 0000000..0d10646 --- /dev/null +++ b/api/controllers/pages/logviewer.js @@ -0,0 +1,35 @@ +const path = require('path'); +const {LINES, DEFAULT_LINES} = require('../../lib/log-viewer'); + +// GET /logviewer: the FOG 1.6 Log Viewer (LogViewerManagement.php, +// status/logtoview.php), over the fog-node log file (api/lib/file-logger.js). +// It needs setting.read, as 1.6 maps logviewer onto its settings node +// (Authorization.php:87). The page script (views/pages/partials/logviewer.js) +// reads the lines from POST /api/v1/log/tail (api/controllers/log/tail.js). +module.exports = { + friendlyName: 'Log Viewer', + description: 'The Log Viewer page.', + exits: { + forbidden: { + responseType: 'forbidden' + }, + success: { + viewTemplatePath: 'pages/logviewer' + } + }, + fn: async function () { + if (!sails.helpers.audit.can(this.req, 'setting.read')) { + throw 'forbidden'; + } + return { + section: 'Log Viewer', + page: 'Log Viewer', + // The files the files rule lists now: fog-node.log, then .1 to .5. + files: sails.helpers.log.files().files.map((f) => f.name), + // The Lines select and its default, as the tail action accepts them. + lineChoices: LINES, + defaultLines: DEFAULT_LINES, + partialname: path.join(__dirname, '..', '..', '..', 'views', 'pages', 'partials', 'logviewer.js') + }; + } +}; diff --git a/api/helpers/log/files.js b/api/helpers/log/files.js new file mode 100644 index 0000000..689ee2b --- /dev/null +++ b/api/helpers/log/files.js @@ -0,0 +1,44 @@ +const fs = require('fs'); +const path = require('path'); +const {FILE, KEEP, FALLBACK_DIR, resolveDir} = require('../../lib/file-logger'); + +/** + * The files rule of the Log Viewer: which log files a browser may read. + * + * Outputs: {dir, files}. `dir` is the log folder, read on each call + * (api/lib/file-logger.js resolveDir). `files` is a list of {name, dev, ino}, + * in the order fog-node.log, .1 ... .5. A name is listed only when it matches + * exactly `fog-node.log` with an optional `.1` to `.5`, AND lstat reports a + * regular file there. A symlink, a folder or anything else is not listed. + * dev and ino are bigint (an NTFS file index is 64-bit). The tail action + * compares them with the file it opens, so a file swapped after this call is + * refused. Nothing outside this list is ever read. + * + * The fallback folder is the one config/log.js gives the logger, so the + * viewer reads the folder that the logger writes. + */ +const NAMES = [FILE, ...Array.from({length: KEEP}, (_, i) => `${FILE}.${i + 1}`)]; + +module.exports = { + friendlyName: 'Log files', + description: 'The log files that the Log Viewer may read.', + sync: true, + exits: { + success: {outputType: 'ref', description: '{dir, files: [{name, dev, ino}]}.'} + }, + fn: function () { + const dir = resolveDir({fallbackDir: FALLBACK_DIR}); + const files = []; + for (const name of NAMES) { + let st; + try { + st = fs.lstatSync(path.join(dir, name), {bigint: true}); + } catch { + // Missing, or not readable: not listed. + continue; + } + if (st.isFile()) files.push({name, dev: st.dev, ino: st.ino}); + } + return {dir, files}; + } +}; diff --git a/api/helpers/log/tail.js b/api/helpers/log/tail.js new file mode 100644 index 0000000..cf44351 --- /dev/null +++ b/api/helpers/log/tail.js @@ -0,0 +1,84 @@ +const fs = require('fs'); + +/** + * The last lines of an open file, for the Log Viewer. + * + * Inputs: fd (an open file), size (its size in bytes), lines (how many). + * Outputs: {lines, bytesRead}, the lines oldest first. + * + * It reads backwards from the end in CHUNK-byte reads and keeps the raw + * buffers. It stops when the bytes read hold more than `lines` newline bytes + * (0x0A), at the start of the file, or at MAX_READ bytes. It then joins the + * buffers, splits on 0x0A and decodes each line as UTF-8. A newline byte never + * occurs inside a multibyte character, so no character is split. A trailing + * newline does not make an empty last line. A last line with no newline (still + * being written) counts. When the read did not reach the start of the file, + * the first line may be partial, so it is dropped. + */ +const {CHUNK, MAX_READ} = require('../../lib/log-viewer'); +const NEWLINE = 0x0A; + +const countNewlines = (buf) => { + let n = 0; + for (let i = buf.indexOf(NEWLINE); i !== -1; i = buf.indexOf(NEWLINE, i + 1)) n++; + return n; +}; + +module.exports = { + friendlyName: 'Tail a file', + description: 'The last lines of an open file.', + sync: true, + inputs: { + fd: {type: 'number', required: true}, + size: {type: 'number', required: true}, + lines: {type: 'number', required: true} + }, + exits: { + success: {outputType: 'ref', description: '{lines, bytesRead}.'} + }, + fn: function ({fd, size, lines}) { + const buffers = []; + let pos = size; + let bytesRead = 0; + let newlines = 0; + let cut = false; + while (pos > 0 && bytesRead < MAX_READ && newlines <= lines) { + const length = Math.min(CHUNK, pos, MAX_READ - bytesRead); + pos -= length; + const buf = Buffer.alloc(length); + // readSync can return fewer bytes than asked: read until the chunk is full. + let got = 0; + while (got < length) { + const n = fs.readSync(fd, buf, got, length - got, pos + got); + if (n === 0) break; + got += n; + } + // The file shrank under the read. This chunk is not whole, and the bytes + // before it are not the bytes that came before it: stop, and keep only + // the chunks already read in full. The first line is then not known to + // be whole, so it is dropped below. + if (got < length) { + cut = true; + break; + } + buffers.unshift(buf); + bytesRead += length; + newlines += countNewlines(buf); + } + if (bytesRead === 0) return {lines: [], bytesRead}; + + const data = Buffer.concat(buffers); + const parts = []; + let from = 0; + for (let i = data.indexOf(NEWLINE); i !== -1; i = data.indexOf(NEWLINE, from)) { + parts.push(data.subarray(from, i)); + from = i + 1; + } + // Bytes after the last newline are a line with no newline yet. None means + // the data ended with a newline: no empty last line. + if (from < data.length) parts.push(data.subarray(from)); + // The read began inside the file: the first line may be partial. + if (pos > 0 || cut) parts.shift(); + return {lines: parts.slice(-lines).map((part) => part.toString('utf8')), bytesRead}; + } +}; diff --git a/api/hooks/audit/index.js b/api/hooks/audit/index.js index 0327de0..5e18126 100644 --- a/api/hooks/audit/index.js +++ b/api/hooks/audit/index.js @@ -47,6 +47,8 @@ const READ_ACTIONS = [ // The Agent Activity reads: the same reason as the Audit Log one. 'agent-activity/summary', 'agent-activity/host', + // The Log Viewer polls this every 10 seconds: a row for each read would flood the trail. + 'log/tail', // Signs a JWT for the user and changes no record. 'auth/token' ]; diff --git a/api/lib/file-logger.js b/api/lib/file-logger.js index 429befe..1ba67dc 100644 --- a/api/lib/file-logger.js +++ b/api/lib/file-logger.js @@ -14,6 +14,9 @@ const FILE = 'fog-node.log'; const MAX_BYTES = 10 * 1024 * 1024; // The number of old files kept: fog-node.log.1 to fog-node.log.5. const KEEP = 5; +// The folder when custom.logDir is not set: /logs. config/log.js and the +// Log Viewer (api/helpers/log/files.js) both use it. +const FALLBACK_DIR = path.resolve(__dirname, '..', '..', 'logs'); // These levels go to stderr on the console, the rest to stdout. const STDERR_LEVELS = new Set(['error', 'warn', 'crit']); const LEVELS = ['log', 'error', 'warn', 'info', 'verbose', 'debug', 'silly', 'crit']; @@ -109,4 +112,4 @@ const create = ({fallbackDir, logDir, maxBytes = MAX_BYTES} = {}) => { return logger; }; -module.exports = {resolveDir, create}; +module.exports = {FILE, KEEP, FALLBACK_DIR, resolveDir, create}; diff --git a/api/lib/log-viewer.js b/api/lib/log-viewer.js new file mode 100644 index 0000000..590e2bf --- /dev/null +++ b/api/lib/log-viewer.js @@ -0,0 +1,12 @@ +// The constants of the Log Viewer, defined once: the tail helper +// (api/helpers/log/tail.js), the tail action (api/controllers/log/tail.js), +// the page (api/controllers/pages/logviewer.js) and the tests use them. + +module.exports = { + // The read size of the tail helper, and the most bytes it reads. + CHUNK: 4096, + MAX_READ: 4 * 1024 * 1024, + // The Lines select (1.6 LogViewerManagement.php:442-450), and its default. + LINES: [10, 25, 50, 100, 250, 500, 1000], + DEFAULT_LINES: 100 +}; diff --git a/assets/styles/zz-fog-ui.css b/assets/styles/zz-fog-ui.css index 46686c2..e4aed84 100644 --- a/assets/styles/zz-fog-ui.css +++ b/assets/styles/zz-fog-ui.css @@ -1678,3 +1678,13 @@ body.fog-col-resizing { --fog-chart-grid: rgba(255,255,255,0.12); --fog-chart-empty: var(--bs-secondary-color); } + +/* The Log Viewer
 (views/pages/logviewer.ejs): a scrolling box of lines. */
+.logviewer-pre {
+  max-height: 70vh;
+  min-height: 12rem;
+  overflow: auto;
+  padding: 0.5rem;
+  font-size: 0.8rem;
+  border: 1px solid var(--bs-border-color);
+}
diff --git a/config/globals.js b/config/globals.js
index e1bfa50..3615664 100644
--- a/config/globals.js
+++ b/config/globals.js
@@ -159,7 +159,8 @@ module.exports.globals = {
         // Activity comes before Audit Log (1.6 FOGPage.php:658-661).
         {text: 'Activity', link: '/activity', icon: 'fas fa-clock-rotate-left'},
         {text: 'Audit Log', link: '/audit', icon: 'fas fa-clipboard-list'},
-        {text: 'Agent Activity', link: '/agent-activity', icon: 'fas fa-satellite-dish'}
+        {text: 'Agent Activity', link: '/agent-activity', icon: 'fas fa-satellite-dish'},
+        {text: 'Log Viewer', link: '/logviewer', icon: 'fas fa-file-lines'}
       ]
     }
   ],
diff --git a/config/log.js b/config/log.js
index 9bba1cc..355a37d 100644
--- a/config/log.js
+++ b/config/log.js
@@ -10,7 +10,7 @@
  * https://sailsjs.com/docs/concepts/logging
  */
 
-const path = require('path');
+const fileLogger = require('../api/lib/file-logger');
 
 module.exports.log = {
 
@@ -32,6 +32,6 @@ module.exports.log = {
   // (api/lib/file-logger.js). The folder is custom.logDir, else /logs.
   // inspect is off so that the logger gets the raw arguments.
   inspect: false,
-  custom: require('../api/lib/file-logger').create({fallbackDir: path.resolve(__dirname, '..', 'logs')})
+  custom: fileLogger.create({fallbackDir: fileLogger.FALLBACK_DIR})
 
 };
diff --git a/config/policies.js b/config/policies.js
index 7435237..5837d3a 100644
--- a/config/policies.js
+++ b/config/policies.js
@@ -46,6 +46,9 @@ module.exports.policies = {
   'agent-activity/summary': ['isLoggedIn','isAuthenticated'],
   'agent-activity/host':    ['isLoggedIn','isAuthenticated'],
 
+  // The Log Viewer lines (the action checks setting.read itself). It only reads.
+  'log/tail':              ['isLoggedIn','isAuthenticated'],
+
   // fog-agent enrollment admin routes (each action checks its host permission
   // itself). apiCsrfGuard: a cookie-authed mutation on CSRF-exempt /api/v1.
   'agent/enrollments':     ['isLoggedIn','isAuthenticated','apiCsrfGuard'],
diff --git a/config/routes.js b/config/routes.js
index 56592c6..b7d4416 100644
--- a/config/routes.js
+++ b/config/routes.js
@@ -82,6 +82,11 @@ module.exports.routes = {
   'POST /api/v1/agent-activity/summary':     {action: 'agent-activity/summary', csrf: false},
   'POST /api/v1/agent-activity/host':        {action: 'agent-activity/host', csrf: false},
 
+  // The Log Viewer page (GET /logviewer) reads the fog-node log files. It is a
+  // POST read that needs setting.read; it must precede POST /api/v1/:model/...,
+  // or it is read as :model=log.
+  'POST /api/v1/log/tail':                   {action: 'log/tail', csrf: false},
+
   // fog-agent enrollment admin API (host permissions; must precede the :model
   // routes, or GET /api/v1/agent/tokens is read as :model=agent/:id=tokens).
   'GET /api/v1/agent/enrollments':           {action: 'agent/enrollments', csrf: false},
@@ -157,6 +162,9 @@ module.exports.routes = {
   // The Agent Activity page (1.6 AgentActivityManagement), read-only; it needs agentactivity.view.
   'GET /agent-activity':                     {action: 'pages/list/agent-activity'},
 
+  // The Log Viewer page (1.6 LogViewerManagement), read-only; it needs setting.read.
+  'GET /logviewer':                          {action: 'pages/logviewer'},
+
   // Group Views
   'GET /groups':                             {action: 'pages/list/groups'},
   'GET /groups/create':                      {action: 'pages/create/groups'},
diff --git a/test/helpers/log-tail.test.js b/test/helpers/log-tail.test.js
new file mode 100644
index 0000000..0571e1d
--- /dev/null
+++ b/test/helpers/log-tail.test.js
@@ -0,0 +1,122 @@
+const assert = require('assert');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const {CHUNK, MAX_READ} = require('../../api/lib/log-viewer');
+
+// The Log Viewer tail helper (api/helpers/log/tail.js), called as the app
+// calls it: .with() with no .now(), as a sync helper (see menu.test.js).
+describe('Log tail helper::', () => {
+  let dir;
+  let n = 0;
+  before(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fog-node-tail-')); });
+  after(() => { fs.rmSync(dir, {recursive: true, force: true}); });
+
+  // Tails `content` (a string or a Buffer), written to a new file.
+  const tail = (content, lines) => {
+    const file = path.join(dir, `f${n++}.log`);
+    fs.writeFileSync(file, content);
+    const fd = fs.openSync(file, 'r');
+    try {
+      return sails.helpers.log.tail.with({fd, size: fs.fstatSync(fd).size, lines});
+    } finally {
+      fs.closeSync(fd);
+    }
+  };
+  const numbered = (count) => Array.from({length: count}, (_, i) => `L${i + 1}`);
+
+  it('returns the last N lines of a file bigger than one chunk, oldest first', () => {
+    const all = numbered(2000);
+    const got = tail(all.join('\n') + '\n', 10);
+    assert.deepStrictEqual(got.lines, all.slice(-10));
+  });
+
+  it('returns the whole file when it holds fewer lines than asked', () => {
+    assert.deepStrictEqual(tail('a\nb\nc\n', 10).lines, ['a', 'b', 'c']);
+  });
+
+  it('makes no empty last line from a trailing newline', () => {
+    assert.deepStrictEqual(tail('a\nb\n', 10).lines, ['a', 'b']);
+  });
+
+  it('counts a last line with no newline as a line', () => {
+    assert.deepStrictEqual(tail('a\nb\nc', 2).lines, ['b', 'c']);
+  });
+
+  it('keeps an empty line in the middle', () => {
+    assert.deepStrictEqual(tail('a\n\nb\n', 10).lines, ['a', '', 'b']);
+  });
+
+  it('returns no lines for an empty file', () => {
+    assert.deepStrictEqual(tail('', 10), {lines: [], bytesRead: 0});
+  });
+
+  it('returns a multibyte character whole when it sits across a 4096-byte boundary', () => {
+    // The file is "first\n", a long line K with one "é" (2 bytes), then "last\n".
+    // The first read chunk starts CHUNK bytes before the end of the file. `after`
+    // is the number of bytes of K after the "é": it moves the "é" so that the
+    // chunk edge falls before it, between its two bytes, and after it.
+    for (const after of [CHUNK - 8, CHUNK - 7, CHUNK - 6, CHUNK - 5, CHUNK - 4]) {
+      const long = 'k'.repeat(50) + 'é' + 'm'.repeat(after);
+      const got = tail(Buffer.from(`first\n${long}\nlast\n`), 2);
+      assert.deepStrictEqual(got.lines, [long, 'last'], `after=${after}`);
+      assert.ok(!got.lines.join('').includes('�'), `a replacement character, after=${after}`);
+    }
+  });
+
+  it('puts the chunk edge between the two bytes of the "é" in at least one case', () => {
+    // The guard of the test above: a layout in which the edge is inside "é".
+    const hits = [];
+    for (const after of [CHUNK - 8, CHUNK - 7, CHUNK - 6, CHUNK - 5, CHUNK - 4]) {
+      const content = Buffer.from(`first\n${'k'.repeat(50)}é${'m'.repeat(after)}\nlast\n`);
+      const edge = content.length - CHUNK;
+      const first = content.indexOf(0xC3);
+      if (edge === first + 1) hits.push(after);
+    }
+    assert.ok(hits.length > 0, 'no layout puts the chunk edge inside the character');
+  });
+
+  it('stops on a short read mid-file, and returns only the chunks read in full', () => {
+    // 3 chunks of whole lines. The second read (the middle chunk) comes back
+    // short, as if the file shrank: the partial chunk is not used, and the
+    // first line left is dropped as partial.
+    const all = numbered(1200);
+    const content = Buffer.from(all.join('\n') + '\n');
+    const file = path.join(dir, `f${n++}.log`);
+    fs.writeFileSync(file, content);
+    const fd = fs.openSync(file, 'r');
+    const real = fs.readSync;
+    let reads = 0;
+    // Read 2 gives 100 bytes, read 3 (the rest of that chunk) gives none.
+    fs.readSync = (...args) => {
+      reads++;
+      if (reads === 2) return real(args[0], args[1], args[2], 100, args[4]);
+      return reads === 3 ? 0 : real(...args);
+    };
+    try {
+      // lines 1000 needs far more than 2 chunks, so the short read is reached.
+      const got = sails.helpers.log.tail.with({fd, size: content.length, lines: 1000});
+      assert.strictEqual(got.bytesRead, CHUNK);
+      // Only the last chunk: its first line is dropped, and the rest is whole.
+      const tailText = content.subarray(content.length - CHUNK).toString('utf8').split('\n');
+      assert.deepStrictEqual(got.lines, tailText.slice(1, -1));
+    } finally {
+      fs.readSync = real;
+      fs.closeSync(fd);
+    }
+  });
+
+  it('stops at MAX_READ on one 6 MB line with no newline, and returns no lines', () => {
+    const got = tail(Buffer.alloc(6 * 1024 * 1024, 0x61), 100);
+    assert.strictEqual(got.bytesRead, MAX_READ);
+    assert.deepStrictEqual(got.lines, []);
+  });
+
+  it('drops the partial first line at MAX_READ and keeps the whole lines after it', () => {
+    // 5 MB of "a" then 3 lines: the read ends inside the "a" line.
+    const content = Buffer.concat([Buffer.alloc(5 * 1024 * 1024, 0x61), Buffer.from('\nx\ny\nz\n')]);
+    const got = tail(content, 100);
+    assert.strictEqual(got.bytesRead, MAX_READ);
+    assert.deepStrictEqual(got.lines, ['x', 'y', 'z']);
+  });
+});
diff --git a/test/integration/log-viewer.test.js b/test/integration/log-viewer.test.js
new file mode 100644
index 0000000..0ee6088
--- /dev/null
+++ b/test/integration/log-viewer.test.js
@@ -0,0 +1,236 @@
+const assert = require('assert');
+const crypto = require('crypto');
+const fs = require('fs');
+const path = require('path');
+const supertest = require('supertest');
+const auditWait = require('../support/audit-wait');
+const {waitFor} = auditWait;
+
+// The Log Viewer (issue #209): GET /logviewer and POST /api/v1/log/tail,
+// behind setting.read. The fixture files go in a sub folder of
+// sails.config.custom.logDir (the mocha lift's temporary folder), which this
+// file points custom.logDir at for its run: the running logger keeps its own
+// fog-node.log open in the lift's folder, and a fixture must not meet it.
+// The seam writes after the response, so a test that expects a row polls for
+// it. A test that expects NO row makes its request, then a sentinel request
+// that does write a row, waits for the sentinel row, and only then asserts
+// the absence (test/integration/audit.test.js).
+describe('Log Viewer::', function () {
+  this.timeout(30000);
+
+  const app = () => sails.hooks.http.app;
+  const HTML = ['Accept', 'text/html'];
+  const AJAX = ['X-Requested-With', 'XMLHttpRequest'];
+  const RUN = crypto.randomBytes(3).toString('hex');
+  const PREFIX = 'mocha-lv' + RUN;
+  const PASSWORD = 'mocha-lv-pw';
+  const TAIL = '/api/v1/log/tail';
+  const MAIN = 'fog-node.log';
+  let seq = 0;
+  let realDir;
+  let dir;
+
+  async function mkUser(label, {isAdmin = false, permissions = {}} = {}) {
+    const name = `${PREFIX}-${label}`;
+    const role = await Role.create({name, isAdmin, permissions}).fetch();
+    await User.create({username: name, password: PASSWORD, email: `${name}@example.com`, roles: [role.id]});
+    return name;
+  }
+
+  // Signs in as a browser does: a CSRF token for the login form, then the form POST.
+  async function signIn(username) {
+    const agent = supertest.agent(app());
+    const {body} = await agent.get('/csrfToken').expect(200);
+    await agent.post('/login').type('form').set(...HTML)
+      .send({username, password: PASSWORD, _csrf: body._csrf})
+      .expect(302).expect('Location', '/');
+    agent.username = username;
+    return agent;
+  }
+
+  const sentinel = (agent, start) => auditWait.sentinel((url) => agent.get(url).set(...AJAX), `${PREFIX}-sentinel-${seq++}`, start);
+  const post = (agent, body) => agent.post(TAIL).set(...AJAX).send(body);
+  const numbered = (count) => Array.from({length: count}, (_, i) => `L${i + 1}`);
+  const put = (name, text) => fs.writeFileSync(path.join(dir, name), text);
+
+  async function cleanup() {
+    await AuditLog.destroy({createdBy: {startsWith: PREFIX}});
+    await User.destroy({username: {startsWith: PREFIX}});
+    await Role.destroy({name: {startsWith: PREFIX}});
+  }
+
+  let admin;
+  let limited;
+  before(async () => {
+    await cleanup();
+    realDir = sails.config.custom.logDir;
+    dir = path.join(realDir, `viewer-${RUN}`);
+    fs.mkdirSync(dir, {recursive: true});
+    sails.config.custom.logDir = dir;
+    admin = await signIn(await mkUser('admin', {isAdmin: true}));
+    limited = await signIn(await mkUser('limited', {permissions: {stock: {host: {read: true}}}}));
+  });
+  after(async () => {
+    sails.config.custom.logDir = realDir;
+    fs.rmSync(dir, {recursive: true, force: true});
+    await cleanup();
+  });
+  beforeEach(() => {
+    for (const name of fs.readdirSync(dir)) fs.rmSync(path.join(dir, name), {recursive: true, force: true});
+  });
+
+  describe('the page', () => {
+    it('answers 200 for an admin, and the File select lists fog-node.log and the old files', async () => {
+      put(MAIN, 'x\n');
+      put(`${MAIN}.2`, 'y\n');
+      const res = await admin.get('/logviewer').set(...HTML).expect(200);
+      assert.ok(res.text.includes('Log Viewer | FOG Project'), 'no Log Viewer tab title');
+      const select = res.text.match(//)[0];
+      assert.deepStrictEqual([...lines.matchAll(/