From 27f3e198e90ee874064515921c4e8e53a3b20120 Mon Sep 17 00:00:00 2001 From: Tom Elliott Date: Tue, 17 Nov 2026 08:28:09 -0600 Subject: [PATCH] refactor(settings): move the four remaining setting readers onto the catalog FOG_HOST_IDENTIFY_SMBIOS, FOG_AGENT_ENROLL_DEPLOY_WINDOW, FOG_CLIENT_CHECKIN_TIME and FOG_ENABLE_SHOW_PASSWORDS now come from config/fog-settings.js through sails.helpers.settings.get, so the FOG Configuration page shows and validates every runtime setting fog-node reads. Each normalize and default copies the old reader's rule, so no agent identity, enrollment auto-approval, poll interval or password-reveal decision changes. A table-driven test feeds 18 stored values (no row, '', null, {}, booleans, numbers, strings) to the old rule and to the catalog path for each key and requires the same result. The page gains number and checkbox controls. A number field that is empty or not a number sends nothing and shows "Enter a number.": Number('') is 0, so a cleared deploy-window field would otherwise switch off deploy auto-approval in one edit. The descriptions say what fog-node does where the 1.6 text is false for it. Closes #201 Co-Authored-By: Claude Opus 5.5 --- api/controllers/agent/poll.js | 13 +--- api/controllers/pages/settings.js | 13 ++-- api/helpers/agent/auto-approve.js | 5 +- api/helpers/agent/resolve-host.js | 3 +- api/helpers/form-generator.js | 9 +-- config/fog-settings.js | 91 +++++++++++++++++++++++- test/helpers/settings-catalog.test.js | 68 ++++++++++++++++++ test/integration/agent-mtls.test.js | 17 +++++ test/integration/settings-page.test.js | 56 +++++++++++++-- tools/smoke/checks/fog-settings.js | 98 +++++++++++++++++++++----- views/pages/partials/settings.js | 35 +++++++-- views/pages/settings.ejs | 11 ++- 12 files changed, 359 insertions(+), 60 deletions(-) diff --git a/api/controllers/agent/poll.js b/api/controllers/agent/poll.js index ffe4d4d..2c8b657 100644 --- a/api/controllers/agent/poll.js +++ b/api/controllers/agent/poll.js @@ -13,9 +13,6 @@ */ const {jsonBody, version} = require('../../lib/agent-pki'); -// The 1.6 default of FOG_CLIENT_CHECKIN_TIME, in seconds. -const DEFAULT_POLL_INTERVAL = 60; - module.exports = { friendlyName: 'Agent poll', description: 'Record the check-in of a fog-agent and answer with the minimal poll state.', @@ -33,12 +30,8 @@ module.exports = { if (agentVersion) { set.agentVersion = agentVersion; } await sails.models.host.updateOne({id: host.id}).set(set); - const setting = await sails.models.setting.findOne({name: 'FOG_CLIENT_CHECKIN_TIME'}); - // An integer, because the Go agent's PollInterval is an int and fails to - // decode 90.5. 1.6 casts with (int) and passes 0 or a negative number on: - // the agent then keeps its own default. A missing or non-numeric value - // gives 60. - const interval = parseInt(setting && setting.value, 10); + // An integer, with the 1.6 default of 60: config/fog-settings.js holds the rule. + const interval = await sails.helpers.settings.get('FOG_CLIENT_CHECKIN_TIME'); return res.status(200).json({ status: 'ok', @@ -46,7 +39,7 @@ module.exports = { host: {id: host.agentId, name: host.name}, revision: '', state: {revision: '', capabilities: []}, - poll_interval: Number.isNaN(interval) ? DEFAULT_POLL_INTERVAL : interval, + poll_interval: interval, // ISO 8601 with an offset, as 1.6 sends it (Route.php:3207, format('c')). server_time: new Date().toISOString().replace(/\.\d{3}Z$/, '+00:00') }); diff --git a/api/controllers/pages/settings.js b/api/controllers/pages/settings.js index 62fa9e6..88ac0f8 100644 --- a/api/controllers/pages/settings.js +++ b/api/controllers/pages/settings.js @@ -9,9 +9,9 @@ const path = require('path'); // 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 control types this page renders. A `text` entry has no control yet: the +// change that adds the first text key adds it. +const RENDERED_TYPES = ['select', 'number', 'checkbox']; // The 1.6 reload note, added to the label tooltip of a `reload: true` row // (FOGConfigurationPage.php _renderSettings, $refreshtip). @@ -66,7 +66,12 @@ module.exports = { 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) + // The view picks the control off the type. A select has options with + // the stored value selected; a number shows the value; a checkbox is + // checked when the value is true. + type: entry.type, + value, + options: entry.type === 'select' ? selectOptions(entry, value) : [] }); } return { diff --git a/api/helpers/agent/auto-approve.js b/api/helpers/agent/auto-approve.js index 5b96092..4ce72a4 100644 --- a/api/helpers/agent/auto-approve.js +++ b/api/helpers/agent/auto-approve.js @@ -25,7 +25,6 @@ * Usage: let issued = await sails.helpers.agent.autoApprove.with({row, token}) */ const HOUR_MS = 60 * 60 * 1000; -const DEFAULT_WINDOW_HOURS = 24; module.exports = { friendlyName: 'Auto-approve an agent enrollment', @@ -63,9 +62,7 @@ module.exports = { } if (!via && ['known-host-no-agent', 'rebind'].includes(row.reason)) { - const setting = await sails.models.setting.findOne({name: 'FOG_AGENT_ENROLL_DEPLOY_WINDOW'}); - const window = setting ? Number(setting.value) : DEFAULT_WINDOW_HOURS; - const hours = Number.isNaN(window) ? DEFAULT_WINDOW_HOURS : window; + const hours = await sails.helpers.settings.get('FOG_AGENT_ENROLL_DEPLOY_WINDOW'); const host = hours >= 1 ? await sails.models.host.findOne({id: row.host}) : undefined; const deployed = host ? Date.parse(host.deployed) : NaN; if (!Number.isNaN(deployed) && deployed <= Date.now() && Date.now() - deployed <= hours * HOUR_MS) { diff --git a/api/helpers/agent/resolve-host.js b/api/helpers/agent/resolve-host.js index a5a1a30..81cf49e 100644 --- a/api/helpers/agent/resolve-host.js +++ b/api/helpers/agent/resolve-host.js @@ -94,8 +94,7 @@ module.exports = { // The Host model stores guid, serial and asset in lower case. let smbiosId = ''; - const setting = await sails.models.setting.findOne({name: 'FOG_HOST_IDENTIFY_SMBIOS'}); - const smbiosOff = setting && String(setting.value).trim().toLowerCase() === 'off'; + const smbiosOff = (await sails.helpers.settings.get('FOG_HOST_IDENTIFY_SMBIOS')) === 'off'; if (!smbiosOff && (smbios.guid || smbios.serial)) { const guid = smbios.guid.toLowerCase(); const serial = smbios.serial.toLowerCase(); diff --git a/api/helpers/form-generator.js b/api/helpers/form-generator.js index 9150e10..334f215 100644 --- a/api/helpers/form-generator.js +++ b/api/helpers/form-generator.js @@ -9,12 +9,6 @@ function esc(s) { .replace(/>/g, '>').replace(/"/g, '"'); } -// A FOG setting value is on when it is truthy and not the string "0" or -// "false". FOG stores its settings as strings, so "0" means off there. -function settingOn(value) { - return !!value && value !== '0' && value !== 'false'; -} - const MODES = ['create', 'create-modal', 'edit']; module.exports = { @@ -81,8 +75,7 @@ module.exports = { // only for a form with a password field, and never created here. let showPasswords = false; if (Object.keys(formItems).some((k) => formItems[k].type === 'password')) { - let setting = await sails.models.setting.findOne({name: 'FOG_ENABLE_SHOW_PASSWORDS'}); - showPasswords = !!setting && settingOn(setting.value); + showPasswords = await sails.helpers.settings.get('FOG_ENABLE_SHOW_PASSWORDS'); } // One field row on the FOG 1.6 grid (FOGPage.php:5654-5667): the label in diff --git a/config/fog-settings.js b/config/fog-settings.js index 2c96559..ea46243 100644 --- a/config/fog-settings.js +++ b/config/fog-settings.js @@ -29,7 +29,10 @@ * Each entry, keyed by the FOG 1.6 setting name: * * category the FOG 1.6 category name, e.g. 'FOG View Settings' - * description the FOG 1.6 settingDesc text, as plain text (no HTML) + * description the FOG 1.6 settingDesc text, as plain text (no HTML). + * Where fog-node behaves differently from 1.6, the text says + * what fog-node does: a wrong description on a trust setting + * misleads the admin who sets it. * type 'select', 'number', 'text' or 'checkbox' * options for a 'select' only: an array of {value, label} * default the value when no record exists or the stored value is bad @@ -89,6 +92,92 @@ module.exports.fogSettings = { return /^(-1|[1-9][0-9]*)$/.test(text) ? Number(text) : undefined; }, reload: true + }, + + // Issue #201: the readers below used to call Setting.findOne themselves. + // Each normalize() and default copies the rule of the reader it replaced, + // so no stored value, missing record or bad value changes a decision. The + // test in test/helpers/settings-catalog.test.js holds the old rules. + + // How api/helpers/agent/resolve-host.js matches an enrolling agent + // (1.6 schema.php). That reader acts only on 'off'. 'log' and + // 'enforce' both keep the SMBIOS-first match, as the 1.6 enrollment path + // does with either, and a missing record reads 'log' (not 'off'). + FOG_HOST_IDENTIFY_SMBIOS: { + category: 'General Settings', + description: 'How much to trust the SMBIOS identity (UUID, system serial, ' + + 'chassis asset tag) a fog-agent reports when it enrolls. Off: the MAC ' + + 'addresses alone find the host. Log or Enforce: a unique firmware ' + + 'match wins over the MAC. fog-node has no boot identity path yet, so ' + + 'Log and Enforce act the same.', + type: 'select', + options: [ + {value: 'off', label: 'Off'}, + {value: 'log', label: 'Log'}, + {value: 'enforce', label: 'Enforce'} + ], + default: 'log', + // 'off', 'log' or 'enforce', in any case and with surrounding spaces. + normalize: (value) => { + let mode = String(value).trim().toLowerCase(); + return (mode === 'off' || mode === 'log' || mode === 'enforce') ? mode : undefined; + }, + reload: false + }, + + // The deploy shortcut of api/helpers/agent/auto-approve.js (1.6 schema.php + // step 416, moved to FOG Agent by a later step). A value below 1 disables + // the shortcut, so a stored 0 is a good value and stays 0. Only a value + // that is not a number reads as the default. + FOG_AGENT_ENROLL_DEPLOY_WINDOW: { + category: 'FOG Agent', + description: 'Hours after this server completes a deploy to a host during ' + + 'which an agent presenting that host\'s firmware identity is enrolled ' + + 'without an admin approving it. A value below 1 disables the ' + + 'shortcut. fog-node does not record deploys yet, so the shortcut does ' + + 'not fire until it does.', + type: 'number', + default: 24, + // Number(), as the reader did: '' and null are 0, which disables. + normalize: (value) => { + let hours = Number(value); + return Number.isNaN(hours) ? undefined : hours; + }, + reload: false + }, + + // The poll_interval of POST /agent/v1/poll (api/controllers/agent/poll.js, + // 1.6 schema.php step 116), in seconds. + FOG_CLIENT_CHECKIN_TIME: { + category: 'FOG Client', + description: 'This setting returns the client service checkin times to ' + + 'the server.', + type: 'number', + default: 60, + // An integer, because the Go agent's PollInterval is an int and fails to + // decode 90.5. 1.6 casts with (int) and passes 0 or a negative number + // on: the agent then keeps its own default. A missing or non-numeric + // value gives the default. + normalize: (value) => { + let interval = parseInt(value, 10); + return Number.isNaN(interval) ? undefined : interval; + }, + reload: false + }, + + // The password reveal control of api/helpers/form-generator.js (1.6 + // schema.php step 271). 1.6 defaults to on. fog-node is off when no record + // exists, and stays so. + FOG_ENABLE_SHOW_PASSWORDS: { + category: 'General Settings', + description: 'Show a control that displays a password field as plain ' + + 'text. Off when no value is set.', + type: 'checkbox', + default: false, + // FOG stores its settings as strings, so '0' and 'false' mean off. Always + // a boolean, so no stored value is bad. + normalize: (value) => !!value && value !== '0' && value !== 'false', + reload: false } }; diff --git a/test/helpers/settings-catalog.test.js b/test/helpers/settings-catalog.test.js index a110770..e05cdc7 100644 --- a/test/helpers/settings-catalog.test.js +++ b/test/helpers/settings-catalog.test.js @@ -65,4 +65,72 @@ describe('Settings catalog::', () => { it('rejects an inherited property name as unknown', async () => { await assert.rejects(get('constructor'), /Unknown setting: constructor/); }); + + // Issue #201: four readers moved onto the catalog. The HARD rule is that + // each reader makes the same decision as before, for every stored value. + // Each OLD function is the reader's own rule, copied from the code it + // replaced (the file and line are named). `row` is the Setting record, or + // null for none, as findOne answered. + describe('the four moved readers::', () => { + const NO_ROW = Symbol('no row'); + const INPUTS = [NO_ROW, '', '0', 0, '1', 1, true, false, 'false', 'abc', '90.5', -5, + 'OFF', ' off ', 'log', 'enforce', null, {}]; + + // api/helpers/agent/resolve-host.js: smbiosOff. + const oldSmbiosOff = (row) => !!row && String(row.value).trim().toLowerCase() === 'off'; + // api/helpers/agent/auto-approve.js: hours (DEFAULT_WINDOW_HOURS was 24). + const oldHours = (row) => { + const window = row ? Number(row.value) : 24; + return Number.isNaN(window) ? 24 : window; + }; + // api/controllers/agent/poll.js: poll_interval (DEFAULT_POLL_INTERVAL was 60). + const oldInterval = (row) => { + const interval = parseInt(row && row.value, 10); + return Number.isNaN(interval) ? 60 : interval; + }; + // api/helpers/form-generator.js: showPasswords, with its settingOn rule. + const oldShowPasswords = (row) => !!row && (!!row.value && row.value !== '0' && row.value !== 'false'); + + const CASES = [ + ['FOG_HOST_IDENTIFY_SMBIOS', oldSmbiosOff, async () => (await get('FOG_HOST_IDENTIFY_SMBIOS')) === 'off'], + ['FOG_AGENT_ENROLL_DEPLOY_WINDOW', oldHours, () => get('FOG_AGENT_ENROLL_DEPLOY_WINDOW')], + ['FOG_CLIENT_CHECKIN_TIME', oldInterval, () => get('FOG_CLIENT_CHECKIN_TIME')], + ['FOG_ENABLE_SHOW_PASSWORDS', oldShowPasswords, () => get('FOG_ENABLE_SHOW_PASSWORDS')] + ]; + + // Setting.value is json and required, so Waterline refuses '' and null. + // The fixture row goes through the raw collection. + const coll = () => sails.getDatastore(sails.models.setting.datastore).manager.collection(sails.models.setting.tableName); + const names = CASES.map(([key]) => key); + // The records as they were, put back after (a dev database may hold some). + let before; + const wipe = () => coll().deleteMany({name: {$in: names}}); + beforeEach(async () => { + before = await coll().find({name: {$in: names}}).toArray(); + await wipe(); + }); + afterEach(async () => { + await wipe(); + if (before.length) { await coll().insertMany(before); } + }); + + it('holds the four keys', () => { + names.forEach((key) => assert.ok(Object.hasOwn(catalog(), key), `no ${key}`)); + }); + + for (const [key, oldRule, newRule] of CASES) { + it(`${key}: the catalog path decides as the old reader did, for every input`, async () => { + for (const input of INPUTS) { + await wipe(); + let row = null; + if (input !== NO_ROW) { + await coll().insertOne({name: key, value: input}); + row = {value: input}; + } + const label = input === NO_ROW ? 'no row' : JSON.stringify(input); + assert.deepStrictEqual(await newRule(), oldRule(row), `${key} with ${label}`); + } + }); + } + }); }); diff --git a/test/integration/agent-mtls.test.js b/test/integration/agent-mtls.test.js index 3283f62..6a7c626 100644 --- a/test/integration/agent-mtls.test.js +++ b/test/integration/agent-mtls.test.js @@ -341,6 +341,23 @@ describe('Agent mTLS::', function () { if (saved) { await sails.models.setting.create(saved); } } }); + + // Issue #201: the FOG Settings page route stores the value, and the next + // poll reads it through the settings catalog. + it('answers the poll_interval saved through POST /api/v1/setting/save', async () => { + const a = await enrolled(); + const name = 'FOG_CLIENT_CHECKIN_TIME'; + const saved = await sails.models.setting.findOne({name}); + try { + await sails.models.setting.destroy({name}); + await admin.agent.post('/api/v1/setting/save').set(...AJAX).set('X-CSRF-Token', admin.csrf) + .set('Accept', 'application/json').send({key: name, value: 120}).expect(202); + assert.strictEqual((await poll(a)).json.poll_interval, 120); + } finally { + await sails.models.setting.destroy({name}); + if (saved) { await sails.models.setting.create(saved); } + } + }); }); describe('POST /agent/v1/renew', () => { diff --git a/test/integration/settings-page.test.js b/test/integration/settings-page.test.js index 8a618e4..06dd55a 100644 --- a/test/integration/settings-page.test.js +++ b/test/integration/settings-page.test.js @@ -16,7 +16,9 @@ describe('FOG Settings page::', function () { 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 SMBIOS = 'FOG_HOST_IDENTIFY_SMBIOS'; + const CHECKIN = 'FOG_CLIENT_CHECKIN_TIME'; + const NAMES = [SCROLL, SCREEN, SMBIOS, CHECKIN, 'FOG_ENABLE_SHOW_PASSWORDS', 'FOG_AGENT_ENROLL_DEPLOY_WINDOW', 'schema']; const RUN = crypto.randomBytes(3).toString('hex'); const PREFIX = 'mset' + RUN; const PASSWORD = 'mocha-settings-pw'; @@ -70,7 +72,8 @@ describe('FOG Settings page::', function () { assert.ok(start !== -1 && end > start, 'the page has no settings card'); return html.slice(start, end); }; - const selects = (html) => card(html).match(/]*>/g) || []; + // Every control of the card: a select, or a number or checkbox input. + const controls = (html) => card(html).match(/<(?:select|input)\b[^>]*\sname="FOG_[^>]*>/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. @@ -126,7 +129,32 @@ describe('FOG Settings page::', function () { 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(`]*id="FOG_AGENT_ENROLL_DEPLOY_WINDOW"[^>]*value="12"/.test(html), 'no number input with 12'); + assert.ok(/]*id="FOG_ENABLE_SHOW_PASSWORDS"[^>]*\schecked/.test(html), 'the checkbox is not checked'); + await Setting().destroy({name: 'FOG_ENABLE_SHOW_PASSWORDS'}); + const off = card((await admin.agent.get('/about/settings').set(...HTML).expect(200)).text); + assert.ok(/]*id="FOG_ENABLE_SHOW_PASSWORDS"/.test(off) && !/]*id="FOG_ENABLE_SHOW_PASSWORDS"[^>]*\schecked/.test(off), 'the checkbox is checked with no record'); + } finally { + await restore('FOG_ENABLE_SHOW_PASSWORDS'); + await restore('FOG_AGENT_ENROLL_DEPLOY_WINDOW'); } }); @@ -147,15 +175,15 @@ describe('FOG Settings page::', function () { it('disables every control for a user with setting.read but not setting.update', async () => { const res = await reader.agent.get('/about/settings').set(...HTML).expect(200); - const found = selects(res.text); + const found = controls(res.text); assert.strictEqual(found.length, Object.keys(sails.config.fogSettings).length); found.forEach((tag) => assert.ok(/\sdisabled(\s|>)/.test(tag), `not disabled: ${tag}`)); }); it('disables no control for an admin', async () => { const res = await admin.agent.get('/about/settings').set(...HTML).expect(200); - const found = selects(res.text); - assert.ok(found.length > 0, 'no select'); + const found = controls(res.text); + assert.ok(found.length > 0, 'no control'); found.forEach((tag) => assert.ok(!/\sdisabled(\s|>)/.test(tag), `disabled: ${tag}`)); }); @@ -210,6 +238,22 @@ describe('FOG Settings page::', function () { assert.strictEqual(await value(SCROLL), 'infinite'); }); + it('answers 400 for a SMBIOS mode that is not valid, and stores nothing', async () => { + await Setting().destroy({name: SMBIOS}); + const res = await save(admin, {key: SMBIOS, value: 'sideways'}).expect(400); + assert.deepStrictEqual(res.body, {error: `${SMBIOS} value is not valid`, title: 'Settings Update Fail'}); + assert.strictEqual(await Setting().count({name: SMBIOS}), 0); + }); + + it('stores a number and a checkbox value, normalized', async () => { + await save(admin, {key: CHECKIN, value: 120}).expect(202); + assert.strictEqual(await value(CHECKIN), 120); + await save(admin, {key: 'FOG_ENABLE_SHOW_PASSWORDS', value: 1}).expect(202); + assert.strictEqual(await value('FOG_ENABLE_SHOW_PASSWORDS'), true); + await save(admin, {key: 'FOG_ENABLE_SHOW_PASSWORDS', value: 0}).expect(202); + assert.strictEqual(await value('FOG_ENABLE_SHOW_PASSWORDS'), false); + }); + it('answers 400 for a key that is not in the catalog, and stores nothing', async () => { for (const key of ['FOG_MOCHA_NOPE', 'constructor']) { const res = await save(admin, {key, value: 'x'}).expect(400); diff --git a/tools/smoke/checks/fog-settings.js b/tools/smoke/checks/fog-settings.js index 2d1f9dd..35b8e9b 100644 --- a/tools/smoke/checks/fog-settings.js +++ b/tools/smoke/checks/fog-settings.js @@ -9,12 +9,20 @@ * the success and "Reload required" toasts, and /hosts then shows the paged * bar; a refused save (400, answered by page.route()) puts the select back * and toasts the error; and at 600px a panel title collapses its panel. + * Issue #201 adds: a cleared FOG_AGENT_ENROLL_DEPLOY_WINDOW number field + * sends no request, toasts "Enter a number." and shows the stored value + * again; and ticking FOG_ENABLE_SHOW_PASSWORDS saves true, so /users/create + * then shows the password reveal control. * tools/smoke/ui.js runs this file (see the comment at its top). * + * "FOG Agent" sorts first, so it is the active panel on load. A step that + * acts on a row of another category clicks that category's nav pill first. + * * It runs before ui16-06-tables.js (file-name order), which POSTs its own * FOG_TABLE_SCROLL_MODE record, and Setting.name is unique. So it records - * that record first, and in a `finally` puts its value back, or deletes it - * when there was none. + * the records it touches first (FOG_TABLE_SCROLL_MODE, + * FOG_ENABLE_SHOW_PASSWORDS, FOG_AGENT_ENROLL_DEPLOY_WINDOW), and in a + * `finally` puts each value back, or deletes the record when there was none. */ const expect = (what, actual, expected) => { @@ -29,27 +37,35 @@ const KEY = 'FOG_TABLE_SCROLL_MODE'; const SAVE = '/api/v1/setting/save'; const TOAST = '#fog-toast-container .toast.fog-toast'; const RELOAD_TEXT = 'This setting takes effect after you reload the page.'; +const WINDOW = 'FOG_AGENT_ENROLL_DEPLOY_WINDOW'; +const PASSWORDS = 'FOG_ENABLE_SHOW_PASSWORDS'; +// The records this check touches, each put back in the `finally`. +const NAMES = [KEY, PASSWORDS, WINDOW]; +const VIEW_PILL = '#settings-nav a[data-cat="FOG View Settings"]'; + +// The next save response. Start it before the change that sends the save. +const saveResponse = (page) => page.waitForResponse((r) => new URL(r.url()).pathname === SAVE && r.request().method() === 'POST', {timeout: 10000}); -// The FOG_TABLE_SCROLL_MODE record, or null. GET /api/v1/setting lists every +// The record of `name`, or null. GET /api/v1/setting lists every // record (general/list), so the name is matched here. -async function scrollRecord(page, base) { +async function settingRecord(page, base, name) { const res = await page.request.get(`${base}/api/v1/setting`, {headers: AJAX}); if (res.status() !== 200) throw new Error(`GET /api/v1/setting answered ${res.status()}`); - return (await res.json()).find((row) => row.name === KEY) || null; + return (await res.json()).find((row) => row.name === name) || null; } -// Puts the record back as `was` found it: the old value, or no record. -async function restore(page, base, was) { - const now = await scrollRecord(page, base); +// Puts the record of `name` back as `was` found it: the old value, or no record. +async function restore(page, base, name, was) { + const now = await settingRecord(page, base, name); let res; if (was && now) { res = await page.request.put(`${base}/api/v1/setting/${now.id}`, {headers: AJAX, data: {value: was.value}}); } else if (was) { - res = await page.request.post(`${base}/api/v1/setting`, {headers: AJAX, data: {name: KEY, value: was.value}}); + res = await page.request.post(`${base}/api/v1/setting`, {headers: AJAX, data: {name, value: was.value}}); } else if (now) { res = await page.request.delete(`${base}/api/v1/setting`, {headers: AJAX, data: {id: [now.id]}}); } - if (res && res.status() >= 400) throw new Error(`restoring ${KEY} answered ${res.status()}`); + if (res && res.status() >= 400) throw new Error(`restoring ${name} answered ${res.status()}`); } // The keys of the rows on screen. @@ -65,8 +81,8 @@ async function navAndSearch({page, checkPage}) { const active = await page.$$eval('.app-sidebar a.nav-link.active', (links) => links.map((a) => a.textContent.replace(/\s+/g, ' ').trim())); expect('the active sidebar links', active, ['FOG Configuration']); const nav = await page.$$eval('#settings-nav li', (items) => items.map((li) => [li.textContent.replace(/\s+/g, ' ').trim(), li.classList.contains('active')])); - expect('the category nav', nav, [['FOG View Settings 2', true]]); - expect('the rows on load', await visibleRows(page), ['FOG_TABLE_SCROLL_MODE', 'FOG_VIEW_DEFAULT_SCREEN']); + expect('the category nav', nav, [['FOG Agent 1', true], ['FOG Client 1', false], ['FOG View Settings 2', false], ['General Settings 2', false]]); + expect('the rows on load', await visibleRows(page), [WINDOW]); await page.fill('#settings-search', 'scroll'); expect('the rows for "scroll"', await visibleRows(page), ['FOG_TABLE_SCROLL_MODE']); @@ -84,7 +100,7 @@ async function navAndSearch({page, checkPage}) { await page.fill('#settings-search', 'zzz'); await page.click('#settings-nav a'); expect('the search box after a category click', await page.inputValue('#settings-search'), ''); - expect('the rows after a category click', await visibleRows(page), ['FOG_TABLE_SCROLL_MODE', 'FOG_VIEW_DEFAULT_SCREEN']); + expect('the rows after a category click', await visibleRows(page), [WINDOW]); expect('the no-match line after a category click', await page.locator('.settings-noresults').isVisible(), false); await checkPage(page, {path: '/about/settings?search=scroll'}); @@ -95,7 +111,9 @@ async function navAndSearch({page, checkPage}) { // "Paged" saves, toasts twice, and /hosts then pages. async function saveOnChange({page, checkPage}) { await checkPage(page, {path: '/about/settings'}); - const answer = page.waitForResponse((r) => new URL(r.url()).pathname === SAVE && r.request().method() === 'POST', {timeout: 10000}); + // FOG Agent is the active panel on load; the scroll mode is in this one. + await page.click(VIEW_PILL); + const answer = saveResponse(page); await page.selectOption(`#${KEY}`, 'paged'); const res = await answer; expect('the save status', res.status(), 202); @@ -110,6 +128,41 @@ async function saveOnChange({page, checkPage}) { await page.locator('div.dt-length select').waitFor({state: 'visible', timeout: 10000}); } +// A cleared number field sends no request, toasts "Enter a number." and shows +// the stored value again (Number('') is 0, which would disable the deploy +// shortcut). +async function emptyNumber({page, checkPage}) { + await checkPage(page, {path: '/about/settings'}); + const stored = await page.inputValue(`#${WINDOW}`); + const posts = []; + const onRequest = (r) => { if (new URL(r.url()).pathname === SAVE) posts.push(r.method()); }; + page.on('request', onRequest); + try { + await page.fill(`#${WINDOW}`, ''); + await page.press(`#${WINDOW}`, 'Tab'); + expect('the error toast title', await toastTitle(page, 'Enter a number.'), 'Settings Update Fail'); + expect('the number field after the empty change', await page.inputValue(`#${WINDOW}`), stored); + // A request would be in flight by now: the toast comes after the change handler. + expect('the save requests after an empty number', posts, []); + } finally { + page.off('request', onRequest); + } +} + +// Ticking FOG_ENABLE_SHOW_PASSWORDS saves 1 (stored true), and the create +// form of a user then shows the password reveal control. +async function checkbox({page, checkPage}) { + await checkPage(page, {path: '/about/settings'}); + await page.click('#settings-nav a[data-cat="General Settings"]'); + const answer = saveResponse(page); + await page.check(`#${PASSWORDS}`); + const res = await answer; + expect('the checkbox save status', res.status(), 202); + expect('the checkbox save body', res.request().postDataJSON(), {key: PASSWORDS, value: 1}); + await checkPage(page, {path: '/users/create'}); + expect('the password reveal controls', (await page.locator('.fogpasswordeye').count()) > 0, true); +} + // A refused save puts the select back; at 600px a panel title collapses its // panel. A context of its own: the refused save is a 400 and a console // error, and either fails a check on ctx.page. @@ -121,6 +174,7 @@ async function refusedAndNarrow({browser, base, login}) { page.on('pageerror', (e) => errors.push(e.message)); await login(page); await page.goto(`${base}/about/settings`, {waitUntil: 'networkidle'}); + await page.click(VIEW_PILL); await page.route(`**${SAVE}`, (route) => route.fulfill({ status: 400, contentType: 'application/json', @@ -133,8 +187,9 @@ async function refusedAndNarrow({browser, base, login}) { await page.unroute(`**${SAVE}`); await page.setViewportSize({width: 600, height: 900}); - const body = page.locator('.settings-panel').first().locator('.settings-panel-body'); - const title = page.locator('.settings-panel-title').first(); + // The FOG View Settings panel is the active one, after the pill click. + const body = page.locator('.settings-panel[data-cat="FOG View Settings"] .settings-panel-body'); + const title = page.locator('.settings-panel-title[data-cat="FOG View Settings"]'); expect('the first panel body at 600px', await body.isVisible(), true); await title.click(); expect('the first panel body after a title click', await body.isVisible(), false); @@ -149,13 +204,20 @@ async function refusedAndNarrow({browser, base, login}) { module.exports = { name: 'fog-settings: FOG 1.6 FOG Settings page', run: async (ctx) => { - const was = await scrollRecord(ctx.page, ctx.base); + const was = {}; + for (const name of NAMES) { + was[name] = await settingRecord(ctx.page, ctx.base, name); + } try { await navAndSearch(ctx); await saveOnChange(ctx); + await emptyNumber(ctx); + await checkbox(ctx); await refusedAndNarrow(ctx); } finally { - await restore(ctx.page, ctx.base, was); + for (const name of NAMES) { + await restore(ctx.page, ctx.base, name, was[name]); + } } } }; diff --git a/views/pages/partials/settings.js b/views/pages/partials/settings.js index 924269b..63b116d 100644 --- a/views/pages/partials/settings.js +++ b/views/pages/partials/settings.js @@ -47,7 +47,7 @@ let fields = [ $row.attr('data-key') || '', $row.attr('data-description') || '', - String($row.find('.settings-control :input').val() || '').slice(0, 200) + String(current($row.find('.settings-control :input')) || '').slice(0, 200) ]; if ($row.is('[data-reload]')) { fields.push(RELOAD_WORDS); } return fields.some((field) => field.toLowerCase().indexOf(term) !== -1); @@ -80,33 +80,58 @@ $('.settings-noresults').toggleClass('d-none', anyVisible); } + // The current value of a control: a checkbox is true or false, any other + // control gives its text. 'saved' holds the last stored one. + function current($el) { + return $el.is(':checkbox') ? $el.prop('checked') : $el.val(); + } + function setCurrent($el, value) { + if ($el.is(':checkbox')) { $el.prop('checked', value); } else { $el.val(value); } + } + // Save one control. A good save remembers the value, toasts the server's // reply and, for a reload row, the reload reminder. A failed save puts the // control back to its last stored value and toasts the error. function save(el) { let $el = $(el); + let value = current($el); + if ($el.is(':checkbox')) { + // 1.6 JS:191-200 sends 1 or 0. + value = value ? 1 : 0; + } else if ($el.is('[type=number]')) { + // Send nothing for an empty or non-numeric field. Number('') is 0, so + // a cleared deploy-window field would otherwise switch off deploy + // auto-approval in one edit. The server's normalize() decides the rest. + let text = String(value).trim(); + if (text === '' || !Number.isFinite(Number(text))) { + setCurrent($el, $el.data('saved')); + window.fogToast('error', 'Enter a number.', 'Settings Update Fail'); + return; + } + value = Number(text); + } $.ajax({ url: '/api/v1/setting/save', type: 'POST', contentType: 'application/json', dataType: 'json', - data: JSON.stringify({key: el.name, value: $el.val()}), + data: JSON.stringify({key: el.name, value}), success: function(body) { - $el.data('saved', $el.val()); + $el.data('saved', current($el)); window.fogToast('success', body.msg, body.title); if ($el.closest('.settings-row').is('[data-reload]')) { window.fogToast('info', 'This setting takes effect after you reload the page.', 'Reload required'); } }, error: function(xhr) { - $el.val($el.data('saved')); + setCurrent($el, $el.data('saved')); window.fogToast('error', window.fogErrorOf(xhr), (xhr.responseJSON && xhr.responseJSON.title) || 'Settings Update Fail'); } }); } $('#settings-content .settings-control :input').each(function() { - $(this).data('saved', $(this).val()); + $(this).data('saved', current($(this))); }).on('change', function() { save(this); }); diff --git a/views/pages/settings.ejs b/views/pages/settings.ejs index 8a40047..7025728 100644 --- a/views/pages/settings.ejs +++ b/views/pages/settings.ejs @@ -5,8 +5,9 @@ settings cache. Locals (api/controllers/pages/settings.js): categories - [{name, rows: [{key, description, reload, tip, options}]}], every row a - select, and canUpdate (false: every control is disabled). + [{name, rows: [{key, description, reload, tip, type, value, options}]}], + and canUpdate (false: every control is disabled). The type picks the + control: select (options), number (value) or checkbox (value true). The nav link carries the BS5 nav-link class beside the 1.6 li.active, so the active category paints as a pill. The row carries data-key, @@ -48,11 +49,17 @@
data-reload<% } %>>
+ <% if (row.type === 'number') { %> + disabled<% } %>> + <% } else if (row.type === 'checkbox') { %> + checked<% } %> autocomplete="off"<% if (!canUpdate) { %> disabled<% } %>> + <% } else { %> + <% } %>
<% }); %>