@jskit-ai/workspaces-core 0.2.27 → 0.2.29

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,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A workspace route that names no permission of its own, such as every CRUD route, reads its workspace context once per request instead of twice. The route visibility resolver read the workspace, the membership and the settings without the request, so the workspace action context contributor read them all again: a CRUD list sent six statements more than it needed (on SQLite, 13 statements where 7 do). The visibility resolver now passes the request, and both share the request's one resolution, as the auth policy and the action context already did. The same user, workspace, membership and permissions decide, with the same refusals: 401 signed out, 403 `workspaces.workspace.accessDenied` for a non-member, 404 `workspaces.workspace.notFound` for an unknown slug and 403 `ACTION_PERMISSION_DENIED` for a member without the permission.
6
+ - The unknown-grant refusal now says, right after the grants it reports, to search the application's own code for a permission before removing or renaming its grant (`hasPermission()`, `can()`, permission string checks, including names built in code such as `` `crud.${resource}.list` ``), since the check cannot see those; a permission the application checks goes in `roleCatalog.customPermissions`, and a grant is removed only when nothing uses it. Before, a reported grant that an application service still checked with `hasPermission()` read as dead, and removing it took that access from every role but the owner. The did-you-mean suggestions are unchanged, and the workspace-server pattern says the same.
7
+ - 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.
8
+
5
9
  - 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
10
  - **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
11
  - `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.27",
3
+ "version": "0.2.29",
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.211",
28
- "@jskit-ai/users-core": "0.2.27",
26
+ "@jskit-ai/resource-core": "0.1.210",
27
+ "@jskit-ai/resource-crud-core": "0.1.212",
28
+ "@jskit-ai/users-core": "0.2.29",
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.23"
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,24 @@ 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. The check cannot see a permission the
50
+ application checks itself (a service, a row policy, `access.can()`): before
51
+ removing or renaming a reported grant, search the code for it, including built
52
+ names such as `crud.${resource}.list`. List one the application checks in
53
+ `roleCatalog.customPermissions`; remove a grant only when nothing uses it.
54
+
37
55
  ## Role display labels
38
56
 
39
57
  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 };
@@ -52,10 +52,11 @@ function createWorkspaceRouteVisibilityResolver({ workspaceService, workspaceMem
52
52
  const activeSurfaceId = normalizeSurfaceId(
53
53
  request?.routeOptions?.config?.surface || context?.surface
54
54
  );
55
+ // With the request, this is the resolution the workspace action context contributor then reuses.
55
56
  const resolvedWorkspaceContext = await workspaceService.resolveWorkspaceContextForUserBySlug(
56
57
  actor,
57
58
  workspaceSlug,
58
- { requireMembership: !membershipOptionalSurfaceIds.has(activeSurfaceId) }
59
+ { requireMembership: !membershipOptionalSurfaceIds.has(activeSurfaceId), request }
59
60
  );
60
61
 
61
62
  return buildVisibilityContribution({
@@ -248,9 +248,9 @@ function createService({
248
248
  return returnJsonApiData(await workspacesRepository.updateById(workspaceContext.workspace.id, patch, options));
249
249
  }
250
250
 
251
- // The checks that run before a request's handler (its auth policy and its action context)
252
- // each need the request's workspace context. They pass the request and share one resolution
253
- // for the same user, slug and membership requirement, instead of reading the workspace, the
251
+ // The checks that run before a request's handler (its auth policy, its route visibility and its
252
+ // action context) each need the request's workspace context. They pass the request and share one
253
+ // resolution for the same user, slug and membership requirement, instead of reading the workspace, the
254
254
  // membership and the settings again for each check. A call without a request resolves on
255
255
  // its own.
256
256
  const requestWorkspaceContexts = new WeakMap();
@@ -0,0 +1,235 @@
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, what to do about a
217
+ * permission the application checks in its own code (which this check cannot see), then how JSKIT 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
+ "Before removing or renaming a grant, search the application's own code for that permission (hasPermission(), " +
226
+ "can(), permission string checks, including built names such as `crud.${resource}.list`), which this check " +
227
+ "cannot see. If the application checks it, list it in roleCatalog.customPermissions; remove it only when " +
228
+ "nothing uses it.",
229
+ "A CRUD action requires crud.<namespace>.<operation>, where the operation is list, view, create, update or delete " +
230
+ "(an HTTP PATCH is update), and a custom CRUD action crud.<namespace>.<action name>. \"*\" grants every " +
231
+ "permission and \"<prefix>.*\" every permission under the prefix."
232
+ ].join("\n");
233
+ }
234
+
235
+ export { collectRequiredPermissions, describeUnknownRoleGrants, findUnknownRoleGrants };
@@ -0,0 +1,154 @@
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
+ // The check cannot see a permission the app checks in its own code, so right after the findings the message says to
55
+ // look for one before removing a grant, and where it goes.
56
+ assert.equal(
57
+ message.split("\n")[3],
58
+ "Before removing or renaming a grant, search the application's own code for that permission (hasPermission(), " +
59
+ "can(), permission string checks, including built names such as `crud.${resource}.list`), which this check " +
60
+ "cannot see. If the application checks it, list it in roleCatalog.customPermissions; remove it only when " +
61
+ "nothing uses it."
62
+ );
63
+ });
64
+
65
+ test("every form of grant that covers a required permission is valid", () => {
66
+ assert.deepEqual(findings({
67
+ owner: { permissions: ["*"] },
68
+ admin: { inherits: "member", permissions: ["crud.labels.*", "crud.*", "workspace.*", "crud.issues.close"] },
69
+ member: { assignable: true, permissions: ["crud.issues.update", "workspace.settings.view", "workspace.members.view"] }
70
+ }), []);
71
+ });
72
+
73
+ test("an owner granting everything is valid even when no action requires a permission", () => {
74
+ const config = configWithRoles({ owner: { permissions: ["*"] } });
75
+ assert.deepEqual(findUnknownRoleGrants(config, collectRequiredPermissions({ actions: [], routes: [], config })), []);
76
+ });
77
+
78
+ test("a route's permission, a surface access policy's permissions and the app's custom permissions are required too", () => {
79
+ const roles = {
80
+ member: {
81
+ assignable: true,
82
+ permissions: ["projects.view", "reports.export", "reports.audit", "bookings.view-all"]
83
+ }
84
+ };
85
+ const extra = { customPermissions: ["bookings.view-all"] };
86
+ const config = {
87
+ ...configWithRoles(roles, extra),
88
+ surfaceAccessPolicies: {
89
+ reports: { requireAnyPermissions: ["reports.export"], requireAllPermissions: ["reports.audit"] }
90
+ }
91
+ };
92
+ const routes = [{ method: "GET", path: "/api/w/:workspaceSlug/projects", permission: "projects.view" }, { method: "GET", path: "/api/health" }];
93
+
94
+ assert.deepEqual(findUnknownRoleGrants(config, collectRequiredPermissions({ actions: ACTIONS, routes, config })), []);
95
+ });
96
+
97
+ test("a wildcard that covers no required permission is reported with the prefix it meant", () => {
98
+ const found = findings({ member: { assignable: true, permissions: ["crud.lables.*", "billing.*"] } });
99
+
100
+ assert.deepEqual(found.map(({ grant, suggestions }) => ({ grant, suggestions })), [
101
+ { grant: "crud.lables.*", suggestions: ["crud.labels.*"] },
102
+ { grant: "billing.*", suggestions: [] }
103
+ ]);
104
+ const message = describeUnknownRoleGrants(found);
105
+ assert.match(message, /Role "member" grants "crud\.lables\.\*", which covers no permission an action requires; did you mean "crud\.labels\.\*"\?/u);
106
+ assert.match(message, /Role "member" grants "billing\.\*", which covers no permission an action requires\./u);
107
+ });
108
+
109
+ test("a wildcard anywhere but alone or at the end matches nothing and is reported", () => {
110
+ const found = findings({ member: { assignable: true, permissions: ["crud.*.view", "crud.labels*"] } });
111
+
112
+ assert.deepEqual(found.map(({ grant }) => grant), ["crud.*.view", "crud.labels*"]);
113
+ assert.match(describeUnknownRoleGrants(found), /Role "member" grants "crud\.\*\.view", which matches nothing: "\*" stands alone or ends a grant as "\.\*"\./u);
114
+ });
115
+
116
+ test("a misspelt grant is matched to the nearest required permission, else to its namespace's permissions", () => {
117
+ const found = findings({
118
+ member: { assignable: true, permissions: ["crud.lables.update", "workspace.members.edit", "workspace.settings.read", "reports.run"] }
119
+ });
120
+
121
+ assert.deepEqual(found.map(({ grant, suggestions }) => ({ grant, suggestions })), [
122
+ { grant: "crud.lables.update", suggestions: ["crud.labels.update"] },
123
+ { grant: "workspace.members.edit", suggestions: ["workspace.members.invite", "workspace.members.manage", "workspace.members.view"] },
124
+ { grant: "workspace.settings.read", suggestions: ["workspace.settings.view"] },
125
+ { grant: "reports.run", suggestions: [] }
126
+ ]);
127
+ const message = describeUnknownRoleGrants(found);
128
+ 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);
129
+ assert.match(message, /grants "reports\.run", which no action requires\./u);
130
+ });
131
+
132
+ test("an inherited grant is reported once, at the role that writes it", () => {
133
+ const found = findings({
134
+ admin: { assignable: true, inherits: "member", permissions: ["crud.labels.delete"] },
135
+ member: { assignable: true, permissions: ["crud.labels.edit"] }
136
+ });
137
+
138
+ assert.deepEqual(found.map(({ roleId, grant }) => ({ roleId, grant })), [{ roleId: "member", grant: "crud.labels.edit" }]);
139
+ });
140
+
141
+ test("customPermissions holds permission names only", () => {
142
+ for (const customPermissions of ["bookings.view-all", [""], ["bookings.*"], ["*"], [42]]) {
143
+ const config = configWithRoles({ member: { permissions: [] } }, { customPermissions });
144
+ assert.throws(
145
+ () => collectRequiredPermissions({ actions: ACTIONS, routes: [], config }),
146
+ /roleCatalog\.customPermissions must be a list of permission names/u,
147
+ JSON.stringify(customPermissions)
148
+ );
149
+ }
150
+ });
151
+
152
+ test("an application without a role catalogue has nothing to report", () => {
153
+ assert.deepEqual(findUnknownRoleGrants({}, collectRequiredPermissions({ actions: ACTIONS, routes: [], config: {} })), []);
154
+ });
@@ -0,0 +1,182 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import Fastify from "fastify";
4
+ import { AuthExtensionsProvider } from "@jskit-ai/auth-core/server/providers/AuthExtensionsProvider";
5
+ import { AuthPolicyProvider } from "@jskit-ai/auth-core/server/providers/AuthPolicyProvider";
6
+ import { CrudContractsProvider } from "@jskit-ai/crud-core/server/crudContracts";
7
+ import { defineCrudFeature } from "@jskit-ai/crud-core/server/defineCrudFeature";
8
+ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
9
+ import { HttpProvider } from "@jskit-ai/kernel/server/http";
10
+ import { createBootstrapRuntime } from "@jskit-ai/kernel/server/runtime";
11
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
12
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
13
+ import { createPackageTestKnex, startTestFeatures } from "@jskit-ai/resource-runtime/test";
14
+ import { UsersExtensionsProvider } from "@jskit-ai/users-core/server/UsersExtensionsProvider";
15
+ import { UsersIdentityProvider } from "@jskit-ai/users-core/server/UsersIdentityProvider";
16
+ import { WorkspacesFeature } from "../src/server/WorkspacesFeature.js";
17
+ import { WorkspacesIntegrationsProvider } from "../src/server/WorkspacesIntegrationsProvider.js";
18
+ import { WORKSPACE_CRUD_SCOPE } from "../src/server/support/workspaceCrud.js";
19
+
20
+ // A workspace CRUD list served as an application serves it: Fastify, the auth policy plugin, the HTTP runtime's
21
+ // visibility resolvers, the action context contributors and a CRUD feature on a workspace surface, over the users and
22
+ // workspaces owners. Its route names no permission, so the auth policy resolves no workspace context; the action's
23
+ // context contributors do (the route visibility resolver for the scope, the workspace contributor for the permissions).
24
+
25
+ const issues = defineTableResource({
26
+ name: "issues",
27
+ tableName: "issues",
28
+ ownership: "workspace",
29
+ schema: {
30
+ workspaceId: { type: "id", storage: { column: "workspace_id" } },
31
+ title: { type: "string", required: true }
32
+ }
33
+ });
34
+
35
+ const IssuesFeature = defineCrudFeature({
36
+ crud: defineCrudContract(issues, {
37
+ namespace: "issues",
38
+ operations: ["list", "view"],
39
+ fields: { title: { output: "required" } }
40
+ }),
41
+ operations: ["list"],
42
+ surface: "app",
43
+ scope: WORKSPACE_CRUD_SCOPE
44
+ });
45
+
46
+ const config = Object.freeze({
47
+ appPublicUrl: "http://localhost:5173",
48
+ tenancyMode: "workspaces",
49
+ tenancyPolicy: { workspace: { allowSelfCreate: true } },
50
+ workspaceInvitations: { enabled: true },
51
+ workspaceMembers: { defaults: { inviteExpiresInMs: 86400000 } },
52
+ workspaceSettings: { defaults: { invitesEnabled: true } },
53
+ surfaceDefaultId: "app",
54
+ surfaceDefinitions: { app: { id: "app", requiresWorkspace: true, accessPolicyId: "workspace_member" } },
55
+ surfaceAccessPolicies: { workspace_member: { requireWorkspaceMembership: true } },
56
+ roleCatalog: {
57
+ workspace: { defaultInviteRole: "member" },
58
+ roles: {
59
+ owner: { permissions: ["*"] },
60
+ member: { assignable: true, permissions: ["crud.issues.list"] },
61
+ guest: { assignable: true, permissions: [] }
62
+ }
63
+ }
64
+ });
65
+
66
+ // The signed-in user is the profile the test names in a header, as a session would name it.
67
+ const headerAuthService = Object.freeze({
68
+ async authenticateRequest(request) {
69
+ const id = String(request.headers["x-test-user"] || "");
70
+ return id
71
+ ? { authenticated: true, actor: { id, email: `${id}@example.com`, displayName: id }, transientFailure: false }
72
+ : { authenticated: false, actor: null, transientFailure: false };
73
+ }
74
+ });
75
+
76
+ async function issuesApp(t) {
77
+ const knex = await createPackageTestKnex(t, { environment: process.env });
78
+ const app = Fastify();
79
+ t.after(() => app.close());
80
+ const started = await startTestFeatures({
81
+ knex,
82
+ createTables: true,
83
+ features: [
84
+ HttpProvider,
85
+ AuthExtensionsProvider,
86
+ AuthPolicyProvider,
87
+ UsersExtensionsProvider,
88
+ UsersIdentityProvider,
89
+ WorkspacesFeature,
90
+ WorkspacesIntegrationsProvider,
91
+ CrudContractsProvider,
92
+ IssuesFeature
93
+ ],
94
+ requires: { profiles: "users.profiles", workspaces: "workspaces.core", memberships: "workspaces.memberships" },
95
+ inputs: {
96
+ "auth.service": headerAuthService,
97
+ "runtime.app-root": process.cwd(),
98
+ "runtime.bootstrap": createBootstrapRuntime(),
99
+ "runtime.config": config,
100
+ "runtime.env": {},
101
+ "runtime.fastify": app
102
+ }
103
+ });
104
+ t.after(started.stop);
105
+ const { profiles, workspaces, memberships } = started.capabilities;
106
+ const person = (name) => profiles.upsert({
107
+ authProvider: "local",
108
+ authProviderUserSid: `identity-${name}`,
109
+ email: `${name}@example.com`,
110
+ displayName: name
111
+ });
112
+ const owner = await person("owner");
113
+ const member = await person("member");
114
+ const guest = await person("guest");
115
+ const outsider = await person("outsider");
116
+ const workspace = await workspaces.services.directory.ensurePersonalWorkspaceForUser(owner);
117
+ const other = await workspaces.services.directory.ensurePersonalWorkspaceForUser(outsider);
118
+ await memberships.addMember({ workspaceId: workspace.id, userId: member.id });
119
+ await memberships.addMember({ workspaceId: workspace.id, userId: guest.id, roleSid: "guest" });
120
+ await knex("issues").insert([
121
+ { workspace_id: workspace.id, title: "Door sticks" },
122
+ { workspace_id: workspace.id, title: "Lamp flickers" },
123
+ { workspace_id: other.id, title: "Another workspace's issue" }
124
+ ]);
125
+
126
+ async function list(user, slug = workspace.slug) {
127
+ const { result: response, queries } = await countQueries(knex, () => app.inject({
128
+ method: "GET",
129
+ url: `/api/w/${slug}/issues`,
130
+ headers: user ? { "x-test-user": user.id } : {}
131
+ }));
132
+ return { response, queries };
133
+ }
134
+ return { list, owner, member, guest, outsider, workspace };
135
+ }
136
+
137
+ // The statements of one read of the workspace context, whatever the database quotes its names with: the workspace by
138
+ // its slug, the actor's membership and the workspace's settings. (Reading a row also checks that the rows it refers to
139
+ // exist, a `select distinct id` of each, which these leave out.)
140
+ const quoted = (name) => `["\`]${name}["\`]`;
141
+ const CONTEXT_READS = Object.freeze({
142
+ workspace: new RegExp(`from ${quoted("workspaces")} where .*${quoted("slug")} =`, "u"),
143
+ membership: new RegExp(`from ${quoted("workspace_memberships")} where`, "u"),
144
+ settings: new RegExp(`from ${quoted("workspace_settings")} where`, "u"),
145
+ issues: new RegExp(`from ${quoted("issues")}`, "u")
146
+ });
147
+ const reading = (queries, read) => queries.filter((sql) => CONTEXT_READS[read].test(sql));
148
+
149
+ test("a workspace CRUD list request resolves its workspace, membership and settings once", async (t) => {
150
+ const { list, owner, member } = await issuesApp(t);
151
+
152
+ for (const user of [owner, member]) {
153
+ const { response, queries } = await list(user);
154
+ assert.equal(response.statusCode, 200, response.body);
155
+ assert.deepEqual(response.json().data.map((record) => record.attributes.title).sort(), ["Door sticks", "Lamp flickers"]);
156
+ const statements = queries.join("\n");
157
+ t.diagnostic(`a list request for the ${user === owner ? "owner" : "member"} sends ${queries.length} statements`);
158
+ // Before, the route visibility resolver read them for the scope and the workspace contributor again for the
159
+ // permissions: two of each.
160
+ assert.equal(reading(queries, "workspace").length, 1, statements);
161
+ assert.equal(reading(queries, "membership").length, 1, statements);
162
+ assert.equal(reading(queries, "settings").length, 1, statements);
163
+ assert.equal(reading(queries, "issues").length, 1, statements);
164
+ }
165
+ });
166
+
167
+ test("a workspace CRUD list request refuses as strictly as before", async (t) => {
168
+ const { list, guest, outsider, owner } = await issuesApp(t);
169
+
170
+ const refusals = [
171
+ ["signed out", await list(null), 401, "auth.session.required"],
172
+ ["not a member", await list(outsider), 403, "workspaces.workspace.accessDenied"],
173
+ ["a member without crud.issues.list", await list(guest), 403, "ACTION_PERMISSION_DENIED"],
174
+ ["an unknown workspace", await list(owner, "no-such-workspace"), 404, "workspaces.workspace.notFound"]
175
+ ];
176
+ for (const [label, { response, queries }, statusCode, code] of refusals) {
177
+ assert.equal(response.statusCode, statusCode, `${label}: ${response.body}`);
178
+ assert.equal(response.body.includes(code), true, `${label}: ${response.body}`);
179
+ assert.equal(reading(queries, "issues").length, 0, `${label} reads no issue: ${queries.join("\n")}`);
180
+ assert.ok(reading(queries, "workspace").length <= 1, `${label} reads the workspace at most once: ${queries.join("\n")}`);
181
+ }
182
+ });
@@ -0,0 +1,101 @@
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
+ (error) => {
65
+ assert.match(error.message, /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u);
66
+ assert.match(
67
+ error.message,
68
+ /Before removing or renaming a grant, search the application's own code for that permission \(hasPermission\(\)/u,
69
+ "the refusal says to look for the permission in the app's own code before removing the grant"
70
+ );
71
+ return true;
72
+ }
73
+ );
74
+ await assert.rejects(
75
+ startRuntime({ config: memberGrants(["crud.labels.patch"]) }),
76
+ /crud\.labels\.patch/u,
77
+ "an unset NODE_ENV is development"
78
+ );
79
+ });
80
+
81
+ test("in production the server starts and logs the grant as a warning", async () => {
82
+ const { warnings, logger } = captureLogger();
83
+ await startRuntime({ config: memberGrants(["crud.labels.patch"]), env: { NODE_ENV: "production" }, logger });
84
+
85
+ assert.equal(warnings.length, 1);
86
+ assert.match(String(warnings[0].at(-1)), /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u);
87
+ });
88
+
89
+ test("a role catalogue whose grants each cover a required permission starts quietly", async () => {
90
+ const { warnings, logger } = captureLogger();
91
+ await startRuntime({
92
+ config: memberGrants(["crud.labels.update", "crud.labels.*", "projects.view"]),
93
+ routes: [{ method: "GET", path: "/api/w/:workspaceSlug/projects", permission: "projects.view" }],
94
+ logger
95
+ });
96
+ assert.deepEqual(warnings, []);
97
+ });
98
+
99
+ test("an application without workspaces uses no role catalogue, so nothing is checked", async () => {
100
+ await startRuntime({ config: memberGrants(["crud.labels.patch"]), workspacesEnabled: false });
101
+ });
@@ -105,6 +105,7 @@ test("workspace route visibility honors membership-optional workspace surfaces",
105
105
  });
106
106
 
107
107
  assert.equal(calls[0].options.requireMembership, false);
108
+ assert.equal(calls[0].options.request, request, "The request's later workspace checks reuse this resolution");
108
109
  assert.deepEqual(contribution, {
109
110
  scopeKind: "workspace_user",
110
111
  requiresActorScope: true,