diff --git a/api/controllers/pages/settings.js b/api/controllers/pages/settings.js new file mode 100644 index 0000000..62fa9e6 --- /dev/null +++ b/api/controllers/pages/settings.js @@ -0,0 +1,83 @@ +const path = require('path'); + +// GET /about/settings: the FOG 1.6 FOG Settings page +// (FOGConfigurationPage::settings and _renderSettings, +// FOGConfigurationPage.php:5638-5870). It lists every key of the settings +// catalog (config/fog-settings.js) with its value from +// sails.helpers.settings.get, one panel per category. A Setting record whose +// name is not a catalog key, such as `schema`, never shows. Each control +// saves on change through POST /api/v1/setting/save +// (api/controllers/setting/save.js, views/pages/partials/settings.js). + +// The control types this page renders. Both catalog keys are `select`. The +// change that adds the first number, text or checkbox key adds its control. +const RENDERED_TYPES = ['select']; + +// The 1.6 reload note, added to the label tooltip of a `reload: true` row +// (FOGConfigurationPage.php _renderSettings, $refreshtip). +const RELOAD_TIP = 'Changing this setting takes effect after you reload the page. ' + + 'A hard refresh (Ctrl+F5, or Cmd+Shift+R) may be required.'; + +// Natural order without case, as 1.6 ksort(SORT_NATURAL | SORT_FLAG_CASE). +const natural = (a, b) => a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'}); + +// The options of a select, with the stored value selected. A valid stored +// value that is not one of the options (FOG_VIEW_DEFAULT_SCREEN = 30) is one +// more option, labeled with the value, so the page shows what is stored. +function selectOptions(entry, value) { + const options = entry.options.map((option) => ({ + value: String(option.value), + label: option.label, + selected: String(option.value) === String(value) + })); + if (!options.some((option) => option.selected)) { + options.push({value: String(value), label: String(value), selected: true}); + } + return options; +} + +module.exports = { + friendlyName: 'FOG Settings', + description: 'The FOG Settings page.', + exits: { + forbidden: { + responseType: 'forbidden' + }, + success: { + viewTemplatePath: 'pages/settings' + } + }, + fn: async function () { + if (!sails.helpers.audit.can(this.req, 'setting.read')) { + throw 'forbidden'; + } + const catalog = sails.config.fogSettings; + const byCategory = {}; + for (const key of Object.keys(catalog).sort(natural)) { + const entry = catalog[key]; + // A thrown Error answers 500, and Sails logs its message. + if (!RENDERED_TYPES.includes(entry.type)) { + throw new Error(`FOG Settings: the catalog key ${key} has the type "${entry.type}", and this page renders no control for it`); + } + const value = await sails.helpers.settings.get(key); + (byCategory[entry.category] = byCategory[entry.category] || []).push({ + key, + description: entry.description, + reload: entry.reload, + // One tooltip on the label: the description, then the reload note. + tip: entry.reload ? `${entry.description} — ${RELOAD_TIP}` : entry.description, + options: selectOptions(entry, value) + }); + } + return { + // The FOG 1.6 content header and tab title (FOGConfigurationPage.php:64, :5640). + section: 'FOG Configuration', + page: 'FOG Settings', + categories: Object.keys(byCategory).sort(natural).map((name) => ({name, rows: byCategory[name]})), + // false disables every control. The save route checks setting.update + // itself, so this only spares a user a save that is refused. + canUpdate: sails.helpers.audit.can(this.req, 'setting.update'), + partialname: path.join(__dirname, '..', '..', '..', 'views', 'pages', 'partials', 'settings.js') + }; + } +}; diff --git a/api/controllers/setting/save.js b/api/controllers/setting/save.js new file mode 100644 index 0000000..c58586b --- /dev/null +++ b/api/controllers/setting/save.js @@ -0,0 +1,56 @@ +/** + * POST /api/v1/setting/save + * + * Stores one setting of the FOG settings catalog (config/fog-settings.js) + * from the FOG Settings page (views/pages/partials/settings.js), as 1.6 + * FOGConfigurationPage::settingsPost does (FOGConfigurationPage.php:5218). + * Body: {key, value}. Needs setting.update. + * + * - A key that is not in the catalog answers 400 + * {error: 'Unknown setting: ', title: 'Settings Update Fail'}. + * - A value that the entry's normalize() rejects answers 400 + * {error: ' value is not valid', title: 'Settings Update Fail'}. + * - Otherwise it stores the normalized value in the Setting record of that + * name (updated, or created) and answers 202 with the 1.6 success body + * (FOGConfigurationPage.php:5534-5552). + * + * A 400 stores nothing. req.audit names the stored setting, so the audit + * hook's row (api/hooks/audit) says which one changed. + */ +module.exports = { + friendlyName: 'Save a setting', + description: 'Store one catalog setting, validated by its normalize().', + fn: async function () { + const req = this.req; + const res = this.res; + if (!sails.helpers.audit.can(req, 'setting.update')) { + return res.forbidden(); + } + const fail = (error) => res.status(400).json({error, title: 'Settings Update Fail'}); + const catalog = sails.config.fogSettings; + const key = _.get(req.body, 'key'); + // Own keys only, as sails.helpers.settings.get reads them: neither + // 'constructor' nor the 'schema' record is a setting. A key that is not + // a string is named by its JSON: a template string would call its + // toString, which a JSON body can replace ({"toString": 1} throws). + if (typeof key !== 'string' || !Object.hasOwn(catalog, key)) { + return fail(`Unknown setting: ${typeof key === 'string' ? key : JSON.stringify(key)}`); + } + // normalize() gets a string or a number only, as a form or a stored + // record holds. An object or an array is not a valid value, and an + // object can make String() throw. + const raw = _.get(req.body, 'value'); + const value = (typeof raw === 'string' || typeof raw === 'number') ? catalog[key].normalize(raw) : undefined; + if (value === undefined) { + return fail(`${key} value is not valid`); + } + let row = await sails.models.setting.findOne({name: key}); + if (row) { + row = await sails.models.setting.updateOne({id: row.id}).set({value}); + } else { + row = await sails.models.setting.create({name: key, value}).fetch(); + } + sails.helpers.audit.subject(req, 'setting', row); + return res.status(202).json({msg: 'Settings successfully stored!', title: 'Settings Update Success'}); + } +}; diff --git a/config/globals.js b/config/globals.js index 9a804ff..20f2376 100644 --- a/config/globals.js +++ b/config/globals.js @@ -148,7 +148,10 @@ module.exports.globals = { {link: '/pxemenus/create', text: 'Create New iPXE Menu'} ] }, - // The 1.6 "Logging" group (FOGPage.php:899-902). It sits after the planned + // The 1.6 "FOG Configuration" node (FOGConfigurationPage.php). A leaf to + // FOG Settings until a second sub-page exists. + {order: 150, text: 'FOG Configuration', link: '/about/settings', icon: 'fas fa-wrench'}, + // The 1.6 "Logging" group (FOGPage.php:899-902). It sits after the // FOG Configuration entry (150). { order: 170, text: 'Logging', icon: 'fas fa-scroll', diff --git a/config/policies.js b/config/policies.js index 90193f8..b465e1c 100644 --- a/config/policies.js +++ b/config/policies.js @@ -47,6 +47,10 @@ module.exports.policies = { 'agent/mint-token': ['isLoggedIn','isAuthenticated','apiCsrfGuard'], 'agent/revoke-token': ['isLoggedIn','isAuthenticated','apiCsrfGuard'], + // The FOG Settings save (checks setting.update itself). apiCsrfGuard: a + // cookie-authed mutation on CSRF-exempt /api/v1. + 'setting/save': ['isLoggedIn','isAuthenticated','apiCsrfGuard'], + // Image Policies 'image/capture': ['isLoggedIn','isAuthenticated', 'image/capture'], 'image/deploy': ['isLoggedIn','isAuthenticated', 'image/deploy'], diff --git a/config/routes.js b/config/routes.js index 7059191..dd7b187 100644 --- a/config/routes.js +++ b/config/routes.js @@ -83,6 +83,12 @@ module.exports.routes = { // Global search (must precede the :model routes). 'GET /api/v1/search': {action: 'search', csrf: false}, + // The FOG Settings page saves one setting per request (setting.update). + // Grouped above the :model routes with the other explicit /api/v1 routes. + // A cookie-authed mutation on CSRF-exempt /api/v1, so apiCsrfGuard guards + // it (config/policies.js). + 'POST /api/v1/setting/save': {action: 'setting/save', csrf: false}, + // General API elements. 'POST /api/v1/image/scan': {action: 'image/scan', csrf: false}, 'POST /api/v1/:model': {action: 'general/create', csrf: false}, @@ -164,6 +170,10 @@ module.exports.routes = { 'GET /pxemenus/create': {action: 'pages/create/pxemenus'}, 'POST /pxemenus/create': {action: 'general/save'}, + // FOG Configuration Views, at the FOG 1.6 node and sub names + // (FOGConfigurationPage::settings, about&sub=settings) + 'GET /about/settings': {action: 'pages/settings'}, + // Edit Views (generic edit page + save) 'GET /hosts/edit/:id': {action: 'pages/edit'}, 'POST /hosts/edit/:id': {action: 'general/save'}, diff --git a/test/helpers/menu.test.js b/test/helpers/menu.test.js index 101362c..814864d 100644 --- a/test/helpers/menu.test.js +++ b/test/helpers/menu.test.js @@ -78,6 +78,7 @@ describe('Sidebar menu helpers::', () => { ['Workflows', 'fas fa-diagram-project'], ['User Administration', 'fas fa-shield'], ['iPXE Menu', 'fas fa-list-ol'], + ['FOG Configuration', 'fas fa-wrench'], ['Logging', 'fas fa-scroll'] ]); assert.deepStrictEqual(menu.filter((n) => n.pluginOption), []); @@ -129,6 +130,15 @@ describe('Sidebar menu helpers::', () => { assert.deepStrictEqual(entries(menu).filter((n) => n.active).map((n) => n.text), ['Hosts']); }); + // Issue #199: the FOG Configuration leaf opens FOG Settings. + it('on /about/settings, makes the FOG Configuration leaf the one active item', () => { + const menu = build('/about/settings'); + const node = find(menu, 'FOG Configuration'); + assert.strictEqual(node.type, 'leaf'); + assert.strictEqual(node.link, '/about/settings'); + assert.deepStrictEqual(entries(menu).filter((n) => n.active).map((n) => n.text), ['FOG Configuration']); + }); + it('on /hosts, makes "List All Hosts" the active sub-link', () => { assert.deepStrictEqual(activeSubs(build('/hosts')).map((s) => s.text), ['List All Hosts']); }); diff --git a/test/integration/settings-page.test.js b/test/integration/settings-page.test.js new file mode 100644 index 0000000..8a618e4 --- /dev/null +++ b/test/integration/settings-page.test.js @@ -0,0 +1,254 @@ +const assert = require('assert'); +const crypto = require('crypto'); +const supertest = require('supertest'); + +// The FOG Settings page (GET /about/settings) and its save route +// (POST /api/v1/setting/save), issue #199. The page renders the settings +// catalog (config/fog-settings.js); the route stores one key, validated by +// the entry's normalize(), behind setting.update and apiCsrfGuard. +describe('FOG Settings page::', function () { + this.timeout(20000); + + const app = () => sails.hooks.http.app; + const HTML = ['Accept', 'text/html']; + const AJAX = ['X-Requested-With', 'XMLHttpRequest']; + const SAVE = '/api/v1/setting/save'; + const SCROLL = 'FOG_TABLE_SCROLL_MODE'; + const SCREEN = 'FOG_VIEW_DEFAULT_SCREEN'; + // The Setting records these tests touch. Each is put back after. + const NAMES = [SCROLL, SCREEN, 'schema']; + const RUN = crypto.randomBytes(3).toString('hex'); + const PREFIX = 'mset' + RUN; + const PASSWORD = 'mocha-settings-pw'; + const OK = {msg: 'Settings successfully stored!', title: 'Settings Update Success'}; + const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + const Setting = () => sails.models.setting; + + // Signs in as a browser does (see limited-role.test.js): a CSRF token for + // the login form, then the form POST, then a fresh token (the sign-in + // regenerates the session). + async function signIn(username, password) { + const agent = supertest.agent(app()); + let {body} = await agent.get('/csrfToken').expect(200); + await agent.post('/login').type('form').set(...HTML) + .send({username, password, _csrf: body._csrf}) + .expect(302).expect('Location', '/'); + ({body} = await agent.get('/csrfToken').expect(200)); + return {agent, csrf: body._csrf}; + } + // A non-admin user whose role holds the given stock.setting permissions. + async function limited(label, setting) { + const name = `${PREFIX}-${label}`; + const role = await sails.models.role.create({name, isAdmin: false, permissions: {stock: {setting}}}).fetch(); + await sails.models.user.create({username: name, password: PASSWORD, email: `${name}@example.com`, roles: [role.id]}); + return signIn(name, PASSWORD); + } + const cleanupUsers = async () => { + await sails.models.user.destroy({username: {startsWith: PREFIX}}); + await sails.models.role.destroy({name: {startsWith: PREFIX}}); + }; + + // A browser save: the session cookie, the CSRF header and X-Requested-With. + const save = (who, body) => who.agent.post(SAVE).set(...AJAX).set('X-CSRF-Token', who.csrf) + .set('Accept', 'application/json').send(body); + const value = async (name) => { + const row = await Setting().findOne({name}); + return row ? row.value : undefined; + }; + // Stores a value directly, as an earlier admin change would have. + const put = async (name, val) => { + if (await Setting().findOne({name})) { + await Setting().updateOne({name}).set({value: val}); + } else { + await Setting().create({name, value: val}); + } + }; + // The settings card of the page: from the card body to the no-result line. + const card = (html) => { + const start = html.indexOf('id="settings-content"'); + const end = html.indexOf('settings-noresults'); + assert.ok(start !== -1 && end > start, 'the page has no settings card'); + return html.slice(start, end); + }; + const selects = (html) => card(html).match(/]*>/g) || []; + + // Poll every 25 ms, up to 2 s, for an audit row at or after `start` + // (audit.test.js): the hook writes after the response finishes. + async function waitFor(where, start) { + const deadline = Date.now() + 2000; + for (;;) { + const found = await AuditLog.find(Object.assign({}, where, {createdAt: {'>=': start}})); + if (found.length) { return found; } + if (Date.now() > deadline) { assert.fail(`no audit row for ${JSON.stringify(where)} within 2 s`); } + await sleep(25); + } + } + + // Each record as it was before the tests (null for none). After the tests, + // a record they created is deleted and a changed value is put back. + const recorded = {}; + const restore = async (name) => { + const was = recorded[name]; + const now = await Setting().findOne({name}); + if (!was) { + if (now) { await Setting().destroy({name}); } + } else if (!now) { + await Setting().create(_.pick(was, ['name', 'description', 'value'])); + } else if (!_.isEqual(now.value, was.value)) { + await Setting().updateOne({name}).set({value: was.value}); + } + }; + + let admin; + let reader; + let nobody; + before(async () => { + for (const name of NAMES) { + recorded[name] = (await Setting().findOne({name})) || null; + } + await cleanupUsers(); + admin = await signIn('mochatestadmin', 'mochatestadmin'); + reader = await limited('reader', {read: true}); + nobody = await limited('nobody', {}); + }); + after(async () => { + for (const name of NAMES) { + await restore(name); + } + await cleanupUsers(); + }); + + describe('GET /about/settings::', () => { + it('answers 200 for an admin, with the category nav and a row for each catalog key', async () => { + const res = await admin.agent.get('/about/settings').set(...HTML).expect(200); + assert.ok(res.text.includes('FOG Settings | FOG Project'), 'no FOG Settings tab title'); + const html = card(res.text); + assert.ok(/data-cat="FOG View Settings">FOG View Settings 2<\/span>/.test(html), 'no "FOG View Settings (2)" nav item'); + for (const key of Object.keys(sails.config.fogSettings)) { + assert.ok(html.includes(`data-key="${key}"`), `no row for ${key}`); + assert.ok(html.includes(``)); + assert.ok(select, `no ${SCREEN} select`); + assert.ok(/