diff --git a/api/controllers/activity/datatable.js b/api/controllers/activity/datatable.js new file mode 100644 index 0000000..51d8476 --- /dev/null +++ b/api/controllers/activity/datatable.js @@ -0,0 +1,44 @@ +/** + * POST /api/v1/activity/datatable + * + * The rows of the Activity page (GET /activity), as DataTables server-side rows + * {draw, recordsTotal, recordsFiltered, data}. Needs activity.view. + * + * Activity is a view over the audit trail (1.6 ADR 0023). A row shows when the + * write succeeded and named its record (an access.api or access.page row with a + * subjectType), or when the event marks itself renderable (the agent events). + * Denials, failures, sign-ins and sign-outs stay on the Audit Log page only. + * + * The paging, the 500-row bound, the search and the order are in + * api/helpers/audit/datatable.js. Each row carries a server-built `summary` + * (api/helpers/audit/summary.js). + */ +const SEARCH_FIELDS = ['createdBy', 'subjectType', 'subjectLabel', 'ip']; +const ROW_FIELDS = ['id', 'createdAt', 'createdBy', 'ip', 'text']; +// The 1.6 "Administrative actions" rule, in Waterline. +const RULE = { + outcome: 'allowed', + or: [ + {renderable: true}, + {type: {in: ['access.api', 'access.page']}, subjectType: {'!=': ''}} + ] +}; + +module.exports = { + friendlyName: 'Activity datatable', + description: 'The Activity feed, as DataTables server-side rows.', + fn: async function () { + const req = this.req; + const res = this.res; + if (!sails.helpers.audit.can(req, 'activity.view')) { + return res.forbidden(); + } + return res.json(await sails.helpers.audit.datatable.with({ + req, + where: RULE, + searchFields: SEARCH_FIELDS, + fields: ROW_FIELDS, + extra: (row) => ({summary: sails.helpers.audit.summary.with({row})}) + })); + } +}; diff --git a/api/controllers/audit/datatable.js b/api/controllers/audit/datatable.js index 66d026e..68f41dc 100644 --- a/api/controllers/audit/datatable.js +++ b/api/controllers/audit/datatable.js @@ -2,21 +2,9 @@ * 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. + * {draw, recordsTotal, recordsFiltered, data}. Needs audit.view. The paging, the + * 500-row bound, the search and the order are in api/helpers/audit/datatable.js. */ -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', @@ -32,26 +20,6 @@ module.exports = { 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)) - }); + return res.json(await sails.helpers.audit.datatable.with({req, where: {}, searchFields: SEARCH_FIELDS, fields: ROW_FIELDS})); } }; diff --git a/api/controllers/pages/list/activity.js b/api/controllers/pages/list/activity.js new file mode 100644 index 0000000..c031522 --- /dev/null +++ b/api/controllers/pages/list/activity.js @@ -0,0 +1,51 @@ +const path = require('path'); +const partialPath = path.join(__dirname,'..','..','..','..','views','pages','partials','list'); +// GET /activity: what has been done on the server, in plain words, read only +// (1.6 ActivityManagement, issue #206). The rows come from +// POST /api/v1/activity/datatable. Needs activity.view. +// +// It does not call sails.helpers.listLocals, for the reason that +// pages/list/audit.js gives: the activity feed is a view over the audit trail, +// not a CRUD model. It sets no editBase, so no row links to an edit page. +module.exports = { + friendlyName: 'Activity', + description: 'Activity 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, 'activity.view')) { + throw 'forbidden'; + } + return { + // The columns of 1.6 ActivityManagement.php:199-204, in order. + theads: [ + 'Who', + 'When', + 'What', + 'From' + ], + section: 'Activity', + page: 'Activity', + singular: 'entry', + plural: 'entries', + model: 'activity', + // No row selection and no Delete selected, as 1.6 ($selectable = false). + selectable: false, + deleteButton: false, + partialname: path.join(partialPath, 'activity.js'), + ...await sails.helpers.tableSettings() + }; + } +}; diff --git a/api/helpers/audit/datatable.js b/api/helpers/audit/datatable.js new file mode 100644 index 0000000..cdd66fc --- /dev/null +++ b/api/helpers/audit/datatable.js @@ -0,0 +1,72 @@ +/** + * The DataTables server-side rows of an AuditLog view: the Audit Log page + * (audit/datatable.js) and the Activity page (activity/datatable.js). The caller + * checks its own permission first, then calls this helper. + * + * 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 the searchFields. It runs in the + * database query. Without makeLikeModifierCaseInsensitive, sails-mongo matches + * case-sensitively. With a search, the query is {and: [where, {or: search}]}; a + * `where` of {} is left out, so the query is {or: search}. + * + * recordsTotal counts the rows that match `where`, not the whole trail. + * + * 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. + * + * Inputs: req, where (the base filter; {} for none), searchFields (field names), + * fields (the row fields to pick), extra (optional: called with the stored row, + * returns more keys to add to the picked row, such as Activity's `summary`). + * + * Usage: await sails.helpers.audit.datatable.with({req, where, searchFields, fields}) + */ +const MAX_ROWS = 500; + +module.exports = { + friendlyName: 'Audit datatable', + description: 'AuditLog rows as DataTables server-side rows.', + inputs: { + req: {type: 'ref', required: true}, + // Typed, so a wrong shape fails at the call, not deep in the query. + where: {type: {}, required: true}, + searchFields: {type: ['string'], required: true}, + fields: {type: ['string'], required: true}, + extra: {type: 'ref', defaultsTo: null} + }, + exits: { + success: {description: '{draw, recordsTotal, recordsFiltered, data}.'} + }, + fn: async function ({req, where, searchFields, fields, extra}) { + // 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; + + // Waterline normalizes criteria in place, and one request runs up to three + // queries on `where`, so each query gets its own copy. + const queryOf = () => { + if (text === '') { return _.cloneDeep(where); } + const search = {or: searchFields.map((field) => ({[field]: {contains: text}}))}; + return Object.keys(where).length === 0 ? search : {and: [_.cloneDeep(where), search]}; + }; + const recordsTotal = await sails.models.auditlog.count(_.cloneDeep(where)); + const recordsFiltered = text === '' ? recordsTotal : await sails.models.auditlog.count(queryOf()).meta({makeLikeModifierCaseInsensitive: true}); + const rows = await sails.models.auditlog.find(queryOf()) + .meta({makeLikeModifierCaseInsensitive: true}) + .sort([{createdAt: 'DESC'}, {id: 'DESC'}]) + .skip(start) + .limit(length); + return { + draw: parsed.draw, + recordsTotal, + recordsFiltered, + data: rows.map((row) => Object.assign(_.pick(row, fields), extra ? extra(row) : {})) + }; + } +}; diff --git a/api/helpers/audit/summary.js b/api/helpers/audit/summary.js new file mode 100644 index 0000000..6836766 --- /dev/null +++ b/api/helpers/audit/summary.js @@ -0,0 +1,61 @@ +/** + * The plain-words summary of an AuditLog row, for the Activity page + * (GET /activity, issue #206; 1.6 ActivityManagement.php). + * + * It is built at read time from the stored fields, so a row written before + * this helper existed gets a summary too. + * + * - A renderable row: the event name, `, ` and the subject, then `: ` and the + * stored text. agent.enroll is "Agent enrollment", agent.token is "Agent + * token", any other type is shown as it is. + * - An access.* row: a verb from the HTTP method that starts `text`, then the + * subject, then ` (N records)` when more than one record changed. + * - Any other row: the stored text. + * + * The subject is the type, then the label in double quotes, else #id. + * + * Inputs: row (an AuditLog row, or any object with the same fields). + * + * Usage: sails.helpers.audit.summary.with({row}) + */ +const EVENTS = { + 'agent.enroll': 'Agent enrollment', + 'agent.token': 'Agent token' +}; +const VERBS = {DELETE: 'Deleted', PUT: 'Updated', PATCH: 'Updated', POST: 'Saved'}; + +module.exports = { + friendlyName: 'Summarize an audit row', + description: 'One plain sentence for an AuditLog row.', + sync: true, + inputs: { + row: {type: 'ref', required: true} + }, + exits: { + success: {description: 'The summary string.'} + }, + fn: function ({row}) { + let subject = ''; + if (row.subjectType) { + subject = row.subjectType; + if (row.subjectLabel) { + subject += ` "${row.subjectLabel}"`; + } else if (row.subjectId) { + subject += ` #${row.subjectId}`; + } + } + const text = row.text || ''; + if (row.renderable === true) { + const event = EVENTS[row.type] || row.type; + return `${event}${subject ? `, ${subject}` : ''}: ${text}`; + } + if (typeof row.type === 'string' && row.type.startsWith('access.')) { + const verb = VERBS[text.split(' ')[0]]; + if (verb) { + const count = row.affectedCount > 1 ? ` (${row.affectedCount} records)` : ''; + return `${verb}${subject ? ` ${subject}` : ''}${count}`; + } + } + return text; + } +}; diff --git a/api/hooks/audit/index.js b/api/hooks/audit/index.js index 57d6d44..9f9a6b2 100644 --- a/api/hooks/audit/index.js +++ b/api/hooks/audit/index.js @@ -42,6 +42,8 @@ const READ_ACTIONS = [ // The Audit Log DataTable. Without it, every page load and scroll of the // audit page would write an AuditLog row. 'audit/datatable', + // The Activity DataTable: the same reason as the Audit Log one. + 'activity/datatable', // Signs a JWT for the user and changes no record. 'auth/token' ]; diff --git a/config/globals.js b/config/globals.js index 20f2376..f1dbaae 100644 --- a/config/globals.js +++ b/config/globals.js @@ -156,6 +156,8 @@ module.exports.globals = { { order: 170, text: 'Logging', icon: 'fas fa-scroll', children: [ + // 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'} ] } diff --git a/config/permissions.js b/config/permissions.js index a71f359..d03e5af 100644 --- a/config/permissions.js +++ b/config/permissions.js @@ -6,6 +6,12 @@ module.exports.permissions = { audit: { view: false }, + // The Activity page (GET /activity, POST /api/v1/activity/datatable). The + // key matches no model, so it opens no generic /api/v1/:model route. An + // admin role gets it through api/helpers/permissions/resolve.js, as every leaf. + activity: { + view: false + }, host: { create: false, destroy: false, diff --git a/config/policies.js b/config/policies.js index b465e1c..6a9d321 100644 --- a/config/policies.js +++ b/config/policies.js @@ -39,6 +39,9 @@ module.exports.policies = { // The Audit Log rows (the action checks audit.view itself). It only reads. 'audit/datatable': ['isLoggedIn','isAuthenticated'], + // The Activity rows (the action checks activity.view itself). It only reads. + 'activity/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 dd7b187..8de94cd 100644 --- a/config/routes.js +++ b/config/routes.js @@ -72,6 +72,10 @@ module.exports.routes = { // must precede POST /api/v1/:model/datatable, or it is read as :model=audit. 'POST /api/v1/audit/datatable': {action: 'audit/datatable', csrf: false}, + // The Activity page rows (GET /activity). A POST read that needs activity.view; + // it must precede POST /api/v1/:model/datatable, or it is read as :model=activity. + 'POST /api/v1/activity/datatable': {action: 'activity/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}, @@ -141,6 +145,9 @@ module.exports.routes = { // The Audit Log page (1.6 AuditManagement), read-only; it needs audit.view. 'GET /audit': {action: 'pages/list/audit'}, + // The Activity page (1.6 ActivityManagement), read-only; it needs activity.view. + 'GET /activity': {action: 'pages/list/activity'}, + // Group Views 'GET /groups': {action: 'pages/list/groups'}, 'GET /groups/create': {action: 'pages/create/groups'}, diff --git a/test/helpers/audit-summary.test.js b/test/helpers/audit-summary.test.js new file mode 100644 index 0000000..ade0fda --- /dev/null +++ b/test/helpers/audit-summary.test.js @@ -0,0 +1,52 @@ +const assert = require('assert'); + +// The Activity summary (api/helpers/audit/summary.js): one plain sentence for an +// AuditLog row. It is a sync helper, called as the app calls it: .with() with +// no .now(). A helper that lost `sync: true` returns a Deferred, and the +// strictEqual assertions fail on it. +describe('Audit summary helper::', () => { + const summary = (row) => sails.helpers.audit.summary.with({row}); + + it('names a PUT on a labeled subject', () => { + assert.strictEqual(summary({ + type: 'access.api', text: 'PUT /api/v1/host/abc', subjectType: 'host', subjectLabel: 'PC-01' + }), 'Updated host "PC-01"'); + }); + + it('names a DELETE with a count and no label', () => { + assert.strictEqual(summary({ + type: 'access.api', text: 'DELETE /api/v1/image', subjectType: 'image', subjectId: '', affectedCount: 3 + }), 'Deleted image (3 records)'); + }); + + it('names a POST with a count of 1 without the count', () => { + assert.strictEqual(summary({ + type: 'access.api', text: 'POST /api/v1/host/bulk', subjectType: 'host', subjectId: '', affectedCount: 1 + }), 'Saved host'); + }); + + it('names a renderable row by its event, subject and text', () => { + assert.strictEqual(summary({ + type: 'agent.token', renderable: true, subjectType: 'agentenrolltoken', subjectLabel: 'lab', text: 'minted, 3 use(s)' + }), 'Agent token, agentenrolltoken "lab": minted, 3 use(s)'); + }); + + it('names agent.enroll, and an unknown event by its type', () => { + assert.strictEqual(summary({type: 'agent.enroll', renderable: true, text: 'enrolled'}), 'Agent enrollment: enrolled'); + assert.strictEqual(summary({type: 'x.y', renderable: true, subjectType: 'host', subjectId: '7', text: 't'}), 'x.y, host #7: t'); + }); + + it('gives a subject with an id and no label as type #id', () => { + assert.strictEqual(summary({type: 'access.api', text: 'PATCH /api/v1/host/7', subjectType: 'host', subjectId: '7'}), 'Updated host #7'); + }); + + it('leaves no trailing space for a row with no subject', () => { + assert.strictEqual(summary({ + type: 'access.page', text: 'POST /account/preferences', subjectType: '', subjectId: '' + }), 'Saved'); + }); + + it('gives the stored text for any other row', () => { + assert.strictEqual(summary({type: 'auth.login', text: 'signed in'}), 'signed in'); + }); +}); diff --git a/test/integration/activity-page.test.js b/test/integration/activity-page.test.js new file mode 100644 index 0000000..6499654 --- /dev/null +++ b/test/integration/activity-page.test.js @@ -0,0 +1,194 @@ +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 Activity page (issue #206): GET /activity and POST /api/v1/activity/datatable, +// behind the activity.view permission. It is a view over the audit trail: a +// successful write that named its record, and the renderable events. 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('Activity 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-act' + RUN; + const PASSWORD = 'mocha-act-pw'; + const URL = '/api/v1/activity/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 adminName; + + 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(); + adminName = await mkUser('admin', {isAdmin: true}); + const limitedName = await mkUser('limited', {permissions: {stock: {host: {read: true}}}}); + const grantedName = await mkUser('granted', {permissions: {stock: {activity: {view: true}}}}); + admin = await signIn(adminName); + limited = await signIn(limitedName); + granted = await signIn(grantedName); + limited.username = limitedName; + }); + after(cleanup); + + describe('the page', () => { + it('answers 200 with the four headings for an admin', async () => { + const res = await admin.get('/activity').set(...HTML).expect(200); + // The elements of the table head, in order. + const heads = [...res.text.matchAll(/]*>([\s\S]*?)<\/th>/g)].map((m) => m[1].replace(/<[^>]*>/g, '').trim()); + assert.deepStrictEqual(heads, ['Who', 'When', 'What', 'From']); + }); + + it('answers 403 for a limited user, and writes a denied row for activity.view', async () => { + const start = Date.now(); + await limited.get('/activity').set(...HTML).expect(403); + const [row] = await waitFor({createdBy: limited.username, permission: 'activity.view'}, start); + assert.strictEqual(row.outcome, 'denied'); + }); + + it('answers 200 for a limited role that holds stock.activity.view', async () => { + await granted.get('/activity').set(...HTML).expect(200); + }); + + // A regression guard: it passes before and after the change. + it('still refuses the generic route, and writes one denied row', async () => { + const start = Date.now(); + await admin.get('/api/v1/activity').set(...AJAX).expect(403); + await waitFor({createdBy: adminName, permission: 'activity.read'}, start); + // A sentinel row proves that a late duplicate would be stored by now. + await sentinel(admin, start); + const rows = await AuditLog.find({createdBy: adminName, permission: 'activity.read', createdAt: {'>=': start}}); + assert.strictEqual(rows.length, 1); + assert.strictEqual(rows[0].outcome, 'denied'); + }); + }); + + describe('the rows', () => { + it('answers 403 without activity.view, and writes a denied row for activity.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: 'activity.view'}, start); + assert.strictEqual(row.outcome, 'denied'); + }); + + it('answers a limited role that holds activity.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 the row fields', async () => { + await AuditLog.create({ + createdAt: FUTURE, createdBy: `${PREFIX}-row-shape`, type: 'access.api', outcome: 'allowed', + subjectType: 'host', subjectLabel: 'PC-01', text: 'PUT /api/v1/host/abc' + }); + 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.deepStrictEqual(Object.keys(res.body.data[0]).sort(), ['createdAt', 'createdBy', 'id', 'ip', 'summary', 'text']); + const times = res.body.data.map((r) => r.createdAt); + assert.deepStrictEqual(times, times.slice().sort((a, b) => b - a)); + assert.strictEqual(res.body.data[0].summary, 'Updated host "PC-01"'); + }); + + it('returns a host update and a renderable agent row, and no other row', async () => { + // Every row carries the marker -row-rr-, so the search finds only these rows. + const marker = `${PREFIX}-row-rr-`; + await AuditLog.createEach([ + {createdAt: FUTURE, createdBy: `${marker}ok`, type: 'access.api', outcome: 'allowed', subjectType: 'host', subjectLabel: 'ok-h', text: 'PUT /api/v1/host/1'}, + {createdAt: FUTURE, createdBy: `${marker}agent`, type: 'agent.token', outcome: 'allowed', renderable: true, subjectType: 'agentenrolltoken', subjectLabel: 'lab', text: 'minted'}, + {createdAt: FUTURE, createdBy: `${marker}denied`, type: 'access.api', outcome: 'denied', subjectType: 'host', text: 'PUT /api/v1/host/1'}, + {createdAt: FUTURE, createdBy: `${marker}failed`, type: 'access.api', outcome: 'failed', subjectType: 'host', text: 'PUT /api/v1/host/1'}, + {createdAt: FUTURE, createdBy: `${marker}login`, type: 'auth.login', outcome: 'allowed', text: 'signed in'}, + {createdAt: FUTURE, createdBy: `${marker}nosubject`, type: 'access.api', outcome: 'allowed', subjectType: '', text: 'POST /api/v1/x'} + ]); + const res = await table(admin, {draw: 1, start: 0, length: 500, search: {value: marker}}).expect(200); + assert.deepStrictEqual(res.body.data.map((r) => r.createdBy.slice(marker.length)).sort(), ['agent', 'ok']); + assert.strictEqual(res.body.recordsFiltered, 2); + }); + + it('counts recordsTotal over the rows that match the rule, not the whole trail', async () => { + const res = await table(admin, {draw: 1, start: 0, length: 5}).expect(200); + const all = await AuditLog.count(); + const rule = await AuditLog.count({ + outcome: 'allowed', + or: [{renderable: true}, {type: {in: ['access.api', 'access.page']}, subjectType: {'!=': ''}}] + }); + assert.strictEqual(res.body.recordsTotal, rule); + assert.ok(rule < all, 'the sign-ins are not Activity'); + }); + + it('reads at most 500 rows', async () => { + await AuditLog.createEach(Array.from({length: 501}, (_unused, i) => ({ + createdAt: FUTURE - 1, createdBy: `${PREFIX}-row-bulk-${i}`, type: 'access.api', outcome: 'allowed', subjectType: 'host', text: 'PUT /api/v1/host/1' + }))); + for (const length of [-1, 0, 9999, undefined, 'x']) { + const res = await table(admin, {draw: 1, start: 0, length}).expect(200); + assert.strictEqual(res.body.data.length, 500, `length ${length}`); + } + 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); + }); + + it('searches case-insensitively, and counts only the matches', async () => { + await AuditLog.create({createdBy: `${PREFIX}-row-CaSe`, type: 'access.api', outcome: 'allowed', subjectType: 'host', text: 'PUT /api/v1/host/1'}); + 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: adminName, createdAt: {'>=': start}}); + assert.deepStrictEqual(rows.filter((r) => r.permission === 'activity.view' || /activity\/datatable/.test(r.text)), []); + }); + }); +}); diff --git a/tools/smoke/checks/activity.js b/tools/smoke/checks/activity.js new file mode 100644 index 0000000..10a623f --- /dev/null +++ b/tools/smoke/checks/activity.js @@ -0,0 +1,44 @@ +/** + * The Activity page (issue #206). + * + * It proves, in a browser, that GET /activity loads with the headings Who, + * When, What and From; that the grid fills (the round trips that ui.js runs + * before this file write successful host and image changes, and those are + * Activity rows); and that a click on a row opens the "Activity entry" modal + * with a Close button and no request. tools/smoke/ui.js runs this file (see + * the comment at its top). + */ + +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}`); +}; + +module.exports = { + name: 'activity: the Activity page', + run: async ({page, checkPage}) => { + await checkPage(page, {path: '/activity', table: true}); + expect('the headings', (await page.locator('#listtable thead th').allInnerTexts()).map((t) => t.trim()), ['Who', 'When', 'What', 'From']); + await page.locator('#listtable tbody tr:not(.dt-empty) td').first().waitFor({timeout: 10000}); + + // A click on a row opens the modal, and the modal makes no request. + const requests = []; + const onRequest = (r) => requests.push(r.url()); + page.on('request', onRequest); + try { + 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(), 'Activity entry'); + const labels = await modal.locator('dt').allInnerTexts(); + expect('the first modal labels', labels.slice(0, 4), ['Who', 'When', 'From', 'What']); + 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}); + } finally { + page.off('request', onRequest); + } + expect('the requests that the row click made', requests, []); + } +}; diff --git a/tools/smoke/checks/ui16-03-shell.js b/tools/smoke/checks/ui16-03-shell.js index 841334b..88c3c4f 100644 --- a/tools/smoke/checks/ui16-03-shell.js +++ b/tools/smoke/checks/ui16-03-shell.js @@ -36,6 +36,7 @@ const HEADERS = { // Issue #199: 1.6 FOGConfigurationPage name and settings() title. '/about/settings': ['FOG Configuration', 'FOG Settings'], '/audit': ['Audit Log', 'Audit Log'], + '/activity': ['Activity', 'Activity'], '/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 0eb1597..6a1c3f7 100644 --- a/tools/smoke/checks/ui16-04-sidebar.js +++ b/tools/smoke/checks/ui16-04-sidebar.js @@ -49,7 +49,9 @@ const sidebar = (page) => page.evaluate(() => { const top = [...main.querySelectorAll(':scope > li.nav-item')]; const group = top.find((li) => link(li).text === 'User Administration'); const hosts = top.find((li) => link(li).text === 'Hosts'); + const logging = top.find((li) => link(li).text === 'Logging'); return { + loggingChildren: logging ? [...logging.querySelectorAll(':scope > ul.nav-treeview > li.nav-item')].map((li) => link(li).text) : null, top: top.map((li) => [link(li).text, link(li).icon]), headers: [...document.querySelectorAll('.app-sidebar .nav-header')].map(text), pluginLists: document.querySelectorAll('.app-sidebar ul.plugin-options').length, @@ -83,6 +85,8 @@ async function checkShape({page, base, checkPage}) { expect('the sidebar headers', got.headers, ['MAIN NAVIGATION', 'RESOURCES']); expect('the number of ul.plugin-options', got.pluginLists, 0); expect('the User Administration children', got.groupChildren, [['Users', 'fas fa-users'], ['Roles', 'fas fa-user-shield']]); + // Issue #206: Activity comes before Audit Log (1.6 FOGPage.php:658-661). + expect('the Logging children', got.loggingChildren, ['Activity', 'Audit Log']); // Pending MACs, Export Hosts and Import Hosts have no route, so the sidebar hides them. expect('the Hosts sub-links', got.hostsSubs, ['List All Hosts', 'Create New Host', 'Pending Hosts', 'Pending Agents', 'Agent Tokens'] .map((text) => [text, 'nav-icon far fa-circle'])); diff --git a/tools/smoke/checks/ui16-06-tables.js b/tools/smoke/checks/ui16-06-tables.js index d202681..a601bce 100644 --- a/tools/smoke/checks/ui16-06-tables.js +++ b/tools/smoke/checks/ui16-06-tables.js @@ -30,10 +30,12 @@ const TOOLBARS = { '/images': [...SELECT, ...SHARED, 'Scan store'], '/tasks': SHARED, // The Audit Log is not selectable (1.6 AuditManagement $selectable = false). - '/audit': SHARED + '/audit': SHARED, + // The Activity page is not selectable either (1.6 ActivityManagement $selectable = false). + '/activity': SHARED }; // The 1.6 title of a list that does not start with "All " (HostManagement::agentTokens). -const TITLES = {'/hosts/agentTokens': 'Agent Enrollment Tokens', '/audit': 'Audit Log'}; +const TITLES = {'/hosts/agentTokens': 'Agent Enrollment Tokens', '/audit': 'Audit Log', '/activity': 'Activity'}; // 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 26a8948..2379570 100644 --- a/tools/smoke/ui.js +++ b/tools/smoke/ui.js @@ -87,6 +87,7 @@ const PAGES = [ {path: '/workflows', table: true}, {path: '/about/settings'}, {path: '/audit', table: true}, + {path: '/activity', table: true}, {path: '/hosts/create'}, {path: '/groups/create'}, {path: '/images/create'}, diff --git a/views/pages/partials/list/activity.js b/views/pages/partials/list/activity.js new file mode 100644 index 0000000..0f0a4b4 --- /dev/null +++ b/views/pages/partials/list/activity.js @@ -0,0 +1,68 @@ +(function($) { + // The Activity list (GET /activity; 1.6 fog.activity.list.js): what has been + // done on the server, in plain words, newest first. A click on a row opens + // the "Activity entry" modal and makes no request. A server value shows as + // text, never as markup (window.fogTextCell, and textContent in the modal). + + // The "Activity entry" modal (1.6 fog.activity.list.js:83-123): label and + // value pairs. "Logged" shows the stored text only when it differs from the + // summary. + function showEntry(row) { + const pairs = [ + ['Who', row.createdBy], + ['When', window.fogWhen(row.createdAt)], + ['From', row.ip], + ['What', row.summary] + ]; + if (row.text && row.text !== row.summary) { pairs.push(['Logged', row.text]); } + 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-3'; + dt.textContent = label; + const dd = document.createElement('dd'); + dd.className = 'col-sm-9'; + dd.textContent = value === null || value === undefined ? '' : String(value); + list.appendChild(dt); + list.appendChild(dd); + }); + body.appendChild(list); + // Only a Close button: the feed has nothing to confirm. + const ctrl = window.fogModal({title: 'Activity 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 (activity/datatable). + ordering: false, + // No "All": the server reads at most 500 rows (activity/datatable MAX_ROWS). + lengthMenu: [[10, 25, 50, 100, 250, 500], [10, 25, 50, 100, 250, 500]], + columns: [ + {data: 'createdBy', render: window.fogTextCell}, + {data: 'createdAt', render: window.fogWhenCell}, + {data: 'summary', render: window.fogTextCell}, + {data: 'ip', render: window.fogTextCell} + ], + rowId: 'id', + serverSide: true, + ajax: { + type: 'post', + url: '/api/v1/activity/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);