@jskit-ai/workspaces-core 0.2.28 → 0.2.30

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,9 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A test copy (`SIDE_EFFECTS` is not `live`) sends no invitation email: a provided invite mailer is replaced by one that logs the invitation and answers the new delivery status `simulated`, with "Test copy: the invitation email was not sent. Copy the invite link to share it." (`workspaces.invite.simulated`). The feature now requires `runtime.logger`.
6
+ - 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.
7
+ - 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.
5
8
  - 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
9
 
7
10
  - 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.
package/locales/en.json CHANGED
@@ -38,6 +38,7 @@
38
38
  "emailMismatchAccount": "Invitation email does not match account email.",
39
39
  "notAvailable": "Invitation is not available.",
40
40
  "mailerUnconfigured": "No workspace invite mailer is configured.",
41
+ "simulated": "Test copy: the invitation email was not sent. Copy the invite link to share it.",
41
42
  "sendFailed": "Unable to send workspace invite email.",
42
43
  "decisionRequired": "Decision is required.",
43
44
  "decisionInvalid": "Decision must be accept or refuse."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.28",
3
+ "version": "0.2.30",
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.210",
27
- "@jskit-ai/resource-crud-core": "0.1.212",
28
- "@jskit-ai/users-core": "0.2.28",
26
+ "@jskit-ai/resource-core": "0.1.211",
27
+ "@jskit-ai/resource-crud-core": "0.1.213",
28
+ "@jskit-ai/users-core": "0.2.30",
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.",
@@ -211,10 +211,10 @@
211
211
  }
212
212
  },
213
213
  "peerDependencies": {
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
+ "@jskit-ai/auth-core": "0.2.20",
215
+ "@jskit-ai/database-runtime": "0.1.269",
216
+ "@jskit-ai/http-runtime": "0.2.20",
217
+ "@jskit-ai/kernel": "0.2.20",
218
+ "@jskit-ai/resource-runtime": "0.2.25"
219
219
  }
220
220
  }
@@ -46,9 +46,11 @@ A role's `permissions` grant names that something requires:
46
46
 
47
47
  At startup a grant that covers no permission an action, a route's `permission`
48
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`.
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.
52
54
 
53
55
  ## Role display labels
54
56
 
@@ -1,4 +1,5 @@
1
1
  import { defineFeature } from "@jskit-ai/kernel/server/features";
2
+ import { sideEffectsAreLive } from "@jskit-ai/kernel/shared/support/sideEffects";
2
3
  import { createWorkspaceBootstrapContributor } from "./workspaceBootstrapContributor.js";
3
4
  import { registerWorkspaceDirectoryRoutes } from "./workspaceDirectory/workspaceDirectoryRoutes.js";
4
5
  import { createWorkspaceDirectoryActions } from "./workspaceDirectory/workspaceDirectoryActions.js";
@@ -8,6 +9,7 @@ import { registerWorkspacePendingInvitationsRoutes } from "./workspacePendingInv
8
9
  import { createWorkspacePendingInvitationsActions } from "./workspacePendingInvitations/workspacePendingInvitationsActions.js";
9
10
  import { registerWorkspaceSettingsRoutes } from "./workspaceSettings/workspaceSettingsRoutes.js";
10
11
  import { unconfiguredWorkspaceInviteMailer } from "./workspaceMembers/unconfiguredWorkspaceInviteMailer.js";
12
+ import { createSimulatedWorkspaceInviteMailer } from "./workspaceMembers/simulatedWorkspaceInviteMailer.js";
11
13
  import { renderDefaultWorkspaceInviteEmail } from "./workspaceMembers/defaultWorkspaceInviteEmail.js";
12
14
  import { noInviteAcceptanceParticipant } from "./workspacePendingInvitations/noInviteAcceptanceParticipant.js";
13
15
  import { noWorkspaceCreatedParticipant } from "./workspaceDirectory/noWorkspaceCreatedParticipant.js";
@@ -25,6 +27,7 @@ const WorkspacesFeature = defineFeature({
25
27
  config: "runtime.config",
26
28
  env: "runtime.env",
27
29
  http: "runtime.http",
30
+ logger: "runtime.logger",
28
31
  userProfiles: "users.profiles",
29
32
  userSettings: "users.settings"
30
33
  },
@@ -47,6 +50,7 @@ const WorkspacesFeature = defineFeature({
47
50
  * @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} capabilities.config
48
51
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} capabilities.env
49
52
  * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
53
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} capabilities.logger
50
54
  * @param {import("./types.js").WorkspaceInviteAcceptanceParticipant | null} capabilities.inviteAcceptanceParticipant
51
55
  * @param {import("./types.js").WorkspaceInviteEmailTemplate | null} capabilities.inviteEmailTemplate
52
56
  * @param {import("./types.js").WorkspaceInviteMailer | null} capabilities.inviteMailer
@@ -65,6 +69,7 @@ const WorkspacesFeature = defineFeature({
65
69
  inviteAcceptanceParticipant,
66
70
  inviteEmailTemplate,
67
71
  inviteMailer,
72
+ logger,
68
73
  personalWorkspaceName,
69
74
  resources,
70
75
  userProfiles,
@@ -78,7 +83,10 @@ const WorkspacesFeature = defineFeature({
78
83
  env,
79
84
  inviteAcceptanceParticipant: inviteAcceptanceParticipant ?? noInviteAcceptanceParticipant,
80
85
  inviteEmailTemplate: inviteEmailTemplate ?? renderDefaultWorkspaceInviteEmail,
81
- inviteMailer: inviteMailer ?? unconfiguredWorkspaceInviteMailer,
86
+ // A test copy (SIDE_EFFECTS is not live) logs the invitations a provided mailer would send, and sends none.
87
+ inviteMailer: inviteMailer
88
+ ? (sideEffectsAreLive(env) ? inviteMailer : createSimulatedWorkspaceInviteMailer(logger))
89
+ : unconfiguredWorkspaceInviteMailer,
82
90
  personalWorkspaceName: personalWorkspaceName ?? buildWorkspaceName,
83
91
  resources,
84
92
  userProfiles,
@@ -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();
@@ -213,8 +213,8 @@ function describeFinding({ roleId, grant, problem, suggestions }) {
213
213
  }
214
214
 
215
215
  /**
216
- * What a startup error or warning says about the grants findUnknownRoleGrants() found: each grant, then how JSKIT
217
- * names permissions.
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
218
  * @param {ReadonlyArray<UnknownRoleGrant>} findings
219
219
  */
220
220
  function describeUnknownRoleGrants(findings) {
@@ -222,10 +222,13 @@ function describeUnknownRoleGrants(findings) {
222
222
  "The workspace role catalogue (roleCatalog.roles) grants permissions that nothing in the application requires, " +
223
223
  "so those roles lack the access that was meant:",
224
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.",
225
229
  "A CRUD action requires crud.<namespace>.<operation>, where the operation is list, view, create, update or delete " +
226
230
  "(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."
231
+ "permission and \"<prefix>.*\" every permission under the prefix."
229
232
  ].join("\n");
230
233
  }
231
234
 
@@ -0,0 +1,29 @@
1
+ import { logSimulatedSideEffect } from "@jskit-ai/kernel/server/runtime/sideEffects";
2
+
3
+ /**
4
+ * The invite mailer of a test copy (SIDE_EFFECTS is not `live`) in place of the provided
5
+ * `workspaces.invite-mailer`: it emails nothing, logs the invitation's recipient, subject and link, and reports the
6
+ * delivery as simulated, so the inviter copies the link to share it.
7
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
8
+ * @returns {import("../types.js").WorkspaceInviteMailer}
9
+ */
10
+ function createSimulatedWorkspaceInviteMailer(logger) {
11
+ async function sendWorkspaceInvite({ email, inviteUrl, message }) {
12
+ logSimulatedSideEffect(logger, {
13
+ kind: "email",
14
+ summary: `the workspace invitation email to ${email}`,
15
+ details: { email, subject: String(message?.subject || ""), inviteUrl }
16
+ });
17
+ return {
18
+ status: "simulated",
19
+ message: "Test copy: the invitation email was not sent. Copy the invite link to share it.",
20
+ messageCode: "workspaces.invite.simulated",
21
+ messageParams: {},
22
+ providerMessageId: ""
23
+ };
24
+ }
25
+
26
+ return Object.freeze({ sendWorkspaceInvite });
27
+ }
28
+
29
+ export { createSimulatedWorkspaceInviteMailer };
@@ -14,7 +14,7 @@ const workspaceInviteAssistantOutput = createSchemaDefinition(createSchema({
14
14
  expiresAt: { type: "string", required: true }
15
15
  })
16
16
  },
17
- deliveryStatus: { type: "string", required: true, enum: ["sent", "failed", "mailer_unconfigured"] }
17
+ deliveryStatus: { type: "string", required: true, enum: ["sent", "simulated", "failed", "mailer_unconfigured"] }
18
18
  }), "replace");
19
19
 
20
20
  const pendingInvitationsAssistantOutput = createSchemaDefinition(createSchema({
@@ -120,7 +120,7 @@ const workspaceInviteCreateOutputSchema = createSchema({
120
120
  status: {
121
121
  type: "string",
122
122
  required: true,
123
- enum: ["sent", "failed", "mailer_unconfigured"]
123
+ enum: ["sent", "simulated", "failed", "mailer_unconfigured"]
124
124
  },
125
125
  message: {
126
126
  type: "string",
@@ -51,7 +51,15 @@ test("a grant no action requires is reported at its role, with the operation the
51
51
  assert.match(message, /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u);
52
52
  assert.match(message, /Role "member" grants "crud\.issues\.patch", which no action requires; did you mean "crud\.issues\.update"\?/u);
53
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");
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
+ );
55
63
  });
56
64
 
57
65
  test("every form of grant that covers a required permission is valid", () => {
@@ -0,0 +1,29 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createSimulatedWorkspaceInviteMailer } from "../src/server/workspaceMembers/simulatedWorkspaceInviteMailer.js";
4
+
5
+ test("a test copy's invite mailer sends nothing, logs the invitation and reports it simulated", async () => {
6
+ const logs = [];
7
+ const mailer = createSimulatedWorkspaceInviteMailer({
8
+ info: (details, message) => logs.push({ details, message }),
9
+ warn() {},
10
+ error() {},
11
+ debug() {}
12
+ });
13
+ const delivery = await mailer.sendWorkspaceInvite({
14
+ email: "guest@example.com",
15
+ inviteUrl: "https://app.example.test/invite?token=abc",
16
+ message: { subject: "You're invited to Books", text: "Join us", html: "<p>Join us</p>" }
17
+ });
18
+ assert.equal(delivery.status, "simulated");
19
+ assert.equal(delivery.messageCode, "workspaces.invite.simulated");
20
+ assert.equal(logs.length, 1);
21
+ assert.deepEqual(logs[0].details, {
22
+ sideEffects: "simulate",
23
+ kind: "email",
24
+ email: "guest@example.com",
25
+ subject: "You're invited to Books",
26
+ inviteUrl: "https://app.example.test/invite?token=abc"
27
+ });
28
+ assert.match(logs[0].message, /^Test copy: the workspace invitation email to guest@example\.com was simulated, not sent/u);
29
+ });
@@ -35,7 +35,7 @@ test("workspace members invite mutation outputs expose their tracking ids explic
35
35
  assert.deepEqual(inviteDeliverySchema.required, ["status", "message", "providerMessageId"]);
36
36
  assert.deepEqual(
37
37
  inviteDeliverySchema.properties.status.enum,
38
- ["sent", "failed", "mailer_unconfigured"]
38
+ ["sent", "simulated", "failed", "mailer_unconfigured"]
39
39
  );
40
40
  assert.equal(revokeOutputSchema.properties.revokedInviteId.type, "string");
41
41
  assert.equal(revokeOutputSchema.properties.roleCatalog["x-json-rest-schema"]?.castType, "object");
@@ -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
+ });
@@ -61,7 +61,15 @@ function startRuntime({ config, env = {}, logger = captureLogger().logger, works
61
61
  test("outside production the server refuses to start while a role grants a permission no action requires", async () => {
62
62
  await assert.rejects(
63
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
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
+ }
65
73
  );
66
74
  await assert.rejects(
67
75
  startRuntime({ config: memberGrants(["crud.labels.patch"]) }),
@@ -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,