From 68dcfd14fef672cc025cae3bc84385a24dcceacb Mon Sep 17 00:00:00 2001 From: Lauri Ojansivu Date: Sun, 22 Nov 2026 18:46:33 +0200 Subject: [PATCH] Admin Panel / Settings / Features: an unticked feature is refused on the server, not only hidden. An unticked feature hid its menus and nothing else: the Table, Chat, Email, Version Control and Scrum views' methods and publications still answered, setBoardView still stored a hidden view, and a client could still turn on a list policy, a commitment point, a WIP limit per person or a split list. models/lib/featureServerGates.js lists, for every catalog feature, its server paths, its write gates, or why it is display only. requireFeature / featureAllowed (server/lib/assistGate.js) refuse with feature-disabled and record the attempt in Admin Panel / Problems as Disabled setting; the Scrum methods are wrapped in one place, except the ones the card details, Board Settings and data recovery use too; Boards / Lists deny rules refuse turning a flow policy on; setCardFlow refuses Done here while split lists is off; setBoardView refuses a hidden view. Board Settings / Scrum settings follows the Scrum views tick, as it opens in the Sprints view. tests/featureServerGates.test.cjs fails when a catalog feature is undecided, or when a method or publication of a feature file does not ask the gate. Thanks to xet7 ! --- client/components/sidebar/sidebar.jade | 17 +- .../Settings-Enforced-On-Server.md | 38 +++- .../Features/Admin-Panel/Settings/Features.md | 5 +- models/lib/featureServerGates.js | 116 +++++++++++ models/lib/instanceFeatures.js | 3 + server/chatView.js | 5 + server/emailView.js | 7 + server/lib/assistGate.js | 35 ++++ server/lib/cardFlowMethod.js | 5 +- server/lib/tests/featureServerGates.tests.js | 86 ++++++++ server/lib/tests/index.js | 2 + server/models/users.js | 14 ++ server/permissions/boards.js | 15 ++ server/permissions/lists.js | 14 ++ server/scrum.js | 20 ++ server/tableViewCards.js | 3 + server/versionControlView.js | 4 + tests/boardMenuOrder.test.cjs | 5 +- tests/featureServerGates.test.cjs | 184 ++++++++++++++++++ 19 files changed, 567 insertions(+), 11 deletions(-) create mode 100644 models/lib/featureServerGates.js create mode 100644 server/lib/tests/featureServerGates.tests.js create mode 100644 tests/featureServerGates.test.cjs diff --git a/client/components/sidebar/sidebar.jade b/client/components/sidebar/sidebar.jade index e03403041c..3d1d3c9f1c 100644 --- a/client/components/sidebar/sidebar.jade +++ b/client/components/sidebar/sidebar.jade @@ -726,13 +726,16 @@ template(name="boardMenuPopup") //- Rules and its views are one group; the board's look starts below it. hr //- Scrum settings: how this board plans its work, above the group that - decides how the board looks, with a rule of its own between them. - ul.pop-over-list - li - a.js-open-board-scrum-settings - i.fa.fa-repeat - | {{_ 'scrum-settings'}} - hr + decides how the board looks, with a rule of its own between them. They + open in the Sprints view, so only while Admin Panel / Settings / Features + offers the Scrum views (the server refuses that view otherwise). + if allowFeature 'views-scrum' + ul.pop-over-list + li + a.js-open-board-scrum-settings + i.fa.fa-repeat + | {{_ 'scrum-settings'}} + hr ul.pop-over-list //- "Custom Fields" was here. The board's list of them is in the card's own menu now - Card menu / Custom Fields, whose Settings cog opens it - which diff --git a/docs/Features/Admin-Panel/Settings-Enforced-On-Server.md b/docs/Features/Admin-Panel/Settings-Enforced-On-Server.md index e4cc6eb667..131ccc89be 100644 --- a/docs/Features/Admin-Panel/Settings-Enforced-On-Server.md +++ b/docs/Features/Admin-Panel/Settings-Enforced-On-Server.md @@ -51,6 +51,27 @@ Nothing to turn on: every setting below is enforced as soon as it is saved. | (always) The last site administrator | Deleting or anonymizing your own account when you are the only site administrator - it used to skip the check that deleting somebody else had. Not recorded: the buttons are there, so it is ordinary use. | - | | People / Login: Username Change unticked | A direct client write of your own `username` (`Users.update`), the way round the `setUsername` method, which already refused. E-mail addresses are never written that way. | Disabled setting | +**Admin Panel / Settings / Features** + +An unticked feature is hidden, and the server paths of that feature refuse it: +a method answers `feature-disabled`, a publication sends nothing. It is still +never a permission - a feature that is on grants nobody a board - and its data +is kept. A site administrator previewing features, and a pilot user, may use +it, as they see it. + +| Feature | What the server refuses while it is off | Problems | +| --- | --- | --- | +| Table view | `tableViewAddCard`; choosing the view (`setBoardView`). | Disabled setting | +| Chat view | `chatViewChannels`, `chatViewBoardChannels`, the `chatViewCardComments` publication; choosing the view. | Disabled setting | +| Email view | `emailViewCount`, `sendBoardEmail`, the `emailViewPage` publication; choosing the view. | Disabled setting | +| Version Control view | `vcsCreateIssue`, `vcsSetIssueState`; choosing the view. | Disabled setting | +| Scrum views | Every Scrum method of the Sprints, Product backlog and report views (sprints, releases, events, a card's sprint, the sprint histories, Scrum import into a board); choosing the views. Not refused: `scrum.getBoardData` and `scrum.configure`, which the card details' Scrum fields use too, and the import and History recovery methods, which repair board data. Board Settings / Scrum settings is hidden too, since it opens in the Sprints view. | Disabled setting | +| Summary, Since your last visit, Rule suggestions | Their methods answer nothing (they did already). `boards.markVisited` keeps recording visits, so the list is right when the feature is on again. | - | +| Workload and capacity, Budget and billing | Every `workload*` and `billing*` method (they did already). | - | +| List policies, Commitment point, WIP limit per person, Split lists | A client write turning one on: the board's `allowsListPolicies`, `commitmentListId`, `personWipLimit`, `allowsSplitLists`, a list's `policy` or `split` (Boards / Lists deny rules); a card marked *Done here* (`setCardFlow`). Turning one off is always allowed. | Disabled setting | +| Every other board view (calendar, time, overview, Gantt, flow charts, map, website, column sets) | Choosing the view (`setBoardView`). Nothing else: they read the cards the board already publishes and write ordinary card fields. | Disabled setting | +| Search phrases, Daily standup timer, Retrospective board | Nothing - display only. A phrase becomes the search operators anybody may type; the timer runs in the browser and writes nothing; the retrospective board is an ordinary board anybody may make by hand. | - | + ## How the numbers are calculated Problems counts every refused call once in the row of its kind; the actor @@ -73,6 +94,17 @@ tally names the account (when the call had one) and the address it came from. [server/models/users.js](../../../server/models/users.js). The username write is a `Users.deny` rule in [server/permissions/users.js](../../../server/permissions/users.js). +- [models/lib/featureServerGates.js](../../../models/lib/featureServerGates.js) + lists every feature's server paths (`SERVER_PATHS`), the ones refused as + writes (`WRITE_GATED`) and the display-only ones with why (`DISPLAY_ONLY`). + [server/lib/assistGate.js](../../../server/lib/assistGate.js) + `requireFeature` / `featureAllowed` ask + [models/lib/instanceFeatures.js](../../../models/lib/instanceFeatures.js) + for the caller (feature profiles and previews included); the Scrum methods + are wrapped in one place in [server/scrum.js](../../../server/scrum.js), the + flow policies are deny rules in + [server/permissions/boards.js](../../../server/permissions/boards.js) and + [server/permissions/lists.js](../../../server/permissions/lists.js). - The Problems names are keys of [models/lib/securityCategories.js](../../../models/lib/securityCategories.js), recorded with `securityLog.record({ key, action: 'blocked', ... })`. @@ -82,4 +114,8 @@ tally names the account (when the call had one) and the address it came from. (a DDP and a REST sign-in refused on a running server); [tests/selfAccountRemoval.test.cjs](../../../tests/selfAccountRemoval.test.cjs) (the rule, and every server file that removes or anonymizes users asks it) - and [server/lib/tests/selfAccountRemoval.tests.js](../../../server/lib/tests/selfAccountRemoval.tests.js). + and [server/lib/tests/selfAccountRemoval.tests.js](../../../server/lib/tests/selfAccountRemoval.tests.js); + [tests/featureServerGates.test.cjs](../../../tests/featureServerGates.test.cjs) + (every catalog feature is decided, and every method and publication of a + feature file asks the gate, so a new one cannot skip it) and + [server/lib/tests/featureServerGates.tests.js](../../../server/lib/tests/featureServerGates.tests.js). diff --git a/docs/Features/Admin-Panel/Settings/Features.md b/docs/Features/Admin-Panel/Settings/Features.md index b43defb69e..a6aac25bd9 100644 --- a/docs/Features/Admin-Panel/Settings/Features.md +++ b/docs/Features/Admin-Panel/Settings/Features.md @@ -6,6 +6,8 @@ What this WeKan offers. Address: `/admin/settings/features`. Site administrators only. A site administrator turns optional features - board views, helpers, Kanban and Scrum tools, card fields, SQRL, ActivityPub, read-only Rules and the Optional APIs - on or off for the whole instance. An unticked feature is hidden, +and its server paths refuse it too +([Settings enforced on the server](../Settings-Enforced-On-Server.md)); it is never deleted, and no permission changes. Until 2026-11-19 these groups were part of Settings / Visibility (now [Appearance](Appearance.md)). @@ -48,7 +50,8 @@ Save. Who among your users sees a feature is decided one level down, by matches nobody. **Features.** Which optional features this WeKan offers. An unticked feature is -hidden from everyone's interface; its data is kept and no permission changes. +hidden from everyone's interface and refused by the server; its data is kept +and no permission changes. The catalog, in page order: Table view, Calendar views, Time views, Overview views, Gantt views, Scrum views, Flow charts, Map view, Email view, Chat view, Website view, Version Control view, Column sets, Rule suggestions, Summary, diff --git a/models/lib/featureServerGates.js b/models/lib/featureServerGates.js new file mode 100644 index 0000000000..8074ed9bbc --- /dev/null +++ b/models/lib/featureServerGates.js @@ -0,0 +1,116 @@ +'use strict'; + +// Admin Panel / Settings / Features (models/lib/instanceFeatures.js) on the +// SERVER (docs/Features/Admin-Panel/Settings-Enforced-On-Server.md). +// +// An unticked feature is hidden from the interface, and since 2026-11-22 the +// server paths of that feature refuse it too: a Meteor method answers +// 'feature-disabled', a publication sends nothing. It is still never a +// permission: a feature that is on grants nobody a board or an edit right, +// every path keeps its own access check. And its data is untouched, so +// enabling it again shows everything as it was. +// +// SERVER_PATHS is the list tests/featureServerGates.test.cjs holds the code +// to: every method and publication of a feature file must ask the gate +// (server/lib/assistGate.js requireFeature / featureAllowed / featureOnFor), +// or be in `exempt` with the reason it is not that feature's - so a method +// added to one of these files cannot skip the check. +// +// Features with no server path of their own are in DISPLAY_ONLY, with why. +// +// Pure CommonJS, no Meteor. + +const SERVER_PATHS = [ + { key: 'views-chat', file: 'server/chatView.js' }, + { key: 'views-email', file: 'server/emailView.js' }, + { key: 'views-version-control', file: 'server/versionControlView.js' }, + { key: 'views-table', file: 'server/tableViewCards.js' }, + { key: 'views-scrum', file: 'server/scrum.js', + exempt: { + 'scrum.getBoardData': 'also read by the card details Scrum fields (scrumFields.js), which are card fields', + 'scrum.configure': 'also called by Board Settings / Card for the Scrum fields\' visibility (sidebar.js, scrumFields.js)', + 'scrum.resumeImport': 'finishes an interrupted import: board data repair, whatever is on', + 'scrum.discardImport': 'discards an interrupted import: board data repair, whatever is on', + 'scrum.inspectHistoryCheckpoint': 'History recovery of a stopped undo (historyKeyRecovery.js), not the view', + 'scrum.resolveHistoryCheckpoint': 'History recovery of a stopped undo (historyKeyRecovery.js), not the view', + } }, + { key: 'board-summary', file: 'server/methods/boardSummary.js' }, + { key: 'since-last-visit', file: 'server/methods/sinceLastVisit.js', + exempt: { + 'boards.markVisited': 'records the visit on every board open and shows nothing, so the list is right the moment the feature is on again', + } }, + { key: 'rule-suggestions', file: 'server/methods/ruleSuggestions.js' }, + { key: 'workload', file: 'server/workload.js' }, + { key: 'billing', file: 'server/billing.js' }, +]; + +// Catalog features whose server side is a write of the board or a list +// (Boards.deny / Lists.deny in server/permissions/featureGates.js), or of a +// card's flow (server/lib/cardFlowMethod.js). +const WRITE_GATED = ['list-policies', 'commitment-point', 'person-wip-limit', 'split-lists']; + +// Catalog features with nothing to refuse on the server, and why. +const DISPLAY_ONLY = { + 'views-calendar': 'the calendar views read the board\'s published cards; nothing they show or write is theirs alone', + 'views-time': 'the time views read the published cards and write ordinary card dates', + 'views-overview': 'the overview views read the published cards only', + 'views-gantt': 'the Gantt views read the published cards and write ordinary card dates and dependencies', + 'views-flow-charts': 'the charts are computed in the browser from the published cards', + 'views-map': 'the map reads the published cards\' locations and writes ordinary card fields', + 'views-website': 'the website view renders the published cards in the browser', + 'views-column-sets': 'column sets are a layout of the published lists, kept in the browser', + 'search-phrases': 'a phrase is rewritten in the browser into the search operators anybody may type', + 'standup-timer': 'the timer runs in the browser only and writes nothing', + 'retrospective-board': 'it makes an ordinary board with four lists, which the user may create by hand anyway', +}; + +// The flow-policy board fields a client write turns ON, and their features. +// Turning one off ($unset, false, '') is always allowed: it is the cleanup. +// A board copied or imported on the server keeps them: those writes are the +// server's, not a client's. +const BOARD_FIELD_FEATURES = Object.freeze({ + allowsListPolicies: 'list-policies', + commitmentListId: 'commitment-point', + personWipLimit: 'person-wip-limit', + allowsSplitLists: 'split-lists', +}); +const LIST_FIELD_FEATURES = Object.freeze({ + policy: 'list-policies', + split: 'split-lists', +}); + +const turnsOn = value => value !== undefined && value !== null && value !== false && value !== '' && value !== 0; + +// The feature keys a Mongo modifier turns on through `fields`. +function featuresTurnedOn(modifier, fieldFeatures) { + const keys = new Set(); + if (!modifier || typeof modifier !== 'object') return []; + for (const [op, value] of Object.entries(modifier)) { + if (!value || typeof value !== 'object') continue; + if (op === '$rename') { + for (const target of Object.values(value)) if (fieldFeatures[target]) keys.add(fieldFeatures[target]); + continue; + } + if (op === '$unset') continue; + for (const [field, v] of Object.entries(value)) { + if (fieldFeatures[field] && (op !== '$set' || turnsOn(v))) keys.add(fieldFeatures[field]); + } + } + return [...keys]; +} + +const boardWriteFeatures = modifier => featuresTurnedOn(modifier, BOARD_FIELD_FEATURES); +const listWriteFeatures = modifier => featuresTurnedOn(modifier, LIST_FIELD_FEATURES); + +const FEATURE_DISABLED = Object.freeze({ error: 'feature-disabled', reason: 'This feature is turned off' }); + +module.exports = { + SERVER_PATHS, + WRITE_GATED, + DISPLAY_ONLY, + BOARD_FIELD_FEATURES, + LIST_FIELD_FEATURES, + boardWriteFeatures, + listWriteFeatures, + FEATURE_DISABLED, +}; diff --git a/models/lib/instanceFeatures.js b/models/lib/instanceFeatures.js index edf27b9f5b..587a650584 100644 --- a/models/lib/instanceFeatures.js +++ b/models/lib/instanceFeatures.js @@ -10,6 +10,9 @@ // What a disabled feature means: // * it is HIDDEN from the interface - its menu entries are not drawn, not // greyed out - and a user who had it open is moved to what remains; +// * its server paths REFUSE it too (models/lib/featureServerGates.js): the +// methods and publications of the feature answer 'feature-disabled' or +// nothing, so hiding is never the only thing that stops it; // * its data is untouched: enabling it again shows everything as it was; // * it never changes permissions: availability is not access, so enabling // a feature grants nobody a board, a card or an edit right. diff --git a/server/chatView.js b/server/chatView.js index 517716a393..8a78989c31 100644 --- a/server/chatView.js +++ b/server/chatView.js @@ -17,6 +17,8 @@ import Boards from '/models/boards'; import { ReactiveCache } from '/imports/reactiveCache'; import { visibleAllBoards } from '/server/allBoardsFacets'; const { notCurrentUser } = require('/server/lib/notCurrentUser'); +// Admin Panel / Settings / Features / Chat view (models/lib/featureServerGates.js). +import { requireFeature, featureAllowed } from '/server/lib/assistGate'; const { isAssignedOnlyMember } = require('/models/lib/boardCardScope'); @@ -69,6 +71,7 @@ async function assignedCardIds(boardIds, userId) { Meteor.methods({ async chatViewChannels() { if (!this.userId) throw new Meteor.Error('not-authorized'); + await requireFeature(this.userId, 'views-chat', 'ddp:chatViewChannels'); const { user, boards } = await visibleBoardsFor(this.userId); if (!user) return { boards: [], channels: [], swimlanes: [], lists: [] }; const talking = boards.filter(b => readsComments(b, this.userId)); @@ -114,6 +117,7 @@ Meteor.methods({ async chatViewBoardChannels(boardId) { check(boardId, String); if (!this.userId) throw new Meteor.Error('not-authorized'); + await requireFeature(this.userId, 'views-chat', 'ddp:chatViewBoardChannels'); const { boards } = await visibleBoardsFor(this.userId); const board = boards.find(b => b._id === boardId); if (!board) throw new Meteor.Error('not-authorized'); @@ -139,6 +143,7 @@ Meteor.methods({ Meteor.publish('chatViewCardComments', async function (cardId) { check(cardId, String); if (!this.userId) return this.ready(); + if (!(await featureAllowed(this.userId, 'views-chat', 'sub:chatViewCardComments'))) return this.ready(); const card = await Cards.findOneAsync(cardId, { fields: { boardId: 1, assignees: 1, members: 1 } }); const board = card && await Boards.findOneAsync(card.boardId); if (!board || !(await board.isVisibleBy({ _id: this.userId })) || !readsComments(board, this.userId)) return this.ready(); diff --git a/server/emailView.js b/server/emailView.js index f3b5fcbfb7..922bede033 100644 --- a/server/emailView.js +++ b/server/emailView.js @@ -18,6 +18,8 @@ import { Meteor } from 'meteor/meteor'; import { check, Match } from 'meteor/check'; import { Random } from 'meteor/random'; +// Admin Panel / Settings / Features / Email view (models/lib/featureServerGates.js). +import { requireFeature, featureAllowed } from '/server/lib/assistGate'; import { ReactiveCache } from '/imports/reactiveCache'; import Cards from '/models/cards'; import { cardCreation } from '/models/cards'; @@ -74,7 +76,9 @@ const OptionsPattern = { folder: String, page: Match.Optional(Number), search: M // client subscribes again when the board's card count moves, so new mail // still appears. Meteor.publish('emailViewPage', async function emailViewPage(boardId, options) { + check(boardId, String); check(options, OptionsPattern); + if (!(await featureAllowed(this.userId, 'views-email', 'sub:emailViewPage'))) return this.ready(); const board = await readableBoard(this.userId, boardId); if (!board) return this.ready(); const selector = await selectorFor(board, this.userId, options.folder, options.search); @@ -95,7 +99,9 @@ Meteor.publish('emailViewPage', async function emailViewPage(boardId, options) { Meteor.methods({ async emailViewCount(boardId, options) { + check(boardId, String); check(options, OptionsPattern); + await requireFeature(this.userId, 'views-email', 'ddp:emailViewCount'); const board = await readableBoard(this.userId, boardId); if (!board) throw new Meteor.Error('not-authorized'); const total = await Cards.find(await selectorFor(board, this.userId, options.folder, options.search)).countAsync(); @@ -110,6 +116,7 @@ Meteor.methods({ check(input, { to: [String], cc: Match.Optional([String]), subject: String, text: String, cardId: Match.Optional(String) }); const userId = this.userId; + await requireFeature(userId, 'views-email', 'ddp:sendBoardEmail'); const board = await ReactiveCache.getBoard(boardId); if (!userId || !board || !allowIsBoardMemberWithWriteAccess(userId, board)) throw new Meteor.Error('not-authorized'); let email; diff --git a/server/lib/assistGate.js b/server/lib/assistGate.js index 318751f5ce..1c17cf077c 100644 --- a/server/lib/assistGate.js +++ b/server/lib/assistGate.js @@ -1,3 +1,4 @@ +import { Meteor } from 'meteor/meteor'; import { ReactiveCache } from '/imports/reactiveCache'; import { canReadBoard } from '/models/lib/boardVisibility'; @@ -31,3 +32,37 @@ export async function featureOnFor(userId, key) { ]); return isFeatureAvailable(setting, user, key); } + +// The same question for a server path of an Admin Panel / Settings / Features +// entry (models/lib/featureServerGates.js SERVER_PATHS), answered for a +// signed-in caller. An off feature is refused and recorded: no screen offers +// its path then, only a page open from before the change or a crafted call +// reaches it. Without a login the path's own login check answers, as before. +export async function featureAllowed(userId, key, source) { + if (!userId) return true; + if (await featureOnFor(userId, key)) return true; + try { + require('/server/lib/securityLog').record({ + key: 'authz.disabled-setting', action: 'blocked', source, userId, + detail: `Admin Panel / Settings / Features: ${key} is turned off.`, + }); + } catch (e) { /* logging must never break the guard */ } + return false; +} + +// For a Meteor method: throws 'feature-disabled' when the feature is off. +export async function requireFeature(userId, key, source) { + if (await featureAllowed(userId, key, source)) return; + const { FEATURE_DISABLED } = require('/models/lib/featureServerGates'); + throw new Meteor.Error(FEATURE_DISABLED.error, FEATURE_DISABLED.reason); +} + +// For a Boards / Lists deny rule: true (deny) when a client write turns on a +// field of a feature that is off for this user (models/lib/featureServerGates.js +// boardWriteFeatures / listWriteFeatures). Recorded once per write. +export async function deniedByOffFeatures(userId, keys, source) { + for (const key of keys || []) { + if (!(await featureAllowed(userId, key, source))) return true; + } + return false; +} diff --git a/server/lib/cardFlowMethod.js b/server/lib/cardFlowMethod.js index ce16aaeb81..7c800e4cc0 100644 --- a/server/lib/cardFlowMethod.js +++ b/server/lib/cardFlowMethod.js @@ -36,8 +36,11 @@ export async function setCardFlowFor(userId, cardId, patch) { } catch (e) { throw new Meteor.Error(e.code || 'invalid-flow-patch'); } - // Done here only in a list split into Doing and Done. + // Done here only in a list split into Doing and Done, and only while + // Admin Panel / Settings / Features offers split lists: the minicard draws no + // Done here toggle otherwise (models/lib/featureServerGates.js). if (patch.splitDone === true) { + await require('/server/lib/assistGate').requireFeature(userId, 'split-lists', 'ddp:setCardFlow-splitDone'); const list = await Lists.findOneAsync(card.listId, { fields: { split: 1 } }); if (!list || list.split !== true) throw new Meteor.Error('not-a-split-list'); } diff --git a/server/lib/tests/featureServerGates.tests.js b/server/lib/tests/featureServerGates.tests.js new file mode 100644 index 0000000000..293a365580 --- /dev/null +++ b/server/lib/tests/featureServerGates.tests.js @@ -0,0 +1,86 @@ +/* eslint-env mocha */ +// Admin Panel / Settings / Features: with a feature unticked, the server paths +// of that feature refuse the call (models/lib/featureServerGates.js), and +// with it ticked they answer as before. +import assert from 'node:assert/strict'; +import { Meteor } from 'meteor/meteor'; +import { DDP } from 'meteor/ddp'; +import { Random } from 'meteor/random'; +import Settings from '/models/settings'; + +describe('Admin Panel features are refused on the server while off', function () { + this.timeout(30000); + let setting; + let savedStates; + const userId = Random.id(); + const adminId = Random.id(); + + const call = (uid, name, ...args) => { + const context = { userId: uid, isSimulation: false, connection: null, setUserId() {}, unblock() {} }; + return DDP._CurrentMethodInvocation.withValue(context, () => + Meteor.server.method_handlers[name].apply(context, args)); + }; + const turn = (key, on) => Settings.updateAsync(setting._id, { $set: { [`featureStates.${key}`]: on } }); + + before(async function () { + setting = await Settings.findOneAsync({}); + if (!setting) this.skip(); + savedStates = setting.featureStates; + await Meteor.users.rawCollection().insertMany([ + { _id: userId, username: `gate-${userId}`, profile: {} }, + // A site admin, without the preview: an off feature is off for them too. + { _id: adminId, username: `gate-admin-${adminId}`, isAdmin: true, profile: {} }, + ]); + }); + after(async function () { + if (setting) { + await Settings.updateAsync(setting._id, savedStates === undefined + ? { $unset: { featureStates: '' } } : { $set: { featureStates: savedStates } }); + } + await Meteor.users.removeAsync({ _id: { $in: [userId, adminId] } }); + }); + + const refused = async promise => assert.rejects(promise, err => err && err.error === 'feature-disabled'); + const notRefusedForTheFeature = async promise => { + try { await promise; } catch (err) { assert.notEqual(err && err.error, 'feature-disabled'); } + }; + + it('refuses the Table view, Chat view and Scrum view methods while their features are off', async function () { + await turn('views-table', false); + await turn('views-chat', false); + await turn('views-scrum', false); + await refused(call(userId, 'tableViewAddCard', { boardId: 'b', listId: 'l', swimlaneId: 's', title: 'x' })); + await refused(call(userId, 'chatViewChannels')); + await refused(call(adminId, 'chatViewChannels')); + await refused(call(userId, 'scrum.startSprint', 'b', 's', 0)); + }); + + it('keeps the Scrum methods the card details and recovery use (negative)', async function () { + await turn('views-scrum', false); + await notRefusedForTheFeature(call(userId, 'scrum.getBoardData', 'no-such-board')); + }); + + it('refuses choosing a board view whose feature is off, and allows Swimlanes', async function () { + await turn('views-table', false); + await refused(call(userId, 'setBoardView', 'board-view-table', null)); + const before = await Meteor.users.findOneAsync(userId); + assert.notEqual(before.profile && before.profile.boardView, 'board-view-table'); + await notRefusedForTheFeature(call(userId, 'setBoardView', 'board-view-swimlanes', null)); + }); + + it('answers as before while the features are on (negative)', async function () { + await turn('views-table', true); + await turn('views-chat', true); + await turn('views-scrum', true); + await notRefusedForTheFeature(call(userId, 'tableViewAddCard', { boardId: 'b', listId: 'l', swimlaneId: 's', title: 'x' })); + await notRefusedForTheFeature(call(userId, 'chatViewChannels')); + await notRefusedForTheFeature(call(userId, 'scrum.startSprint', 'b', 's', 0)); + await notRefusedForTheFeature(call(userId, 'setBoardView', 'board-view-table', null)); + }); + + it('leaves a logged-out call to the method\'s own login check (negative)', async function () { + await turn('views-table', false); + await assert.rejects(call(null, 'tableViewAddCard', { boardId: 'b', listId: 'l', swimlaneId: 's', title: 'x' }), + err => err && err.error === 'not-authorized'); + }); +}); diff --git a/server/lib/tests/index.js b/server/lib/tests/index.js index deb7a4b575..11af911689 100644 --- a/server/lib/tests/index.js +++ b/server/lib/tests/index.js @@ -158,3 +158,5 @@ import './webPush.tests'; import './passwordLoginDisabled.tests'; // Own account deletion follows the self delete setting on the server. import './selfAccountRemoval.tests'; +// Admin Panel / Settings / Features refused on the server while off. +import './featureServerGates.tests'; diff --git a/server/models/users.js b/server/models/users.js index 38081f13b1..224fedd3dd 100644 --- a/server/models/users.js +++ b/server/models/users.js @@ -1533,6 +1533,20 @@ Meteor.methods({ check(boardId, Match.Optional(Match.Maybe(String))); const user = await ReactiveCache.getCurrentUser(); if (!user) throw new Meteor.Error('not-authorized', 'Must be logged in'); + // A view of an Admin Panel / Settings / Features entry that is off for this + // user is not offered by the View menu, so choosing it is refused here too + // (models/lib/featureServerGates.js). The board then shows its fallback. + const { isBoardViewAvailable } = require('/models/lib/instanceFeatures'); + if (!isBoardViewAvailable(await ReactiveCache.getCurrentSetting(), user, view)) { + try { + require('/server/lib/securityLog').record({ + key: 'authz.disabled-setting', action: 'blocked', source: 'ddp:setBoardView', userId: user._id, + detail: `Admin Panel / Settings / Features: the board view ${view} is turned off.`, + }); + } catch (e) { /* logging must never break the guard */ } + const { FEATURE_DISABLED } = require('/models/lib/featureServerGates'); + throw new Meteor.Error(FEATURE_DISABLED.error, FEATURE_DISABLED.reason); + } // Must be awaited: the helper returns Users.updateAsync(...), so without await the // method resolves (and the client reloads) before profile.boardView is written — // and a rejected schema/write never surfaces. This made switching the board view diff --git a/server/permissions/boards.js b/server/permissions/boards.js index a84a3deeb9..0820fec143 100644 --- a/server/permissions/boards.js +++ b/server/permissions/boards.js @@ -225,3 +225,18 @@ Boards.deny({ }, fetch: [], }); + +// Admin Panel / Settings / Features: the list policies, the commitment point, +// the WIP limit per person and split lists are turned on per board in Board +// Settings / List, which shows each only while the instance offers it. A +// client write turning one on while it is off is refused +// (models/lib/featureServerGates.js); turning one off is always allowed. +Boards.deny({ + async update(userId, doc, fields, modifier) { + const { boardWriteFeatures } = require('/models/lib/featureServerGates'); + const keys = boardWriteFeatures(modifier); + if (!keys.length) return false; + return require('/server/lib/assistGate').deniedByOffFeatures(userId, keys, 'ddp:boards.update-flow-policy'); + }, + fetch: [], +}); diff --git a/server/permissions/lists.js b/server/permissions/lists.js index 68b806b038..2207097652 100644 --- a/server/permissions/lists.js +++ b/server/permissions/lists.js @@ -44,3 +44,17 @@ Lists.deny({ }, fetch: ['boardId'], }); + +// Admin Panel / Settings / Features: a list's policy text and its split into +// Doing and Done are written only while the instance offers them; the list +// header hides both otherwise (models/lib/featureServerGates.js). Clearing +// them is always allowed. +Lists.deny({ + async update(userId, doc, fields, modifier) { + const { listWriteFeatures } = require('/models/lib/featureServerGates'); + const keys = listWriteFeatures(modifier); + if (!keys.length) return false; + return require('/server/lib/assistGate').deniedByOffFeatures(userId, keys, 'ddp:lists.update-flow-policy'); + }, + fetch: [], +}); diff --git a/server/scrum.js b/server/scrum.js index 46b8b4ec23..5f76d01e1a 100644 --- a/server/scrum.js +++ b/server/scrum.js @@ -651,6 +651,26 @@ for (const kind of ['Card', 'List', 'Swimlane']) { return locked(boardId, () => updateMetadata(this.userId, kind.toLowerCase(), boardId, id, metadata, expectedRevision)); }; } +// Admin Panel / Settings / Features / Scrum views (models/lib/featureServerGates.js): +// every method of the Scrum view is refused while the feature is off, except +// the ones the card details, Board Settings and data recovery use too, which +// SERVER_PATHS lists with why. A method added above is gated by default. +{ + const { requireFeature } = require('/server/lib/assistGate'); + const scrumGate = require('/models/lib/featureServerGates').SERVER_PATHS.find(entry => entry.key === 'views-scrum'); + for (const name of Object.keys(methods)) { + if (Object.prototype.hasOwnProperty.call(scrumGate.exempt, name)) continue; + const method = methods[name]; + methods[name] = async function scrumViewGated(...args) { + // audit-argument-checks counts only the check() calls made before the + // first await, and the gate awaits: the method's own check() calls + // below still validate every argument and throw on a bad one. + check(args, [Match.Any]); + await requireFeature(this.userId, 'views-scrum', `ddp:${name}`); + return method.apply(this, args); + }; + } +} Meteor.methods(methods); DDPRateLimiter.addRule({ type: 'method', name: name => Object.prototype.hasOwnProperty.call(methods, name), connectionId: () => true }, 120, 60000); diff --git a/server/tableViewCards.js b/server/tableViewCards.js index 509d03b980..87d2369595 100644 --- a/server/tableViewCards.js +++ b/server/tableViewCards.js @@ -8,11 +8,14 @@ import Cards from '/models/cards'; import Lists from '/models/lists'; import Swimlanes from '/models/swimlanes'; import { canWriteInList } from '/server/lib/listPermissionGate'; +// Admin Panel / Settings / Features / Table view (models/lib/featureServerGates.js). +import { requireFeature } from '/server/lib/assistGate'; Meteor.methods({ async tableViewAddCard(input) { check(input, { boardId: String, listId: String, swimlaneId: String, title: String }); if (!this.userId) throw new Meteor.Error('not-authorized'); + await requireFeature(this.userId, 'views-table', 'ddp:tableViewAddCard'); const title = input.title.replace(/\s+/g, ' ').trim().slice(0, 1000); if (!title) throw new Meteor.Error('table-view-empty-title'); const board = await Boards.findOneAsync(input.boardId); diff --git a/server/versionControlView.js b/server/versionControlView.js index 4036d7cc5b..5ab2963d82 100644 --- a/server/versionControlView.js +++ b/server/versionControlView.js @@ -10,6 +10,8 @@ // Both write through the ordinary collections, not `.direct`, so the change // history hooks (server/models/changeHistoryHooks.js) record them and the // History tab - the board's history table - can undo them like any other move. +// Admin Panel / Settings / Features / Version Control view (models/lib/featureServerGates.js). +import { requireFeature } from '/server/lib/assistGate'; import { Meteor } from 'meteor/meteor'; import { check, Match } from 'meteor/check'; import { ReactiveCache } from '/imports/reactiveCache'; @@ -43,6 +45,7 @@ Meteor.methods({ check(boardId, String); check(input, { title: String, body: Match.Optional(String), labelIds: Match.Optional([String]) }); const userId = this.userId; + await requireFeature(userId, 'views-version-control', 'ddp:vcsCreateIssue'); const board = await writableBoard(userId, boardId); let issue; try { @@ -79,6 +82,7 @@ Meteor.methods({ check(cardId, String); check(state, Match.OneOf('open', 'closed')); const userId = this.userId; + await requireFeature(userId, 'views-version-control', 'ddp:vcsSetIssueState'); const card = await ReactiveCache.getCard(cardId); if (!card) throw new Meteor.Error('not-found'); const board = await writableBoard(userId, card.boardId); diff --git a/tests/boardMenuOrder.test.cjs b/tests/boardMenuOrder.test.cjs index 9769682eb5..0872497528 100644 --- a/tests/boardMenuOrder.test.cjs +++ b/tests/boardMenuOrder.test.cjs @@ -165,7 +165,10 @@ test('the reorder kept every guard (negative: nothing became visible to more peo assert.deepStrictEqual(guardsOf('js-open-board-date-settings'), [admin]); assert.deepStrictEqual(guardsOf('js-board-info-on-my-boards'), [admin]); assert.deepStrictEqual(guardsOf('js-open-board-list-settings'), ['if currentUser', admin]); - assert.deepStrictEqual(guardsOf('js-open-board-scrum-settings'), [admin]); + // 2026-11-22: Scrum settings open the Sprints view, which the server refuses + // while Admin Panel / Settings / Features turns the Scrum views off + // (models/lib/featureServerGates.js), so the entry follows that tick too. + assert.deepStrictEqual(guardsOf('js-open-board-scrum-settings'), [admin, "if allowFeature 'views-scrum'"]); assert.deepStrictEqual(guardsOf('js-open-board-card-settings'), ['if currentUser'], 'Card stays open to any board member for its personal Labels text row'); assert.deepStrictEqual(guardsOf('js-export-board'), ['if withApi', 'unless exportDisabled']); diff --git a/tests/featureServerGates.test.cjs b/tests/featureServerGates.test.cjs new file mode 100644 index 0000000000..23766441be --- /dev/null +++ b/tests/featureServerGates.test.cjs @@ -0,0 +1,184 @@ +'use strict'; + +// Admin Panel / Settings / Features: an unticked feature is refused on the +// SERVER, not only hidden (models/lib/featureServerGates.js, +// docs/Features/Admin-Panel/Settings-Enforced-On-Server.md). +// Run: node tests/featureServerGates.test.cjs + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); + +const ROOT = path.join(__dirname, '..'); +const read = rel => fs.readFileSync(path.join(ROOT, rel), 'utf8'); +const gates = require('../models/lib/featureServerGates'); +const { FEATURE_KEYS } = require('../models/lib/instanceFeatures'); + +let passed = 0; +function test(name, fn) { fn(); passed += 1; console.log(' ok -', name); } + +// The text of the block that opens at the first `{` from `from`, braces +// matched outside strings, template literals and comments. +function blockAt(src, from) { + const open = src.indexOf('{', from); + let depth = 0; + for (let i = open; i < src.length; i += 1) { + const c = src[i]; + if (c === '/' && src[i + 1] === '/') { i = src.indexOf('\n', i); continue; } + if (c === '/' && src[i + 1] === '*') { i = src.indexOf('*/', i) + 1; continue; } + if (c === '\'' || c === '"' || c === '`') { + for (i += 1; i < src.length && src[i] !== c; i += 1) if (src[i] === '\\') i += 1; + continue; + } + if (c === '{') depth += 1; + if (c === '}') { depth -= 1; if (depth === 0) return src.slice(open, i + 1); } + } + throw new Error('unbalanced block'); +} + +// Every Meteor method (two-space-indented `async name(` / `async 'name'(`) +// and every publication of a file, with its body. +function serverPathsOf(src) { + const out = []; + for (const m of src.matchAll(/^ {2}async '?([\w.]+)'?\s*\(/gm)) { + out.push({ kind: 'method', name: m[1], body: blockAt(src, src.indexOf(')', m.index)) }); + } + for (const m of src.matchAll(/Meteor\.publish\('([\w.]+)',\s*async function[^(]*\(/g)) { + out.push({ kind: 'publication', name: m[1], body: blockAt(src, src.indexOf(')', m.index)) }); + } + return out; +} + +// The file-local helpers that ask featureOnFor(…, key), e.g. workload's signedIn. +function gateHelpersOf(src, key) { + const names = []; + for (const m of src.matchAll(/^(?:async )?function (\w+)\s*\(/gm)) { + const body = blockAt(src, src.indexOf(')', m.index)); + if (body.includes(`featureOnFor(`) && body.includes(`'${key}'`)) names.push(m[1]); + } + return names; +} + +test('turning a flow policy ON is a feature write; turning it off never is', () => { + assert.deepStrictEqual(gates.boardWriteFeatures({ $set: { allowsListPolicies: true } }), ['list-policies']); + assert.deepStrictEqual(gates.boardWriteFeatures({ $set: { personWipLimit: 3, commitmentListId: 'l1' } }).sort(), + ['commitment-point', 'person-wip-limit']); + assert.deepStrictEqual(gates.boardWriteFeatures({ $set: { allowsSplitLists: true, title: 'x' } }), ['split-lists']); + assert.deepStrictEqual(gates.boardWriteFeatures({ $rename: { other: 'commitmentListId' } }), ['commitment-point']); + assert.deepStrictEqual(gates.listWriteFeatures({ $set: { policy: 'Done when tested' } }), ['list-policies']); + assert.deepStrictEqual(gates.listWriteFeatures({ $set: { split: true } }), ['split-lists']); +}); + +test('negative: cleanup and unrelated writes are never refused', () => { + assert.deepStrictEqual(gates.boardWriteFeatures({ $set: { allowsListPolicies: false, allowsSplitLists: false } }), []); + assert.deepStrictEqual(gates.boardWriteFeatures({ $unset: { commitmentListId: '', personWipLimit: '' } }), []); + assert.deepStrictEqual(gates.boardWriteFeatures({ $set: { title: 'Board', color: 'red' } }), []); + assert.deepStrictEqual(gates.listWriteFeatures({ $unset: { policy: '', split: '' } }), []); + assert.deepStrictEqual(gates.listWriteFeatures({ $set: { policy: '' } }), []); + for (const junk of [null, undefined, 'x', 1, [], { $set: null }]) { + assert.deepStrictEqual(gates.boardWriteFeatures(junk), []); + assert.deepStrictEqual(gates.listWriteFeatures(junk), []); + } +}); + +test('every catalog feature is decided: server paths, write gates, or display only with a reason', () => { + const decided = new Map(); + const mark = (key, where) => { + assert.ok(!decided.has(key), `${key} is both ${decided.get(key)} and ${where}`); + decided.set(key, where); + }; + gates.SERVER_PATHS.forEach(entry => mark(entry.key, 'SERVER_PATHS')); + gates.WRITE_GATED.forEach(key => mark(key, 'WRITE_GATED')); + Object.entries(gates.DISPLAY_ONLY).forEach(([key, reason]) => { + assert.ok(typeof reason === 'string' && reason.length >= 25, `${key}: give the reason it is display only`); + mark(key, 'DISPLAY_ONLY'); + }); + const unknown = [...decided.keys()].filter(key => !FEATURE_KEYS.includes(key)); + assert.deepStrictEqual(unknown, [], 'not catalog features'); + const undecided = FEATURE_KEYS.filter(key => !decided.has(key)); + assert.deepStrictEqual(undecided, [], + 'a new Admin Panel / Settings / Features entry must say what the server refuses for it ' + + '(models/lib/featureServerGates.js SERVER_PATHS / WRITE_GATED / DISPLAY_ONLY)'); +}); + +for (const entry of gates.SERVER_PATHS.filter(e => e.key !== 'views-scrum')) { + test(`${entry.key}: every method and publication of ${entry.file} asks the gate (negative, whole file)`, () => { + const src = read(entry.file); + const paths = serverPathsOf(src); + assert.ok(paths.length > 0, `${entry.file} has server paths`); + const helpers = gateHelpersOf(src, entry.key); + const exempt = entry.exempt || {}; + const missing = []; + for (const p of paths) { + if (exempt[p.name]) continue; + const direct = new RegExp(`(?:requireFeature|featureAllowed|featureOnFor)\\([^)]*'${entry.key}'`).test(p.body); + const viaHelper = helpers.some(name => new RegExp(`\\b${name}\\(`).test(p.body)); + if (!direct && !viaHelper) missing.push(`${p.kind} ${p.name}`); + } + assert.deepStrictEqual(missing, [], `these ${entry.key} paths do not ask the feature gate`); + for (const name of Object.keys(exempt)) { + assert.ok(paths.some(p => p.name === name), `${name} is exempt but not in ${entry.file}`); + } + }); +} + +test('the gate never comes before an argument check (audit-argument-checks counts only checks before the first await)', () => { + const late = []; + for (const entry of gates.SERVER_PATHS) { + for (const p of serverPathsOf(read(entry.file))) { + const at = p.body.search(/await (?:requireFeature|featureAllowed)\(/); + if (at >= 0 && /\bcheck\(/.test(p.body.slice(at))) late.push(`${entry.file} ${p.name}`); + } + } + assert.deepStrictEqual(late, []); +}); + +test('views-scrum: every Scrum method is wrapped by the gate unless exempt with a reason', () => { + const src = read('server/scrum.js'); + const entry = gates.SERVER_PATHS.find(e => e.key === 'views-scrum'); + const wrap = src.indexOf("const scrumGate = require('/models/lib/featureServerGates').SERVER_PATHS.find(entry => entry.key === 'views-scrum');"); + assert.ok(wrap > 0, 'the Scrum methods are wrapped'); + assert.ok(wrap < src.indexOf('Meteor.methods(methods);'), 'before they are registered'); + assert.match(src, /if \(Object\.prototype\.hasOwnProperty\.call\(scrumGate\.exempt, name\)\) continue;/); + assert.match(src, /check\(args, \[Match\.Any\]\);\n\s*await requireFeature\(this\.userId, 'views-scrum', `ddp:\$\{name\}`\);/); + const methods = serverPathsOf(src).map(p => p.name); + for (const [name, reason] of Object.entries(entry.exempt)) { + assert.ok(methods.includes(name), `${name} is exempt but not a Scrum method`); + assert.ok(reason.length >= 25, `${name}: give the reason`); + } + // The sprint lifecycle is the Scrum view's own: never exempt. + for (const name of ['scrum.startSprint', 'scrum.closeSprint', 'scrum.cancelSprint', 'scrum.getDailyHistory', + 'scrum.getScopeHistory', 'scrum.importIntoBoard']) { + assert.ok(!entry.exempt[name], `${name} must be gated`); + } +}); + +test('setBoardView refuses a board view whose feature is off', () => { + const users = read('server/models/users.js'); + const start = users.indexOf(' async setBoardView(view, boardId) {'); + const body = blockAt(users, users.indexOf(')', start)); + assert.ok(body.indexOf('isBoardViewAvailable(') < body.indexOf('user.setBoardView(')); + assert.match(body, /key: 'authz\.disabled-setting', action: 'blocked', source: 'ddp:setBoardView'/); +}); + +test('the flow policies: Boards and Lists deny turning them on, setCardFlow refuses Done here', () => { + assert.match(read('server/permissions/boards.js'), /boardWriteFeatures\(modifier\);[\s\S]*deniedByOffFeatures\(userId, keys, 'ddp:boards\.update-flow-policy'\)/); + assert.match(read('server/permissions/lists.js'), /listWriteFeatures\(modifier\);[\s\S]*deniedByOffFeatures\(userId, keys, 'ddp:lists\.update-flow-policy'\)/); + assert.match(read('server/lib/cardFlowMethod.js'), /requireFeature\(userId, 'split-lists', 'ddp:setCardFlow-splitDone'\)/); +}); + +test('the gate records an attempt, refuses with feature-disabled, and leaves logged-out calls to their own check', () => { + const src = read('server/lib/assistGate.js'); + const allowed = blockAt(src, src.indexOf(')', src.indexOf('export async function featureAllowed('))); + assert.match(allowed, /if \(!userId\) return true;/); + assert.match(allowed, /key: 'authz\.disabled-setting', action: 'blocked', source, userId/); + assert.match(src, /throw new Meteor\.Error\(FEATURE_DISABLED\.error, FEATURE_DISABLED\.reason\)/); + assert.strictEqual(gates.FEATURE_DISABLED.error, 'feature-disabled'); +}); + +test('Scrum settings in Board Settings follow the Scrum views tick', () => { + const jade = read('client/components/sidebar/sidebar.jade'); + assert.match(jade, /if allowFeature 'views-scrum'\n\s+ul\.pop-over-list\n\s+li\n\s+a\.js-open-board-scrum-settings/); +}); + +console.log(`\nfeatureServerGates: ${passed} passed`);