From d188cad580f6608f3a0eb3838e40ae7e645c4c57 Mon Sep 17 00:00:00 2001 From: Tom Elliott Date: Tue, 17 Nov 2026 06:33:27 -0600 Subject: [PATCH] feat(audit): add the FOG 1.6 Audit Log page and the audit.view permission Add the read-only Audit Log page (GET /audit) over the AuditLog rows that the audit trail core writes, as FOG 1.6 AuditManagement shows them: the When/Who/Action/Permission/Outcome/Subject/From grid, the outcome badges, and the "Audit entry" detail modal. A "Logging" sidebar group holds it. - New permission stock.audit.view gates the page and POST /api/v1/audit/datatable. The key is `audit`, not `auditlog`, so the generic :model routes stay closed on the trail (ADR 0003 updated). - The datatable reads at most 500 rows per request and the length menu has no "All": the trail grows for the life of the install (1.6 bounds it in the query). Search is a case-insensitive substring match in the query; order is createdAt DESC, id DESC. - An allowed datatable read writes no audit row (READ_ACTIONS). - New shared helper datatables/parse-request parses the DataTables body without throwing. A JSON body with a toString object or a 1e20 start made both this endpoint and the pending-hosts datatable answer 500; the pending hosts endpoint now uses the helper too, and both get a regression test. - waitFor and sentinel move to test/support/audit-wait.js. Closes #200 Co-Authored-By: Claude Opus 5.5 --- api/controllers/audit/datatable.js | 57 ++++++ api/controllers/host/pending-datatable.js | 11 +- api/controllers/pages/list/audit.js | 54 +++++ api/helpers/datatables/parse-request.js | 55 ++++++ api/hooks/audit/index.js | 3 + config/globals.js | 8 + config/permissions.js | 6 + config/policies.js | 3 + config/routes.js | 7 + docs/adr/0003-audit-trail.md | 6 +- test/helpers/datatables-parse-request.test.js | 60 ++++++ test/helpers/menu.test.js | 3 +- test/helpers/permissions-resolve.test.js | 9 + test/integration/audit-log-page.test.js | 186 ++++++++++++++++++ test/integration/audit.test.js | 23 +-- test/integration/pending-hosts.test.js | 9 + test/support/audit-wait.js | 31 +++ tools/smoke/checks/audit-log.js | 157 +++++++++++++++ tools/smoke/checks/ui16-03-shell.js | 1 + tools/smoke/checks/ui16-04-sidebar.js | 12 +- tools/smoke/checks/ui16-06-tables.js | 6 +- tools/smoke/ui.js | 1 + views/pages/partials/list/audit.js | 104 ++++++++++ 23 files changed, 783 insertions(+), 29 deletions(-) create mode 100644 api/controllers/audit/datatable.js create mode 100644 api/controllers/pages/list/audit.js create mode 100644 api/helpers/datatables/parse-request.js create mode 100644 test/helpers/datatables-parse-request.test.js create mode 100644 test/integration/audit-log-page.test.js create mode 100644 test/support/audit-wait.js create mode 100644 tools/smoke/checks/audit-log.js create mode 100644 views/pages/partials/list/audit.js diff --git a/api/controllers/audit/datatable.js b/api/controllers/audit/datatable.js new file mode 100644 index 0000000..66d026e --- /dev/null +++ b/api/controllers/audit/datatable.js @@ -0,0 +1,57 @@ +/** + * POST /api/v1/audit/datatable + * + * The rows of the Audit Log page (GET /audit), as DataTables server-side rows + * {draw, recordsTotal, recordsFiltered, data}. Needs audit.view. + * + * The page size is bounded in the query, as 1.6 AuditManagement.php does: the + * trail grows for the life of the install, so no request reads it whole. A + * `length` that is missing, -1, not a number, or above MAX_ROWS reads MAX_ROWS + * rows. + * + * Search: a case-insensitive substring match on createdBy, type, permission, + * outcome, subjectType, subjectLabel and ip. It runs in the database query. + * Without makeLikeModifierCaseInsensitive, sails-mongo matches case-sensitively. + * + * Order: createdAt DESC, then id DESC as a tie-break, so paging never skips or + * repeats rows that share a millisecond. The client sets ordering: false. + */ +const MAX_ROWS = 500; +const SEARCH_FIELDS = ['createdBy', 'type', 'permission', 'outcome', 'subjectType', 'subjectLabel', 'ip']; +const ROW_FIELDS = [ + 'id', 'createdAt', 'createdBy', 'ip', 'authSource', 'type', 'subjectType', 'subjectId', + 'subjectLabel', 'permission', 'outcome', 'correlationId', 'affectedCount', 'text' +]; + +module.exports = { + friendlyName: 'Audit log datatable', + description: 'The audit trail, as DataTables server-side rows.', + fn: async function () { + const req = this.req; + const res = this.res; + if (!sails.helpers.audit.can(req, 'audit.view')) { + return res.forbidden(); + } + // Safe for any JSON value (api/helpers/datatables/parse-request.js). + const parsed = sails.helpers.datatables.parseRequest.with({body: req.body}); + const start = parsed.start; + const text = parsed.search; + // A length that is missing, -1, not a number, or above MAX_ROWS reads MAX_ROWS. + const length = parsed.length > 0 && parsed.length <= MAX_ROWS ? parsed.length : MAX_ROWS; + + const where = text === '' ? {} : {or: SEARCH_FIELDS.map((field) => ({[field]: {contains: text}}))}; + const recordsTotal = await sails.models.auditlog.count(); + const recordsFiltered = text === '' ? recordsTotal : await sails.models.auditlog.count(where).meta({makeLikeModifierCaseInsensitive: true}); + const rows = await sails.models.auditlog.find(where) + .meta({makeLikeModifierCaseInsensitive: true}) + .sort([{createdAt: 'DESC'}, {id: 'DESC'}]) + .skip(start) + .limit(length); + return res.json({ + draw: parsed.draw, + recordsTotal, + recordsFiltered, + data: rows.map((row) => _.pick(row, ROW_FIELDS)) + }); + } +}; diff --git a/api/controllers/host/pending-datatable.js b/api/controllers/host/pending-datatable.js index 0b59a97..035bab4 100644 --- a/api/controllers/host/pending-datatable.js +++ b/api/controllers/host/pending-datatable.js @@ -19,10 +19,11 @@ module.exports = { if (!sails.helpers.audit.can(req, 'host.read')) { return res.forbidden(); } - const body = req.body || {}; - const start = Math.max(0, parseInt(body.start, 10) || 0); - const length = parseInt(body.length, 10); - const text = String(_.get(body, 'search.value', '')).trim().toLowerCase(); + // Safe for any JSON value (api/helpers/datatables/parse-request.js). + const parsed = sails.helpers.datatables.parseRequest.with({body: req.body}); + const start = parsed.start; + const length = parsed.length; + const text = parsed.search.toLowerCase(); const macText = text.replace(/[:\-. ]/g, ''); const pending = await sails.models.host.find({pending: true}).sort('name ASC'); @@ -41,7 +42,7 @@ module.exports = { return /^[0-9a-f]{12}$/i.test(first) ? first.toLowerCase().match(/../g).join(':') : first; }; return res.json({ - draw: parseInt(body.draw, 10) || 0, + draw: parsed.draw, recordsTotal: pending.length, recordsFiltered: found.length, data: page.map((host) => ({id: host.id, name: host.name, mac: show(host), description: host.description || ''})) diff --git a/api/controllers/pages/list/audit.js b/api/controllers/pages/list/audit.js new file mode 100644 index 0000000..1217e75 --- /dev/null +++ b/api/controllers/pages/list/audit.js @@ -0,0 +1,54 @@ +const path = require('path'); +const partialPath = path.join(__dirname,'..','..','..','..','views','pages','partials','list'); +// GET /audit: the audit trail, read only (1.6 AuditManagement, issue #200). The +// rows come from POST /api/v1/audit/datatable. Needs audit.view. +// +// It does not call sails.helpers.listLocals: that helper needs a page-title +// entry, and the audit trail is not a CRUD model. So this action sets the +// locals that views/pages/list.ejs and the content header read. It sets no +// editBase, so no row links to an edit page. +module.exports = { + friendlyName: 'Audit log', + description: 'Audit Log page.', + inputs: { + }, + exits: { + error: { + responseType: 'serverError' + }, + forbidden: { + responseType: 'forbidden' + }, + success: { + viewTemplatePath: 'pages/list', + description: 'Successful' + } + }, + fn: async function () { + if (!sails.helpers.audit.can(this.req, 'audit.view')) { + throw 'forbidden'; + } + return { + // The columns of 1.6 AuditManagement.php:103-120, in order. + theads: [ + 'When', + 'Who', + 'Action', + 'Permission', + 'Outcome', + 'Subject', + 'From' + ], + section: 'Audit Log', + page: 'Audit Log', + singular: 'entry', + plural: 'entries', + model: 'audit', + // No row selection and no Delete selected, as 1.6 ($selectable = false). + selectable: false, + deleteButton: false, + partialname: path.join(partialPath, 'audit.js'), + ...await sails.helpers.tableSettings() + }; + } +}; diff --git a/api/helpers/datatables/parse-request.js b/api/helpers/datatables/parse-request.js new file mode 100644 index 0000000..8877638 --- /dev/null +++ b/api/helpers/datatables/parse-request.js @@ -0,0 +1,55 @@ +/** + * The DataTables server-side request fields that a datatable action reads, made + * safe for a JSON body. A JSON body can hold any value, so String() or + * parseInt() on a field can throw (an object with a `toString` key), and a + * start that is not a safe integer makes Waterline refuse the skip. + * + * Input: body, the request body (may be undefined). + * Output: {draw, start, length, search} + * draw, start a whole number of at least 0 from a string or a number, and + * a safe integer. Anything else is 0. + * length the whole number, or NaN when the field is not a string or a + * number, or is not a safe integer. Each caller keeps its own + * rule for -1, 0 and NaN. + * search body.search.value as trimmed text, when it is a string or a + * finite number. Anything else is ''. + * + * Usage: const {draw, start, length, search} = sails.helpers.datatables.parseRequest.with({body: req.body}); + * It returns the object itself, with no .now(): see api/helpers/permissions/resolve.js. + */ +// A whole number from a string or a number, or NaN. +function whole(value) { + let n = NaN; + if (typeof value === 'number') { n = Math.trunc(value); } + if (typeof value === 'string') { n = parseInt(value, 10); } + return Number.isSafeInteger(n) ? n : NaN; +} + +module.exports = { + friendlyName: 'Parse a DataTables request', + description: 'The draw, start, length and search of a server-side request body, safe for any JSON value.', + sync: true, + inputs: { + body: {type: 'ref', description: 'The request body.'} + }, + exits: { + success: {outputType: 'ref', description: '{draw, start, length, search}'} + }, + // A sync machine must answer through exits.success. + fn: function ({body}, exits) { + // An array body has its own `length`, so it counts as no body. + const source = body !== null && typeof body === 'object' && !Array.isArray(body) ? body : {}; + const nonNegative = (value) => { + const n = whole(value); + return n >= 0 ? n : 0; + }; + const found = _.get(source, 'search.value'); + const usable = typeof found === 'string' || (typeof found === 'number' && Number.isFinite(found)); + return exits.success({ + draw: nonNegative(source.draw), + start: nonNegative(source.start), + length: whole(source.length), + search: usable ? String(found).trim() : '' + }); + } +}; diff --git a/api/hooks/audit/index.js b/api/hooks/audit/index.js index 47d3af2..57d6d44 100644 --- a/api/hooks/audit/index.js +++ b/api/hooks/audit/index.js @@ -39,6 +39,9 @@ const READ_ACTIONS = [ 'task-history', // The pending hosts DataTable (a POST read, like general/datatable). 'host/pending-datatable', + // The Audit Log DataTable. Without it, every page load and scroll of the + // audit page would write an AuditLog row. + 'audit/datatable', // Signs a JWT for the user and changes no record. 'auth/token' ]; diff --git a/config/globals.js b/config/globals.js index 2603f2f..9a804ff 100644 --- a/config/globals.js +++ b/config/globals.js @@ -147,6 +147,14 @@ module.exports.globals = { subLinks: [ {link: '/pxemenus/create', text: 'Create New iPXE Menu'} ] + }, + // The 1.6 "Logging" group (FOGPage.php:899-902). It sits after the planned + // FOG Configuration entry (150). + { + order: 170, text: 'Logging', icon: 'fas fa-scroll', + children: [ + {text: 'Audit Log', link: '/audit', icon: 'fas fa-clipboard-list'} + ] } ], authenticationMechanisms: [ diff --git a/config/permissions.js b/config/permissions.js index 76eed10..a71f359 100644 --- a/config/permissions.js +++ b/config/permissions.js @@ -1,5 +1,11 @@ module.exports.permissions = { stock: { + // The Audit Log page (GET /audit, POST /api/v1/audit/datatable). The key is + // audit, not auditlog: a stock.auditlog entry would open the generic + // /api/v1/:model routes on the AuditLog model (ADR 0003). + audit: { + view: false + }, host: { create: false, destroy: false, diff --git a/config/policies.js b/config/policies.js index 034f8f2..90193f8 100644 --- a/config/policies.js +++ b/config/policies.js @@ -36,6 +36,9 @@ module.exports.policies = { 'host/pending-approve': ['isLoggedIn','isAuthenticated','apiCsrfGuard'], 'host/pending-delete': ['isLoggedIn','isAuthenticated','apiCsrfGuard'], + // The Audit Log rows (the action checks audit.view itself). It only reads. + 'audit/datatable': ['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 692213c..7059191 100644 --- a/config/routes.js +++ b/config/routes.js @@ -68,6 +68,10 @@ module.exports.routes = { 'POST /api/v1/host/pending/approve': {action: 'host/pending-approve', csrf: false}, 'DELETE /api/v1/host/pending': {action: 'host/pending-delete', csrf: false}, + // The Audit Log page rows (GET /audit). A POST read that needs audit.view; it + // must precede POST /api/v1/:model/datatable, or it is read as :model=audit. + 'POST /api/v1/audit/datatable': {action: 'audit/datatable', 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}, @@ -128,6 +132,9 @@ module.exports.routes = { 'GET /hosts/pendingAgents': {action: 'pages/list/pending-agents'}, 'GET /hosts/agentTokens': {action: 'pages/list/agent-tokens'}, + // The Audit Log page (1.6 AuditManagement), read-only; it needs audit.view. + 'GET /audit': {action: 'pages/list/audit'}, + // Group Views 'GET /groups': {action: 'pages/list/groups'}, 'GET /groups/create': {action: 'pages/create/groups'}, diff --git a/docs/adr/0003-audit-trail.md b/docs/adr/0003-audit-trail.md index ef1fa14..d7a9ea1 100644 --- a/docs/adr/0003-audit-trail.md +++ b/docs/adr/0003-audit-trail.md @@ -56,6 +56,10 @@ The events: A failed sign-in stores the attempted name and no reason, to avoid user enumeration (1.6 stores none either). +- `audit.view` is the key `stock.audit.view`, not `auditlog`, so the generic + `:model` routes stay closed. It gates the Audit Log page (`GET /audit`) and + `POST /api/v1/audit/datatable`, which reads at most 500 rows per request. + ## Differences from 1.6 - The correlation id is set per request. A middleware in `config/http.js` puts @@ -90,7 +94,7 @@ enumeration (1.6 stores none either). - Change rows with redaction (1.6 decisions 5 to 7): `AuditChange`, the before and after values, and the redaction of a credential field. -- The `audit.view` and `audit.manage` permissions, and the Audit Log page. +- The `audit.manage` permission, with retention. - Retention, and the rule that shrinking the trail writes a row first (1.6 decision 10). - The machine paths other than the agent enrollment and renew routes. diff --git a/test/helpers/datatables-parse-request.test.js b/test/helpers/datatables-parse-request.test.js new file mode 100644 index 0000000..42abf5f --- /dev/null +++ b/test/helpers/datatables-parse-request.test.js @@ -0,0 +1,60 @@ +const assert = require('assert'); + +// The datatables/parse-request helper: the draw, start, length and search of a +// server-side request, safe for any JSON value. A JSON body can make String() +// or parseInt() throw (an object with a toString key), and a start of 1e20 is +// not a safe integer, so Waterline refuses it as a skip. +describe('datatables parse-request helper::', () => { + const parse = (body) => sails.helpers.datatables.parseRequest.with({body}); + const OBJ = {toString: 1}; + + it('reads draw, start, length and search from a form-style body', () => { + assert.deepStrictEqual(parse({draw: '3', start: '20', length: '10', search: {value: ' Lab '}}), + {draw: 3, start: 20, length: 10, search: 'Lab'}); + assert.deepStrictEqual(parse({draw: 3, start: 20, length: -1, search: {value: 7}}), + {draw: 3, start: 20, length: -1, search: '7'}); + }); + + it('turns a missing or unusable body into the defaults', () => { + [undefined, null, 'text', 5, []].forEach((body) => { + const got = parse(body); + assert.deepStrictEqual([got.draw, got.start, got.search], [0, 0, ''], JSON.stringify(body)); + assert.ok(Number.isNaN(got.length), JSON.stringify(body)); + }); + }); + + // [value, expected] for draw and start. + const WHOLE = [ + ['5', 5], [5, 5], [5.9, 5], ['5abc', 5], [0, 0], ['0', 0], [-1, 0], ['-3', 0], ['x', 0], ['', 0], + ['99999999999999999999', 0], [1e20, 0], [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + [NaN, 0], [Infinity, 0], [null, 0], [true, 0], [OBJ, 0], [[5], 0], [undefined, 0] + ]; + ['draw', 'start'].forEach((field) => { + it(`reads ${field} as a safe integer of at least 0, else 0`, () => { + WHOLE.forEach(([value, want]) => { + assert.strictEqual(parse({[field]: value})[field], want, `${field} ${String(typeof value === 'object' ? JSON.stringify(value) : value)}`); + }); + }); + }); + + it('reads length as a safe integer, else NaN, and keeps -1 and 0', () => { + [['10', 10], [10, 10], [-1, -1], ['-1', -1], [0, 0], [1000, 1000]].forEach(([value, want]) => { + assert.strictEqual(parse({length: value}).length, want, String(value)); + }); + ['x', '', '99999999999999999999', 1e20, NaN, Infinity, null, true, OBJ, [5], undefined].forEach((value) => { + assert.ok(Number.isNaN(parse({length: value}).length), typeof value === 'object' ? JSON.stringify(value) : String(value)); + }); + }); + + it('reads search only from a string or a finite number, else an empty string', () => { + [['lab', 'lab'], [' lab ', 'lab'], [12, '12'], [0, '0'], ['', '']].forEach(([value, want]) => { + assert.strictEqual(parse({search: {value}}).search, want, String(value)); + }); + [OBJ, {x: 1}, [1], null, true, NaN, Infinity, undefined].forEach((value) => { + assert.strictEqual(parse({search: {value}}).search, '', typeof value === 'object' ? JSON.stringify(value) : String(value)); + }); + assert.strictEqual(parse({search: 'lab'}).search, ''); + assert.strictEqual(parse({search: null}).search, ''); + assert.strictEqual(parse({search: OBJ}).search, ''); + }); +}); diff --git a/test/helpers/menu.test.js b/test/helpers/menu.test.js index e359670..101362c 100644 --- a/test/helpers/menu.test.js +++ b/test/helpers/menu.test.js @@ -77,7 +77,8 @@ describe('Sidebar menu helpers::', () => { ['Tasks', 'fas fa-bars-progress'], ['Workflows', 'fas fa-diagram-project'], ['User Administration', 'fas fa-shield'], - ['iPXE Menu', 'fas fa-list-ol'] + ['iPXE Menu', 'fas fa-list-ol'], + ['Logging', 'fas fa-scroll'] ]); assert.deepStrictEqual(menu.filter((n) => n.pluginOption), []); const admin = menu.find((n) => n.text === 'User Administration'); diff --git a/test/helpers/permissions-resolve.test.js b/test/helpers/permissions-resolve.test.js index 408cd35..6b1bf51 100644 --- a/test/helpers/permissions-resolve.test.js +++ b/test/helpers/permissions-resolve.test.js @@ -51,6 +51,15 @@ describe('Permissions resolve helper::', () => { assert.ok(leaves(result).every(([, value]) => value === false)); }); + // stock.audit.view opens the Audit Log page (issue #200). The key is audit, + // not auditlog, so the generic /api/v1/:model routes still refuse the model. + it('resolves stock.audit.view true for an admin role and false for a role with no grant', () => { + assert.strictEqual(resolve([{isAdmin: true, permissions: {}}]).stock.audit.view, true); + assert.strictEqual(resolve([B]).stock.audit.view, false); + assert.strictEqual(resolve([{permissions: {stock: {audit: {view: true}}}}]).stock.audit.view, true); + assert.strictEqual(sails.config.permissions.stock.audit.view, false); + }); + it('returns a new tree, so a change to it leaves the defaults alone', () => { const result = resolve([]); assert.notStrictEqual(result.stock, sails.config.permissions.stock); diff --git a/test/integration/audit-log-page.test.js b/test/integration/audit-log-page.test.js new file mode 100644 index 0000000..c39441d --- /dev/null +++ b/test/integration/audit-log-page.test.js @@ -0,0 +1,186 @@ +const assert = require('assert'); +const crypto = require('crypto'); +const supertest = require('supertest'); +const support = require('../support/pki'); +const auditWait = require('../support/audit-wait'); +const {waitFor} = auditWait; + +// The Audit Log page (issue #200): GET /audit and POST /api/v1/audit/datatable, +// behind the audit.view permission. 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('Audit Log page::', function () { + this.timeout(120000); + + support.useFixture(); + 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-alp' + RUN; + const PASSWORD = 'mocha-alp-pw'; + const URL = '/api/v1/audit/datatable'; + // A time far ahead of every real row, so the rows of a test sort first. + const FUTURE = 4102444800000; + let seq = 0; + + 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', '/'); + return agent; + } + + // A denied GET on a model that no one can read (test/support/audit-wait.js). + const sentinel = (agent, start) => auditWait.sentinel((url) => agent.get(url).set(...AJAX), `${PREFIX}-sentinel-${seq++}`, start); + + const table = (agent, body) => agent.post(URL).set(...AJAX).send(body); + // The rows that a test created: its own createdBy values start with PREFIX. + const mine = (rows) => rows.filter((r) => r.createdBy.startsWith(PREFIX + '-row')); + + let admin; + let limited; + let granted; + let adminNames; + + async function cleanup() { + await AuditLog.destroy({createdBy: {startsWith: PREFIX}}); + await User.destroy({username: {startsWith: PREFIX}}); + await Role.destroy({name: {startsWith: PREFIX}}); + } + + before(async () => { + await cleanup(); + adminNames = await mkUser('admin', {isAdmin: true}); + const limitedName = await mkUser('limited', {permissions: {stock: {host: {read: true}}}}); + const grantedName = await mkUser('granted', {permissions: {stock: {audit: {view: true}}}}); + admin = await signIn(adminNames); + limited = await signIn(limitedName); + granted = await signIn(grantedName); + limited.username = limitedName; + }); + after(cleanup); + + describe('the page', () => { + it('answers 200 for an admin, and 403 for a limited user without audit.view', async () => { + await admin.get('/audit').set(...HTML).expect(200); + await limited.get('/audit').set(...HTML).expect(403); + }); + + it('answers 200 for a limited role that holds stock.audit.view', async () => { + await granted.get('/audit').set(...HTML).expect(200); + }); + + it('still refuses the generic routes for the audit trail', async () => { + await admin.get('/api/v1/auditlog').set(...AJAX).expect(403); + await admin.get('/api/v1/audit').set(...AJAX).expect(403); + }); + }); + + describe('the rows', () => { + it('answers 403 without audit.view, and writes a denied row for audit.view', async () => { + const start = Date.now(); + await table(limited, {draw: 1, start: 0, length: 10}).expect(403); + const [row] = await waitFor({createdBy: limited.username, permission: 'audit.view'}, start); + assert.strictEqual(row.outcome, 'denied'); + }); + + it('answers a limited role that holds audit.view', async () => { + const res = await table(granted, {draw: 3, start: 0, length: 5}).expect(200); + assert.strictEqual(res.body.draw, 3); + }); + + it('returns the shape, newest first, with every row field', async () => { + const res = await table(admin, {draw: 7, start: 0, length: 25}).expect(200); + assert.strictEqual(res.body.draw, 7); + assert.ok(res.body.recordsTotal >= res.body.recordsFiltered); + assert.ok(res.body.data.length > 0, 'the sign-ins wrote rows'); + assert.deepStrictEqual(Object.keys(res.body.data[0]).sort(), [ + 'affectedCount', 'authSource', 'correlationId', 'createdAt', 'createdBy', 'id', 'ip', + 'outcome', 'permission', 'subjectId', 'subjectLabel', 'subjectType', 'text', 'type' + ]); + const times = res.body.data.map((r) => r.createdAt); + assert.deepStrictEqual(times, times.slice().sort((a, b) => b - a)); + }); + + it('pages rows that share one createdAt without a skip or a repeat', async () => { + const made = await AuditLog.createEach([0, 1, 2, 3, 4].map((i) => ({ + createdAt: FUTURE, createdBy: `${PREFIX}-row-tie-${i}`, type: 'test.tie', outcome: 'allowed' + }))).fetch(); + const want = made.map((r) => r.id).sort().reverse(); + const got = []; + for (const start of [0, 2, 4]) { + const res = await table(admin, {draw: 1, start, length: 2}).expect(200); + res.body.data.forEach((r) => got.push(r.id)); + } + // The third page holds the last tied row, then the next older row. + assert.deepStrictEqual(got.slice(0, want.length), want); + assert.strictEqual(new Set(got).size, got.length, 'a row repeats'); + }); + + it('reads at most 500 rows, and recordsTotal counts every row', async () => { + await AuditLog.createEach(Array.from({length: 501}, (_unused, i) => ({ + createdAt: FUTURE - 1, createdBy: `${PREFIX}-row-bulk-${i}`, type: 'test.bulk', outcome: 'allowed' + }))); + for (const length of [-1, 1000, undefined, 'x']) { + const res = await table(admin, {draw: 1, start: 0, length}).expect(200); + assert.strictEqual(res.body.data.length, 500, `length ${length}`); + assert.ok(res.body.recordsTotal >= 501, `recordsTotal ${res.body.recordsTotal}`); + } + const res = await table(admin, {draw: 1, start: 0, length: 10}).expect(200); + assert.strictEqual(res.body.data.length, 10); + }); + + it('answers 200 when search is sent as an object', async () => { + await table(admin, {draw: 1, start: 0, length: 5, search: {value: {x: 1}}}).expect(200); + await admin.post(URL).set(...AJAX).type('form').send('draw=1&start=0&length=5&search[value][x]=1').expect(200); + }); + + // A JSON body can hold any value: String() or parseInt() on an object with + // a toString key throws, and a start of 1e20 is not a safe integer. + it('answers 200 for a JSON body with a toString object and a start of 1e20', async () => { + await table(admin, {draw: 1, start: 0, length: 5, search: {value: {toString: 1}}}).expect(200); + await table(admin, {draw: {toString: 1}, start: {toString: 1}, length: {toString: 1}}).expect(200); + await table(admin, {draw: 1, start: '99999999999999999999', length: 5}).expect(200); + }); + + it('searches case-insensitively, in the query, and counts only the matches', async () => { + const res = await table(admin, {draw: 1, start: 0, length: 500, search: {value: 'LOGIN'}}).expect(200); + assert.ok(res.body.recordsFiltered > 0, 'the sign-ins wrote auth.login rows'); + assert.ok(res.body.recordsFiltered < res.body.recordsTotal, 'a filter that keeps every row is no filter'); + assert.ok(res.body.data.some((r) => r.type === 'auth.login')); + res.body.data.forEach((r) => { + const fields = [r.createdBy, r.type, r.permission, r.outcome, r.subjectType, r.subjectLabel, r.ip].join('\n'); + assert.ok(/login/i.test(fields), JSON.stringify(r)); + }); + const none = await table(admin, {draw: 1, start: 0, length: 5, search: {value: `${PREFIX}-no-such-text`}}).expect(200); + assert.strictEqual(none.body.recordsFiltered, 0); + assert.deepStrictEqual(none.body.data, []); + // The mixed-case user name of a row is found by its lowercase form. + await AuditLog.create({createdBy: `${PREFIX}-row-CaSe`, type: 'test.case', outcome: 'allowed'}); + const hit = await table(admin, {draw: 1, start: 0, length: 5, search: {value: `${PREFIX}-ROW-case`.toLowerCase()}}).expect(200); + assert.strictEqual(hit.body.recordsFiltered, 1); + assert.strictEqual(mine(hit.body.data).length, 1); + }); + + it('writes no row for an allowed call', async () => { + const start = Date.now(); + await table(admin, {draw: 1, start: 0, length: 5}).expect(200); + await sentinel(admin, start); + const rows = await AuditLog.find({createdBy: adminNames, createdAt: {'>=': start}}); + assert.deepStrictEqual(rows.filter((r) => r.permission === 'audit.view' || r.subjectLabel.includes('audit/datatable')), []); + assert.deepStrictEqual(rows.filter((r) => /audit\/datatable/.test(r.text)), []); + }); + }); +}); diff --git a/test/integration/audit.test.js b/test/integration/audit.test.js index c8d3da8..150cdc2 100644 --- a/test/integration/audit.test.js +++ b/test/integration/audit.test.js @@ -5,6 +5,8 @@ const path = require('path'); const supertest = require('supertest'); const agentCsr = require('../support/agent-csr'); const support = require('../support/pki'); +const auditWait = require('../support/audit-wait'); +const {waitFor} = auditWait; // The audit trail core (docs/adr/0003-audit-trail.md): the AuditLog model, the // record helper, the request seam (api/hooks/audit), the sign-in events and the @@ -31,21 +33,10 @@ describe('Audit trail::', function () { let seq = 0; const uniq = () => PREFIX + '-' + (seq++); const short = () => SHORT + (seq++); - const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const mac = () => '02:' + crypto.randomBytes(5).toString('hex').match(/../g).join(':'); const bare = (m) => m.replace(/[:-]/g, '').toLowerCase(); const LOOPBACK = ['127.0.0.1', '::ffff:127.0.0.1', '::1']; - // Poll every 25 ms, up to 2 s, for at least `count` rows at or after `start`. - async function waitFor(where, start, count = 1) { - const deadline = Date.now() + 2000; - for (;;) { - const found = await AuditLog.find(Object.assign({}, where, {createdAt: {'>=': start}})).sort('createdAt ASC'); - if (found.length >= count) { return found; } - if (Date.now() > deadline) { assert.fail(`no audit row for ${JSON.stringify(where)} within 2 s`); } - await sleep(25); - } - } const rowsOf = (where, start) => AuditLog.find(Object.assign({}, where, {createdAt: {'>=': start}})).sort('createdAt ASC'); // Users. `permissions` is the role's {stock: {...}}; isAdmin gives all. @@ -94,14 +85,8 @@ describe('Audit trail::', function () { }; return {get: verb('get'), post: verb('post'), put: verb('put'), del: verb('delete')}; }; - // A denied GET by the actor on a model that no one can read: a row for sure. - // Returns the row once it is stored. It proves the earlier writes landed. - async function sentinel(actor, start) { - const model = `${PREFIX}-sentinel-${seq++}`; - await as(actor).get(`/api/v1/${model}`).expect(403); - const [row] = await waitFor({permission: `${model}.read`}, start); - return row; - } + // A denied GET by the actor on a model that no one can read (test/support/audit-wait.js). + const sentinel = (actor, start) => auditWait.sentinel(as(actor).get, `${PREFIX}-sentinel-${seq++}`, start); let admin; let adminSession; diff --git a/test/integration/pending-hosts.test.js b/test/integration/pending-hosts.test.js index eddb294..8f99651 100644 --- a/test/integration/pending-hosts.test.js +++ b/test/integration/pending-hosts.test.js @@ -125,6 +125,15 @@ describe('Pending hosts::', function () { assert.strictEqual(res.body.recordsFiltered, 2); }); + // A JSON body can hold any value: String() or parseInt() on an object with + // a toString key throws, and a start of 1e20 is not a safe integer. + it('answers 200 for a JSON body with a toString object and a start of 1e20', async () => { + const post = (body) => admin.agent.post('/api/v1/host/pending/datatable').set(...AJAX).send(body); + await post({draw: 1, start: 0, length: 5, search: {value: {toString: 1}}}).expect(200); + await post({draw: {toString: 1}, start: {toString: 1}, length: {toString: 1}}).expect(200); + await post({draw: 1, start: '99999999999999999999', length: 5}).expect(200); + }); + it('answers 403 without host.read', async () => { const none = await limited('rows-none', {update: true, destroy: true}); await rows(none).expect(403); diff --git a/test/support/audit-wait.js b/test/support/audit-wait.js new file mode 100644 index 0000000..dd2fccb --- /dev/null +++ b/test/support/audit-wait.js @@ -0,0 +1,31 @@ +const assert = require('assert'); + +// Helpers for a test that expects an audit row. The request seam +// (api/hooks/audit) writes after the response finishes, so a test polls for the +// row. 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). +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// Poll every 25 ms, up to 2 s, for at least `count` rows at or after `start`. +async function waitFor(where, start, count = 1) { + const deadline = Date.now() + 2000; + for (;;) { + const found = await AuditLog.find(Object.assign({}, where, {createdAt: {'>=': start}})).sort('createdAt ASC'); + if (found.length >= count) { return found; } + if (Date.now() > deadline) { assert.fail(`no audit row for ${JSON.stringify(where)} within 2 s`); } + await sleep(25); + } +} + +// A denied GET on a model that no one can read: a row for sure. `get(url)` is +// the test's own GET for the actor (with its credential and headers); `model` +// is a name that no test shares. Returns the row once it is stored. It proves +// the earlier writes landed. +async function sentinel(get, model, start) { + await get(`/api/v1/${model}`).expect(403); + const [row] = await waitFor({permission: `${model}.read`}, start); + return row; +} + +module.exports = {waitFor, sentinel}; diff --git a/tools/smoke/checks/audit-log.js b/tools/smoke/checks/audit-log.js new file mode 100644 index 0000000..bde652a --- /dev/null +++ b/tools/smoke/checks/audit-log.js @@ -0,0 +1,157 @@ +/** + * The Audit Log page (issue #200). + * + * It proves, in a browser, that GET /audit lists the trail; that a click on a + * row opens the "Audit entry" modal; that a server value shows as text, not as + * markup, in the grid and in the modal; that the paged length menu has no + * "All"; and that the infinite table, with FOG_VIEW_DEFAULT_SCREEN at -1, asks + * for a length of 1 to 499 rows (Scroller sets the length from the viewport, + * so it is not 50, and it is never the 500 of the paged mode). A row whose + * `text` holds markup shows as text in the modal Detail block. + * tools/smoke/ui.js runs this file (see the comment at its top). It sets two + * Setting records and puts them back. + */ +const http = require('http'); + +const expect = (what, actual, expected) => { + const a = JSON.stringify(actual); + const e = JSON.stringify(expected); + if (a !== e) throw new Error(`${what} is ${a}, expected ${e}`); +}; + +// The length menu of the 1.6 paged table, without "All" (the server reads at most 500 rows). +const LENGTH_MENU = ['10', '25', '50', '100', '250', '500']; +// A user name that is markup: the failed sign-in stores it as the row's Who. +const MARKUP = 'audit-smoke-x'; + +// $.ajax from the page, so fog.csrf.js adds the CSRF header. +const ajax = (page, opts) => page.evaluate((o) => new Promise((resolve, reject) => { + jQuery.ajax(Object.assign({contentType: 'application/json'}, o, {data: o.data && JSON.stringify(o.data)})) + .done(resolve).fail((xhr) => reject(new Error(`${o.type} ${o.url} answered ${xhr.status}`))); +}), opts); + +// Opens /audit and waits for DataTables and for its first row. +async function openAudit(page, checkPage) { + await checkPage(page, {path: '/audit', table: true}); + await page.locator('#listtable tbody tr:not(.dt-empty) td').first().waitFor({timeout: 10000}); +} + +// Sets a Setting record, and returns what puts it back: the old value, or a delete. +async function setSetting(page, name, value) { + const all = await ajax(page, {url: '/api/v1/setting', type: 'GET'}); + const old = (Array.isArray(all) ? all : []).find((s) => s.name === name); + if (old) { + await ajax(page, {url: `/api/v1/setting/${old.id}`, type: 'PUT', data: {value}}); + return () => ajax(page, {url: `/api/v1/setting/${old.id}`, type: 'PUT', data: {value: old.value}}); + } + const made = await ajax(page, {url: '/api/v1/setting', type: 'POST', data: {name, value}}); + return () => ajax(page, {url: '/api/v1/setting', type: 'DELETE', data: {id: [made.id]}}); +} + +async function rowAndModal({page, browser, checkPage, base}) { + await openAudit(page, checkPage); + await page.locator('#listtable tbody tr:not(.dt-empty)').first().locator('td').first().click(); + const modal = page.locator('.modal.show'); + await modal.locator('.modal-title').waitFor({timeout: 10000}); + expect('the modal title', (await modal.locator('.modal-title').innerText()).trim(), 'Audit entry'); + expect('the modal labels', await modal.locator('dt').allInnerTexts(), [ + 'When', 'Who', 'From', 'Authenticated by', 'Action', 'Outcome', 'Subject', 'Permission', 'Affected', 'Operation' + ]); + expect('the modal buttons', await modal.locator('.modal-footer button').allInnerTexts(), ['Close']); + await modal.locator('.modal-footer button').click(); + await page.locator('.modal.show').waitFor({state: 'detached', timeout: 10000}); + + // A user name with markup is text in the grid and in the modal. A signed-out + // context sends the sign-in, because the signed-in page answers it with 200, + // and the 401 on ctx.page would fail the check. + const anonymous = await browser.newContext(); + try { + const res = await anonymous.request.post(`${base}/api/v1/auth/login`, {data: {username: MARKUP, password: 'wrong'}}); + expect('the status of the failed sign-in', res.status(), 401); + } finally { + await anonymous.close(); + } + await page.goto(`${base}/audit?search=${encodeURIComponent('audit-smoke-x')}`, {waitUntil: 'networkidle'}); + const cell = page.locator('#listtable tbody tr:not(.dt-empty) td', {hasText: MARKUP}).first(); + await cell.waitFor({timeout: 10000}); + expect('the number of in the grid', await page.locator('#listtable tbody b').count(), 0); + await cell.click(); + const entry = page.locator('.modal.show'); + await entry.locator('.modal-title').waitFor({timeout: 10000}); + expect('the Who value', (await entry.locator('dd').nth(1).innerText()).trim(), MARKUP); + expect('the number of in the modal', await entry.locator('b').count(), 0); + await entry.locator('.modal-footer button').click(); + await page.locator('.modal.show').waitFor({state: 'detached', timeout: 10000}); +} + +// A row whose `text` holds markup. No form writes `text` from the browser, but +// the seam stores ` ` as the text of a denied request. A raw +// request sends the path with its `<` and `>` unencoded (a browser would encode +// them). The signed-in admin asks for a model that no one can read: a 403 and a +// row whose text is `GET /api/v1/audit-smoke-t`. +async function markupText({page, base}) { + const url = new URL(base); + const cookies = (await page.context().cookies(base)).map((c) => `${c.name}=${c.value}`).join('; '); + const status = await new Promise((resolve, reject) => { + const req = http.request({ + host: url.hostname, port: url.port, method: 'GET', path: '/api/v1/audit-smoke-t', + headers: {Cookie: cookies, Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest'} + }, (res) => { res.resume(); res.on('end', () => resolve(res.statusCode)); }); + req.on('error', reject); + req.end(); + }); + expect('the status of the raw request', status, 403); + await page.goto(`${base}/audit?search=audit-smoke-t`, {waitUntil: 'networkidle'}); + const row = page.locator('#listtable tbody tr:not(.dt-empty)').first(); + await row.waitFor({timeout: 10000}); + expect('the number of in the grid', await page.locator('#listtable tbody b').count(), 0); + await row.locator('td').first().click(); + const entry = page.locator('.modal.show'); + await entry.locator('.modal-title').waitFor({timeout: 10000}); + expect('the Detail text', (await entry.locator('pre').innerText()).trim(), 'GET /api/v1/audit-smoke-t'); + expect('the number of in the Detail block', await entry.locator('pre b').count(), 0); + await entry.locator('.modal-footer button').click(); + await page.locator('.modal.show').waitFor({state: 'detached', timeout: 10000}); +} + +async function pagedMode({page, checkPage}) { + await openAudit(page, checkPage); + const restore = await setSetting(page, 'FOG_TABLE_SCROLL_MODE', 'paged'); + try { + await openAudit(page, checkPage); + expect('the paged length menu', await page.locator('div.dt-length select option').allInnerTexts(), LENGTH_MENU); + } finally { + await restore(); + } +} + +async function infiniteMode({page, checkPage}) { + await openAudit(page, checkPage); + const restoreMode = await setSetting(page, 'FOG_TABLE_SCROLL_MODE', 'infinite'); + let restoreLength; + try { + restoreLength = await setSetting(page, 'FOG_VIEW_DEFAULT_SCREEN', -1); + const asked = page.waitForRequest((r) => new URL(r.url()).pathname === '/api/v1/audit/datatable' && r.method() === 'POST', {timeout: 10000}); + await checkPage(page, {path: '/audit', table: true}); + const request = await asked; + // Scroller sets the page length to the viewport rows times its + // displayBuffer of 9 (dataTables.scroller.js:97), so the number depends on + // the window. The check asserts what matters: the table asks for a chunk, + // never for the 500 of the paged-mode default. + const length = Number(new URLSearchParams(request.postData()).get('length')); + if (!(length >= 1 && length < 500)) throw new Error(`the length of the datatable request is ${length}, expected 1 to 499`); + } finally { + if (restoreLength) await restoreLength(); + await restoreMode(); + } +} + +module.exports = { + name: 'audit-log: the Audit Log page', + run: async (ctx) => { + await rowAndModal(ctx); + await markupText(ctx); + await pagedMode(ctx); + await infiniteMode(ctx); + } +}; diff --git a/tools/smoke/checks/ui16-03-shell.js b/tools/smoke/checks/ui16-03-shell.js index 65e65c9..6ddabf1 100644 --- a/tools/smoke/checks/ui16-03-shell.js +++ b/tools/smoke/checks/ui16-03-shell.js @@ -33,6 +33,7 @@ const HEADERS = { '/tasks': ['Task Management', 'All Tasks'], '/users': ['User Management', 'All Users'], '/workflows': ['Workflow Management', 'All Workflows'], + '/audit': ['Audit Log', 'Audit Log'], '/snapins': ['Snapin Management', 'All Snapins'], '/printers': ['Printer Management', 'All Printers'], '/hosts/create': ['Host Management', 'Create New Host'], diff --git a/tools/smoke/checks/ui16-04-sidebar.js b/tools/smoke/checks/ui16-04-sidebar.js index 4dbff73..40b6632 100644 --- a/tools/smoke/checks/ui16-04-sidebar.js +++ b/tools/smoke/checks/ui16-04-sidebar.js @@ -30,7 +30,8 @@ const TOP = [ ['Tasks', 'fas fa-bars-progress'], ['Workflows', 'fas fa-diagram-project'], ['User Administration', 'fas fa-shield'], - ['iPXE Menu', 'fas fa-list-ol'] + ['iPXE Menu', 'fas fa-list-ol'], + ['Logging', 'fas fa-scroll'] ]; // What the sidebar on screen shows. @@ -98,6 +99,14 @@ async function checkCreate({page, checkPage}) { await checkActive(page, '/hosts/create', ['Create New Host']); } +// The Logging group holds Audit Log, and the link is active and open on /audit (issue #200). +async function checkAudit({page, checkPage}) { + await checkPage(page, {path: '/audit', table: true}); + const got = await sidebar(page); + expect('/audit: the active sub-links', got.activeSubs, ['Audit Log']); + expect('/audit: the open items', got.open, ['Logging']); +} + // The edit page of the host that the round trip created (ctx.created.host). async function checkEdit({page, checkPage, created}) { const name = created.host; @@ -119,6 +128,7 @@ module.exports = { run: async (ctx) => { await checkShape(ctx); await checkCreate(ctx); + await checkAudit(ctx); await checkEdit(ctx); } }; diff --git a/tools/smoke/checks/ui16-06-tables.js b/tools/smoke/checks/ui16-06-tables.js index 594c58b..d202681 100644 --- a/tools/smoke/checks/ui16-06-tables.js +++ b/tools/smoke/checks/ui16-06-tables.js @@ -28,10 +28,12 @@ const TOOLBARS = { '/hosts/pendingAgents': [...SELECT, ...SHARED, 'Approve selected', 'Deny selected'], '/hosts/agentTokens': [...SELECT, ...SHARED, 'Create token', 'Revoke selected'], '/images': [...SELECT, ...SHARED, 'Scan store'], - '/tasks': SHARED + '/tasks': SHARED, + // The Audit Log is not selectable (1.6 AuditManagement $selectable = false). + '/audit': SHARED }; // The 1.6 title of a list that does not start with "All " (HostManagement::agentTokens). -const TITLES = {'/hosts/agentTokens': 'Agent Enrollment Tokens'}; +const TITLES = {'/hosts/agentTokens': 'Agent Enrollment Tokens', '/audit': 'Audit Log'}; // The 1.6 paged length menu (1.6 fog.common.js lengthMenu). const LENGTH_MENU = ['10', '25', '50', '100', '250', '500', 'All']; diff --git a/tools/smoke/ui.js b/tools/smoke/ui.js index d321b0f..aa8f9ca 100644 --- a/tools/smoke/ui.js +++ b/tools/smoke/ui.js @@ -85,6 +85,7 @@ const PAGES = [ {path: '/tasks', table: true}, {path: '/users', table: true}, {path: '/workflows', table: true}, + {path: '/audit', table: true}, {path: '/hosts/create'}, {path: '/groups/create'}, {path: '/images/create'}, diff --git a/views/pages/partials/list/audit.js b/views/pages/partials/list/audit.js new file mode 100644 index 0000000..0933673 --- /dev/null +++ b/views/pages/partials/list/audit.js @@ -0,0 +1,104 @@ +(function($) { + // The Audit Log list (GET /audit; 1.6 fog.audit.list.js): the audit trail, + // read only, newest first. A click on a row opens the "Audit entry" modal. + // A server value shows as text, never as markup (window.fogTextCell, and + // textContent in the modal). + + // The outcome badge color (1.6 fog.audit.list.js:97-128). + const BADGES = {allowed: 'success', denied: 'danger', failed: 'warning', partial: 'warning'}; + + // The Subject cell: the label, else type#id, else the type. + function subjectOf(row) { + if (row.subjectLabel) { return row.subjectLabel; } + if (row.subjectType && row.subjectId) { return row.subjectType + '#' + row.subjectId; } + return row.subjectType || ''; + } + + // The Permission cell: an empty permission means no authorization ran. + function permissionCell(data, type) { + if (type !== 'display') { return data; } + return data ? window.fogTextCell(data, type) : 'none'; + } + + function outcomeCell(data, type) { + if (type !== 'display') { return data; } + return '' + window.fogTextCell(data, type) + ''; + } + + // The "Audit entry" modal: label and value pairs, then the Detail block. + function showEntry(row) { + const pairs = [ + ['When', window.fogWhen(row.createdAt)], + ['Who', row.createdBy], + ['From', row.ip], + ['Authenticated by', row.authSource], + ['Action', row.type], + ['Outcome', row.outcome], + ['Subject', subjectOf(row)], + ['Permission', row.permission || 'none - this path has no authorization gate'], + ['Affected', row.affectedCount], + ['Operation', row.correlationId] + ]; + const body = document.createElement('div'); + const list = document.createElement('dl'); + list.className = 'row mb-0'; + pairs.forEach(([label, value]) => { + const dt = document.createElement('dt'); + dt.className = 'col-sm-4'; + dt.textContent = label; + const dd = document.createElement('dd'); + dd.className = 'col-sm-8'; + dd.textContent = value === null || value === undefined ? '' : String(value); + list.appendChild(dt); + list.appendChild(dd); + }); + body.appendChild(list); + if (row.text) { + const title = document.createElement('h6'); + title.className = 'mt-3'; + title.textContent = 'Detail'; + const pre = document.createElement('pre'); + pre.textContent = row.text; + body.appendChild(title); + body.appendChild(pre); + } + // Only a Close button: the audit trail has nothing to confirm. + const ctrl = window.fogModal({title: 'Audit entry', body: body, size: 'modal-lg', cancelText: 'Close'}); + if (ctrl) { ctrl.el.querySelector('[data-fog-confirm]').remove(); } + } + + let opts = { + // The server orders by createdAt, then id (audit/datatable). + ordering: false, + // No "All": the server reads at most 500 rows (audit/datatable MAX_ROWS). + lengthMenu: [[10, 25, 50, 100, 250, 500], [10, 25, 50, 100, 250, 500]], + columns: [ + {data: 'createdAt', render: window.fogWhenCell}, + {data: 'createdBy', render: window.fogTextCell}, + {data: 'type', render: window.fogTextCell}, + {data: 'permission', render: permissionCell}, + {data: 'outcome', render: outcomeCell}, + {data: null, render: (data, type, row) => window.fogTextCell(subjectOf(row), type)}, + {data: 'ip', render: window.fogTextCell} + ], + rowId: 'id', + serverSide: true, + ajax: { + type: 'post', + url: '/api/v1/audit/datatable' + } + }; + // The server default "All" (-1) means 500 here, in paged mode only. In + // infinite mode registerTable turns -1 into 50, and a page option would win + // over it, so 500 would load 500 rows for each scroll. + if (($('#scrollMode').val() || 'infinite').toLowerCase() === 'paged' && parseInt($('#pageLength').val(), 10) === -1) { + opts.pageLength = 500; + } + + let table = $('#listtable').registerTable(undefined, opts); + + $('#listtable tbody').on('click', 'tr', function() { + const row = table.row(this).data(); + if (row) { showEntry(row); } + }); +})(jQuery);