@jskit-ai/workspaces-core 0.2.26 → 0.2.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A role that grants a permission nothing requires is caught when the server starts, where before it silently left the role refused (`ACTION_PERMISSION_DENIED`) wherever the grant was meant to allow it, such as `crud.labels.patch` for the update operation. The new `WorkspaceRoleGrantsProvider` (`workspaces.role-grants`, which needs `runtime.logger`) compares each role's own grants with the permissions the registered actions, the routes' `permission` and the surface access policies require, and the new `roleCatalog.customPermissions`, a list of the permission names the application checks itself (a service, a row policy, the browser). A grant that covers none, an exact name, a `<prefix>.*` or a `*` placed where it matches nothing, is reported at the role that writes it with the name it probably meant: `Role "member" grants "crud.labels.patch", which no action requires; did you mean "crud.labels.update"?`. Outside production the server refuses to start; in production it starts and logs a warning, since such a grant gives nothing. An application whose roles grant a permission it checks only itself adds it to `customPermissions`. Without workspaces nothing is checked.
6
+
5
7
  - The realtime audience contributor answers a question about some scopes by reading only the memberships of the workspaces they name, with the new `workspaces.memberships.listActiveWorkspaceIdsByUserIdsAmong(userIds, workspaceIds, options)`, and reads nothing when they name no workspace (a publish to user rooms). Before, every publish read all the active memberships of every online actor.
6
8
  - **Breaking.** The members and invites lists answer one page at a time, and each page is one statement. Before this, they read every active membership or pending invite and sorted them in code.
7
9
  - `GET .../members` and `GET .../invites` (the `workspace.members.list` and `workspace.invites.list` actions) take `limit` (1 to 100, 20 when none) and `cursor`, the previous page's `nextCursor`. They answer the page with `nextCursor`, which is null on the last page.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.26",
3
+ "version": "0.2.28",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -23,9 +23,9 @@
23
23
  "./locales/en.json": "./locales/en.json"
24
24
  },
25
25
  "dependencies": {
26
- "@jskit-ai/resource-core": "0.1.209",
27
- "@jskit-ai/resource-crud-core": "0.1.210",
28
- "@jskit-ai/users-core": "0.2.26",
26
+ "@jskit-ai/resource-core": "0.1.210",
27
+ "@jskit-ai/resource-crud-core": "0.1.212",
28
+ "@jskit-ai/users-core": "0.2.28",
29
29
  "json-rest-schema": "^1.0.20"
30
30
  },
31
31
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
@@ -46,6 +46,7 @@
46
46
  "runtime.database",
47
47
  "runtime.env",
48
48
  "runtime.http",
49
+ "runtime.logger",
49
50
  "runtime.resources",
50
51
  "users.extensions",
51
52
  "users.profiles",
@@ -62,6 +63,10 @@
62
63
  {
63
64
  "entrypoint": "src/server/WorkspacesIntegrationsProvider.js",
64
65
  "export": "WorkspacesIntegrationsProvider"
66
+ },
67
+ {
68
+ "entrypoint": "src/server/WorkspaceRoleGrantsProvider.js",
69
+ "export": "WorkspaceRoleGrantsProvider"
65
70
  }
66
71
  ]
67
72
  },
@@ -206,10 +211,10 @@
206
211
  }
207
212
  },
208
213
  "peerDependencies": {
209
- "@jskit-ai/auth-core": "0.2.18",
210
- "@jskit-ai/database-runtime": "0.1.267",
211
- "@jskit-ai/http-runtime": "0.2.18",
212
- "@jskit-ai/kernel": "0.2.18",
213
- "@jskit-ai/resource-runtime": "0.2.22"
214
+ "@jskit-ai/auth-core": "0.2.19",
215
+ "@jskit-ai/database-runtime": "0.1.268",
216
+ "@jskit-ai/http-runtime": "0.2.19",
217
+ "@jskit-ai/kernel": "0.2.19",
218
+ "@jskit-ai/resource-runtime": "0.2.24"
214
219
  }
215
220
  }
@@ -34,6 +34,22 @@ the other palette fields) that new workspaces start with.
34
34
  Use workspace routes, resources, scope helpers, tenancy profiles, and settings
35
35
  contracts exported by `@jskit-ai/workspaces-core`.
36
36
 
37
+ ## Role permissions
38
+
39
+ A role's `permissions` grant names that something requires:
40
+
41
+ | Grant | Covers |
42
+ | --- | --- |
43
+ | `crud.<namespace>.list`, `.view`, `.create`, `.update`, `.delete` | A workspace CRUD operation; an HTTP `PATCH` is `update` |
44
+ | `crud.<namespace>.<action name>` | A custom CRUD action |
45
+ | `<prefix>.*`, `*` | Every required permission under the prefix; every permission |
46
+
47
+ At startup a grant that covers no permission an action, a route's `permission`
48
+ or a surface access policy requires stops the server outside production, with
49
+ a "did you mean"; production logs it. List a permission the application checks
50
+ itself (a service, a row policy, `access.can()`) in
51
+ `roleCatalog.customPermissions`.
52
+
37
53
  ## Role display labels
38
54
 
39
55
  Each `roleCatalog.roles[roleId]` definition may include an optional string
@@ -0,0 +1,58 @@
1
+ import { isProductionEnv } from "@jskit-ai/kernel/server/runtime/runtimeMode";
2
+ import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
3
+ import {
4
+ collectRequiredPermissions,
5
+ describeUnknownRoleGrants,
6
+ findUnknownRoleGrants
7
+ } from "./support/roleCatalogGrants.js";
8
+
9
+ /**
10
+ * Checks, once every feature has registered its actions and routes, that each grant of the workspace role catalogue
11
+ * covers a permission the application requires: an action's, a route's, a surface access policy's, or one the role
12
+ * catalogue's `customPermissions` declares. A grant such as `crud.labels.patch`, which no action requires, would
13
+ * otherwise leave a role silently refused (`ACTION_PERMISSION_DENIED`) where it was meant to be allowed. Outside
14
+ * production the server refuses to start; in production, where the grant gives nothing and costs nothing, it starts
15
+ * and logs a warning.
16
+ */
17
+ const WorkspaceRoleGrantsProvider = defineProvider({
18
+ id: "workspaces.role-grants",
19
+ requires: {
20
+ actions: "runtime.actions",
21
+ config: "runtime.config",
22
+ env: "runtime.env",
23
+ http: "runtime.http",
24
+ logger: "runtime.logger",
25
+ workspaces: "workspaces.core"
26
+ },
27
+ setup() {
28
+ return {};
29
+ },
30
+ /**
31
+ * @param {object} capabilities
32
+ * @param {import("@jskit-ai/kernel/server/types").ActionCatalogue} capabilities.actions
33
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} capabilities.config
34
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} capabilities.env
35
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
36
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} capabilities.logger
37
+ * @param {import("./types.js").WorkspacesCore} capabilities.workspaces
38
+ */
39
+ boot({ actions, config, env, http, logger, workspaces }) {
40
+ // Without workspaces there are no memberships, so no role's permissions reach a request.
41
+ if (!workspaces.enabled) {
42
+ return;
43
+ }
44
+ const required = collectRequiredPermissions({ actions: actions.listDefinitions(), routes: http.router.list(), config });
45
+ const findings = findUnknownRoleGrants(config, required);
46
+ if (findings.length === 0) {
47
+ return;
48
+ }
49
+ const message = describeUnknownRoleGrants(findings);
50
+ if (isProductionEnv(env)) {
51
+ logger.warn({ unknownRoleGrants: findings.map(({ roleId, grant }) => ({ roleId, grant })) }, message);
52
+ return;
53
+ }
54
+ throw new Error(message);
55
+ }
56
+ });
57
+
58
+ export { WorkspaceRoleGrantsProvider };
@@ -0,0 +1,232 @@
1
+ import { hasPermission, normalizePermissionList } from "@jskit-ai/kernel/shared/support";
2
+ import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
+
4
+ /** @typedef {import("@jskit-ai/kernel/server/types").RuntimeConfig} RuntimeConfig */
5
+
6
+ /**
7
+ * A grant that covers no required permission, at the role that writes it.
8
+ * @typedef {object} UnknownRoleGrant
9
+ * @property {string} roleId
10
+ * @property {string} grant
11
+ * @property {"unrequired" | "uncovered" | "pattern"} problem An exact name nothing requires, a `<prefix>.*` that
12
+ * covers nothing required, or a `*` placed where it matches nothing.
13
+ * @property {string[]} suggestions The grants it probably meant, nearest first; none when nothing is close.
14
+ */
15
+
16
+ // The CRUD operation a grant's last word usually means: an HTTP PATCH is the update operation, and so on.
17
+ const OPERATION_WORDS = Object.freeze({
18
+ patch: "update",
19
+ edit: "update",
20
+ put: "update",
21
+ modify: "update",
22
+ read: "view",
23
+ get: "view",
24
+ show: "view",
25
+ index: "list",
26
+ browse: "list",
27
+ add: "create",
28
+ new: "create",
29
+ post: "create",
30
+ insert: "create",
31
+ remove: "delete",
32
+ destroy: "delete"
33
+ });
34
+
35
+ // A misspelling this close to a required name (in single-character edits) is taken to mean it.
36
+ const NEAREST_DISTANCE = 2;
37
+ // A grant with no close match lists at most this many required names of its namespace.
38
+ const MAX_SIBLINGS = 6;
39
+
40
+ /**
41
+ * The permission names roleCatalog.customPermissions declares, which the application checks itself.
42
+ * @param {RuntimeConfig} config
43
+ * @returns {string[]}
44
+ */
45
+ function customPermissionNames(config) {
46
+ const declared = isRecord(config.roleCatalog) ? config.roleCatalog.customPermissions : undefined;
47
+ if (declared === undefined) {
48
+ return [];
49
+ }
50
+ const valid = Array.isArray(declared)
51
+ && declared.every((entry) => typeof entry === "string" && normalizeText(entry) && !entry.includes("*"));
52
+ if (!valid) {
53
+ throw new TypeError(
54
+ "roleCatalog.customPermissions must be a list of permission names (no \"*\"): the permissions the application " +
55
+ "checks itself, in a service, a row policy or the browser."
56
+ );
57
+ }
58
+ return normalizePermissionList(declared);
59
+ }
60
+
61
+ /**
62
+ * Every permission something in the application requires: each registered action's, each HTTP route's `permission`,
63
+ * each surface access policy's `requireAnyPermissions` and `requireAllPermissions`, and the role catalogue's
64
+ * `customPermissions`, which the application checks itself.
65
+ * @param {object} sources
66
+ * @param {ReadonlyArray<{ permission: { permissions: ReadonlyArray<string> } }>} sources.actions The registered action definitions.
67
+ * @param {ReadonlyArray<{ permission?: unknown }>} sources.routes The registered HTTP routes.
68
+ * @param {RuntimeConfig} sources.config
69
+ * @returns {Set<string>}
70
+ */
71
+ function collectRequiredPermissions({ actions, routes, config }) {
72
+ const required = new Set(customPermissionNames(config));
73
+ for (const definition of actions) {
74
+ for (const permission of definition.permission.permissions) required.add(permission);
75
+ }
76
+ for (const route of routes) {
77
+ for (const permission of normalizePermissionList(route.permission)) required.add(permission);
78
+ }
79
+ const policies = isRecord(config.surfaceAccessPolicies) ? Object.values(config.surfaceAccessPolicies) : [];
80
+ for (const policy of policies.filter(isRecord)) {
81
+ for (const permission of normalizePermissionList(policy.requireAnyPermissions)) required.add(permission);
82
+ for (const permission of normalizePermissionList(policy.requireAllPermissions)) required.add(permission);
83
+ }
84
+ return required;
85
+ }
86
+
87
+ /** The number of single-character insertions, deletions and substitutions that turn one text into the other. */
88
+ function editDistance(left, right) {
89
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
90
+ for (let row = 1; row <= left.length; row += 1) {
91
+ const current = [row];
92
+ for (let column = 1; column <= right.length; column += 1) {
93
+ const substitution = previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1);
94
+ current.push(Math.min(previous[column] + 1, current[column - 1] + 1, substitution));
95
+ }
96
+ previous = current;
97
+ }
98
+ return previous[right.length];
99
+ }
100
+
101
+ /** The candidate nearest the text within NEAREST_DISTANCE edits, the first in alphabetical order on a tie; else "". */
102
+ function nearest(text, candidates) {
103
+ let best = "";
104
+ let bestDistance = NEAREST_DISTANCE + 1;
105
+ // A length further apart than NEAREST_DISTANCE is never that close, so only the rest are measured.
106
+ const close = [...candidates].filter((candidate) => Math.abs(candidate.length - text.length) <= NEAREST_DISTANCE);
107
+ for (const candidate of close.sort()) {
108
+ const distance = editDistance(text, candidate);
109
+ if (distance < bestDistance) {
110
+ best = candidate;
111
+ bestDistance = distance;
112
+ }
113
+ }
114
+ return best;
115
+ }
116
+
117
+ /** Every dotted prefix of the required permissions: `crud` and `crud.labels` for `crud.labels.update`. */
118
+ function requiredNamespaces(required) {
119
+ const namespaces = new Set();
120
+ for (const permission of required) {
121
+ const words = permission.split(".");
122
+ for (let length = 1; length < words.length; length += 1) namespaces.add(words.slice(0, length).join("."));
123
+ }
124
+ return namespaces;
125
+ }
126
+
127
+ /**
128
+ * The required names an exact grant probably meant: its namespace's permission for the operation its last word
129
+ * usually means, else the nearest required name, else every required name of its namespace.
130
+ * @param {string} grant
131
+ * @param {Set<string>} required
132
+ */
133
+ function suggestPermissions(grant, required) {
134
+ const dot = grant.lastIndexOf(".");
135
+ const namespace = dot > 0 ? grant.slice(0, dot) : "";
136
+ const operation = namespace ? OPERATION_WORDS[grant.slice(dot + 1)] : undefined;
137
+ if (operation && required.has(`${namespace}.${operation}`)) {
138
+ return [`${namespace}.${operation}`];
139
+ }
140
+ const close = nearest(grant, required);
141
+ if (close) {
142
+ return [close];
143
+ }
144
+ if (!namespace) {
145
+ return [];
146
+ }
147
+ return [...required]
148
+ .filter((permission) => permission.startsWith(`${namespace}.`) && !permission.slice(dot + 1).includes("."))
149
+ .sort()
150
+ .slice(0, MAX_SIBLINGS);
151
+ }
152
+
153
+ /**
154
+ * One grant checked against the required permissions: null when it covers one, as hasPermission() reads a grant
155
+ * (`*` covers everything, even when nothing is required yet). Only a grant with a `*` can cover a name other than
156
+ * its own, so only those are compared with every required name.
157
+ * @param {string} grant
158
+ * @param {Set<string>} required
159
+ * @returns {Pick<UnknownRoleGrant, "problem" | "suggestions"> | null}
160
+ */
161
+ function checkGrant(grant, required) {
162
+ if (grant === "*" || required.has(grant)) {
163
+ return null;
164
+ }
165
+ if (grant.includes("*") && [...required].some((permission) => hasPermission([grant], permission))) {
166
+ return null;
167
+ }
168
+ if (grant.endsWith(".*") && !grant.slice(0, -2).includes("*")) {
169
+ const close = nearest(grant.slice(0, -2), requiredNamespaces(required));
170
+ return { problem: "uncovered", suggestions: close ? [`${close}.*`] : [] };
171
+ }
172
+ if (grant.includes("*")) {
173
+ return { problem: "pattern", suggestions: [] };
174
+ }
175
+ return { problem: "unrequired", suggestions: suggestPermissions(grant, required) };
176
+ }
177
+
178
+ /**
179
+ * The grants of the role catalogue's roles (`roleCatalog.roles.<id>.permissions`) that cover no required
180
+ * permission. Each is reported at the role that writes it, not at the roles that inherit it.
181
+ * @param {RuntimeConfig} config
182
+ * @param {Set<string>} required What collectRequiredPermissions() answers.
183
+ * @returns {UnknownRoleGrant[]}
184
+ */
185
+ function findUnknownRoleGrants(config, required) {
186
+ const roles = isRecord(config.roleCatalog) && isRecord(config.roleCatalog.roles) ? config.roleCatalog.roles : {};
187
+ const found = [];
188
+ for (const [roleId, role] of Object.entries(roles)) {
189
+ const grants = isRecord(role) ? normalizePermissionList(role.permissions) : [];
190
+ for (const grant of grants) {
191
+ const problem = checkGrant(grant, required);
192
+ if (problem) found.push({ roleId, grant, ...problem });
193
+ }
194
+ }
195
+ return found;
196
+ }
197
+
198
+ function quoted(names) {
199
+ return names.map((name) => `"${name}"`).join(", ");
200
+ }
201
+
202
+ /** @param {UnknownRoleGrant} finding */
203
+ function describeFinding({ roleId, grant, problem, suggestions }) {
204
+ const start = `Role "${roleId}" grants "${grant}"`;
205
+ if (problem === "pattern") {
206
+ return `${start}, which matches nothing: "*" stands alone or ends a grant as ".*".`;
207
+ }
208
+ const reason = problem === "uncovered" ? "which covers no permission an action requires" : "which no action requires";
209
+ if (suggestions.length === 0) {
210
+ return `${start}, ${reason}.`;
211
+ }
212
+ return `${start}, ${reason}; did you mean ${suggestions.length === 1 ? "" : "one of "}${quoted(suggestions)}?`;
213
+ }
214
+
215
+ /**
216
+ * What a startup error or warning says about the grants findUnknownRoleGrants() found: each grant, then how JSKIT
217
+ * names permissions.
218
+ * @param {ReadonlyArray<UnknownRoleGrant>} findings
219
+ */
220
+ function describeUnknownRoleGrants(findings) {
221
+ return [
222
+ "The workspace role catalogue (roleCatalog.roles) grants permissions that nothing in the application requires, " +
223
+ "so those roles lack the access that was meant:",
224
+ ...findings.map((finding) => `- ${describeFinding(finding)}`),
225
+ "A CRUD action requires crud.<namespace>.<operation>, where the operation is list, view, create, update or delete " +
226
+ "(an HTTP PATCH is update), and a custom CRUD action crud.<namespace>.<action name>. \"*\" grants every " +
227
+ "permission and \"<prefix>.*\" every permission under the prefix. List a permission the application checks " +
228
+ "itself (in a service, a row policy or the browser) in roleCatalog.customPermissions."
229
+ ].join("\n");
230
+ }
231
+
232
+ export { collectRequiredPermissions, describeUnknownRoleGrants, findUnknownRoleGrants };
@@ -0,0 +1,146 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import {
4
+ collectRequiredPermissions,
5
+ describeUnknownRoleGrants,
6
+ findUnknownRoleGrants
7
+ } from "../src/server/support/roleCatalogGrants.js";
8
+
9
+ function crudActions(namespace, operations = ["list", "view", "create", "update", "delete"]) {
10
+ return operations.map((operation) => ({
11
+ id: `crud.${namespace}.${operation}`,
12
+ permission: { require: "all", permissions: [`crud.${namespace}.${operation}`] }
13
+ }));
14
+ }
15
+
16
+ const ACTIONS = Object.freeze([
17
+ ...crudActions("labels"),
18
+ ...crudActions("issues"),
19
+ { id: "crud.issues.close", permission: { require: "all", permissions: ["crud.issues.close"] } },
20
+ { id: "workspace.settings.read", permission: { require: "any", permissions: ["workspace.settings.view", "workspace.settings.update"] } },
21
+ { id: "workspace.members.list", permission: { require: "all", permissions: ["workspace.members.view"] } },
22
+ { id: "workspace.member.remove", permission: { require: "all", permissions: ["workspace.members.manage"] } },
23
+ { id: "workspace.invite.create", permission: { require: "all", permissions: ["workspace.members.invite"] } },
24
+ { id: "workspace.workspaces.list", permission: { require: "authenticated", permissions: [] } }
25
+ ]);
26
+
27
+ function configWithRoles(roles, extra = {}) {
28
+ return { roleCatalog: { workspace: { defaultInviteRole: "member" }, roles, ...extra } };
29
+ }
30
+
31
+ function required(config, { actions = ACTIONS, routes = [] } = {}) {
32
+ return collectRequiredPermissions({ actions, routes, config });
33
+ }
34
+
35
+ function findings(roles, extra = {}, sources = {}) {
36
+ const config = configWithRoles(roles, extra);
37
+ return findUnknownRoleGrants(config, required(config, sources));
38
+ }
39
+
40
+ test("a grant no action requires is reported at its role, with the operation the grant meant", () => {
41
+ const found = findings({
42
+ owner: { permissions: ["*"] },
43
+ member: { assignable: true, permissions: ["crud.labels.list", "crud.labels.patch", "crud.issues.patch"] }
44
+ });
45
+
46
+ assert.deepEqual(found.map(({ roleId, grant, suggestions }) => ({ roleId, grant, suggestions })), [
47
+ { roleId: "member", grant: "crud.labels.patch", suggestions: ["crud.labels.update"] },
48
+ { roleId: "member", grant: "crud.issues.patch", suggestions: ["crud.issues.update"] }
49
+ ]);
50
+ const message = describeUnknownRoleGrants(found);
51
+ assert.match(message, /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u);
52
+ assert.match(message, /Role "member" grants "crud\.issues\.patch", which no action requires; did you mean "crud\.issues\.update"\?/u);
53
+ assert.match(message, /list, view, create, update or delete/u, "the message names the CRUD operations");
54
+ assert.match(message, /roleCatalog\.customPermissions/u, "the message says where an app-checked permission goes");
55
+ });
56
+
57
+ test("every form of grant that covers a required permission is valid", () => {
58
+ assert.deepEqual(findings({
59
+ owner: { permissions: ["*"] },
60
+ admin: { inherits: "member", permissions: ["crud.labels.*", "crud.*", "workspace.*", "crud.issues.close"] },
61
+ member: { assignable: true, permissions: ["crud.issues.update", "workspace.settings.view", "workspace.members.view"] }
62
+ }), []);
63
+ });
64
+
65
+ test("an owner granting everything is valid even when no action requires a permission", () => {
66
+ const config = configWithRoles({ owner: { permissions: ["*"] } });
67
+ assert.deepEqual(findUnknownRoleGrants(config, collectRequiredPermissions({ actions: [], routes: [], config })), []);
68
+ });
69
+
70
+ test("a route's permission, a surface access policy's permissions and the app's custom permissions are required too", () => {
71
+ const roles = {
72
+ member: {
73
+ assignable: true,
74
+ permissions: ["projects.view", "reports.export", "reports.audit", "bookings.view-all"]
75
+ }
76
+ };
77
+ const extra = { customPermissions: ["bookings.view-all"] };
78
+ const config = {
79
+ ...configWithRoles(roles, extra),
80
+ surfaceAccessPolicies: {
81
+ reports: { requireAnyPermissions: ["reports.export"], requireAllPermissions: ["reports.audit"] }
82
+ }
83
+ };
84
+ const routes = [{ method: "GET", path: "/api/w/:workspaceSlug/projects", permission: "projects.view" }, { method: "GET", path: "/api/health" }];
85
+
86
+ assert.deepEqual(findUnknownRoleGrants(config, collectRequiredPermissions({ actions: ACTIONS, routes, config })), []);
87
+ });
88
+
89
+ test("a wildcard that covers no required permission is reported with the prefix it meant", () => {
90
+ const found = findings({ member: { assignable: true, permissions: ["crud.lables.*", "billing.*"] } });
91
+
92
+ assert.deepEqual(found.map(({ grant, suggestions }) => ({ grant, suggestions })), [
93
+ { grant: "crud.lables.*", suggestions: ["crud.labels.*"] },
94
+ { grant: "billing.*", suggestions: [] }
95
+ ]);
96
+ const message = describeUnknownRoleGrants(found);
97
+ assert.match(message, /Role "member" grants "crud\.lables\.\*", which covers no permission an action requires; did you mean "crud\.labels\.\*"\?/u);
98
+ assert.match(message, /Role "member" grants "billing\.\*", which covers no permission an action requires\./u);
99
+ });
100
+
101
+ test("a wildcard anywhere but alone or at the end matches nothing and is reported", () => {
102
+ const found = findings({ member: { assignable: true, permissions: ["crud.*.view", "crud.labels*"] } });
103
+
104
+ assert.deepEqual(found.map(({ grant }) => grant), ["crud.*.view", "crud.labels*"]);
105
+ assert.match(describeUnknownRoleGrants(found), /Role "member" grants "crud\.\*\.view", which matches nothing: "\*" stands alone or ends a grant as "\.\*"\./u);
106
+ });
107
+
108
+ test("a misspelt grant is matched to the nearest required permission, else to its namespace's permissions", () => {
109
+ const found = findings({
110
+ member: { assignable: true, permissions: ["crud.lables.update", "workspace.members.edit", "workspace.settings.read", "reports.run"] }
111
+ });
112
+
113
+ assert.deepEqual(found.map(({ grant, suggestions }) => ({ grant, suggestions })), [
114
+ { grant: "crud.lables.update", suggestions: ["crud.labels.update"] },
115
+ { grant: "workspace.members.edit", suggestions: ["workspace.members.invite", "workspace.members.manage", "workspace.members.view"] },
116
+ { grant: "workspace.settings.read", suggestions: ["workspace.settings.view"] },
117
+ { grant: "reports.run", suggestions: [] }
118
+ ]);
119
+ const message = describeUnknownRoleGrants(found);
120
+ assert.match(message, /grants "workspace\.members\.edit", which no action requires; did you mean one of "workspace\.members\.invite", "workspace\.members\.manage", "workspace\.members\.view"\?/u);
121
+ assert.match(message, /grants "reports\.run", which no action requires\./u);
122
+ });
123
+
124
+ test("an inherited grant is reported once, at the role that writes it", () => {
125
+ const found = findings({
126
+ admin: { assignable: true, inherits: "member", permissions: ["crud.labels.delete"] },
127
+ member: { assignable: true, permissions: ["crud.labels.edit"] }
128
+ });
129
+
130
+ assert.deepEqual(found.map(({ roleId, grant }) => ({ roleId, grant })), [{ roleId: "member", grant: "crud.labels.edit" }]);
131
+ });
132
+
133
+ test("customPermissions holds permission names only", () => {
134
+ for (const customPermissions of ["bookings.view-all", [""], ["bookings.*"], ["*"], [42]]) {
135
+ const config = configWithRoles({ member: { permissions: [] } }, { customPermissions });
136
+ assert.throws(
137
+ () => collectRequiredPermissions({ actions: ACTIONS, routes: [], config }),
138
+ /roleCatalog\.customPermissions must be a list of permission names/u,
139
+ JSON.stringify(customPermissions)
140
+ );
141
+ }
142
+ });
143
+
144
+ test("an application without a role catalogue has nothing to report", () => {
145
+ assert.deepEqual(findUnknownRoleGrants({}, collectRequiredPermissions({ actions: ACTIONS, routes: [], config: {} })), []);
146
+ });
@@ -0,0 +1,93 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createSchema } from "json-rest-schema";
4
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
5
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
6
+ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
7
+ import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
8
+ import { WorkspaceRoleGrantsProvider } from "../src/server/WorkspaceRoleGrantsProvider.js";
9
+
10
+ const LabelsFeature = defineFeature({
11
+ id: "test.labels",
12
+ domain: "labels",
13
+ actions: () => ["list", "view", "create", "update", "delete"].map((operation) => ({
14
+ id: `crud.labels.${operation}`,
15
+ kind: operation === "list" || operation === "view" ? "query" : "command",
16
+ channels: ["api"],
17
+ surfaces: ["app"],
18
+ permission: { require: "all", permissions: [`crud.labels.${operation}`] },
19
+ input: { schema: createSchema({}), mode: "replace" },
20
+ execute: async () => null
21
+ }))
22
+ });
23
+
24
+ function memberGrants(permissions) {
25
+ return {
26
+ tenancyMode: "workspaces",
27
+ roleCatalog: {
28
+ workspace: { defaultInviteRole: "member" },
29
+ roles: {
30
+ owner: { permissions: ["*"] },
31
+ member: { assignable: true, permissions }
32
+ }
33
+ }
34
+ };
35
+ }
36
+
37
+ function captureLogger() {
38
+ const warnings = [];
39
+ const ignore = () => {};
40
+ return { warnings, logger: { debug: ignore, info: ignore, error: ignore, warn: (...args) => warnings.push(args) } };
41
+ }
42
+
43
+ function startRuntime({ config, env = {}, logger = captureLogger().logger, workspacesEnabled = true, routes = [] }) {
44
+ const workspaces = defineProvider({
45
+ id: "test.workspaces",
46
+ provides: { workspaces: "workspaces.core" },
47
+ setup: () => ({ workspaces: { enabled: workspacesEnabled } })
48
+ });
49
+ const runtime = createCapabilityRuntime({
50
+ inputs: {
51
+ "runtime.config": config,
52
+ "runtime.env": env,
53
+ "runtime.http": { router: { list: () => routes } },
54
+ "runtime.logger": logger
55
+ },
56
+ providers: [EventProvider, ActionProvider, LabelsFeature, workspaces, WorkspaceRoleGrantsProvider]
57
+ });
58
+ return runtime.start();
59
+ }
60
+
61
+ test("outside production the server refuses to start while a role grants a permission no action requires", async () => {
62
+ await assert.rejects(
63
+ startRuntime({ config: memberGrants(["crud.labels.list", "crud.labels.patch"]), env: { NODE_ENV: "test" } }),
64
+ /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u
65
+ );
66
+ await assert.rejects(
67
+ startRuntime({ config: memberGrants(["crud.labels.patch"]) }),
68
+ /crud\.labels\.patch/u,
69
+ "an unset NODE_ENV is development"
70
+ );
71
+ });
72
+
73
+ test("in production the server starts and logs the grant as a warning", async () => {
74
+ const { warnings, logger } = captureLogger();
75
+ await startRuntime({ config: memberGrants(["crud.labels.patch"]), env: { NODE_ENV: "production" }, logger });
76
+
77
+ assert.equal(warnings.length, 1);
78
+ assert.match(String(warnings[0].at(-1)), /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u);
79
+ });
80
+
81
+ test("a role catalogue whose grants each cover a required permission starts quietly", async () => {
82
+ const { warnings, logger } = captureLogger();
83
+ await startRuntime({
84
+ config: memberGrants(["crud.labels.update", "crud.labels.*", "projects.view"]),
85
+ routes: [{ method: "GET", path: "/api/w/:workspaceSlug/projects", permission: "projects.view" }],
86
+ logger
87
+ });
88
+ assert.deepEqual(warnings, []);
89
+ });
90
+
91
+ test("an application without workspaces uses no role catalogue, so nothing is checked", async () => {
92
+ await startRuntime({ config: memberGrants(["crud.labels.patch"]), workspacesEnabled: false });
93
+ });