From 4c2aa9075a94385d25d0abbb6892a2aafcbcb952 Mon Sep 17 00:00:00 2001 From: Tom Elliott Date: Tue, 17 Nov 2026 06:58:40 -0600 Subject: [PATCH] Add the FOG 1.6 FOG Settings page (#199) GET /about/settings renders the settings catalog (config/fog-settings.js) as the 1.6 FOG Settings page: one card, a live search box, a category nav and one panel per category, with each row's value from sails.helpers.settings.get. A Setting record that is not a catalog key, such as schema, never shows. The page answers 403 without setting.read and disables every control without setting.update. A stored value that is not an option (FOG_VIEW_DEFAULT_SCREEN = 30) shows as one more, selected option. A catalog type the page cannot render answers 500 and logs the key and the type. Each control saves on change through POST /api/v1/setting/save (setting.update, apiCsrfGuard). A key not in the catalog, or a value that normalize() rejects, answers 400 with the 1.6 body and stores nothing. Only a string or a number reaches normalize(), so a crafted JSON body gets a 400, not a 500. A good save stores the normalized value and answers 202 with the 1.6 body. req.audit names the setting. The sidebar gets the 1.6 "FOG Configuration" leaf (order 150, after iPXE Menu). The two pinned menu lists and the ui16-03 header table gain the new entry. Tests: test/integration/settings-page.test.js (fails on the base: the route did not exist) and the UI check tools/smoke/checks/fog-settings.js. Co-Authored-By: Claude Opus 5.5 --- api/controllers/pages/settings.js | 83 ++++++++ api/controllers/setting/save.js | 56 ++++++ config/globals.js | 5 +- config/policies.js | 4 + config/routes.js | 10 + test/helpers/menu.test.js | 12 +- test/integration/settings-page.test.js | 254 +++++++++++++++++++++++++ tools/smoke/checks/fog-settings.js | 161 ++++++++++++++++ tools/smoke/checks/ui16-03-shell.js | 2 + tools/smoke/checks/ui16-04-sidebar.js | 4 +- tools/smoke/ui.js | 1 + views/pages/partials/settings.js | 153 +++++++++++++++ views/pages/settings.ejs | 70 +++++++ 13 files changed, 812 insertions(+), 3 deletions(-) create mode 100644 api/controllers/pages/settings.js create mode 100644 api/controllers/setting/save.js create mode 100644 test/integration/settings-page.test.js create mode 100644 tools/smoke/checks/fog-settings.js create mode 100644 views/pages/partials/settings.js create mode 100644 views/pages/settings.ejs 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 2603f2f..ec8c776 100644 --- a/config/globals.js +++ b/config/globals.js @@ -147,7 +147,10 @@ module.exports.globals = { subLinks: [ {link: '/pxemenus/create', text: 'Create New iPXE Menu'} ] - } + }, + // 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'} ], authenticationMechanisms: [ 'local' diff --git a/config/policies.js b/config/policies.js index 034f8f2..91b65d4 100644 --- a/config/policies.js +++ b/config/policies.js @@ -44,6 +44,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 692213c..78b8c52 100644 --- a/config/routes.js +++ b/config/routes.js @@ -79,6 +79,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}, @@ -157,6 +163,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 e359670..82482af 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'], + ['FOG Configuration', 'fas fa-wrench'] ]); assert.deepStrictEqual(menu.filter((n) => n.pluginOption), []); const admin = menu.find((n) => n.text === 'User Administration'); @@ -128,6 +129,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(/